rtpsession.c 83.6 KB
Newer Older
aymeric's avatar
aymeric committed
1
/*
2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
 * The oRTP library is an RTP (Realtime Transport Protocol - rfc3550) implementation with additional features.
 * Copyright (C) 2017 Belledonne Communications SARL
 *
 *  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.
 */
aymeric's avatar
aymeric committed
19 20


21
#ifdef HAVE_CONFIG_H
aymeric's avatar
aymeric committed
22 23 24 25 26 27 28 29 30 31
#include "ortp-config.h"
#endif

#include "ortp/ortp.h"
#include "ortp/telephonyevents.h"
#include "ortp/rtcp.h"
#include "jitterctl.h"
#include "scheduler.h"
#include "utils.h"
#include "rtpsession_priv.h"
32
#include "congestiondetector.h"
33
#include "videobandwidthestimator.h"
aymeric's avatar
aymeric committed
34

35 36 37
#if (_WIN32_WINNT >= 0x0600)
#include <delayimp.h>
#undef ExternC /* avoid redefinition... */
38
#ifdef ORTP_WINDOWS_DESKTOP
39
#include <QOS2.h>
40
#include <VersionHelpers.h>
41
#endif
Ghislain MARY's avatar
Ghislain MARY committed
42
#endif
43

44
/**
45 46
 * #_RtpTransport object which can handle multiples security protocols. You can for instance use this object
 * to use both sRTP and tunnel transporter. mblk_t messages received and sent from the endpoint
47 48
 * will pass through the list of modifiers given. First modifier in list will be first to modify the message
 * in send mode and last in receive mode.
49 50 51
 * @param[in] endpoint #_RtpTransport object in charge of sending/receiving packets. If NULL, it will use standards sendto and recvfrom functions.
 * @param[in] modifiers_count number of #_RtpTransport object given in the variadic list. Must be 0 if none are given.
 * @returns #_RtpTransport object that will be generated or NULL.
52
**/
53 54 55
RtpTransport* meta_rtp_transport_new(RtpTransport *endpoint, unsigned modifiers_count, ...);
RtpTransport* meta_rtcp_transport_new(RtpTransport *endpoint, unsigned modifiers_count, ...);
void meta_rtp_transport_link(RtpTransport *rtp, RtpTransport *rtcp);
aymeric's avatar
aymeric committed
56 57 58 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

/* this function initialize all session parameter's that depend on the payload type */
static void payload_type_changed(RtpSession *session, PayloadType *pt){
	jitter_control_set_payload(&session->rtp.jittctl,pt);
	rtp_session_set_time_jump_limit(session,session->rtp.time_jump);
	if (pt->type==PAYLOAD_VIDEO){
		session->permissive=TRUE;
		ortp_message("Using permissive algorithm");
	}
	else session->permissive=FALSE;
}

void wait_point_init(WaitPoint *wp){
	ortp_mutex_init(&wp->lock,NULL);
	ortp_cond_init(&wp->cond,NULL);
	wp->time=0;
	wp->wakeup=FALSE;
}
void wait_point_uninit(WaitPoint *wp){
	ortp_cond_destroy(&wp->cond);
	ortp_mutex_destroy(&wp->lock);
}

#define wait_point_lock(wp) ortp_mutex_lock(&(wp)->lock)
#define wait_point_unlock(wp) ortp_mutex_unlock(&(wp)->lock)

void wait_point_wakeup_at(WaitPoint *wp, uint32_t t, bool_t dosleep){
	wp->time=t;
	wp->wakeup=TRUE;
	if (dosleep) ortp_cond_wait(&wp->cond,&wp->lock);
}


bool_t wait_point_check(WaitPoint *wp, uint32_t t){
	bool_t ok=FALSE;
91

aymeric's avatar
aymeric committed
92 93 94 95
	if (wp->wakeup){
		if (TIME_IS_NEWER_THAN(t,wp->time)){
			wp->wakeup=FALSE;
			ok=TRUE;
96

aymeric's avatar
aymeric committed
97 98 99 100 101 102 103 104 105 106
		}
	}
	return ok;
}
#define wait_point_wakeup(wp) ortp_cond_signal(&(wp)->cond);

extern void rtp_parse(RtpSession *session, mblk_t *mp, uint32_t local_str_ts,
		struct sockaddr *addr, socklen_t addrlen);


107
static uint32_t uint32_t_random(void){
108
	return ortp_random();
aymeric's avatar
aymeric committed
109 110 111
}


112 113 114
/* put an rtp packet in queue. It is called by rtp_parse()
   A return value of -1 means the packet was a duplicate, 0 means the packet was ok */
int rtp_putq(queue_t *q, mblk_t *mp)
aymeric's avatar
aymeric committed
115 116 117 118 119 120
{
	mblk_t *tmp;
	rtp_header_t *rtp=(rtp_header_t*)mp->b_rptr,*tmprtp;
	/* insert message block by increasing time stamp order : the last (at the bottom)
		message of the queue is the newest*/
	ortp_debug("rtp_putq(): Enqueuing packet with ts=%i and seq=%i",rtp->timestamp,rtp->seq_number);
121

aymeric's avatar
aymeric committed
122 123
	if (qempty(q)) {
		putq(q,mp);
124
		return 0;
aymeric's avatar
aymeric committed
125 126 127 128 129 130 131 132
	}
	tmp=qlast(q);
	/* we look at the queue from bottom to top, because enqueued packets have a better chance
	to be enqueued at the bottom, since there are surely newer */
	while (!qend(q,tmp))
	{
		tmprtp=(rtp_header_t*)tmp->b_rptr;
		ortp_debug("rtp_putq(): Seeing packet with seq=%i",tmprtp->seq_number);
133

134 135 136 137 138 139
		if (rtp->seq_number == tmprtp->seq_number)
		{
			/* this is a duplicated packet. Don't queue it */
			ortp_debug("rtp_putq: duplicated message.");
			freemsg(mp);
			return -1;
140
		}else if (RTP_SEQ_IS_STRICTLY_GREATER_THAN(rtp->seq_number,tmprtp->seq_number)){
141

aymeric's avatar
aymeric committed
142
			insq(q,tmp->b_next,mp);
143 144
			return 0;
		}
aymeric's avatar
aymeric committed
145 146
		tmp=tmp->b_prev;
	}
147
	/* this packet is the oldest, it has to be
aymeric's avatar
aymeric committed
148 149
	placed on top of the queue */
	insq(q,qfirst(q),mp);
150
	return 0;
aymeric's avatar
aymeric committed
151 152 153 154 155 156 157 158
}


mblk_t *rtp_getq(queue_t *q,uint32_t timestamp, int *rejected)
{
	mblk_t *tmp,*ret=NULL,*old=NULL;
	rtp_header_t *tmprtp;
	uint32_t ts_found=0;
159

aymeric's avatar
aymeric committed
160 161 162 163 164 165 166 167 168 169 170 171 172
	*rejected=0;
	ortp_debug("rtp_getq(): Timestamp %i wanted.",timestamp);
	if (qempty(q))
	{
		/*ortp_debug("rtp_getq: q is empty.");*/
		return NULL;
	}
	/* return the packet with ts just equal or older than the asked timestamp */
	/* packets with older timestamps are discarded */
	while ((tmp=qfirst(q))!=NULL)
	{
		tmprtp=(rtp_header_t*)tmp->b_rptr;
		ortp_debug("rtp_getq: Seeing packet with ts=%i",tmprtp->timestamp);
173

aymeric's avatar
aymeric committed
174 175 176 177 178 179 180
		if ( RTP_TIMESTAMP_IS_NEWER_THAN(timestamp,tmprtp->timestamp) )
		{
			if (ret!=NULL && tmprtp->timestamp==ts_found) {
				/* we've found two packets with same timestamp. return the first one */
				break;
			}
			if (old!=NULL) {
181
				ortp_debug("rtp_getq: discarding too old packet with ts=%u",ts_found);
aymeric's avatar
aymeric committed
182 183 184 185 186
				(*rejected)++;
				freemsg(old);
			}
			ret=getq(q); /* dequeue the packet, since it has an interesting timestamp*/
			ts_found=tmprtp->timestamp;
187
			ortp_debug("rtp_getq: Found packet with ts=%u",tmprtp->timestamp);
188

aymeric's avatar
aymeric committed
189 190 191 192 193 194 195 196 197 198 199 200 201 202
			old=ret;
		}
		else
		{
			break;
		}
	}
	return ret;
}

mblk_t *rtp_getq_permissive(queue_t *q,uint32_t timestamp, int *rejected)
{
	mblk_t *tmp,*ret=NULL;
	rtp_header_t *tmprtp;
203

aymeric's avatar
aymeric committed
204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228
	*rejected=0;
	ortp_debug("rtp_getq_permissive(): Timestamp %i wanted.",timestamp);

	if (qempty(q))
	{
		/*ortp_debug("rtp_getq: q is empty.");*/
		return NULL;
	}
	/* return the packet with the older timestamp (provided that it is older than
	the asked timestamp) */
	tmp=qfirst(q);
	tmprtp=(rtp_header_t*)tmp->b_rptr;
	ortp_debug("rtp_getq_permissive: Seeing packet with ts=%i",tmprtp->timestamp);
	if ( RTP_TIMESTAMP_IS_NEWER_THAN(timestamp,tmprtp->timestamp) )
	{
		ret=getq(q); /* dequeue the packet, since it has an interesting timestamp*/
		ortp_debug("rtp_getq_permissive: Found packet with ts=%i",tmprtp->timestamp);
	}
	return ret;
}


void
rtp_session_init (RtpSession * session, int mode)
{
229
	JBParameters jbp;
230
	if (session == NULL)
231
	{
232 233
		ortp_debug("rtp_session_init: Invalid paramter (session=NULL)");
		return;
234
	}
aymeric's avatar
aymeric committed
235 236 237 238 239 240
	memset (session, 0, sizeof (RtpSession));
	session->mode = (RtpSessionMode) mode;
	if ((mode == RTP_SESSION_RECVONLY) || (mode == RTP_SESSION_SENDRECV))
	{
		rtp_session_set_flag (session, RTP_SESSION_RECV_SYNC);
		rtp_session_set_flag (session, RTP_SESSION_RECV_NOT_STARTED);
241

aymeric's avatar
aymeric committed
242 243 244 245 246 247 248
	}
	if ((mode == RTP_SESSION_SENDONLY) || (mode == RTP_SESSION_SENDRECV))
	{
		rtp_session_set_flag (session, RTP_SESSION_SEND_NOT_STARTED);
		session->snd.ssrc=uint32_t_random();
		/* set default source description */
		rtp_session_set_source_description(session,"unknown@unknown",NULL,NULL,
249
				NULL,NULL,"oRTP-" ORTP_VERSION,NULL);
aymeric's avatar
aymeric committed
250 251
	}
	rtp_session_set_profile (session, &av_profile); /*the default profile to work with */
252 253
	session->rtp.gs.socket=-1;
	session->rtcp.gs.socket=-1;
254
#ifndef _WIN32
aymeric's avatar
aymeric committed
255 256 257 258 259
	session->rtp.snd_socket_size=0;	/*use OS default value unless on windows where they are definitely too short*/
	session->rtp.rcv_socket_size=0;
#else
	session->rtp.snd_socket_size=session->rtp.rcv_socket_size=65536;
#endif
260
	session->rtp.ssrc_changed_thres=50;
aymeric's avatar
aymeric committed
261 262 263 264 265 266 267
	session->dscp=RTP_DEFAULT_DSCP;
	session->multicast_ttl=RTP_DEFAULT_MULTICAST_TTL;
	session->multicast_loopback=RTP_DEFAULT_MULTICAST_LOOPBACK;
	qinit(&session->rtp.rq);
	qinit(&session->rtp.tev_rq);
	qinit(&session->contributing_sources);
	session->eventqs=NULL;
268 269

	/* Initialize RTCP send algorithm */
270
	session->target_upload_bandwidth = 80000; /* 80kbits/s to have 4kbits/s dedicated to RTCP if rtp_session_set_target_upload_bandwidth() is not called. */
271
	session->rtcp.send_algo.initial = TRUE;
272
	session->rtcp.send_algo.allow_early = TRUE;
273

aymeric's avatar
aymeric committed
274 275 276 277 278 279 280 281 282 283 284 285 286 287
	/* init signal tables */
	rtp_signal_table_init (&session->on_ssrc_changed, session,"ssrc_changed");
	rtp_signal_table_init (&session->on_payload_type_changed, session,"payload_type_changed");
	rtp_signal_table_init (&session->on_telephone_event, session,"telephone-event");
	rtp_signal_table_init (&session->on_telephone_event_packet, session,"telephone-event_packet");
	rtp_signal_table_init (&session->on_timestamp_jump,session,"timestamp_jump");
	rtp_signal_table_init (&session->on_network_error,session,"network_error");
	rtp_signal_table_init (&session->on_rtcp_bye,session,"rtcp_bye");
	wait_point_init(&session->snd.wp);
	wait_point_init(&session->rcv.wp);
	/*defaults send payload type to 0 (pcmu)*/
	rtp_session_set_send_payload_type(session,0);
	/*sets supposed recv payload type to undefined */
	rtp_session_set_recv_payload_type(session,-1);
288

aymeric's avatar
aymeric committed
289
	rtp_session_enable_jitter_buffer(session,TRUE);
290
	jb_parameters_init(&jbp);
aymeric's avatar
aymeric committed
291 292 293
	rtp_session_set_jitter_buffer_params(session,&jbp);
	rtp_session_set_time_jump_limit(session,5000);
	rtp_session_enable_rtcp(session,TRUE);
294
	rtp_session_set_rtcp_report_interval(session,RTCP_DEFAULT_REPORT_INTERVAL);
aymeric's avatar
aymeric committed
295 296 297
	session->recv_buf_size = UDP_MAX_SIZE;
	session->symmetric_rtp = FALSE;
	session->permissive=FALSE;
298
	session->reuseaddr=TRUE;
299 300
	msgb_allocator_init(&session->rtp.gs.allocator);
	msgb_allocator_init(&session->rtcp.gs.allocator);
301
	/*set default rtptransport*/
302

303 304 305 306 307 308
	{
		RtpTransport *rtp_tr = meta_rtp_transport_new(NULL, 0);
		RtpTransport *rtcp_tr = meta_rtcp_transport_new(NULL, 0);
		meta_rtp_transport_link(rtp_tr, rtcp_tr);
		rtp_session_set_transports(session, rtp_tr, rtcp_tr);
	}
309
	session->tev_send_pt = -1; /*check in rtp profile when needed*/
310
	
Ghislain MARY's avatar
Ghislain MARY committed
311 312
	ortp_bw_estimator_init(&session->rtp.gs.recv_bw_estimator, 0.95f, 0.01f);
	ortp_bw_estimator_init(&session->rtcp.gs.recv_bw_estimator, 0.95f, 0.01f);
313 314 315 316 317 318
	
#if defined(_WIN32) || defined(_WIN32_WCE)
	session->rtp.is_win_thread_running = FALSE;
	qinit(&session->rtp.winrq);
	ortp_mutex_init(&session->rtp.winrq_lock);
#endif
aymeric's avatar
aymeric committed
319 320
}

321 322
void rtp_session_enable_congestion_detection(RtpSession *session, bool_t enabled){
	if (enabled){
Simon Morlat's avatar
Simon Morlat committed
323 324 325 326
		if (session->rtp.jittctl.params.buffer_algorithm != OrtpJitterBufferRecursiveLeastSquare){
			ortp_error("rtp_session_enable_congestion_detection(): cannot use congestion control without RLS jitter buffer algorithm");
			return;
		}
327 328
		if (!session->rtp.congdetect){
			session->rtp.congdetect = ortp_congestion_detector_new(session);
329 330
		}else{
			if (!session->congestion_detector_enabled) ortp_congestion_detector_reset(session->rtp.congdetect); 
331 332
		}
	}
333
	session->congestion_detector_enabled = enabled;
334 335
}

336 337 338
void rtp_session_enable_video_bandwidth_estimator(RtpSession *session, const OrtpVideoBandwidthEstimatorParams *params) {
	if (params->enabled) {
		if (!session->rtp.video_bw_estimator) {
339 340
			session->rtp.video_bw_estimator = ortp_video_bandwidth_estimator_new(session);
		}
341 342 343 344
		if (params->packet_count_min > 0) session->rtp.video_bw_estimator->packet_count_min = params->packet_count_min;
		if (params->packets_size_max > 0) session->rtp.video_bw_estimator->packets_size_max = params->packets_size_max;
		if (params->trust_percentage > 0) session->rtp.video_bw_estimator->trust_percentage = params->trust_percentage;
		if (!session->video_bandwidth_estimator_enabled) ortp_video_bandwidth_estimator_reset(session->rtp.video_bw_estimator);
345
	}
346
	session->video_bandwidth_estimator_enabled = params->enabled;
347 348
}

349 350 351 352 353 354 355 356 357 358 359 360 361 362
void jb_parameters_init(JBParameters *jbp) {
	/* configure jitter buffer with working default parameters */
	jbp->min_size=RTP_DEFAULT_JITTER_TIME;
	jbp->nom_size=RTP_DEFAULT_JITTER_TIME;
	jbp->max_size=500;
	jbp->max_packets= 200;/* maximum number of packet allowed to be queued */
	jbp->adaptive=TRUE;
	jbp->enabled=TRUE;
	jbp->buffer_algorithm = OrtpJitterBufferRecursiveLeastSquare;
	jbp->refresh_ms=5000;
	jbp->ramp_threshold=70;
	jbp->ramp_step_ms=20;
	jbp->ramp_refresh_ms=5000;
}
aymeric's avatar
aymeric committed
363 364 365 366

/**
 * Creates a new rtp session.
 * If the session is able to send data (RTP_SESSION_SENDONLY or
367
 * RTP_SESSION_SENDRECV), then a random SSRC number is choosed for
aymeric's avatar
aymeric committed
368
 * the outgoing stream.
369
 * @param mode One of the RtpSessionMode flags.
aymeric's avatar
aymeric committed
370 371 372 373 374 375 376 377
 *
 * @return the newly created rtp session.
**/
RtpSession *
rtp_session_new (int mode)
{
	RtpSession *session;
	session = (RtpSession *) ortp_malloc (sizeof (RtpSession));
378 379
	if (session == NULL)
	{
380 381
		ortp_error("rtp_session_new: Memory allocation failed");
		return NULL;
382
	}
383
	rtp_session_init (session, mode);
aymeric's avatar
aymeric committed
384 385 386 387
	return session;
}

/**
388
 * Sets the scheduling mode of the rtp session. If \a yesno is TRUE, the rtp session is in
aymeric's avatar
aymeric committed
389 390 391 392
 *	the scheduled mode, that means that you can use session_set_select() to block until it's time
 *	to receive or send on this session according to the timestamp passed to the respective functions.
 *  You can also use blocking mode (see rtp_session_set_blocking_mode() ), to simply block within
 *	the receive and send functions.
393
 *	If \a yesno is FALSE, the ortp scheduler will not manage those sessions, meaning that blocking mode
aymeric's avatar
aymeric committed
394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424
 *  and the use of session_set_select() for this session are disabled.
 *@param session a rtp session.
 *@param yesno 	a boolean to indicate the scheduling mode.
 *
 *
**/
void
rtp_session_set_scheduling_mode (RtpSession * session, int yesno)
{
	if (yesno)
	{
		RtpScheduler *sched;
		sched = ortp_get_scheduler ();
		if (sched != NULL)
		{
			rtp_session_set_flag (session, RTP_SESSION_SCHEDULED);
			session->sched = sched;
			rtp_scheduler_add_session (sched, session);
		}
		else
			ortp_warning
				("rtp_session_set_scheduling_mode: Cannot use scheduled mode because the "
				 "scheduler is not started. Use ortp_scheduler_init() before.");
	}
	else
		rtp_session_unset_flag (session, RTP_SESSION_SCHEDULED);
}


/**
 *	This function implicitely enables the scheduling mode if yesno is TRUE.
425
 *	rtp_session_set_blocking_mode() defines the behaviour of the rtp_session_recv_with_ts() and
426
 *	rtp_session_send_with_ts() functions. If \a yesno is TRUE, rtp_session_recv_with_ts()
aymeric's avatar
aymeric committed
427 428 429
 *	will block until it is time for the packet to be received, according to the timestamp
 *	passed to the function. After this time, the function returns.
 *	For rtp_session_send_with_ts(), it will block until it is time for the packet to be sent.
430
 *	If \a yesno is FALSE, then the two functions will return immediately.
aymeric's avatar
aymeric committed
431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464
 *
 *  @param session a rtp session
 *  @param yesno a boolean
**/
void
rtp_session_set_blocking_mode (RtpSession * session, int yesno)
{
	if (yesno){
		rtp_session_set_scheduling_mode(session,TRUE);
		rtp_session_set_flag (session, RTP_SESSION_BLOCKING_MODE);
	}else
		rtp_session_unset_flag (session, RTP_SESSION_BLOCKING_MODE);
}

/**
 *	Set the RTP profile to be used for the session. By default, all session are created by
 *	rtp_session_new() are initialized with the AV profile, as defined in RFC 3551. The application
 *	can set any other profile instead using that function.
 *
 * @param session a rtp session
 * @param profile a rtp profile
**/

void
rtp_session_set_profile (RtpSession * session, RtpProfile * profile)
{
	session->snd.profile = profile;
	session->rcv.profile = profile;
	rtp_session_telephone_events_supported(session);
}

/**
 *	By default oRTP automatically sends RTCP SR or RR packets. If
 *	yesno is set to FALSE, the RTCP sending of packet is disabled.
465
 *	This functionality might be needed for some equipments that do not
aymeric's avatar
aymeric committed
466
 *	support RTCP, leading to a traffic of ICMP errors on the network.
467
 *	It can also be used to save bandwidth despite the RTCP bandwidth is
aymeric's avatar
aymeric committed
468 469 470 471 472 473
 *	actually and usually very very low.
**/
void rtp_session_enable_rtcp(RtpSession *session, bool_t yesno){
	session->rtcp.enabled=yesno;
}

474 475 476 477
bool_t rtp_session_rtcp_enabled(const RtpSession *session) {
	return  session->rtcp.enabled;
}

478 479 480 481
/**
 * Sets the default interval in milliseconds for RTCP reports emitted by the session
 *
**/
482
void rtp_session_set_rtcp_report_interval(RtpSession *session, int value_ms) {
483 484
	if (value_ms <= 0) session->rtcp.send_algo.T_rr_interval = 0;
	else session->rtcp.send_algo.T_rr_interval = (uint32_t)value_ms;
485 486
}

487 488 489
void rtp_session_set_target_upload_bandwidth(RtpSession *session, int target_bandwidth) {
	session->target_upload_bandwidth = target_bandwidth;
}
490 491 492
int rtp_session_get_target_upload_bandwidth(RtpSession *session) {
	return session->target_upload_bandwidth;
}
493

aymeric's avatar
aymeric committed
494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559
/**
 *	Set the RTP profile to be used for the sending by this session. By default, all session are created by
 *	rtp_session_new() are initialized with the AV profile, as defined in RFC 3551. The application
 *	can set any other profile instead using that function.
 * @param session a rtp session
 * @param profile a rtp profile
 *
**/

void
rtp_session_set_send_profile (RtpSession * session, RtpProfile * profile)
{
	session->snd.profile = profile;
	rtp_session_send_telephone_events_supported(session);
}



/**
 *	Set the RTP profile to be used for the receiveing by this session. By default, all session are created by
 *	rtp_session_new() are initialized with the AV profile, as defined in RFC 3551. The application
 *	can set any other profile instead using that function.
 *
 * @param session a rtp session
 * @param profile a rtp profile
**/

void
rtp_session_set_recv_profile (RtpSession * session, RtpProfile * profile)
{
	session->rcv.profile = profile;
	rtp_session_recv_telephone_events_supported(session);
}

/**
 *@param session a rtp session
 *
 *	DEPRECATED! Returns current send profile.
 *	Use rtp_session_get_send_profile() or rtp_session_get_recv_profile()
 *
**/
RtpProfile *rtp_session_get_profile(RtpSession *session){
	return session->snd.profile;
}


/**
 *@param session a rtp session
 *
 *	Returns current send profile.
 *
**/
RtpProfile *rtp_session_get_send_profile(RtpSession *session){
	return session->snd.profile;
}

/**
 *@param session a rtp session
 *
 *	Returns current receive profile.
 *
**/
RtpProfile *rtp_session_get_recv_profile(RtpSession *session){
	return session->rcv.profile;
}

Simon Morlat's avatar
Simon Morlat committed
560
void rtp_session_set_send_ts_offset(RtpSession *s, uint32_t offset){
561 562 563 564 565 566 567
	s->send_ts_offset = offset;
}

uint32_t rtp_session_get_send_ts_offset(RtpSession *s){
	return s->send_ts_offset;
}

aymeric's avatar
aymeric committed
568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585
/**
 *	The default value is UDP_MAX_SIZE bytes, a value which is working for mostly everyone.
 *	However if your application can make assumption on the sizes of received packet,
 *	it can be interesting to set it to a lower value in order to save memory.
 *
 * @param session a rtp session
 * @param bufsize max size in bytes for receiving packets
**/
void rtp_session_set_recv_buf_size(RtpSession *session, int bufsize){
	session->recv_buf_size=bufsize;
}

/**
 *	Set kernel send maximum buffer size for the rtp socket.
 *	A value of zero defaults to the operating system default.
**/
void rtp_session_set_rtp_socket_send_buffer_size(RtpSession * session, unsigned int size){
	session->rtp.snd_socket_size=size;
586
	_rtp_session_apply_socket_sizes(session);
aymeric's avatar
aymeric committed
587 588 589 590 591 592 593 594
}

/**
 *	Set kernel recv maximum buffer size for the rtp socket.
 *	A value of zero defaults to the operating system default.
**/
void rtp_session_set_rtp_socket_recv_buffer_size(RtpSession * session, unsigned int size){
	session->rtp.rcv_socket_size=size;
595
	_rtp_session_apply_socket_sizes(session);
aymeric's avatar
aymeric committed
596 597 598 599
}

/**
 *	This function provides the way for an application to be informed of various events that
600
 *	may occur during a rtp session. \a signal_name is a string identifying the event, and \a cb is
aymeric's avatar
aymeric committed
601
 *	a user supplied function in charge of processing it. The application can register
602
 *	several callbacks for the same signal, in the limit of \a RTP_CALLBACK_TABLE_MAX_ENTRIES.
aymeric's avatar
aymeric committed
603 604
 *	Here are name and meaning of supported signals types:
 *
605
 *	"ssrc_changed": the SSRC of the incoming stream has changed.
aymeric's avatar
aymeric committed
606
 *
607
 *	"payload_type_changed": the payload type of the incoming stream has changed.
aymeric's avatar
aymeric committed
608
 *
609
 *	"telephone-event_packet": a telephone-event rtp packet (RFC2833) is received.
aymeric's avatar
aymeric committed
610
 *
611
 *	"telephone-event": a telephone event has occurred. This is a high-level shortcut for "telephone-event_packet".
aymeric's avatar
aymeric committed
612
 *
613
 *	"network_error": a network error happened on a socket. Arguments of the callback functions are
aymeric's avatar
aymeric committed
614 615
 *						a const char * explaining the error, an int errno error code and the user_data as usual.
 *
616
 *	"timestamp_jump": we have received a packet with timestamp in far future compared to last timestamp received.
aymeric's avatar
aymeric committed
617 618 619 620
 *						The farness of far future is set by rtp_sesssion_set_time_jump_limit()
 *  "rtcp_bye": we have received a RTCP bye packet. Arguments of the callback
 *              functions are a const char * containing the leaving reason and
 *              the user_data.
621 622
 *	"congestion_state_changed": congestion detector object changed its internal state. Arguments of
 *								the callback function are previous and new states.
aymeric's avatar
aymeric committed
623 624 625 626 627 628 629 630 631 632 633
 *	Returns: 0 on success, -EOPNOTSUPP if the signal does not exists, -1 if no more callbacks
 *	can be assigned to the signal type.
 *
 * @param session 	a rtp session
 * @param signal_name	the name of a signal
 * @param cb		a RtpCallback
 * @param user_data	a pointer to any data to be passed when invoking the callback.
 *
**/
int
rtp_session_signal_connect (RtpSession * session, const char *signal_name,
634
				RtpCallback cb, void *user_data)
aymeric's avatar
aymeric committed
635
{
636
	bctbx_list_t *elem;
aymeric's avatar
aymeric committed
637 638 639 640 641 642
	for (elem=session->signal_tables;elem!=NULL;elem=o_list_next(elem)){
		RtpSignalTable *s=(RtpSignalTable*) elem->data;
		if (strcmp(signal_name,s->signal_name)==0){
			return rtp_signal_table_add(s,cb,user_data);
		}
	}
643
	ortp_warning ("rtp_session_signal_connect: inexistent signal %s",signal_name);
aymeric's avatar
aymeric committed
644 645 646 647 648
	return -1;
}


/**
649
 *	Removes callback function \a cb to the list of callbacks for signal \a signal.
aymeric's avatar
aymeric committed
650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672
 *
 * @param session a rtp session
 * @param signal_name	a signal name
 * @param cb	a callback function.
 * @return: 0 on success, a negative value if the callback was not found.
**/
int
rtp_session_signal_disconnect_by_callback (RtpSession * session, const char *signal_name,
					   RtpCallback cb)
{
	OList *elem;
	for (elem=session->signal_tables;elem!=NULL;elem=o_list_next(elem)){
		RtpSignalTable *s=(RtpSignalTable*) elem->data;
		if (strcmp(signal_name,s->signal_name)==0){
			return rtp_signal_table_remove_by_callback(s,cb);
		}
	}
	ortp_warning ("rtp_session_signal_connect: inexistant signal %s",signal_name);
	return -1;
}


/**
673
 * Set the initial sequence number for outgoing stream..
aymeric's avatar
aymeric committed
674
 * @param session		a rtp session freshly created.
675
 * @param seq			a 16 bit unsigned number.
aymeric's avatar
aymeric committed
676 677 678 679 680 681
 *
**/
void rtp_session_set_seq_number(RtpSession *session, uint16_t seq){
	session->rtp.snd_seq=seq;
}

682 683 684 685
void rtp_session_set_duplication_ratio(RtpSession *session, float ratio){
	session->duplication_ratio=ratio;
}

aymeric's avatar
aymeric committed
686

687

688 689 690
/**
 * Get the current sequence number for outgoing stream.
**/
aymeric's avatar
aymeric committed
691 692 693 694
uint16_t rtp_session_get_seq_number(RtpSession *session){
	return session->rtp.snd_seq;
}

695 696 697 698 699 700 701
/**
 * Returns the highest extended sequence number received.
**/
uint32_t rtp_session_get_rcv_ext_seq_number(RtpSession *session){
	return session->rtp.hwrcv_extseq;
}

702 703 704 705 706 707
/**
 * Returns the latest cumulative loss value computed
 **/
int rtp_session_get_cum_loss(RtpSession *session){
	return session->cum_loss;
}
aymeric's avatar
aymeric committed
708 709 710 711 712 713 714 715 716 717 718 719 720 721

/**
 *	Sets the SSRC for the outgoing stream.
 *  If not done, a random ssrc is used.
 *
 * @param session a rtp session.
 * @param ssrc an unsigned 32bit integer representing the synchronisation source identifier (SSRC).
**/
void
rtp_session_set_ssrc (RtpSession * session, uint32_t ssrc)
{
	session->snd.ssrc = ssrc;
}

722 723 724 725 726
/**
 *	Get the SSRC for the outgoing stream.
 *
 * @param session a rtp session.
**/
727 728 729 730 731 732
uint32_t
rtp_session_get_send_ssrc (RtpSession* session)
{
	return session->snd.ssrc;
}

733 734
/**
 * Get the SSRC for the incoming stream.
735
 *
736 737 738 739 740 741
 * If no packets have been received yet, 0 is returned.
**/
uint32_t rtp_session_get_recv_ssrc(RtpSession *session){
	return session->rcv.ssrc;
}

742

aymeric's avatar
aymeric committed
743 744 745 746
void rtp_session_update_payload_type(RtpSession *session, int paytype){
	/* check if we support this payload type */
	PayloadType *pt=rtp_profile_get_payload(session->rcv.profile,paytype);
	if (pt!=0){
smorlat's avatar
smorlat committed
747
		session->hw_recv_pt=paytype;
aymeric's avatar
aymeric committed
748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782
		ortp_message ("payload type changed to %i(%s) !",
				 paytype,pt->mime_type);
		payload_type_changed(session,pt);
	}else{
		ortp_warning("Receiving packet with unknown payload type %i.",paytype);
	}
}
/**
 *	Sets the payload type of the rtp session. It decides of the payload types written in the
 *	of the rtp header for the outgoing stream, if the session is SENDRECV or SENDONLY.
 *	For payload type in incoming packets, the application can be informed by registering
 *	for the "payload_type_changed" signal, so that it can make the necessary changes
 *	on the downstream decoder that deals with the payload of the packets.
 *
 * @param session a rtp session
 * @param paytype the payload type number
 * @return 0 on success, -1 if the payload is not defined.
**/

int
rtp_session_set_send_payload_type (RtpSession * session, int paytype)
{
	session->snd.pt=paytype;
	return 0;
}

/**
 *@param session a rtp session
 *
 *@return the payload type currently used in outgoing rtp packets
**/
int rtp_session_get_send_payload_type(const RtpSession *session){
	return session->snd.pt;
}

783 784 785 786 787 788 789 790 791 792 793 794 795 796
/**
 * Assign the payload type number for sending telephone-event.
 * It is required that a "telephone-event" PayloadType is assigned in the RtpProfile set for the RtpSession.
 * This function is in most of cases useless, unless there is an ambiguity where several PayloadType for "telephone-event" are present in the RtpProfile.
 * This might happen during SIP offeranswer scenarios. This function allows to remove any ambiguity by letting the application choose the one to be used.
 * @param session the RtpSession
 * @param paytype the payload type number
 * @returns 0, -1 on error.
**/
int rtp_session_set_send_telephone_event_payload_type(RtpSession *session, int paytype){
	session->tev_send_pt = paytype;
	return 0;
}

aymeric's avatar
aymeric committed
797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835
/**
 *
 *	Sets the expected payload type for incoming packets.
 *	If the actual payload type in incoming packets is different that this expected payload type, thus
 *	the "payload_type_changed" signal is emitted.
 *
 *@param session a rtp session
 *@param paytype the payload type number
 *@return 0 on success, -1 if the payload is not defined.
**/

int
rtp_session_set_recv_payload_type (RtpSession * session, int paytype)
{
	PayloadType *pt;
	session->rcv.pt=paytype;
	session->hw_recv_pt=paytype;
	pt=rtp_profile_get_payload(session->rcv.profile,paytype);
	if (pt!=NULL){
		payload_type_changed(session,pt);
	}
	return 0;
}

/**
 *@param session a rtp session
 *
 * @return the payload type currently used in incoming rtp packets
**/
int rtp_session_get_recv_payload_type(const RtpSession *session){
	return session->rcv.pt;
}

/**
 *	Sets the expected payload type for incoming packets and payload type to be used for outgoing packets.
 *	If the actual payload type in incoming packets is different that this expected payload type, thus
 *	the "payload_type_changed" signal is emitted.
 *
 * @param session a rtp session
836
 * @param pt the payload type number
aymeric's avatar
aymeric committed
837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860
 * @return 0 on success, -1 if the payload is not defined.
**/
int rtp_session_set_payload_type(RtpSession *session, int pt){
	if (rtp_session_set_send_payload_type(session,pt)<0) return -1;
	if (rtp_session_set_recv_payload_type(session,pt)<0) return -1;
	return 0;
}


static void rtp_header_init_from_session(rtp_header_t *rtp, RtpSession *session){
	rtp->version = 2;
	rtp->padbit = 0;
	rtp->extbit = 0;
	rtp->markbit= 0;
	rtp->cc = 0;
	rtp->paytype = session->snd.pt;
	rtp->ssrc = session->snd.ssrc;
	rtp->timestamp = 0;	/* set later, when packet is sended */
	/* set a seq number */
	rtp->seq_number=session->rtp.snd_seq;
}

/**
 *	Allocates a new rtp packet. In the header, ssrc and payload_type according to the session's
smorlat's avatar
smorlat committed
861 862
 *	context. Timestamp is not set, it will be set when the packet is going to be
 *	sent with rtp_session_sendm_with_ts(). Sequence number is initalized to previous sequence number sent + 1
aymeric's avatar
aymeric committed
863 864 865 866 867 868 869 870
 *	If payload_size is zero, thus an empty packet (just a RTP header) is returned.
 *
 *@param session a rtp session.
 *@param header_size the rtp header size. For standart size (without extensions), it is RTP_FIXED_HEADER_SIZE
 *@param payload data to be copied into the rtp packet.
 *@param payload_size size of data carried by the rtp packet.
 *@return a rtp packet in a mblk_t (message block) structure.
**/
871
mblk_t * rtp_session_create_packet(RtpSession *session,size_t header_size, const uint8_t *payload, size_t payload_size)
aymeric's avatar
aymeric committed
872 873
{
	mblk_t *mp;
874
	size_t msglen=header_size+payload_size;
aymeric's avatar
aymeric committed
875
	rtp_header_t *rtp;
876

aymeric's avatar
aymeric committed
877 878 879 880 881 882 883 884 885 886 887 888
	mp=allocb(msglen,BPRI_MED);
	rtp=(rtp_header_t*)mp->b_rptr;
	rtp_header_init_from_session(rtp,session);
	/*copy the payload, if any */
	mp->b_wptr+=header_size;
	if (payload_size){
		memcpy(mp->b_wptr,payload,payload_size);
		mp->b_wptr+=payload_size;
	}
	return mp;
}

889 890 891 892

/**
 * Create a packet already including headers
 */
893
mblk_t * rtp_session_create_packet_raw(const uint8_t *packet, size_t packet_size) {
894 895 896 897 898 899 900 901 902 903
	mblk_t *mp;

	mp=allocb(packet_size,BPRI_MED);
	if (packet_size){
		memcpy(mp->b_wptr,packet,packet_size);
		mp->b_wptr+=packet_size;
	}
	return mp;
}

aymeric's avatar
aymeric committed
904 905 906 907 908 909 910
/**
 *	Creates a new rtp packet using the given payload buffer (no copy). The header will be allocated separetely.
 *  In the header, ssrc and payload_type according to the session's
 *	context. Timestamp and seq number are not set, there will be set when the packet is going to be
 *	sent with rtp_session_sendm_with_ts().
 *	oRTP will send this packet using libc's sendmsg() (if this function is availlable!) so that there will be no
 *	packet concatenation involving copies to be done in user-space.
911
 *  \a freefn can be NULL, in that case payload will be kept untouched.
aymeric's avatar
aymeric committed
912 913 914 915 916 917 918 919
 *
 * @param session a rtp session.
 * @param payload the data to be sent with this packet
 * @param payload_size size of data
 * @param freefn a function that will be called when the payload buffer is no more needed.
 * @return: a rtp packet in a mblk_t (message block) structure.
**/

920
mblk_t * rtp_session_create_packet_with_data(RtpSession *session, uint8_t *payload, size_t payload_size, void (*freefn)(void*))
aymeric's avatar
aymeric committed
921 922 923 924
{
	mblk_t *mp,*mpayload;
	int header_size=RTP_FIXED_HEADER_SIZE; /* revisit when support for csrc is done */
	rtp_header_t *rtp;
925

aymeric's avatar
aymeric committed
926 927 928 929 930 931 932 933 934 935 936 937 938 939
	mp=allocb(header_size,BPRI_MED);
	rtp=(rtp_header_t*)mp->b_rptr;
	rtp_header_init_from_session(rtp,session);
	mp->b_wptr+=header_size;
	/* create a mblk_t around the user supplied payload buffer */
	mpayload=esballoc(payload,payload_size,BPRI_MED,freefn);
	mpayload->b_wptr+=payload_size;
	/* link it with the header */
	mp->b_cont=mpayload;
	return mp;
}


/**
940
 * Creates a new rtp packet using the buffer given in arguments (no copy).
aymeric's avatar
aymeric committed
941 942 943
 * In the header, ssrc and payload_type according to the session's
 *context. Timestamp and seq number are not set, there will be set when the packet is going to be
 *	sent with rtp_session_sendm_with_ts().
944
 * \a freefn can be NULL, in that case payload will be kept untouched.
aymeric's avatar
aymeric committed
945 946 947 948 949 950 951
 *
 * @param session a rtp session.
 * @param buffer a buffer that contains first just enough place to write a RTP header, then the data to send.
 * @param size the size of the buffer
 * @param freefn a function that will be called once the buffer is no more needed (the data has been sent).
 * @return a rtp packet in a mblk_t (message block) structure.
**/
952
mblk_t * rtp_session_create_packet_in_place(RtpSession *session,uint8_t *buffer, size_t size, void (*freefn)(void*) )
aymeric's avatar
aymeric committed
953 954 955
{
	mblk_t *mp;
	rtp_header_t *rtp;
956

aymeric's avatar
aymeric committed
957 958 959 960 961 962 963 964
	mp=esballoc(buffer,size,BPRI_MED,freefn);

	rtp=(rtp_header_t*)mp->b_rptr;
	rtp_header_init_from_session(rtp,session);
	return mp;
}


Ghislain MARY's avatar
Ghislain MARY committed
965
ORTP_PUBLIC int __rtp_session_sendm_with_ts (RtpSession * session, mblk_t *mp, uint32_t packet_ts, uint32_t send_ts)
aymeric's avatar
aymeric committed
966 967 968 969
{
	rtp_header_t *rtp;
	uint32_t packet_time;
	int error = 0;
970
	size_t packsize;
aymeric's avatar
aymeric committed
971 972 973 974 975 976 977 978
	RtpScheduler *sched=session->sched;
	RtpStream *stream=&session->rtp;

	if (session->flags & RTP_SESSION_SEND_NOT_STARTED)
	{
		session->rtp.snd_ts_offset = send_ts;
		/* Set initial last_rcv_time to first send time. */
		if ((session->flags & RTP_SESSION_RECV_NOT_STARTED)
979 980
		|| session->mode == RTP_SESSION_SENDONLY) {
			ortp_gettimeofday(&session->last_recv_time, NULL);
aymeric's avatar
aymeric committed
981
		}
982
		if (session->flags & RTP_SESSION_SCHEDULED) {
aymeric's avatar
aymeric committed
983 984 985 986 987 988 989 990 991 992
			session->rtp.snd_time_offset = sched->time_;
		}
		rtp_session_unset_flag (session,RTP_SESSION_SEND_NOT_STARTED);
	}
	/* if we are in blocking mode, then suspend the process until the scheduler it's time to send  the
	 * next packet */
	/* if the timestamp of the packet queued is older than current time, then you we must
	 * not block */
	if (session->flags & RTP_SESSION_SCHEDULED)
	{
993
		wait_point_lock(&session->snd.wp);
aymeric's avatar
aymeric committed
994 995
		packet_time =
			rtp_session_ts_to_time (session,
996 997
					 send_ts -
					 session->rtp.snd_ts_offset) +
aymeric's avatar
aymeric committed
998 999 1000 1001
					session->rtp.snd_time_offset;
		/*ortp_message("rtp_session_send_with_ts: packet_time=%i time=%i",packet_time,sched->time_);*/
		if (TIME_IS_STRICTLY_NEWER_THAN (packet_time, sched->time_))
		{
1002
			wait_point_wakeup_at(&session->snd.wp,packet_time,(session->flags & RTP_SESSION_BLOCKING_MODE)!=0);
aymeric's avatar
aymeric committed
1003 1004 1005 1006 1007
			session_set_clr(&sched->w_sessions,session);	/* the session has written */
		}
		else session_set_set(&sched->w_sessions,session);	/*to indicate select to return immediately */
		wait_point_unlock(&session->snd.wp);
	}
1008

aymeric's avatar
aymeric committed
1009 1010 1011 1012 1013 1014 1015 1016
	if(mp==NULL) {/*for people who just want to be blocked but
		 do not want to send anything.*/
		session->rtp.snd_last_ts = packet_ts;
		return 0;
	}

	rtp=(rtp_header_t*)mp->b_rptr;

1017 1018
	packsize = msgdsize(mp) ;
	session->duplication_left += session->duplication_ratio;
1019 1020 1021 1022
	if (rtp->version == 0) {
		/* We are probably trying to send a STUN packet so don't change its content. */
	} else {
		rtp->timestamp=packet_ts;
1023
		if (rtp_profile_is_telephone_event(session->snd.profile, rtp->paytype)){
1024 1025 1026 1027
			rtp->seq_number = session->rtp.snd_seq;
			session->rtp.snd_seq++;
		}
		else
1028
		{
1029
			session->rtp.snd_seq=rtp->seq_number+1;
1030
		}
1031
		session->rtp.snd_last_ts = packet_ts;
aymeric's avatar
aymeric committed
1032

1033
		stream->sent_payload_bytes+=(uint32_t)(packsize-RTP_FIXED_HEADER_SIZE);
1034

1035
		ortp_global_stats.sent += (1+(int)session->duplication_left) * packsize;
1036
		session->stats.sent += (1+(int)session->duplication_left) * packsize;
1037

1038
		ortp_global_stats.packet_sent++;
1039
		session->stats.packet_sent++;
1040

1041
		session->stats.packet_dup_sent+=(int)session->duplication_left;
1042
		ortp_global_stats.packet_sent+=(int)session->duplication_left;;
1043
	}
aymeric's avatar
aymeric committed
1044

1045
	while (session->duplication_left>=1.f) {
1046
		error = rtp_session_rtp_send (session, copymsg(mp));
1047
		session->duplication_left -= 1.f;
1048
	}
aymeric's avatar
aymeric committed
1049
	error = rtp_session_rtp_send (session, mp);
1050

aymeric's avatar
aymeric committed
1051
	/*send RTCP packet if needed */
1052
	rtp_session_run_rtcp_send_scheduler(session);
aymeric's avatar
aymeric committed
1053 1054 1055 1056 1057 1058 1059
	/* receives rtcp packet if session is send-only*/
	/*otherwise it is done in rtp_session_recvm_with_ts */
	if (session->mode==RTP_SESSION_SENDONLY) rtp_session_rtcp_recv(session);
	return error;
}

/**
1060 1061
 *	Send the rtp datagram \a packet to the destination set by rtp_session_set_remote_addr()
 *	with timestamp \a timestamp. For audio data, the timestamp is the number
aymeric's avatar
aymeric committed
1062
 *	of the first sample resulting of the data transmitted. See rfc1889 for details.
1063
 *  The packet (\a packet) is freed once it is sent.
aymeric's avatar
aymeric committed
1064 1065
 *
 *@param session a rtp session.
1066
 *@param packet a rtp packet presented as a mblk_t.
aymeric's avatar
aymeric committed
1067 1068 1069 1070 1071
 *@param timestamp the timestamp of the data to be sent.
 * @return the number of bytes sent over the network.
**/

int rtp_session_sendm_with_ts(RtpSession *session, mblk_t *packet, uint32_t timestamp){
1072
	return __rtp_session_sendm_with_ts(session,packet,timestamp+session->send_ts_offset,timestamp+session->send_ts_offset);
aymeric's avatar
aymeric committed
1073 1074 1075 1076 1077 1078 1079
}




/**
 *	Send a rtp datagram to the destination set by rtp_session_set_remote_addr() containing
1080
 *	the data from \a buffer with timestamp \a userts. This is a high level function that uses
aymeric's avatar
aymeric committed
1081 1082 1083 1084 1085 1086
 *	rtp_session_create_packet() and rtp_session_sendm_with_ts() to send the data.
 *
 *@param session a rtp session.
 *@param buffer a buffer containing the data to be sent in a rtp packet.
 *@param len the length of the data buffer, in bytes.
 *@param userts	the timestamp of the data to be sent. Refer to the rfc to know what it is.
1087
 *@return the number of bytes sent over the network.
aymeric's avatar
aymeric committed
1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105
**/
int
rtp_session_send_with_ts (RtpSession * session, const uint8_t * buffer, int len,
			  uint32_t userts)
{
	mblk_t *m;
	int err;
#ifdef USE_SENDMSG
	m=rtp_session_create_packet_with_data(session,(uint8_t*)buffer,len,NULL);
#else
	m = rtp_session_create_packet(session,RTP_FIXED_HEADER_SIZE,(uint8_t*)buffer,len);
#endif
	err=rtp_session_sendm_with_ts(session,m,userts);
	return err;
}


static void payload_type_changed_notify(RtpSession *session, int paytype){
smorlat's avatar
smorlat committed
1106 1107 1108 1109 1110
	PayloadType *pt = rtp_profile_get_payload(session->rcv.profile,paytype);
	if (pt) {
		session->rcv.pt = paytype;
		rtp_signal_table_emit (&session->on_payload_type_changed);
	}
aymeric's avatar
aymeric committed
1111
}
jehan's avatar
jehan committed
1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135
/**
 *	Try to get an rtp packet presented as a mblk_t structure from the rtp session at a given sequence number.
 *	This function is very usefull for codec with Forward error correction capabilities
 *
 *	This function returns the entire packet (with header).
 *
 *	 *
 * @param session a rtp session.
 * @param sequence_number a sequence number.
 *
 * @return a rtp packet presented as a mblk_t, or NULL if not found.
 **/

mblk_t *
rtp_session_pick_with_cseq (RtpSession * session, const uint16_t sequence_number) {
	queue_t* q= &session->rtp.rq;
	mblk_t* mb;
	for (mb=qbegin(q); !qend(q,mb); mb=qnext(q,mb)){
		if (rtp_get_seqnumber(mb)==sequence_number) {
			return mb;
		}
	}
	return NULL;
}
aymeric's avatar
aymeric committed
1136

1137 1138 1139
static void check_for_seq_number_gap(RtpSession *session, rtp_header_t *rtp) {
	uint16_t pid;
	uint16_t i;
1140 1141
	/*don't check anything before first packet delivered*/
	if (session->flags & RTP_SESSION_FIRST_PACKET_DELIVERED && RTP_SEQ_IS_STRICTLY_GREATER_THAN(rtp->seq_number, session->rtp.rcv_last_seq + 1)) {
1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156
		uint16_t first_missed_seq = session->rtp.rcv_last_seq + 1;
		uint16_t diff = rtp->seq_number - first_missed_seq;
		pid = first_missed_seq;
		for (i = 0; i <= (diff / 16); i++) {
			uint16_t seq;
			uint16_t blp = 0;
			for (seq = pid + 1; (seq < rtp->seq_number) && ((seq - pid) < 16); seq++) {
				blp |= (1 << (seq - pid - 1));
			}
			rtp_session_send_rtcp_fb_generic_nack(session, pid, blp);
			pid = seq;
		}
	}
}

aymeric's avatar
aymeric committed
1157 1158
/**
 *	Try to get a rtp packet presented as a mblk_t structure from the rtp session.
1159
 *	The \a user_ts parameter is relative to the first timestamp of the incoming stream. In other
aymeric's avatar
aymeric committed
1160
 *	words, the application does not have to know the first timestamp of the stream, it can
1161
 *	simply call for the first time this function with \a user_ts=0, and then incrementing it
aymeric's avatar
aymeric committed
1162 1163 1164 1165 1166
 *	as it want. The RtpSession takes care of synchronisation between the stream timestamp
 *	and the user timestamp given here.
 *
 *	This function returns the entire packet (with header).
 *
1167
 *	The behaviour of this function has changed since version 0.15.0. Previously the payload data could be
aymeric's avatar
aymeric committed
1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191
 *	accessed using  mblk_t::b_cont::b_rptr field of the returned mblk_t.
 *	This is no more the case.
 *	The convenient way of accessing the payload data is to use rtp_get_payload() :
 *	@code
 *	unsigned char *payload;
 *	int payload_size;
 *	payload_size=rtp_get_payload(mp,&payload);
 *	@endcode
 *	OR simply skip the header this way, the data is then comprised between mp->b_rptr and mp->b_wptr:
 *	@code
 *	rtp_get_payload(mp,&mp->b_rptr);
 *	@endcode
 *
 *
 * @param session a rtp session.
 * @param user_ts a timestamp.
 *
 * @return a rtp packet presented as a mblk_t.
**/

mblk_t *
rtp_session_recvm_with_ts (RtpSession * session, uint32_t user_ts)
{
	mblk_t *mp = NULL;
1192
	rtp_header_t *rtp = NULL;
aymeric's avatar
aymeric committed
1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206
	uint32_t ts;
	uint32_t packet_time;
	RtpScheduler *sched=session->sched;
	int rejected=0;
	bool_t read_socket=TRUE;

	/* if we are scheduled, remember the scheduler time at which the application has
	 * asked for its first timestamp */

	if (session->flags & RTP_SESSION_RECV_NOT_STARTED)
	{
		session->rtp.rcv_query_ts_offset = user_ts;
		/* Set initial last_rcv_time to first recv time. */
		if ((session->flags & RTP_SESSION_SEND_NOT_STARTED)
1207
		|| session->mode == RTP_SESSION_RECVONLY) {
1208
			ortp_gettimeofday(&session->last_recv_time, NULL);
aymeric's avatar
aymeric committed
1209
		}
1210
		if (session->flags & RTP_SESSION_SCHEDULED) {
aymeric's avatar
aymeric committed
1211 1212 1213 1214 1215
			session->rtp.rcv_time_offset = sched->time_;
			//ortp_message("setting snd_time_offset=%i",session->rtp.snd_time_offset);
		}
		rtp_session_unset_flag (session,RTP_SESSION_RECV_NOT_STARTED);
	}else{
1216
		/*prevent reading from the sockets when two
aymeric's avatar
aymeric committed
1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228
		consecutives calls for a same timestamp*/
		if (user_ts==session->rtp.rcv_last_app_ts)
			read_socket=FALSE;
	}
	session->rtp.rcv_last_app_ts = user_ts;
	if (read_socket){
		rtp_session_rtp_recv (session, user_ts);
		rtp_session_rtcp_recv(session);
	}
	/* check for telephone event first */
	mp=getq(&session->rtp.tev_rq);
	if (mp!=NULL){
1229
		size_t msgsize=msgdsize(mp);
aymeric's avatar
aymeric committed
1230
		ortp_global_stats.recv += msgsize;
1231
		session->stats.recv += msgsize;
1232
		rtp_signal_table_emit2(&session->on_telephone_event_packet,mp);
aymeric's avatar
aymeric committed
1233 1234 1235 1236
		rtp_session_check_telephone_events(session,mp);
		freemsg(mp);
		mp=NULL;
	}
1237

aymeric's avatar
aymeric committed
1238 1239 1240
	/* then now try to return a media packet, if possible */
	/* first condition: if the session is starting, don't return anything
	 * until the queue size reaches jitt_comp */
1241

aymeric's avatar
aymeric committed
1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259
	if (session->flags & RTP_SESSION_RECV_SYNC)
	{
		queue_t *q = &session->rtp.rq;
		if (qempty(q))
		{
			ortp_debug ("Queue is empty.");
			goto end;
		}
		rtp = (rtp_header_t *) qfirst(q)->b_rptr;
		session->rtp.rcv_ts_offset = rtp->timestamp;
		session->rtp.rcv_last_ret_ts = user_ts;	/* just to have an init value */
		session->rcv.ssrc = rtp->ssrc;
		/* delete the recv synchronisation flag */
		rtp_session_unset_flag (session, RTP_SESSION_RECV_SYNC);
	}

	/*calculate the stream timestamp from the user timestamp */
	ts = jitter_control_get_compensated_timestamp(&session->rtp.jittctl,user_ts);
1260
	if (session->rtp.jittctl.params.enabled==TRUE){
aymeric's avatar
aymeric committed
1261 1262 1263 1264 1265 1266
		if (session->permissive)
			mp = rtp_getq_permissive(&session->rtp.rq, ts,&rejected);
		else{
			mp = rtp_getq(&session->rtp.rq, ts,&rejected);
		}
	}else mp=getq(&session->rtp.rq);/*no jitter buffer at all*/
1267

1268
	session->stats.outoftime+=rejected;
aymeric's avatar
aymeric committed
1269
	ortp_global_stats.outoftime+=rejected;
1270
	session->rtcp_xr_stats.discarded_count += rejected;
aymeric's avatar
aymeric committed
1271

1272
	end:
aymeric's avatar
aymeric committed
1273 1274
	if (mp != NULL)
	{
1275
		size_t msgsize = msgdsize(mp);	/* evaluate how much bytes (including header) is received by app */
aymeric's avatar
aymeric committed
1276 1277
		uint32_t packet_ts;
		ortp_global_stats.recv += msgsize;
1278
		session->stats.recv += msgsize;
aymeric's avatar
aymeric committed
1279 1280
		rtp = (rtp_header_t *) mp->b_rptr;
		packet_ts=rtp->timestamp;
1281
		ortp_debug("Returning mp with ts=%i", packet_ts);
aymeric's avatar
aymeric committed
1282 1283 1284 1285 1286
		/* check for payload type changes */
		if (session->rcv.pt != rtp->paytype)
		{
			payload_type_changed_notify(session, rtp->paytype);
		}
1287
		check_for_seq_number_gap(session, rtp);
1288
		/* update the packet's timestamp so that it corrected by the
aymeric's avatar
aymeric committed
1289
		adaptive jitter buffer mechanism */
1290
		if (session->rtp.jittctl.params.adaptive){
aymeric's avatar
aymeric committed
1291 1292 1293 1294 1295 1296 1297 1298 1299 1300
			uint32_t changed_ts;
			/* only update correction offset between packets of different
			timestamps*/
			if (packet_ts!=session->rtp.rcv_last_ts)
				jitter_control_update_corrective_slide(&session->rtp.jittctl);
			changed_ts=packet_ts+session->rtp.jittctl.corrective_slide;
			rtp->timestamp=changed_ts;
			/*ortp_debug("Returned packet has timestamp %u, with clock slide compensated it is %u",packet_ts,rtp->timestamp);*/
		}
		session->rtp.rcv_last_ts = packet_ts;
1301
		session->rtp.rcv_last_seq = rtp->seq_number;
aymeric's avatar
aymeric committed
1302 1303 1304 1305 1306 1307 1308 1309 1310
		if (!(session->flags & RTP_SESSION_FIRST_PACKET_DELIVERED)){
			rtp_session_set_flag(session,RTP_SESSION_FIRST_PACKET_DELIVERED);
		}
	}
	else
	{
		ortp_debug ("No mp for timestamp queried");
	}
	rtp_session_rtcp_process_recv(session);
1311

aymeric's avatar
aymeric committed
1312 1313 1314 1315 1316 1317
	if (session->flags & RTP_SESSION_SCHEDULED)
	{
		/* if we are in blocking mode, then suspend the calling process until timestamp
		 * wanted expires */
		/* but we must not block the process if the timestamp wanted by the application is older
		 * than current time */
1318
		wait_point_lock(&session->rcv.wp);
aymeric's avatar
aymeric committed
1319 1320
		packet_time =
			rtp_session_ts_to_time (session,
1321 1322
					 user_ts -
					 session->rtp.rcv_query_ts_offset) +
aymeric's avatar
aymeric committed
1323 1324
			session->rtp.rcv_time_offset;
		ortp_debug ("rtp_session_recvm_with_ts: packet_time=%i, time=%i",packet_time, sched->time_);
1325

aymeric's avatar
aymeric committed
1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342
		if (TIME_IS_STRICTLY_NEWER_THAN (packet_time, sched->time_))
		{
			wait_point_wakeup_at(&session->rcv.wp,packet_time, (session->flags & RTP_SESSION_BLOCKING_MODE)!=0);
			session_set_clr(&sched->r_sessions,session);
		}
		else session_set_set(&sched->r_sessions,session);	/*to unblock _select() immediately */
		wait_point_unlock(&session->rcv.wp);
	}
	return mp;
}


/**
 *	NOTE: use of this function is discouraged when sending payloads other than
 *	pcm/pcmu/pcma/adpcm types.
 *	rtp_session_recvm_with_ts() does better job.
 *
1343
 *	Tries to read the bytes of the incoming rtp stream related to timestamp ts. In case
1344
 *	where the user supplied buffer \a buffer is not large enough to get all the data
aymeric's avatar
aymeric committed
1345 1346
 *	related to timestamp ts, then *( have_more) is set to 1 to indicate that the application
 *	should recall the function with the same timestamp to get more data.
1347 1348
 *
 *  When the rtp session is scheduled (see rtp_session_set_scheduling_mode() ), and the
aymeric's avatar
aymeric committed
1349
 *	blocking mode is on (see rtp_session_set_blocking_mode() ), then the calling thread
1350
 *	is suspended until the timestamp given as argument expires, whatever a received packet
aymeric's avatar
aymeric committed
1351 1352 1353
 *	fits the query or not.
 *
 *	Important note: it is clear that the application cannot know the timestamp of the first
1354
 *	packet of the incoming stream, because it can be random. The \a ts timestamp given to the
aymeric's avatar
aymeric committed
1355 1356 1357 1358 1359
 *	function is used relatively to first timestamp of the stream. In simple words, 0 is a good
 *	value to start calling this function.
 *
 *	This function internally calls rtp_session_recvm_with_ts() to get a rtp packet. The content
 *	of this packet is then copied into the user supplied buffer in an intelligent manner:
1360
 *	the function takes care of the size of the supplied buffer and the timestamp given in
aymeric's avatar
aymeric committed
1361 1362 1363 1364
 *	argument. Using this function it is possible to read continous audio data (e.g. pcma,pcmu...)
 *	with for example a standart buffer of size of 160 with timestamp incrementing by 160 while the incoming
 *	stream has a different packet size.
 *
1365
 *Returns: if a packet was availlable with the corresponding timestamp supplied in argument
aymeric's avatar
aymeric committed
1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377
 *	then the number of bytes written in the user supplied buffer is returned. If no packets
 *	are availlable, either because the sender has not started to send the stream, or either
 *	because silence packet are not transmitted, or either because the packet was lost during
 *	network transport, then the function returns zero.
 *@param session a rtp session.
 *@param buffer a user supplied buffer to write the data.
 *@param len the length in bytes of the user supplied buffer.
 *@param ts the timestamp wanted.
 *@param have_more the address of an integer to indicate if more data is availlable for the given timestamp.
 *
**/
int rtp_session_recv_with_ts (RtpSession * session, uint8_t * buffer,
1378
				   int len, uint32_t ts, int * have_more){
aymeric's avatar
aymeric committed
1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390
	mblk_t *mp=NULL;
	int plen,blen=0;
	*have_more=0;
	while(1){
		if (session->pending){
			mp=session->pending;
			session->pending=NULL;
		}else {
			mp=rtp_session_recvm_with_ts(session,ts);
			if (mp!=NULL) rtp_get_payload(mp,&mp->b_rptr);
		}
		if (mp){
1391
			plen=(int)(mp->b_wptr-mp->b_rptr);
aymeric's avatar
aymeric committed
1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414
			if (plen<=len){
				memcpy(buffer,mp->b_rptr,plen);
				buffer+=plen;
				blen+=plen;
				len-=plen;
				freemsg(mp);
				mp=NULL;
			}else{
				memcpy(buffer,mp->b_rptr,len);
				mp->b_rptr+=len;
				buffer+=len;
				blen+=len;
				len=0;
				session->pending=mp;
				*have_more=1;
				break;
			}
		}else break;
	}
	return blen;
}
/**
 *	When the rtp session is scheduled and has started to send packets, this function
1415
 *	computes the timestamp that matches to the present time. Using this function can be
aymeric's avatar
aymeric committed
1416 1417
 *	usefull when sending discontinuous streams. Some time can be elapsed between the end
 *	of a stream burst and the begin of a new stream burst, and the application may be not
1418
 *	not aware of this elapsed time. In order to get a valid (current) timestamp to pass to
aymeric's avatar
aymeric committed
1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468
 *	#rtp_session_send_with_ts() or #rtp_session_sendm_with_ts(), the application may
 *	use rtp_session_get_current_send_ts().
 *
 * @param session a rtp session.
 * @return the current send timestamp for the rtp session.
**/
uint32_t rtp_session_get_current_send_ts(RtpSession *session)
{
	uint32_t userts;
	uint32_t session_time;
	RtpScheduler *sched=session->sched;
	PayloadType *payload;
	payload=rtp_profile_get_payload(session->snd.profile,session->snd.pt);
	return_val_if_fail(payload!=NULL, 0);
	if ( (session->flags & RTP_SESSION_SCHEDULED)==0 ){
		ortp_warning("can't guess current timestamp because session is not scheduled.");
		return 0;
	}
	session_time=sched->time_-session->rtp.snd_time_offset;
	userts=  (uint32_t)( ( (double)(session_time) * (double) payload->clock_rate )/ 1000.0)
				+ session->rtp.snd_ts_offset;
	return userts;
}

/**
 * Same thing as rtp_session_get_current_send_ts() except that it's for an incoming stream.
 * Works only on scheduled mode.
 *
 * @param session a rtp session.
 * @return the theoritical that would have to be receive now.
 *
**/
uint32_t rtp_session_get_current_recv_ts(RtpSession *session){
	uint32_t userts;
	uint32_t session_time;
	RtpScheduler *sched=ortp_get_scheduler();
	PayloadType *payload;
	payload=rtp_profile_get_payload(session->rcv.profile,session->rcv.pt);
	return_val_if_fail(payload!=NULL, 0);
	if ( (session->flags & RTP_SESSION_SCHEDULED)==0 ){
		ortp_warning("can't guess current timestamp because session is not scheduled.");
		return 0;
	}
	session_time=sched->time_-session->rtp.rcv_time_offset;
	userts=  (uint32_t)( ( (double)(session_time) * (double) payload->clock_rate )/ 1000.0)
				+ session->rtp.rcv_ts_offset;
	return userts;
}

/**
1469 1470
 * oRTP has the possibility to inform the application through a callback registered
 * with rtp_session_signal_connect about crazy incoming RTP stream that jumps from
aymeric's avatar
aymeric committed
1471 1472 1473 1474
 * a timestamp N to N+some_crazy_value. This lets the opportunity for the application
 * to reset the session in order to resynchronize, or any other action like stopping the call
 * and reporting an error.
 * @param session the rtp session
1475
 * @param milisecs a time interval in miliseconds
aymeric's avatar
aymeric committed
1476 1477 1478 1479 1480 1481 1482 1483 1484 1485
 *
**/
void rtp_session_set_time_jump_limit(RtpSession *session, int milisecs){
	uint32_t ts;
	session->rtp.time_jump=milisecs;
	ts=rtp_session_time_to_ts(session,milisecs);
	if (ts==0) session->rtp.ts_jump=1<<31;	/* do not detect ts jump */
	else session->rtp.ts_jump=ts;
}

1486
void _rtp_session_release_sockets(RtpSession *session, bool_t release_transports){
1487

1488 1489 1490
	if (release_transports){
		if (session->rtp.gs.tr) {
			if (session->rtp.gs.tr->t_close)
1491
				session->rtp.gs.tr->t_close(session->rtp.gs.tr);
1492 1493 1494 1495 1496 1497 1498
			session->rtp.gs.tr->t_destroy(session->rtp.gs.tr);

		}
		session->rtp.gs.tr = 0;

		if (session->rtcp.gs.tr)  {
			if (session->rtcp.gs.tr->t_close)
1499
				session->rtcp.gs.tr->t_close(session->rtcp.gs.tr);
1500 1501 1502 1503
			session->rtcp.gs.tr->t_destroy(session->rtcp.gs.tr);
		}
		session->rtcp.gs.tr = 0;
	}
1504

1505 1506 1507 1508
	if (session->rtp.gs.socket!=(ortp_socket_t)-1) close_socket (session->rtp.gs.socket);
	if (session->rtcp.gs.socket!=(ortp_socket_t)-1) close_socket (session->rtcp.gs.socket);
	session->rtp.gs.socket=-1;
	session->rtcp.gs.socket=-1;
1509

aymeric's avatar
aymeric committed
1510
	/* don't discard remote addresses, then can be preserved for next use.
1511 1512
	session->rtp.gs.rem_addrlen=0;
	session->rtcp.gs.rem_addrlen=0;
aymeric's avatar
aymeric committed
1513 1514 1515
	*/
}

1516 1517 1518 1519 1520 1521 1522
/**
 * Closes the rtp and rtcp sockets, and associated RtpTransport.
**/
void rtp_session_release_sockets(RtpSession *session){
	_rtp_session_release_sockets(session, TRUE);
}

aymeric's avatar
aymeric committed
1523
ortp_socket_t rtp_session_get_rtp_socket(const RtpSession *session){
1524
	return rtp_session_using_transport(session, rtp) ? (session->rtp.gs.tr->t_getsocket)(session->rtp.gs.tr) : session->rtp.gs.socket;
aymeric's avatar
aymeric committed
1525 1526 1527
}

ortp_socket_t rtp_session_get_rtcp_socket(const RtpSession *session){
1528
	return rtp_session_using_transport(session, rtcp) ? (session->rtcp.gs.tr->t_getsocket)(session->rtcp.gs.tr) : session->rtcp.gs.socket;
aymeric's avatar
aymeric committed
1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547
}

/**
 * Register an event queue.
 * An application can use an event queue to get informed about various RTP events.
**/
void rtp_session_register_event_queue(RtpSession *session, OrtpEvQueue *q){
	session->eventqs=o_list_append(session->eventqs,q);
}

void rtp_session_unregister_event_queue(RtpSession *session, OrtpEvQueue *q){
	session->eventqs=o_list_remove(session->eventqs,q);
}

void rtp_session_dispatch_event(RtpSession *session, OrtpEvent *ev){
	OList *it;
	int i;
	for(i=0,it=session->eventqs;it!=NULL;it=it->next,++i){
		ortp_ev_queue_put((OrtpEvQueue*)it->data,ortp_event_dup(ev));
1548
	}
aymeric's avatar
aymeric committed
1549 1550 1551
	ortp_event_destroy(ev);
}

1552 1553 1554 1555 1556 1557 1558 1559 1560 1561
void ortp_stream_clear_aux_addresses(OrtpStream *os){
	OList *elem;
	for (elem=os->aux_destinations;elem!=NULL;elem=elem->next){
		OrtpAddress *addr=(OrtpAddress*)elem->data;
		ortp_free(addr);
	}
	os->aux_destinations=o_list_free(os->aux_destinations);
}

static void ortp_stream_uninit(OrtpStream *os){
1562
	msgb_allocator_uninit(&os->allocator);
1563 1564
	ortp_stream_clear_aux_addresses(os);
}
aymeric's avatar
aymeric committed
1565 1566 1567

void rtp_session_uninit (RtpSession * session)
{
1568 1569 1570 1571 1572 1573
#if defined(_WIN32) || defined(_WIN32_WCE)
	session->rtp.is_win_thread_running = FALSE;
	flushq(&session->rtp.winrq, FLUSHALL);
	ortp_mutex_destroy(&session->rtp.winrq_lock);
#endif
	
1574 1575
	RtpTransport *rtp_meta_transport = NULL;
	RtpTransport *rtcp_meta_transport = NULL;
aymeric's avatar
aymeric committed
1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591
	/* first of all remove the session from the scheduler */
	if (session->flags & RTP_SESSION_SCHEDULED)
	{
		rtp_scheduler_remove_session (session->sched,session);
	}
	/*flush all queues */
	flushq(&session->rtp.rq, FLUSHALL);
	flushq(&session->rtp.tev_rq, FLUSHALL);

	if (session->eventqs!=NULL) o_list_free(session->eventqs);
	/* close sockets */
	rtp_session_release_sockets(session);

	wait_point_uninit(&session->snd.wp);
	wait_point_uninit(&session->rcv.wp);
	if (session->current_tev!=NULL) freemsg(session->current_tev);
1592 1593
	ortp_stream_uninit(&session->rtp.gs);
	ortp_stream_uninit(&session->rtcp.gs);
1594 1595 1596 1597
	if (session->full_sdes != NULL)
		freemsg(session->full_sdes);
	if (session->minimal_sdes != NULL)
		freemsg(session->minimal_sdes);
1598
	bctbx_list_free_with_data(session->recv_addr_map, (bctbx_list_free_func)bctbx_free);
aymeric's avatar
aymeric committed
1599 1600

	session->signal_tables = o_list_free(session->signal_tables);
1601

1602 1603
	if (session->net_sim_ctx)
		ortp_network_simulator_destroy(session->net_sim_ctx);
1604 1605 1606 1607
	
	if (session->rtp.congdetect){
		ortp_congestion_detector_destroy(session->rtp.congdetect);
	}
1608

1609 1610 1611 1612
	if (session->rtp.video_bw_estimator){
		ortp_video_bandwidth_estimator_destroy(session->rtp.video_bw_estimator);
	}

1613 1614 1615 1616 1617 1618
	rtp_session_get_transports(session,&rtp_meta_transport,&rtcp_meta_transport);
	if (rtp_meta_transport)
		meta_rtp_transport_destroy(rtp_meta_transport);
	if (rtcp_meta_transport)
		meta_rtp_transport_destroy(rtcp_meta_transport);

1619
#if (_WIN32_WINNT >= 0x0600) && defined(ORTP_WINDOWS_DESKTOP)
Simon Morlat's avatar
Simon Morlat committed
1620
	if (session->rtp.QoSFlowID != 0)
1621
	{
1622 1623
		ortp_message("check OS support for qwave.lib");
		if (IsWindowsVistaOrGreater()) {
1624
			BOOL QoSResult;
1625
			QoSResult = QOSRemoveSocketFromFlow(session->rtp.QoSHandle, 0, session->rtp.QoSFlowID, 0);
1626
			if (QoSResult != TRUE){
1627
				ortp_error("QOSRemoveSocketFromFlow failed to end a flow with error %d", GetLastError());
Simon Morlat's avatar
Simon Morlat committed
1628
			}
1629
			session->rtp.QoSFlowID = 0;
Simon Morlat's avatar
Simon Morlat committed
1630
		}
1631
	}
Simon Morlat's avatar
Simon Morlat committed
1632

1633 1634 1635
	if (session->rtp.QoSHandle != NULL)
	{
		QOSCloseHandle(session->rtp.QoSHandle);