qosanalyzer.c 20.9 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23
/*
mediastreamer2 library - modular sound and video processing and streaming

 * Copyright (C) 2011  Belledonne Communications, Grenoble, France

	 Author: Simon Morlat <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
Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
 */

#include "mediastreamer2/bitratecontrol.h"
24
#include "qosanalyzer.h"
25

26 27
#include <math.h>

28 29 30 31 32 33
#define RED 		""
#define YELLOW 		""
#define GREEN 		""
#define RESET 		""
#define VA_ARGS(...) , ##__VA_ARGS__
#define P(c, ...) 	printf(GREEN c RESET VA_ARGS(__VA_ARGS__))
34

35 36 37
/**
 * Analyses a received RTCP packet.
 * Returns TRUE is relevant information has been found in the rtcp message, FALSE otherwise.
38
**/
39
bool_t ms_qos_analyser_process_rtcp(MSQosAnalyser *obj,mblk_t *msg){
40 41 42 43 44 45 46
	if (obj->desc->process_rtcp){
		return obj->desc->process_rtcp(obj,msg);
	}
	ms_error("Unimplemented process_rtcp() call.");
	return FALSE;
}

47
void ms_qos_analyser_suggest_action(MSQosAnalyser *obj, MSRateControlAction *action){
48 49 50
	if (obj->desc->suggest_action){
		obj->desc->suggest_action(obj,action);
	}
51 52 53 54 55 56
}

void ms_qos_analyser_update(MSQosAnalyser *obj){
	if (obj->desc->update){
		obj->desc->update(obj);
	}
57 58
}

59
bool_t ms_qos_analyser_has_improved(MSQosAnalyser *obj){
60
	if (obj->desc->has_improved){
61
		return obj->desc->has_improved(obj);
62 63 64 65 66
	}
	ms_error("Unimplemented has_improved() call.");
	return TRUE;
}

67 68 69 70 71 72 73 74 75 76 77 78
MSQosAnalyser *ms_qos_analyser_ref(MSQosAnalyser *obj){
	obj->refcnt++;
	return obj;
}

void ms_qos_analyser_unref(MSQosAnalyser *obj){
	obj->refcnt--;
	if (obj->refcnt<=0){
		if (obj->desc->uninit)
			obj->desc->uninit(obj);
		ms_free(obj);
	}
79 80
}

81
const char *ms_rate_control_action_type_name(MSRateControlActionType t){
82 83 84 85 86 87 88 89 90 91 92 93 94
	switch(t){
		case MSRateControlActionDoNothing:
			return "DoNothing";
		case MSRateControlActionIncreaseQuality:
			return "IncreaseQuality";
		case MSRateControlActionDecreaseBitrate:
			return "DecreaseBitrate";
		case MSRateControlActionDecreasePacketRate:
			return "DecreasePacketRate";
	}
	return "bad action type";
}

95 96 97
/******************************************************************************/
/***************************** Simple QoS analyser ****************************/
/******************************************************************************/
98
static bool_t rt_prop_doubled(rtpstats_t *cur,rtpstats_t *prev){
99
	/*ms_message("AudioBitrateController: cur=%f, prev=%f",cur->rt_prop,prev->rt_prop);*/
100
	if (cur->rt_prop>=significant_delay && prev->rt_prop>0){
101 102 103 104 105 106 107 108
		if (cur->rt_prop>=(prev->rt_prop*2.0)){
			/*propagation doubled since last report */
			return TRUE;
		}
	}
	return FALSE;
}

109
static bool_t simple_rt_prop_increased(MSSimpleQosAnalyser *obj){
110 111 112 113 114 115 116 117 118 119 120
	rtpstats_t *cur=&obj->stats[obj->curindex % STATS_HISTORY];
	rtpstats_t *prev=&obj->stats[(STATS_HISTORY+obj->curindex-1) % STATS_HISTORY];

	if (rt_prop_doubled(cur,prev)){
		obj->rt_prop_doubled=TRUE;
		return TRUE;
	}
	return FALSE;
}

static bool_t simple_analyser_process_rtcp(MSQosAnalyser *objbase, mblk_t *rtcp){
121
	MSSimpleQosAnalyser *obj=(MSSimpleQosAnalyser*)objbase;
122 123 124 125 126 127 128
	rtpstats_t *cur;
	const report_block_t *rb=NULL;
	if (rtcp_is_SR(rtcp)){
		rb=rtcp_SR_get_report_block(rtcp,0);
	}else if (rtcp_is_RR(rtcp)){
		rb=rtcp_RR_get_report_block(rtcp,0);
	}
129
	if (rb && report_block_get_ssrc(rb)==rtp_session_get_send_ssrc(obj->session)){
130

131 132
		obj->curindex++;
		cur=&obj->stats[obj->curindex % STATS_HISTORY];
133

134 135 136 137 138
		if (obj->clockrate==0){
			PayloadType *pt=rtp_profile_get_payload(rtp_session_get_send_profile(obj->session),rtp_session_get_send_payload_type(obj->session));
			if (pt!=NULL) obj->clockrate=pt->clock_rate;
			else return FALSE;
		}
139

140 141 142 143
		cur->high_seq_recv=report_block_get_high_ext_seq(rb);
		cur->lost_percentage=100.0*(float)report_block_get_fraction_lost(rb)/256.0;
		cur->int_jitter=1000.0*(float)report_block_get_interarrival_jitter(rb)/(float)obj->clockrate;
		cur->rt_prop=rtp_session_get_round_trip_propagation(obj->session);
144

145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205
		ms_message("MSQosAnalyser: lost_percentage=%f, int_jitter=%f ms, rt_prop=%fsec",
			cur->lost_percentage,cur->int_jitter,cur->rt_prop);
	}
	return rb!=NULL;
}

static void simple_analyser_suggest_action(MSQosAnalyser *objbase, MSRateControlAction *action){
	MSSimpleQosAnalyser *obj=(MSSimpleQosAnalyser*)objbase;
	rtpstats_t *cur=&obj->stats[obj->curindex % STATS_HISTORY];

	/*big losses and big jitter */
	if (cur->lost_percentage>=unacceptable_loss_rate && cur->int_jitter>=big_jitter){
		action->type=MSRateControlActionDecreaseBitrate;
		action->value=MIN(cur->lost_percentage,50);
		ms_message("MSQosAnalyser: loss rate unacceptable and big jitter");
	}else if (simple_rt_prop_increased(obj)){
		action->type=MSRateControlActionDecreaseBitrate;
		action->value=20;
		ms_message("MSQosAnalyser: rt_prop doubled.");
	}else if (cur->lost_percentage>=unacceptable_loss_rate){
		/*big loss rate but no jitter, and no big rtp_prop: pure lossy network*/
		action->type=MSRateControlActionDecreasePacketRate;
		ms_message("MSQosAnalyser: loss rate unacceptable.");
	}else{
		action->type=MSRateControlActionDoNothing;
		ms_message("MSQosAnalyser: everything is fine.");
	}
}

static bool_t simple_analyser_has_improved(MSQosAnalyser *objbase){
	MSSimpleQosAnalyser *obj=(MSSimpleQosAnalyser*)objbase;
	rtpstats_t *cur=&obj->stats[obj->curindex % STATS_HISTORY];
	rtpstats_t *prev=&obj->stats[(STATS_HISTORY+obj->curindex-1) % STATS_HISTORY];

	if (prev->lost_percentage>=unacceptable_loss_rate){
		if (cur->lost_percentage<prev->lost_percentage){
			ms_message("MSQosAnalyser: lost percentage has improved");
			return TRUE;
		}else goto end;
	}
	if (obj->rt_prop_doubled && cur->rt_prop<prev->rt_prop){
		ms_message("MSQosAnalyser: rt prop decreased");
		obj->rt_prop_doubled=FALSE;
		return TRUE;
	}

	end:
	ms_message("MSQosAnalyser: no improvements.");
	return FALSE;
}

static MSQosAnalyserDesc simple_analyser_desc={
	simple_analyser_process_rtcp,
	simple_analyser_suggest_action,
	simple_analyser_has_improved
};

MSQosAnalyser * ms_simple_qos_analyser_new(RtpSession *session){
	MSSimpleQosAnalyser *obj=ms_new0(MSSimpleQosAnalyser,1);
	obj->session=session;
	obj->parent.desc=&simple_analyser_desc;
206
	obj->parent.type=Simple;
207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240
	return (MSQosAnalyser*)obj;
}




/******************************************************************************/
/***************************** Stateful QoS analyser ****************************/
/******************************************************************************/
const char *ms_qos_analyser_network_state_name(MSQosAnalyserNetworkState state){
	switch(state){
		case MSQosAnalyserNetworkFine:
			return "fine";
		case MSQosAnalyserNetworkUnstable:
			return "unstable";
		case MSQosAnalyserNetworkCongested:
			return "congested";
		case MSQosAnalyserNetworkLossy:
			return "lossy";
	}
	return "bad state type";
}

static bool_t stateful_rt_prop_increased(MSStatefulQosAnalyser *obj){
	rtpstats_t *cur=&obj->stats[obj->curindex % STATS_HISTORY];
	rtpstats_t *prev=&obj->stats[(STATS_HISTORY+obj->curindex-1) % STATS_HISTORY];

	if (rt_prop_doubled(cur,prev)){
		obj->rt_prop_doubled=TRUE;
		return TRUE;
	}
	return FALSE;
}

241 242 243
static int earlier_than(const rtcpstatspoint_t *p, const time_t * now){
	return p->timestamp > *now;
}
244 245 246 247
static int sort_points(const rtcpstatspoint_t *p1, const rtcpstatspoint_t *p2){
	return p1->bandwidth > p2->bandwidth;
}

248 249 250 251 252 253 254 255 256 257 258
static double stateful_qos_analyser_upload_bandwidth(MSStatefulQosAnalyser *obj){
	double up_bw=rtp_session_get_send_bandwidth(obj->session)/1000.0;
	double avg_up_bw=(obj->interval_count)?obj->upload_bandwidth_sum/obj->interval_count:up_bw;
	P(GREEN "latest_up_bw=%f vs sum_up_bw=%f\n", up_bw, avg_up_bw);

	obj->interval_count=0;
	obj->upload_bandwidth_sum=0;

	return up_bw;
}

259 260 261 262 263 264 265 266 267 268
static bool_t stateful_analyser_process_rtcp(MSQosAnalyser *objbase, mblk_t *rtcp){
	MSStatefulQosAnalyser *obj=(MSStatefulQosAnalyser*)objbase;
	rtpstats_t *cur;
	const report_block_t *rb=NULL;
	if (rtcp_is_SR(rtcp)){
		rb=rtcp_SR_get_report_block(rtcp,0);
	}else if (rtcp_is_RR(rtcp)){
		rb=rtcp_RR_get_report_block(rtcp,0);
	}
	if (rb && report_block_get_ssrc(rb)==rtp_session_get_send_ssrc(obj->session)){
269
		double up_bw = stateful_qos_analyser_upload_bandwidth(obj);
270 271 272 273 274 275 276 277 278 279 280 281 282
		obj->curindex++;
		cur=&obj->stats[obj->curindex % STATS_HISTORY];

		if (obj->clockrate==0){
			PayloadType *pt=rtp_profile_get_payload(rtp_session_get_send_profile(obj->session),rtp_session_get_send_payload_type(obj->session));
			if (pt!=NULL) obj->clockrate=pt->clock_rate;
			else return FALSE;
		}

		cur->high_seq_recv=report_block_get_high_ext_seq(rb);
		cur->lost_percentage=100.0*(float)report_block_get_fraction_lost(rb)/256.0;
		cur->int_jitter=1000.0*(float)report_block_get_interarrival_jitter(rb)/(float)obj->clockrate;
		cur->rt_prop=rtp_session_get_round_trip_propagation(obj->session);
283 284
		ms_message("MSQosAnalyser: lost_percentage=%f, int_jitter=%f ms, rt_prop=%f sec",cur->lost_percentage,cur->int_jitter,cur->rt_prop);
		if (obj->curindex>2){
285 286
			double loss_rate = cur->lost_percentage/100.0;
			int cum_loss=report_block_get_cum_packet_loss(rb);
287 288
			int cum_loss_curr=cum_loss - obj->cum_loss_prev;
			int uniq_emitted=report_block_get_high_ext_seq(rb) - obj->last_seq;
289 290 291 292 293 294 295 296 297

			if (obj->last_seq > 0){
				int total_emitted=uniq_emitted * (1 + obj->session->duplication_ratio);
				printf("RECEIVE cumloss=%d uniq_emitted=%d total_emitted=%d\n", cum_loss_curr, uniq_emitted, total_emitted);
				loss_rate=100 * (1. - (uniq_emitted - cum_loss_curr) * 1.f / total_emitted);
				/*printf("RECEIVE expec=%d - received=%d =%d --> cum_loss=%ld\n", expected_packets, stream->hwrcv_since_last_SR, packet_loss, stream->stats.cum_packet_loss);*/
				printf("RECEIVE estimated loss rate=%f vs 'real'=%f\n", loss_rate, report_block_get_fraction_lost(rb)/2.56);
			}

298
			if (obj->curindex % 10 == 6){
299
				P(YELLOW "SKIPPED first MIN burst %d: %f %f\n", obj->curindex-1, up_bw, loss_rate);
300 301
			}else{
				obj->latest=ms_new0(rtcpstatspoint_t, 1);
302
				obj->latest->timestamp=ms_time(0);
303 304
				obj->latest->bandwidth=up_bw;
				obj->latest->loss_percent=loss_rate;
305
				obj->latest->rtt=cur->rt_prop;
306 307

				obj->rtcpstatspoint=ms_list_insert_sorted(obj->rtcpstatspoint, obj->latest, (MSCompareFunc)sort_points);
308 309 310

				P(YELLOW "one more %d: %f %f\n", obj->curindex-1, obj->latest->bandwidth, obj->latest->loss_percent);
			}
311 312
			obj->cum_loss_prev=cum_loss;
			obj->last_seq=report_block_get_high_ext_seq(rb);
313 314 315

			if (ms_list_size(obj->rtcpstatspoint) > ESTIM_HISTORY){
				P(RED "Reached list maximum capacity (count=%d)", ms_list_size(obj->rtcpstatspoint));
316
				/*clean everything which occurred 60 sec or more ago*/
317
				time_t clear_time = ms_time(0) - 60;
318
				obj->rtcpstatspoint = ms_list_remove_custom(obj->rtcpstatspoint, (MSCompareFunc)earlier_than, &clear_time);
319 320
				P(RED "--> Cleaned list (count=%d)\n", ms_list_size(obj->rtcpstatspoint));
			}
321
		}
322 323 324 325
	}
	return rb!=NULL;
}

326 327 328 329
static float lerp(float inf, float sup, float v){
	return inf + (sup - inf) * v;
}

330
static void smooth_values(MSStatefulQosAnalyser *obj){
331
	//smooth values
332 333 334 335 336 337 338 339
	MSList *it = obj->rtcpstatspoint;
	double prev_loss;
	rtcpstatspoint_t *curr = (rtcpstatspoint_t *)it->data;
	prev_loss = curr->loss_percent;
	it = it->next;
	curr = (rtcpstatspoint_t *)it->data;
	/*float w = obj->rtcpstatspoint[i].bandwidth/obj->rtcpstatspoint[i+1].bandwidth;
	obj->rtcpstatspoint[i].loss_percent = (prev + obj->rtcpstatspoint[i+1].loss_percent*w)/(1+w);*/
340
	((rtcpstatspoint_t *)it->prev->data)->loss_percent = lerp(prev_loss, curr->loss_percent, .25);
341 342 343 344 345 346 347 348 349 350 351 352 353 354 355
	/*obj->rtcpstatspoint[i].loss_percent = MIN(prev, obj->rtcpstatspoint[i+1].loss_percent);*/
	/*obj->rtcpstatspoint[i].loss_percent = obj->rtcpstatspoint[i+1].loss_percent;*/
	/*float w1 = obj->rtcpstatspoint[i].bandwidth;
	float w2 = obj->rtcpstatspoint[i+1].bandwidth;
	obj->rtcpstatspoint[i].loss_percent = (w2*prev + w1*obj->rtcpstatspoint[i+1].loss_percent)/(w1+w2);*/
	while (it->next != NULL){
		curr = (rtcpstatspoint_t *)it->data;
		rtcpstatspoint_t *prev = ((rtcpstatspoint_t *)it->prev->data);
		rtcpstatspoint_t *next = ((rtcpstatspoint_t *)it->next->data);

		float v = (curr->bandwidth - prev->bandwidth) / (next->bandwidth - prev->bandwidth);
		float new_loss = lerp(prev_loss, next->loss_percent, v);
		prev_loss = curr->loss_percent;
		curr->loss_percent = (curr->loss_percent + new_loss) / 2.;
		it = it->next;
356
	}
357 358 359 360 361 362 363 364 365
	curr = (rtcpstatspoint_t *)it->data;
	/*w = obj->rtcpstatspoint[i-1].bandwidth/obj->rtcpstatspoint[i].bandwidth;
	obj->rtcpstatspoint[i].loss_percent = (obj->rtcpstatspoint[i].loss_percent + prev*w)/(1+w);*/
	curr->loss_percent = lerp(prev_loss, curr->loss_percent, .75);
	/*obj->rtcpstatspoint[i].loss_percent = MAX(prev, obj->rtcpstatspoint[i].loss_percent);*/
	/*obj->rtcpstatspoint[i].loss_percent = prev;*/
	/*w1 = obj->rtcpstatspoint[i-1].bandwidth;
	w2 = obj->rtcpstatspoint[i].bandwidth;
	obj->rtcpstatspoint[i].loss_percent = (w1*prev + w2*obj->rtcpstatspoint[i].loss_percent)/(w1+w2);*/
366
}
367

368
static float compute_available_bw(MSStatefulQosAnalyser *obj){
369
	MSList *it;
370
	double constant_network_loss = 0.;
371
	double mean_bw = 0.;
372 373 374 375
	MSList *current = obj->rtcpstatspoint;
	MSList *last = current;
	int size = ms_list_size(obj->rtcpstatspoint);
	if (current == NULL){
376
		P(RED "Not points available for computation.\n");
377 378 379 380 381
		return -1;
	}else if (size == 1){
		rtcpstatspoint_t *p = (rtcpstatspoint_t *)current->data;
		mean_bw = p->bandwidth * (1 - p->loss_percent);
		P(RED "One single point available for computation. Estimated BW is %f kbit/s\n", mean_bw);
382

383
		return mean_bw;
384 385
	}

386
	while (last->next) last = last->next;
387

388 389 390
	/*suppose that first point is a reliable estimation of the constant network loss rate*/
	if (size > 3){
		smooth_values(obj);
391
		constant_network_loss = ((rtcpstatspoint_t *)obj->rtcpstatspoint->next->data)->loss_percent;
392
	}else{
393
		constant_network_loss = ((rtcpstatspoint_t *)obj->rtcpstatspoint->data)->loss_percent;
394 395
	}

396

397
	P("\tconstant_network_loss=%f\n", constant_network_loss);
398 399
	for (it = obj->rtcpstatspoint; it != NULL; it=it->next){
		rtcpstatspoint_t * point = (rtcpstatspoint_t *)it->data;
400
		P(YELLOW "\t\tsorted values %d: %f %f\n",
401
			ms_list_position(obj->rtcpstatspoint, it), point->bandwidth, point->loss_percent);
402 403
	}

404
	while (current == obj->rtcpstatspoint || (current!=NULL && ((rtcpstatspoint_t*)current->data)->loss_percent<0.03+constant_network_loss)){
405
		P("\t%d is stable\n", ms_list_position(obj->rtcpstatspoint, current));
406

407 408 409 410 411
		for (it=last;it!=current;it=it->prev){
			if (((rtcpstatspoint_t *)it->data)->loss_percent <= 0.03 + ((rtcpstatspoint_t*)current->data)->loss_percent){
				P("\t%d is less than %d\n", ms_list_position(obj->rtcpstatspoint, it), ms_list_position(obj->rtcpstatspoint, current));
				current = it;
				break;
412 413 414
			}
		}

415
		current = current->next;
416 417
	}

418 419 420 421 422 423
	if (current == NULL){
		/*constant loss rate - bad network conditions but no congestion*/
		mean_bw = 2 * ((rtcpstatspoint_t*)last->data)->bandwidth;
	}else{
		/*there is some congestion*/
		mean_bw = .5*(((rtcpstatspoint_t*)current->prev->data)->bandwidth+((rtcpstatspoint_t*)current->data)->bandwidth);
424
	}
425

426 427 428
	P(RED "[0->%d] Last stable is %d(%f;%f)"
		, ms_list_position(obj->rtcpstatspoint, last)
		, ms_list_position(obj->rtcpstatspoint, (current ? current->prev : last))
429 430 431
		, ((rtcpstatspoint_t*) (current ? current->prev->data : last->data))->bandwidth
		, ((rtcpstatspoint_t*) (current ? current->prev->data : last->data))->loss_percent);
	if (current!=NULL){
432 433 434 435
		P(RED ", first unstable is %d(%f;%f)"
			, ms_list_position(obj->rtcpstatspoint, current)
			, ((rtcpstatspoint_t*) current->data)->bandwidth
			, ((rtcpstatspoint_t*) current->data)->loss_percent);
436
	}
437 438
	P(RED " --> estimated_available_bw=%f\n", mean_bw);

439
	obj->network_loss_rate = constant_network_loss;
440
	obj->congestion_bandwidth = mean_bw;
441
	obj->network_state =
442 443 444 445
		(current==NULL && constant_network_loss < .1) ?	MSQosAnalyserNetworkFine
		: (constant_network_loss > .1) ?				MSQosAnalyserNetworkLossy
		:												MSQosAnalyserNetworkCongested;

446
	return mean_bw;
447 448
}

449 450
static void stateful_analyser_suggest_action(MSQosAnalyser *objbase, MSRateControlAction *action){
	MSStatefulQosAnalyser *obj=(MSStatefulQosAnalyser*)objbase;
451
	rtpstats_t *cur=&obj->stats[obj->curindex % STATS_HISTORY];
452

453
	float curbw = obj->latest ? obj->latest->bandwidth : 0.f;
454 455
	float bw = /*0; if (FALSE)*/ compute_available_bw(obj);

456
	/*rtp_session_set_duplication_ratio(obj->session, 0);*/
457
	/*try a burst every 50 seconds (10 RTCP packets)*/
458
	if (obj->curindex > 10){
459
		P(YELLOW "try burst!\n");
460 461
		/*bw *= 3;*/
		rtp_session_set_duplication_ratio(obj->session, 2);
462
	}
463
	/*test a min burst to avoid overestimation of available bandwidth*/
464
	else if (obj->curindex % 10 == 5 || obj->curindex % 10 == 6){
465
		P(YELLOW "try minimal burst!\n");
466
		bw *= .33;
467 468
	}

469 470 471
	/*not bandwidth estimation computed*/
	if (bw <= 0){
		action->type=MSRateControlActionDoNothing;
472
		action->value=0;
473
	}else if (bw > curbw){
474 475 476 477
		action->type=MSRateControlActionIncreaseQuality;
		action->value=MAX(0, 100.* (bw - curbw) / curbw);
	}else{
		action->type=MSRateControlActionDecreaseBitrate;
478
		action->value=MAX(10,(100. - bw * 100. / curbw));
479
	}
480

481
	P(YELLOW "%s of value %d\n", ms_rate_control_action_type_name(action->type), action->value);
482 483
	return;

484
	if (obj->network_state == MSQosAnalyserNetworkCongested){
485 486 487
		action->type=MSRateControlActionDecreaseBitrate;
		action->value=MAX(10,3*(100. - bw * 100. / curbw));
		ms_message("MSQosAnalyser: congested network - decrease %%%d", action->value);
488 489
	} else if (obj->network_state == MSQosAnalyserNetworkLossy){
	/*if (curbw > bw){
490 491 492 493 494 495 496 497 498 499
			action->type=MSRateControlActionDecreaseBitrate;
			action->value=MAX(0,3*(100. - bw * 100. / curbw));
			ms_message("MSQosAnalyser: lossy network - decrease quality %%%d", action->value);
		}else{*/
			action->type=MSRateControlActionIncreaseQuality;
			action->value=MAX(0,curbw * 100. / bw);
			/*action->value=50;*/
			ms_message("MSQosAnalyser: lossy network - increase quality %%%d", action->value);
		/*}*/
	}
500

501
	/*big losses and big jitter */
502
	if (cur->lost_percentage>=unacceptable_loss_rate){
503
		action->type=MSRateControlActionDecreaseBitrate;
504 505 506
		action->value=cur->lost_percentage ;//MIN(cur->lost_percentage,50);
		ms_message("MSQosAnalyser: loss rate unacceptable and big jitter");
	}else if (stateful_rt_prop_increased(obj)){
507 508 509 510 511 512 513 514 515
		action->type=MSRateControlActionDecreaseBitrate;
		action->value=20;
		ms_message("MSQosAnalyser: rt_prop doubled.");
	}else{
		action->type=MSRateControlActionDoNothing;
		ms_message("MSQosAnalyser: everything is fine.");
	}
}

516 517
static bool_t stateful_analyser_has_improved(MSQosAnalyser *objbase){
	MSStatefulQosAnalyser *obj=(MSStatefulQosAnalyser*)objbase;
518 519 520 521 522 523 524 525 526 527
	rtpstats_t *cur=&obj->stats[obj->curindex % STATS_HISTORY];
	rtpstats_t *prev=&obj->stats[(STATS_HISTORY+obj->curindex-1) % STATS_HISTORY];

	if (prev->lost_percentage>=unacceptable_loss_rate){
		if (cur->lost_percentage<prev->lost_percentage){
			ms_message("MSQosAnalyser: lost percentage has improved");
			return TRUE;
		}else goto end;
	}
	if (obj->rt_prop_doubled && cur->rt_prop<prev->rt_prop){
528
		ms_message("MSQosAnalyser: rt prop decreased");
529 530 531 532
		obj->rt_prop_doubled=FALSE;
		return TRUE;
	}

533
	end:
534 535 536 537
	ms_message("MSQosAnalyser: no improvements.");
	return FALSE;
}

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
static void stateful_analyser_update(MSQosAnalyser *objbase){
	MSStatefulQosAnalyser *obj=(MSStatefulQosAnalyser*)objbase;

	static time_t last_measure;

	if (last_measure != ms_time(0)){
		obj->interval_count++;
		obj->upload_bandwidth_sum+=rtp_session_get_send_bandwidth(obj->session)/1000.0;
	}else{
		/*P(RED "already measured bw this sec\n");*/
	}
	last_measure = ms_time(0);

	switch (obj->burst_state){
	case MSStatefulQosAnalyserBurstEnable:{
		obj->burst_state=MSStatefulQosAnalyserBurstInProgress;
		obj->start_seq_number=obj->last_seq_number=obj->session->rtp.snd_seq;
		ortp_gettimeofday(&obj->start_time, NULL);
		rtp_session_set_duplication_ratio(obj->session, 2);
	}
	case MSStatefulQosAnalyserBurstInProgress:{
		struct timeval now;
		double elapsed;
		obj->last_seq_number=obj->session->rtp.snd_seq;

		ortp_gettimeofday(&now,NULL);
		elapsed=((now.tv_sec-obj->start_time.tv_sec)*1000.0) +  ((now.tv_usec-obj->start_time.tv_usec)/1000.0);

		/*burst should last 1sec*/
		if (elapsed > 1.){
			obj->burst_state=MSStatefulQosAnalyserBurstDisable;
			rtp_session_set_duplication_ratio(obj->session, 0);
		}
	}
	case MSStatefulQosAnalyserBurstDisable:{
	}
	}
}
576

577 578 579
static MSQosAnalyserDesc stateful_analyser_desc={
	stateful_analyser_process_rtcp,
	stateful_analyser_suggest_action,
580
	stateful_analyser_has_improved,
581
	stateful_analyser_update
582 583
};

584 585
MSQosAnalyser * ms_stateful_qos_analyser_new(RtpSession *session){
	MSStatefulQosAnalyser *obj=ms_new0(MSStatefulQosAnalyser,1);
586
	obj->session=session;
587
	obj->parent.desc=&stateful_analyser_desc;
588
	obj->parent.type=Stateful;
589
	return (MSQosAnalyser*)obj;
590 591
}

592