quality_reporting.c 34.6 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
/*
linphone
Copyright (C) 2014 - Belledonne Communications, Grenoble, France

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
17
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.
18 19 20
*/

#ifdef HAVE_CONFIG_H
21
#include "config.h"
22 23
#endif

24
#include "linphone/core.h"
25 26
#include "private.h"
#include "sal/sal.h"
27 28
#include "ortp/rtpsession.h"

29 30
#include <math.h>

31 32 33 34
#if TARGET_OS_IPHONE
#include <sys/sysctl.h>
#endif

35
#define STR_REASSIGN(dest, src) {\
36 37 38 39
	if (dest != NULL) \
		ms_free(dest); \
	dest = src; \
}
40

41 42
/*since printf family functions are LOCALE dependent, float separator may differ
depending on the user's locale (LC_NUMERIC environment var).*/
43
static char * float_to_one_decimal_string(float f) {
44 45 46
	float rounded_f = floorf(f * 10 + .5f) / 10;

	int floor_part = (int) rounded_f;
47
	int one_decimal_part = (int)floorf(10 * (rounded_f - floor_part) + .5f);
48

49
	return ms_strdup_printf("%d.%d", floor_part, one_decimal_part);
50 51
}

52 53 54 55
static void append_to_buffer_valist(char **buff, size_t *buff_size, size_t *offset, const char *fmt, va_list args) {
	belle_sip_error_code ret;
	size_t prevoffset = *offset;

56
	#ifndef _WIN32
57 58
		va_list cap;/*copy of our argument list: a va_list cannot be re-used (SIGSEGV on linux 64 bits)*/
		va_copy(cap,args);
59
		ret = belle_sip_snprintf_valist(*buff, *buff_size, offset, fmt, cap);
60
		va_end(cap);
61
	#else
62
		ret = belle_sip_snprintf_valist(*buff, *buff_size, offset, fmt, args);
63
	#endif
64

65
	/*if we are out of memory, we add some size to buffer*/
66
	if (ret == BELLE_SIP_BUFFER_OVERFLOW) {
67
		/*some compilers complain that size_t cannot be formatted as unsigned long, hence forcing cast*/
68
		ms_debug("QualityReporting: Buffer was too small to contain the whole report - increasing its size from %lu to %lu",
69
			(unsigned long)*buff_size, (unsigned long)*buff_size + 2048);
70 71 72 73
		*buff_size += 2048;
		*buff = (char *) ms_realloc(*buff, *buff_size);

		*offset = prevoffset;
74
		/*recall itself since we did not write all things into the buffer but
75
		only a part of it*/
76 77 78 79 80 81 82 83 84 85 86
		append_to_buffer_valist(buff, buff_size, offset, fmt, args);
	}
}

static void append_to_buffer(char **buff, size_t *buff_size, size_t *offset, const char *fmt, ...) {
	va_list args;
	va_start(args, fmt);
	append_to_buffer_valist(buff, buff_size, offset, fmt, args);
	va_end(args);
}

87
static void reset_avg_metrics(reporting_session_report_t * report){
88
	int i;
89
	reporting_content_metrics_t * metrics[2] = {&report->local_metrics, &report->remote_metrics};
90 91

	for (i = 0; i < 2; i++) {
92
		metrics[i]->rtcp_sr_count = 0;
93 94 95 96
		metrics[i]->rtcp_xr_count = 0;
		metrics[i]->jitter_buffer.nominal = 0;
		metrics[i]->jitter_buffer.max = 0;

97 98 99
		metrics[i]->quality_estimates.moslq = 0;
		metrics[i]->quality_estimates.moscq = 0;

100 101
		metrics[i]->delay.round_trip_delay = 0;
	}
102
	report->last_report_date = ms_time(NULL);
103
}
104

105 106 107 108
#define APPEND_IF_NOT_NULL_STR(buffer, size, offset, fmt, arg) if (arg != NULL) append_to_buffer(buffer, size, offset, fmt, arg)
#define APPEND_IF_NUM_IN_RANGE(buffer, size, offset, fmt, arg, inf, sup) if (inf <= arg && arg <= sup) append_to_buffer(buffer, size, offset, fmt, arg)
#define APPEND_IF(buffer, size, offset, fmt, arg, cond) if (cond) append_to_buffer(buffer, size, offset, fmt, arg)
#define IF_NUM_IN_RANGE(num, inf, sup, statement) if (inf <= num && num <= sup) statement
109

110 111 112 113 114 115
#define METRICS_PACKET_LOSS 1 << 0
#define METRICS_QUALITY_ESTIMATES 1 << 1
#define METRICS_SESSION_DESCRIPTION 1 << 2
#define METRICS_JITTER_BUFFER 1 << 3
#define METRICS_DELAY 1 << 4
#define METRICS_SIGNAL 1 << 5
116

117 118 119
static uint8_t are_metrics_filled(const reporting_content_metrics_t rm) {
	uint8_t ret = 0;

120 121
	IF_NUM_IN_RANGE(rm.packet_loss.network_packet_loss_rate, 0, 255, ret|=METRICS_PACKET_LOSS);
	IF_NUM_IN_RANGE(rm.packet_loss.jitter_buffer_discard_rate, 0, 255, ret|=METRICS_PACKET_LOSS);
122

123 124 125 126
	if (rm.session_description.payload_type != -1) ret|=METRICS_SESSION_DESCRIPTION;
	if (rm.session_description.payload_desc != NULL) ret|=METRICS_SESSION_DESCRIPTION;
	if (rm.session_description.sample_rate != -1) ret|=METRICS_SESSION_DESCRIPTION;
	if (rm.session_description.fmtp != NULL) ret|=METRICS_SESSION_DESCRIPTION;
127 128 129 130 131 132 133 134 135 136 137

	IF_NUM_IN_RANGE(rm.jitter_buffer.adaptive, 0, 3, ret|=METRICS_JITTER_BUFFER);
	IF_NUM_IN_RANGE(rm.jitter_buffer.abs_max, 0, 65535, ret|=METRICS_JITTER_BUFFER);

	IF_NUM_IN_RANGE(rm.delay.end_system_delay, 0, 65535, ret|=METRICS_DELAY);
	IF_NUM_IN_RANGE(rm.delay.interarrival_jitter, 0, 65535, ret|=METRICS_DELAY);
	IF_NUM_IN_RANGE(rm.delay.mean_abs_jitter, 0, 65535, ret|=METRICS_DELAY);

	if (rm.signal.level != 127) ret|=METRICS_SIGNAL;
	if (rm.signal.noise_level != 127) ret|=METRICS_SIGNAL;

138 139 140
	IF_NUM_IN_RANGE(rm.quality_estimates.moslq, 1, 5, ret|=METRICS_QUALITY_ESTIMATES);
	IF_NUM_IN_RANGE(rm.quality_estimates.moscq, 1, 5, ret|=METRICS_QUALITY_ESTIMATES);

141 142 143 144
	if (rm.rtcp_xr_count>0){
		IF_NUM_IN_RANGE(rm.jitter_buffer.nominal/rm.rtcp_xr_count, 0, 65535, ret|=METRICS_JITTER_BUFFER);
		IF_NUM_IN_RANGE(rm.jitter_buffer.max/rm.rtcp_xr_count, 0, 65535, ret|=METRICS_JITTER_BUFFER);
	}
145 146 147
	if (rm.rtcp_sr_count+rm.rtcp_xr_count>0){
		IF_NUM_IN_RANGE(rm.delay.round_trip_delay/(rm.rtcp_sr_count+rm.rtcp_xr_count), 0, 65535, ret|=METRICS_DELAY);
	}
148 149

	return ret;
150
}
151

152 153 154 155 156 157 158 159 160 161 162
static bool_t quality_reporting_enabled(const LinphoneCall * call) {
	return (call->dest_proxy != NULL && linphone_proxy_config_quality_reporting_enabled(call->dest_proxy));
}

static bool_t media_report_enabled(LinphoneCall * call, int stats_type){
	if (! quality_reporting_enabled(call))
		return FALSE;

	if (stats_type == LINPHONE_CALL_STATS_VIDEO && !linphone_call_params_video_enabled(linphone_call_get_current_params(call)))
		return FALSE;

163 164 165
	if (stats_type == LINPHONE_CALL_STATS_TEXT && !linphone_call_params_realtime_text_enabled(linphone_call_get_current_params(call)))
		return FALSE;

166
	return (call->log->reporting.reports[stats_type] != NULL);
167 168
}

169
static void append_metrics_to_buffer(char ** buffer, size_t * size, size_t * offset, const reporting_content_metrics_t rm) {
170 171 172 173
	char * timestamps_start_str = NULL;
	char * timestamps_stop_str = NULL;
	char * network_packet_loss_rate_str = NULL;
	char * jitter_buffer_discard_rate_str = NULL;
174
	/*char * gap_loss_density_str = NULL;*/
175 176
	char * moslq_str = NULL;
	char * moscq_str = NULL;
177
	uint8_t available_metrics = are_metrics_filled(rm);
178

179
	if (rm.timestamps.start > 0)
180
		timestamps_start_str = linphone_timestamp_to_rfc3339_string(rm.timestamps.start);
181
	if (rm.timestamps.stop > 0)
182 183 184 185 186 187
		timestamps_stop_str = linphone_timestamp_to_rfc3339_string(rm.timestamps.stop);

	append_to_buffer(buffer, size, offset, "Timestamps:");
		APPEND_IF_NOT_NULL_STR(buffer, size, offset, " START=%s", timestamps_start_str);
		APPEND_IF_NOT_NULL_STR(buffer, size, offset, " STOP=%s", timestamps_stop_str);

188 189 190 191 192 193 194 195 196 197 198 199 200
	if ((available_metrics & METRICS_SESSION_DESCRIPTION) != 0){
		append_to_buffer(buffer, size, offset, "\r\nSessionDesc:");
			APPEND_IF(buffer, size, offset, " PT=%d", rm.session_description.payload_type, rm.session_description.payload_type != -1);
			APPEND_IF_NOT_NULL_STR(buffer, size, offset, " PD=%s", rm.session_description.payload_desc);
			APPEND_IF(buffer, size, offset, " SR=%d", rm.session_description.sample_rate, rm.session_description.sample_rate != -1);
			APPEND_IF(buffer, size, offset, " FD=%d", rm.session_description.frame_duration, rm.session_description.frame_duration != -1);
			APPEND_IF_NOT_NULL_STR(buffer, size, offset, " FMTP=\"%s\"", rm.session_description.fmtp);
			APPEND_IF(buffer, size, offset, " PLC=%d", rm.session_description.packet_loss_concealment, rm.session_description.packet_loss_concealment != -1);
	}

	if ((available_metrics & METRICS_JITTER_BUFFER) != 0){
		append_to_buffer(buffer, size, offset, "\r\nJitterBuffer:");
			APPEND_IF_NUM_IN_RANGE(buffer, size, offset, " JBA=%d", rm.jitter_buffer.adaptive, 0, 3);
201 202 203 204
			if (rm.rtcp_xr_count){
				APPEND_IF_NUM_IN_RANGE(buffer, size, offset, " JBN=%d", rm.jitter_buffer.nominal/rm.rtcp_xr_count, 0, 65535);
				APPEND_IF_NUM_IN_RANGE(buffer, size, offset, " JBM=%d", rm.jitter_buffer.max/rm.rtcp_xr_count, 0, 65535);
			}
205 206 207
			APPEND_IF_NUM_IN_RANGE(buffer, size, offset, " JBX=%d",  rm.jitter_buffer.abs_max, 0, 65535);

		append_to_buffer(buffer, size, offset, "\r\nPacketLoss:");
208 209 210
			IF_NUM_IN_RANGE(rm.packet_loss.network_packet_loss_rate, 0, 255, network_packet_loss_rate_str = float_to_one_decimal_string(rm.packet_loss.network_packet_loss_rate / 256));
			IF_NUM_IN_RANGE(rm.packet_loss.jitter_buffer_discard_rate, 0, 255, jitter_buffer_discard_rate_str = float_to_one_decimal_string(rm.packet_loss.jitter_buffer_discard_rate / 256));

211 212 213 214 215
			APPEND_IF_NOT_NULL_STR(buffer, size, offset, " NLR=%s", network_packet_loss_rate_str);
			APPEND_IF_NOT_NULL_STR(buffer, size, offset, " JDR=%s", jitter_buffer_discard_rate_str);
	}

		/*append_to_buffer(buffer, size, offset, "\r\nBurstGapLoss:");*/
216
			/*IF_NUM_IN_RANGE(rm.burst_gap_loss.gap_loss_density, 0, 10, gap_loss_density_str = float_to_one_decimal_string(rm.burst_gap_loss.gap_loss_density));*/
217 218 219 220 221 222 223 224
		/*	append_to_buffer(buffer, size, offset, " BLD=%d", rm.burst_gap_loss.burst_loss_density);*/
		/*	append_to_buffer(buffer, size, offset, " BD=%d", rm.burst_gap_loss.burst_duration);*/
		/*	APPEND_IF_NOT_NULL_STR(buffer, size, offset, " GLD=%s", gap_loss_density_str);*/
		/*	append_to_buffer(buffer, size, offset, " GD=%d", rm.burst_gap_loss.gap_duration);*/
		/*	append_to_buffer(buffer, size, offset, " GMIN=%d", rm.burst_gap_loss.min_gap_threshold);*/

	if ((available_metrics & METRICS_DELAY) != 0){
		append_to_buffer(buffer, size, offset, "\r\nDelay:");
225 226
			if (rm.rtcp_xr_count+rm.rtcp_sr_count){
				APPEND_IF_NUM_IN_RANGE(buffer, size, offset, " RTD=%d", rm.delay.round_trip_delay/(rm.rtcp_xr_count+rm.rtcp_sr_count), 0, 65535);
227
			}
228 229 230 231 232 233 234 235 236 237 238
			APPEND_IF_NUM_IN_RANGE(buffer, size, offset, " ESD=%d", rm.delay.end_system_delay, 0, 65535);
			APPEND_IF_NUM_IN_RANGE(buffer, size, offset, " IAJ=%d", rm.delay.interarrival_jitter, 0, 65535);
			APPEND_IF_NUM_IN_RANGE(buffer, size, offset, " MAJ=%d", rm.delay.mean_abs_jitter, 0, 65535);
	}

	if ((available_metrics & METRICS_SIGNAL) != 0){
		append_to_buffer(buffer, size, offset, "\r\nSignal:");
			APPEND_IF(buffer, size, offset, " SL=%d", rm.signal.level, rm.signal.level != 127);
			APPEND_IF(buffer, size, offset, " NL=%d", rm.signal.noise_level, rm.signal.noise_level != 127);
	}

239
	/*if quality estimates metrics are available, rtcp_xr_count should be always not null*/
240
	if ((available_metrics & METRICS_QUALITY_ESTIMATES) != 0){
241 242
		IF_NUM_IN_RANGE(rm.quality_estimates.moslq, 1, 5, moslq_str = float_to_one_decimal_string(rm.quality_estimates.moslq));
		IF_NUM_IN_RANGE(rm.quality_estimates.moscq, 1, 5, moscq_str = float_to_one_decimal_string(rm.quality_estimates.moscq));
243

244 245 246 247 248
		append_to_buffer(buffer, size, offset, "\r\nQualityEst:");
			APPEND_IF_NOT_NULL_STR(buffer, size, offset, " MOSLQ=%s", moslq_str);
			APPEND_IF_NOT_NULL_STR(buffer, size, offset, " MOSCQ=%s", moscq_str);
	}

249 250 251 252 253
	if (rm.user_agent!=NULL){
		append_to_buffer(buffer, size, offset, "\r\nLinphoneExt:");
			APPEND_IF_NOT_NULL_STR(buffer, size, offset, " UA=\"%s\"", rm.user_agent);
	}

254 255
	append_to_buffer(buffer, size, offset, "\r\n");

256 257 258 259
	ms_free(timestamps_start_str);
	ms_free(timestamps_stop_str);
	ms_free(network_packet_loss_rate_str);
	ms_free(jitter_buffer_discard_rate_str);
260
	/*ms_free(gap_loss_density_str);*/
261 262
	ms_free(moslq_str);
	ms_free(moscq_str);
263 264
}

265
static int send_report(LinphoneCall* call, reporting_session_report_t * report, const char * report_event) {
266
	LinphoneContent *content;
267 268 269
	size_t offset = 0;
	size_t size = 2048;
	char * buffer;
270
	int ret = 0;
271 272
	LinphoneEvent *lev;
	LinphoneAddress *request_uri;
273
	const char* collector_uri;
274

275 276
	/*if we are on a low bandwidth network, do not send reports to not overload it*/
	if (linphone_call_params_low_bandwidth_enabled(linphone_call_get_current_params(call))){
277
		ms_message("QualityReporting[%p]: Avoid sending reports on low bandwidth network", call);
278 279
		ret = 1;
		goto end;
280 281
	}

282 283
	/*if the call was hung up too early, we might have invalid IPs information
	in that case, we abort the report since it's not useful data*/
284 285
	if (report->info.local_addr.ip == NULL || strlen(report->info.local_addr.ip) == 0
		|| report->info.remote_addr.ip == NULL || strlen(report->info.remote_addr.ip) == 0) {
286
		ms_message("QualityReporting[%p]: Trying to submit a %s too early (call duration: %d sec) but %s IP could "
287
			"not be retrieved so dropping this report"
288
			, call
289
			, report_event
290 291
			, linphone_call_get_duration(call)
			, (report->info.local_addr.ip == NULL || strlen(report->info.local_addr.ip) == 0) ? "local" : "remote");
292 293
		ret = 2;
		goto end;
294 295
	}

296
	buffer = (char *) belle_sip_malloc(size);
297
	content = linphone_content_new();
298 299
	linphone_content_set_type(content, "application");
	linphone_content_set_subtype(content, "vq-rtcpxr");
300

301
	append_to_buffer(&buffer, &size, &offset, "%s\r\n", report_event);
302
	append_to_buffer(&buffer, &size, &offset, "CallID: %s\r\n", report->info.call_id);
303 304
	append_to_buffer(&buffer, &size, &offset, "LocalID: %s\r\n", report->info.local_addr.id);
	append_to_buffer(&buffer, &size, &offset, "RemoteID: %s\r\n", report->info.remote_addr.id);
305 306
	append_to_buffer(&buffer, &size, &offset, "OrigID: %s\r\n", report->info.orig_id);

307 308
	APPEND_IF_NOT_NULL_STR(&buffer, &size, &offset, "LocalGroup: %s\r\n", report->info.local_addr.group);
	APPEND_IF_NOT_NULL_STR(&buffer, &size, &offset, "RemoteGroup: %s\r\n", report->info.remote_addr.group);
309
	append_to_buffer(&buffer, &size, &offset, "LocalAddr: IP=%s PORT=%d SSRC=%u\r\n", report->info.local_addr.ip, report->info.local_addr.port, report->info.local_addr.ssrc);
310
	APPEND_IF_NOT_NULL_STR(&buffer, &size, &offset, "LocalMAC: %s\r\n", report->info.local_addr.mac);
311
	append_to_buffer(&buffer, &size, &offset, "RemoteAddr: IP=%s PORT=%d SSRC=%u\r\n", report->info.remote_addr.ip, report->info.remote_addr.port, report->info.remote_addr.ssrc);
312
	APPEND_IF_NOT_NULL_STR(&buffer, &size, &offset, "RemoteMAC: %s\r\n", report->info.remote_addr.mac);
313

314 315
	append_to_buffer(&buffer, &size, &offset, "LocalMetrics:\r\n");
	append_metrics_to_buffer(&buffer, &size, &offset, report->local_metrics);
316

317
	if (are_metrics_filled(report->remote_metrics)!=0) {
318 319 320
		append_to_buffer(&buffer, &size, &offset, "RemoteMetrics:\r\n");
		append_metrics_to_buffer(&buffer, &size, &offset, report->remote_metrics);
	}
321 322
	APPEND_IF_NOT_NULL_STR(&buffer, &size, &offset, "DialogID: %s\r\n", report->dialog_id);

323 324
	if (report->qos_analyzer.timestamp!=NULL){
		append_to_buffer(&buffer, &size, &offset, "AdaptiveAlg:");
325 326 327 328 329 330
			APPEND_IF_NOT_NULL_STR(&buffer, &size, &offset, " NAME=\"%s\"", report->qos_analyzer.name);
			APPEND_IF_NOT_NULL_STR(&buffer, &size, &offset, " TS=\"%s\"", report->qos_analyzer.timestamp);
			APPEND_IF_NOT_NULL_STR(&buffer, &size, &offset, " IN_LEG=\"%s\"", report->qos_analyzer.input_leg);
			APPEND_IF_NOT_NULL_STR(&buffer, &size, &offset, " IN=\"%s\"", report->qos_analyzer.input);
			APPEND_IF_NOT_NULL_STR(&buffer, &size, &offset, " OUT_LEG=\"%s\"", report->qos_analyzer.output_leg);
			APPEND_IF_NOT_NULL_STR(&buffer, &size, &offset, " OUT=\"%s\"", report->qos_analyzer.output);
331 332 333
		append_to_buffer(&buffer, &size, &offset, "\r\n");
	}

334 335 336 337 338 339 340 341 342 343 344
#if TARGET_OS_IPHONE
	{
		size_t namesize;
		char *machine;
		sysctlbyname("hw.machine", NULL, &namesize, NULL, 0);
		machine = malloc(namesize);
		sysctlbyname("hw.machine", machine, &namesize, NULL, 0);
		APPEND_IF_NOT_NULL_STR(&buffer, &size, &offset, "Device: %s\r\n", machine);
	}
#endif

345
	linphone_content_set_buffer(content, buffer, strlen(buffer));
346
	ms_free(buffer);
347

348
	if (call->log->reporting.on_report_sent != NULL) {
349
		SalStreamType type = report == call->log->reporting.reports[0] ? LINPHONE_CALL_STATS_AUDIO : report == call->log->reporting.reports[1] ? LINPHONE_CALL_STATS_VIDEO : LINPHONE_CALL_STATS_TEXT;
350
		call->log->reporting.on_report_sent(call, type, content);
351 352
	}

353

354 355 356 357 358
	collector_uri = linphone_proxy_config_get_quality_reporting_collector(call->dest_proxy);
	if (!collector_uri){
		collector_uri = ms_strdup_printf("sip:%s", linphone_proxy_config_get_domain(call->dest_proxy));
	}
	request_uri = linphone_address_new(collector_uri);
359
	lev = linphone_core_create_one_shot_publish(call->core, request_uri, "vq-rtcpxr");
360 361 362 363 364 365 366 367 368
	/* Special exception for quality report PUBLISH: if the collector_uri has any transport related parameters
	 * (port, transport, maddr), then it is sent directly.
	 * Otherwise it is routed as any LinphoneEvent publish, following proxy config policy.
	 **/
	if (sal_address_has_uri_param((SalAddress*)request_uri, "transport") || 
		sal_address_has_uri_param((SalAddress*)request_uri, "maddr") ||
		linphone_address_get_port(request_uri) != 0) {
		ms_message("Publishing report with custom route %s", collector_uri);
		sal_op_set_route(lev->op, collector_uri);
369 370
	}

371
	if (linphone_event_send_publish(lev, content) != 0){
372
		lev=NULL;
373
		ret=4;
374 375
	} else {
		reset_avg_metrics(report);
376 377 378 379 380
		STR_REASSIGN(report->qos_analyzer.timestamp, NULL);
		STR_REASSIGN(report->qos_analyzer.input_leg, NULL);
		STR_REASSIGN(report->qos_analyzer.input, NULL);
		STR_REASSIGN(report->qos_analyzer.output_leg, NULL);
		STR_REASSIGN(report->qos_analyzer.output, NULL);
381
	}
382

Simon Morlat's avatar
Simon Morlat committed
383
	linphone_address_unref(request_uri);
384
	linphone_content_unref(content);
385 386

	end:
387
	ms_message("QualityReporting[%p]: Send '%s' with status %d",
388 389 390 391 392
		call,
		report_event,
		ret
	);

393
	return ret;
394 395
}

396 397 398
static const SalStreamDescription * get_media_stream_for_desc(const SalMediaDescription * smd, SalStreamType sal_stream_type) {
	int count;
	if (smd != NULL) {
399 400
		for (count = 0; count < SAL_MEDIA_DESCRIPTION_MAX_STREAMS; ++count) {
			if (sal_stream_description_active(&smd->streams[count]) && smd->streams[count].type == sal_stream_type) {
401
				return &smd->streams[count];
402 403
			}
		}
404
	}
405 406
	return NULL;
}
407

408
static void update_ip(LinphoneCall * call, int stats_type) {
409
	SalStreamType sal_stream_type = stats_type == LINPHONE_CALL_STATS_AUDIO ? SalAudio : stats_type == LINPHONE_CALL_STATS_VIDEO ? SalVideo : SalText;
410 411
	const SalStreamDescription * local_desc = get_media_stream_for_desc(call->localdesc, sal_stream_type);
	const SalStreamDescription * remote_desc = get_media_stream_for_desc(sal_call_get_remote_media_description(call->op), sal_stream_type);
412

413 414 415
	if (local_desc != NULL) {
		/*since this function might be called for video stream AFTER it has been uninitialized, local description might
		be invalid. In any other case, IP/port should be always filled and valid*/
416
		if (strlen(local_desc->rtp_addr) > 0) {
417 418
			call->log->reporting.reports[stats_type]->info.local_addr.port = local_desc->rtp_port;
			STR_REASSIGN(call->log->reporting.reports[stats_type]->info.local_addr.ip, ms_strdup(local_desc->rtp_addr));
419
		}
420
	}
421

422 423 424
	if (remote_desc != NULL) {
		/*port is always stored in stream description struct*/
		call->log->reporting.reports[stats_type]->info.remote_addr.port = remote_desc->rtp_port;
425

426
		/*for IP it can be not set if we are using a direct route*/
427
		if (strlen(remote_desc->rtp_addr) > 0) {
428 429 430
			STR_REASSIGN(call->log->reporting.reports[stats_type]->info.remote_addr.ip, ms_strdup(remote_desc->rtp_addr));
		} else {
			STR_REASSIGN(call->log->reporting.reports[stats_type]->info.remote_addr.ip, ms_strdup(sal_call_get_remote_media_description(call->op)->addr));
431
		}
432
	}
433 434
}

435
static void qos_analyzer_on_action_suggested(void *user_data, int datac, const char** datav){
436 437
	reporting_session_report_t *report = (reporting_session_report_t*)user_data;
	LinphoneCall *call = report->call;
438
	char * appendbuf;
439 440
	int i;
	int ptime = -1;
441 442 443 444 445 446 447
	int bitrate[3] = {-1, -1, -1};
	int up_bw[3] = {-1, -1, -1};
	int down_bw[3] = {-1, -1, -1};
	MediaStream *streams[3] = { (MediaStream*) call->audiostream, (MediaStream *) call->videostream, (MediaStream *) call->textstream };
	for (i = 0; i < 3; i++){
		if (streams[i] != NULL){
			if (streams[i]->encoder != NULL){
448 449
				if (ms_filter_has_method(streams[i]->encoder,MS_FILTER_GET_BITRATE)){
					ms_filter_call_method(streams[i]->encoder,MS_FILTER_GET_BITRATE,&bitrate[i]);
450
					bitrate[i] /= 1000;
451 452
				}
			}
453 454
			up_bw[i] = (int)(media_stream_get_up_bw(streams[i])/1000.f);
			down_bw[i] = (int)(media_stream_get_down_bw(streams[i])/1000.f);
455 456 457 458 459 460 461 462 463
		}
	}
	if (call->audiostream!=NULL){
		if (call->audiostream->ms.encoder!=NULL){
			if(ms_filter_has_method(call->audiostream->ms.encoder,MS_AUDIO_ENCODER_GET_PTIME)){
				ms_filter_call_method(call->audiostream->ms.encoder,MS_AUDIO_ENCODER_GET_PTIME,&ptime);
			}
		}
	}
464

465 466
	appendbuf=ms_strdup_printf("%s%d;", report->qos_analyzer.timestamp?report->qos_analyzer.timestamp:"", ms_time(0));
	STR_REASSIGN(report->qos_analyzer.timestamp,appendbuf);
467

468 469 470
	STR_REASSIGN(report->qos_analyzer.input_leg, ms_strdup_printf("%s aenc_ptime aenc_br a_dbw a_ubw venc_br v_dbw v_ubw tenc_br t_dbw t_ubw", datav[0]));
	appendbuf=ms_strdup_printf("%s%s %d %d %d %d %d %d %d %d %d %d;", report->qos_analyzer.input?report->qos_analyzer.input:"", datav[1],
		ptime, bitrate[0], down_bw[0], up_bw[0], bitrate[1], down_bw[1], up_bw[1], bitrate[2], down_bw[2], up_bw[2]);
471
	STR_REASSIGN(report->qos_analyzer.input,appendbuf);
472 473
	STR_REASSIGN(report->qos_analyzer.output_leg, ms_strdup(datav[2]));
	appendbuf=ms_strdup_printf("%s%s;", report->qos_analyzer.output?report->qos_analyzer.output:"", datav[3]);
474
	STR_REASSIGN(report->qos_analyzer.output, appendbuf);
475 476
}

477
void linphone_reporting_update_ip(LinphoneCall * call) {
478
	update_ip(call, LINPHONE_CALL_STATS_AUDIO);
479
	update_ip(call, LINPHONE_CALL_STATS_VIDEO);
480
	update_ip(call, LINPHONE_CALL_STATS_TEXT);
481
}
482

483
void linphone_reporting_update_media_info(LinphoneCall * call, int stats_type) {
484 485 486
	MediaStream * stream = NULL;
	const PayloadType * local_payload = NULL;
	const PayloadType * remote_payload = NULL;
487
	const LinphoneCallParams * current_params = linphone_call_get_current_params(call);
488
	reporting_session_report_t * report = call->log->reporting.reports[stats_type];
489
	char * dialog_id;
490

491 492
	// call->op might be already released if hanging up in state LinphoneCallOutgoingInit
	if (!media_report_enabled(call, stats_type) || call->op == NULL)
493 494
		return;

495
	dialog_id = sal_op_get_dialog_id(call->op);
496

497
	STR_REASSIGN(report->info.call_id, ms_strdup(call->log->call_id));
498 499 500 501 502 503 504

	STR_REASSIGN(report->local_metrics.user_agent, ms_strdup(linphone_core_get_user_agent(call->core)));
	STR_REASSIGN(report->remote_metrics.user_agent, ms_strdup(linphone_call_get_remote_user_agent(call)));

	// RFC states: "LocalGroupID provides the identification for the purposes
	// of aggregation for the local endpoint.".
	STR_REASSIGN(report->info.local_addr.group, ms_strdup_printf("%s-%s-%s"
505
		, dialog_id ? dialog_id : ""
506
		, "local"
507
		, report->local_metrics.user_agent ? report->local_metrics.user_agent : ""
508
		)
509
	);
510
	STR_REASSIGN(report->info.remote_addr.group, ms_strdup_printf("%s-%s-%s"
511
		, dialog_id ? dialog_id : ""
512
		, "remote"
513
		, report->remote_metrics.user_agent ? report->remote_metrics.user_agent : ""
514
		)
515
	);
516

517

518
	if (call->dir == LinphoneCallIncoming) {
519 520 521
		STR_REASSIGN(report->info.remote_addr.id, linphone_address_as_string(call->log->from));
		STR_REASSIGN(report->info.local_addr.id, linphone_address_as_string(call->log->to));
		STR_REASSIGN(report->info.orig_id, ms_strdup(report->info.remote_addr.id));
522
	} else {
523 524 525
		STR_REASSIGN(report->info.remote_addr.id, linphone_address_as_string(call->log->to));
		STR_REASSIGN(report->info.local_addr.id, linphone_address_as_string(call->log->from));
		STR_REASSIGN(report->info.orig_id, ms_strdup(report->info.local_addr.id));
526
	}
527

528

529 530
	report->local_metrics.timestamps.start = call->log->start_date_time;
	report->local_metrics.timestamps.stop = call->log->start_date_time + linphone_call_get_duration(call);
531

532
	/*we use same timestamps for remote too*/
533 534
	report->remote_metrics.timestamps.start = call->log->start_date_time;
	report->remote_metrics.timestamps.stop = call->log->start_date_time + linphone_call_get_duration(call);
535

536

537
	/*yet we use the same payload config for local and remote, since this is the largest use case*/
538 539
	if (stats_type == LINPHONE_CALL_STATS_AUDIO && call->audiostream != NULL) {
		stream = &call->audiostream->ms;
540 541
		local_payload = linphone_call_params_get_used_audio_codec(current_params);
		remote_payload = local_payload;
542 543
	} else if (stats_type == LINPHONE_CALL_STATS_VIDEO && call->videostream != NULL) {
		stream = &call->videostream->ms;
544 545
		local_payload = linphone_call_params_get_used_video_codec(current_params);
		remote_payload = local_payload;
546 547 548 549
	} else if (stats_type == LINPHONE_CALL_STATS_TEXT && call->textstream != NULL) {
		stream = &call->textstream->ms;
		local_payload = linphone_call_params_get_used_text_codec(current_params);
		remote_payload = local_payload;
550
	}
551

552 553
	if (stream != NULL) {
		RtpSession * session = stream->sessions.rtp_session;
554

555 556
		report->info.local_addr.ssrc = rtp_session_get_send_ssrc(session);
		report->info.remote_addr.ssrc = rtp_session_get_recv_ssrc(session);
557 558

		if (stream->qi != NULL){
559 560 561 562
			report->local_metrics.quality_estimates.moslq = ms_quality_indicator_get_average_lq_rating(stream->qi) >= 0 ?
				MAX(1, ms_quality_indicator_get_average_lq_rating(stream->qi)) : -1;
			report->local_metrics.quality_estimates.moscq = ms_quality_indicator_get_average_rating(stream->qi) >= 0 ?
				MAX(1, ms_quality_indicator_get_average_rating(stream->qi)) : -1;
563
		}
564
	}
565

566
	STR_REASSIGN(report->dialog_id, ms_strdup_printf("%s;%u", dialog_id ? dialog_id : "", report->info.local_addr.ssrc));
567

568 569
	if (local_payload != NULL) {
		report->local_metrics.session_description.payload_type = local_payload->type;
570
		if (local_payload->mime_type!=NULL) STR_REASSIGN(report->local_metrics.session_description.payload_desc, ms_strdup(local_payload->mime_type));
571
		report->local_metrics.session_description.sample_rate = local_payload->clock_rate;
572
		if (local_payload->recv_fmtp!=NULL) STR_REASSIGN(report->local_metrics.session_description.fmtp, ms_strdup(local_payload->recv_fmtp));
573
	}
574

575 576
	if (remote_payload != NULL) {
		report->remote_metrics.session_description.payload_type = remote_payload->type;
577
		STR_REASSIGN(report->remote_metrics.session_description.payload_desc, ms_strdup(remote_payload->mime_type));
578
		report->remote_metrics.session_description.sample_rate = remote_payload->clock_rate;
579
		STR_REASSIGN(report->remote_metrics.session_description.fmtp, ms_strdup(remote_payload->recv_fmtp));
580
	}
581 582

	ms_free(dialog_id);
583 584
}

585 586 587 588 589
/* generate random float in interval ] 0.9 t ; 1.1 t [*/
static float reporting_rand(float t){
	return t * (.2f * (rand() / (RAND_MAX * 1.0f)) + 0.9f);
}

590
void linphone_reporting_on_rtcp_update(LinphoneCall *call, SalStreamType stats_type) {
591
	reporting_session_report_t * report = call->log->reporting.reports[stats_type];
592 593
	reporting_content_metrics_t * metrics = NULL;
	LinphoneCallStats stats = call->stats[stats_type];
594
	mblk_t *block = NULL;
595
	int report_interval;
596

597
	if (! media_report_enabled(call,stats_type))
598 599
		return;

600 601
	report_interval = linphone_proxy_config_get_quality_reporting_interval(call->dest_proxy);

602
	if (stats.updated == LINPHONE_CALL_STATS_RECEIVED_RTCP_UPDATE) {
603
		metrics = &report->remote_metrics;
604
		block = stats.received_rtcp;
605
	} else if (stats.updated == LINPHONE_CALL_STATS_SENT_RTCP_UPDATE) {
606
		metrics = &report->local_metrics;
607
		block = stats.sent_rtcp;
608
	}
609 610
	do{
		if (rtcp_is_XR(block) && (rtcp_XR_get_block_type(block) == RTCP_XR_VOIP_METRICS)){
611

612
			uint8_t config = rtcp_XR_voip_metrics_get_rx_config(block);
613

614
			metrics->rtcp_xr_count++;
615

616 617 618 619 620 621 622 623
			// for local mos rating, we'll use the quality indicator directly
			// because rtcp XR might not be enabled
			if (stats.updated == LINPHONE_CALL_STATS_RECEIVED_RTCP_UPDATE){
				metrics->quality_estimates.moslq = (rtcp_XR_voip_metrics_get_mos_lq(block)==127) ?
					127 : rtcp_XR_voip_metrics_get_mos_lq(block) / 10.f;
				metrics->quality_estimates.moscq = (rtcp_XR_voip_metrics_get_mos_cq(block)==127) ?
					127 : rtcp_XR_voip_metrics_get_mos_cq(block) / 10.f;
			}
624

625 626 627 628 629 630
			metrics->jitter_buffer.nominal += rtcp_XR_voip_metrics_get_jb_nominal(block);
			metrics->jitter_buffer.max += rtcp_XR_voip_metrics_get_jb_maximum(block);
			metrics->jitter_buffer.abs_max = rtcp_XR_voip_metrics_get_jb_abs_max(block);
			metrics->jitter_buffer.adaptive = (config >> 4) & 0x3;
			metrics->packet_loss.network_packet_loss_rate = rtcp_XR_voip_metrics_get_loss_rate(block);
			metrics->packet_loss.jitter_buffer_discard_rate = rtcp_XR_voip_metrics_get_discard_rate(block);
631

632 633 634
			metrics->session_description.packet_loss_concealment = (config >> 6) & 0x3;

			metrics->delay.round_trip_delay += rtcp_XR_voip_metrics_get_round_trip_delay(block);
635 636 637 638 639 640
		}else if (rtcp_is_SR(block)){
			MediaStream *ms=(stats_type==0 ? &call->audiostream->ms : &call->videostream->ms);
			float rtt = rtp_session_get_round_trip_propagation(ms->sessions.rtp_session);

			if (rtt > 1e-6){
				metrics->rtcp_sr_count++;
641
				metrics->delay.round_trip_delay += (int)(1000*rtt);
642
			}
643
		}
644
	}while(rtcp_next_packet(block));
645

646 647
	/* check if we should send an interval report - use a random sending time to
	dispatch reports and avoid sending them too close from each other */
648
	if ((report_interval > 0) && ((float)(ms_time(NULL) - report->last_report_date) > reporting_rand((float)report_interval))) {
649 650
		linphone_reporting_update_media_info(call, stats_type);
		send_report(call, report, "VQIntervalReport");
651 652 653
	}
}

654 655
static int publish_report(LinphoneCall *call, const char *event_type){
	int ret = 0;
656
	int i;
657 658 659
	for (i = 0; i < SAL_MEDIA_DESCRIPTION_MAX_STREAMS; i++){
		int stream_index = i == call->main_audio_stream_index ? LINPHONE_CALL_STATS_AUDIO : call->main_video_stream_index ? LINPHONE_CALL_STATS_VIDEO : LINPHONE_CALL_STATS_TEXT;
		if (media_report_enabled(call, stream_index)) {
660
			int sndret;
661 662
			linphone_reporting_update_media_info(call, stream_index);
			sndret=send_report(call, call->log->reporting.reports[stream_index], event_type);
663 664 665 666 667
			if (sndret>0){
				ret += 10+(i+1)*sndret;
			}
		} else{
			ret += i+1;
668
		}
669
	}
670
	return ret;
671
}
672 673 674 675

int linphone_reporting_publish_session_report(LinphoneCall* call, bool_t call_term) {
	char * session_type = call_term?"VQSessionReport: CallTerm":"VQSessionReport";
	return publish_report(call, session_type);
676
}
677

678 679
int linphone_reporting_publish_interval_report(LinphoneCall* call) {
	return publish_report(call, "VQIntervalReport");
680 681
}

682 683 684 685 686 687 688 689 690 691 692 693 694
static bool_t set_on_action_suggested_cb(MediaStream *stream,void (*on_action_suggested)(void*,int,const char**),void* u) {
	if (stream&&stream->rc){
		MSQosAnalyzer *analyzer=ms_bitrate_controller_get_qos_analyzer(stream->rc);
		if (analyzer){
			ms_qos_analyzer_set_on_action_suggested(analyzer,
													on_action_suggested,
													u);
			return TRUE;
		}
	}
	return FALSE;
}

695 696
void linphone_reporting_call_state_updated(LinphoneCall *call){
	LinphoneCallState state=linphone_call_get_state(call);
697
	if (state == LinphoneCallReleased||!quality_reporting_enabled(call)){
698 699
		return;
	}
700 701
	switch (state){
		case LinphoneCallStreamsRunning:{
702
			int i = 0;
703 704 705 706 707 708 709
			MediaStream *streams[3] = { (MediaStream*) call->audiostream, (MediaStream *) call->videostream, (MediaStream *) call->textstream };
			for (i = 0; i < SAL_MEDIA_DESCRIPTION_MAX_STREAMS; i++) {
				int stream_index = i == call->main_audio_stream_index ? LINPHONE_CALL_STATS_AUDIO : call->main_video_stream_index ? LINPHONE_CALL_STATS_VIDEO : LINPHONE_CALL_STATS_TEXT;
				bool_t enabled = media_report_enabled(call, stream_index);
				if (enabled && set_on_action_suggested_cb(streams[stream_index], qos_analyzer_on_action_suggested, call->log->reporting.reports[stream_index])) {
					call->log->reporting.reports[stream_index]->call=call;
					STR_REASSIGN(call->log->reporting.reports[stream_index]->qos_analyzer.name, ms_strdup(ms_qos_analyzer_get_name(ms_bitrate_controller_get_qos_analyzer(streams[stream_index]->rc))));
710 711 712
				}
			}
			linphone_reporting_update_ip(call);
713
			if (!media_report_enabled(call, LINPHONE_CALL_STATS_VIDEO) && call->log->reporting.was_video_running){
714
				send_report(call, call->log->reporting.reports[LINPHONE_CALL_STATS_VIDEO], "VQSessionReport");
715
			}
716
			call->log->reporting.was_video_running=media_report_enabled(call, LINPHONE_CALL_STATS_VIDEO);
717 718 719
			break;
		}
		case LinphoneCallEnd:{
720 721
			set_on_action_suggested_cb(&call->audiostream->ms, NULL, NULL);
			set_on_action_suggested_cb(&call->videostream->ms, NULL, NULL);
722
			if (call->log->status==LinphoneCallSuccess || call->log->status==LinphoneCallAborted){
723
				linphone_reporting_publish_session_report(call, TRUE);
724 725 726 727 728 729 730 731
			}
			break;
		}
		default:{
			break;
		}
	}
}
732

733 734 735 736
reporting_session_report_t * linphone_reporting_new() {
	int i;
	reporting_session_report_t * rm = ms_new0(reporting_session_report_t,1);
	reporting_content_metrics_t * metrics[2] = {&rm->local_metrics, &rm->remote_metrics};
737 738 739

	memset(rm, 0, sizeof(reporting_session_report_t));

740 741 742 743
	for (i = 0; i < 2; i++) {
		metrics[i]->session_description.payload_type = -1;
		metrics[i]->session_description.sample_rate = -1;
		metrics[i]->session_description.frame_duration = -1;
744
		metrics[i]->session_description.packet_loss_concealment = -1;
745 746 747 748 749 750 751 752 753 754 755 756 757 758

		metrics[i]->packet_loss.network_packet_loss_rate = -1;
		metrics[i]->packet_loss.jitter_buffer_discard_rate = -1;


		metrics[i]->jitter_buffer.adaptive = -1;
		metrics[i]->jitter_buffer.abs_max = -1;

		metrics[i]->delay.end_system_delay = -1;
		metrics[i]->delay.interarrival_jitter = -1;
		metrics[i]->delay.mean_abs_jitter = -1;

		metrics[i]->signal.level = 127;
		metrics[i]->signal.noise_level = 127;
759
	}
760 761

	reset_avg_metrics(rm);
762
	return rm;
763
}
764 765

void linphone_reporting_destroy(reporting_session_report_t * report) {
766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788
	STR_REASSIGN(report->info.call_id, NULL);
	STR_REASSIGN(report->info.local_addr.id, NULL);
	STR_REASSIGN(report->info.remote_addr.id, NULL);
	STR_REASSIGN(report->info.orig_id, NULL);
	STR_REASSIGN(report->info.local_addr.ip, NULL);
	STR_REASSIGN(report->info.remote_addr.ip, NULL);
	STR_REASSIGN(report->info.local_addr.group, NULL);
	STR_REASSIGN(report->info.remote_addr.group, NULL);
	STR_REASSIGN(report->info.local_addr.mac, NULL);
	STR_REASSIGN(report->info.remote_addr.mac, NULL);
	STR_REASSIGN(report->dialog_id, NULL);
	STR_REASSIGN(report->local_metrics.session_description.fmtp, NULL);
	STR_REASSIGN(report->local_metrics.session_description.payload_desc, NULL);
	STR_REASSIGN(report->local_metrics.user_agent, NULL);
	STR_REASSIGN(report->remote_metrics.session_description.fmtp, NULL);
	STR_REASSIGN(report->remote_metrics.session_description.payload_desc, NULL);
	STR_REASSIGN(report->remote_metrics.user_agent, NULL);
	STR_REASSIGN(report->qos_analyzer.name, NULL);
	STR_REASSIGN(report->qos_analyzer.timestamp, NULL);
	STR_REASSIGN(report->qos_analyzer.input_leg, NULL);
	STR_REASSIGN(report->qos_analyzer.input, NULL);
	STR_REASSIGN(report->qos_analyzer.output_leg, NULL);
	STR_REASSIGN(report->qos_analyzer.output, NULL);
789 790 791

	ms_free(report);
}
792

793

794 795 796
void linphone_reporting_set_on_report_send(LinphoneCall *call, LinphoneQualityReportingReportSendCb cb){
	call->log->reporting.on_report_sent = cb;
}