rtpsourcedata.cpp 15.5 KB
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 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 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 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 206 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 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 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 425 426 427 428 429 430 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 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501
/*

  This file is a part of JRTPLIB
  Copyright (c) 1999-2017 Jori Liesenborgs

  Contact: jori.liesenborgs@gmail.com

  This library was developed at the Expertise Centre for Digital Media
  (http://www.edm.uhasselt.be), a research center of the Hasselt University
  (http://www.uhasselt.be). The library is based upon work done for 
  my thesis at the School for Knowledge Technology (Belgium/The Netherlands).

  Permission is hereby granted, free of charge, to any person obtaining a
  copy of this software and associated documentation files (the "Software"),
  to deal in the Software without restriction, including without limitation
  the rights to use, copy, modify, merge, publish, distribute, sublicense,
  and/or sell copies of the Software, and to permit persons to whom the
  Software is furnished to do so, subject to the following conditions:

  The above copyright notice and this permission notice shall be included
  in all copies or substantial portions of the Software.

  THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
  OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.  IN NO EVENT SHALL
  THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
  FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
  IN THE SOFTWARE.

*/

#include "rtpsourcedata.h"
#include "rtpdefines.h"
#include "rtpaddress.h"
#include "rtpmemorymanager.h"
#ifdef RTP_SUPPORT_NETINET_IN
	#include <netinet/in.h>
#endif // RTP_SUPPORT_NETINET_IN

#ifdef RTPDEBUG
	#include <iostream>
	#include <string>
#endif // RTPDEBUG

#include "rtpdebug.h"

#define ACCEPTPACKETCODE									\
		*accept = true;									\
												\
		sentdata = true;								\
		packetsreceived++;								\
		numnewpackets++;								\
												\
		if (pack->GetExtendedSequenceNumber() == 0)					\
		{										\
			baseseqnr = 0x0000FFFF;							\
			numcycles = 0x00010000;							\
		}										\
		else										\
			baseseqnr = pack->GetExtendedSequenceNumber() - 1;			\
												\
		exthighseqnr = baseseqnr + 1;							\
		prevpacktime = receivetime;							\
		prevexthighseqnr = baseseqnr;							\
		savedextseqnr = baseseqnr;							\
												\
		pack->SetExtendedSequenceNumber(exthighseqnr);					\
												\
		prevtimestamp = pack->GetTimestamp();						\
		lastmsgtime = prevpacktime;							\
		if (!ownpacket) /* for own packet, this value is set on an outgoing packet */	\
			lastrtptime = prevpacktime;

namespace jrtplib
{

void RTPSourceStats::ProcessPacket(RTPPacket *pack,const RTPTime &receivetime,double tsunit,
                                   bool ownpacket,bool *accept,bool applyprobation,bool *onprobation)
{
	JRTPLIB_UNUSED(applyprobation); // possibly unused

	// Note that the sequence number in the RTP packet is still just the
	// 16 bit number contained in the RTP header

	*onprobation = false;
	
	if (!sentdata) // no valid packets received yet
	{
#ifdef RTP_SUPPORT_PROBATION
		if (applyprobation)
		{
			bool acceptpack = false;

			if (probation)  
			{	
				uint16_t pseq;
				uint32_t pseq2;
	
				pseq = prevseqnr;
				pseq++;
				pseq2 = (uint32_t)pseq;
				if (pseq2 == pack->GetExtendedSequenceNumber()) // ok, its the next expected packet
				{
					prevseqnr = (uint16_t)pack->GetExtendedSequenceNumber();
					probation--;	
					if (probation == 0) // probation over
						acceptpack = true;
					else
						*onprobation = true;
				}
				else // not next packet
				{
					probation = RTP_PROBATIONCOUNT;
					prevseqnr = (uint16_t)pack->GetExtendedSequenceNumber();
					*onprobation = true;
				}
			}
			else // first packet received with this SSRC ID, start probation
			{
				probation = RTP_PROBATIONCOUNT;
				prevseqnr = (uint16_t)pack->GetExtendedSequenceNumber();	
				*onprobation = true;
			}
	
			if (acceptpack)
			{
				ACCEPTPACKETCODE
			}
			else
			{
				*accept = false;
				lastmsgtime = receivetime;
			}
		}
		else // No probation
		{
			ACCEPTPACKETCODE
		}
#else // No compiled-in probation support

		ACCEPTPACKETCODE

#endif // RTP_SUPPORT_PROBATION
	}
	else // already got packets
	{
		uint16_t maxseq16;
		uint32_t extseqnr;

		// Adjust max extended sequence number and set extende seq nr of packet

		*accept = true;
		packetsreceived++;
		numnewpackets++;

		maxseq16 = (uint16_t)(exthighseqnr&0x0000FFFF);
		if (pack->GetExtendedSequenceNumber() >= maxseq16)
		{
			extseqnr = numcycles+pack->GetExtendedSequenceNumber();
			exthighseqnr = extseqnr;
		}
		else
		{
			uint16_t dif1,dif2;

			dif1 = ((uint16_t)pack->GetExtendedSequenceNumber());
			dif1 -= maxseq16;
			dif2 = maxseq16;
			dif2 -= ((uint16_t)pack->GetExtendedSequenceNumber());
			if (dif1 < dif2)
			{
				numcycles += 0x00010000;
				extseqnr = numcycles+pack->GetExtendedSequenceNumber();
				exthighseqnr = extseqnr;
			}
			else
				extseqnr = numcycles+pack->GetExtendedSequenceNumber();
		}

		pack->SetExtendedSequenceNumber(extseqnr);

		// Calculate jitter

		if (tsunit > 0)
		{
#if 0
			RTPTime curtime = receivetime;
			double diffts1,diffts2,diff;

			curtime -= prevpacktime;
			diffts1 = curtime.GetDouble()/tsunit;	
			diffts2 = (double)pack->GetTimestamp() - (double)prevtimestamp;
			diff = diffts1 - diffts2;
			if (diff < 0)
				diff = -diff;
			diff -= djitter;
			diff /= 16.0;
			djitter += diff;
			jitter = (uint32_t)djitter;
#else
RTPTime curtime = receivetime;
double diffts1,diffts2,diff;
uint32_t curts = pack->GetTimestamp();

curtime -= prevpacktime;
diffts1 = curtime.GetDouble()/tsunit;	

if (curts > prevtimestamp)
{
	uint32_t unsigneddiff = curts - prevtimestamp;

	if (unsigneddiff < 0x10000000) // okay, curts realy is larger than prevtimestamp
		diffts2 = (double)unsigneddiff;
	else
	{
		// wraparound occurred and curts is actually smaller than prevtimestamp

		unsigneddiff = -unsigneddiff; // to get the actual difference (in absolute value)
		diffts2 = -((double)unsigneddiff);
	}
}
else if (curts < prevtimestamp)
{
	uint32_t unsigneddiff = prevtimestamp - curts;

	if (unsigneddiff < 0x10000000) // okay, curts really is smaller than prevtimestamp
		diffts2 = -((double)unsigneddiff); // negative since we actually need curts-prevtimestamp
	else
	{
		// wraparound occurred and curts is actually larger than prevtimestamp

		unsigneddiff = -unsigneddiff; // to get the actual difference (in absolute value)
		diffts2 = (double)unsigneddiff;
	}
}
else
	diffts2 = 0;

diff = diffts1 - diffts2;
if (diff < 0)
	diff = -diff;
diff -= djitter;
diff /= 16.0;
djitter += diff;
jitter = (uint32_t)djitter;
#endif
		}
		else
		{
			djitter = 0;
			jitter = 0;
		}

		prevpacktime = receivetime;
		prevtimestamp = pack->GetTimestamp();
		lastmsgtime = prevpacktime;
		if (!ownpacket) // for own packet, this value is set on an outgoing packet
			lastrtptime = prevpacktime;
	}
}

RTPSourceData::RTPSourceData(uint32_t s, RTPMemoryManager *mgr) : RTPMemoryObject(mgr),SDESinf(mgr),byetime(0,0)
{
	ssrc = s;
	issender = false;
	iscsrc = false;
	timestampunit = -1;
	receivedbye = false;
	byereason = 0;
	byereasonlen = 0;
	rtpaddr = 0;
	rtcpaddr = 0;
	ownssrc = false;
	validated = false;
	processedinrtcp = false;			
	isrtpaddrset = false;
	isrtcpaddrset = false;
}

RTPSourceData::~RTPSourceData()
{
	FlushPackets();
	if (byereason)
		RTPDeleteByteArray(byereason,GetMemoryManager());
	if (rtpaddr)
		RTPDelete(rtpaddr,GetMemoryManager());
	if (rtcpaddr)
		RTPDelete(rtcpaddr,GetMemoryManager());
}

double RTPSourceData::INF_GetEstimatedTimestampUnit() const
{
	if (!SRprevinf.HasInfo())
		return -1.0;
	
	RTPTime t1 = RTPTime(SRinf.GetNTPTimestamp());
	RTPTime t2 = RTPTime(SRprevinf.GetNTPTimestamp());
	if (t1.IsZero() || t2.IsZero()) // one of the times couldn't be calculated
		return -1.0;

	if (t1 <= t2)
		return -1.0;

	t1 -= t2; // get the time difference
	
	uint32_t tsdiff = SRinf.GetRTPTimestamp()-SRprevinf.GetRTPTimestamp();
	
	return (t1.GetDouble()/((double)tsdiff));
}

RTPTime RTPSourceData::INF_GetRoundtripTime() const
{
	if (!RRinf.HasInfo())
		return RTPTime(0,0);
	if (RRinf.GetDelaySinceLastSR() == 0 && RRinf.GetLastSRTimestamp() == 0)
		return RTPTime(0,0);

	RTPNTPTime recvtime = RRinf.GetReceiveTime().GetNTPTime();
	uint32_t rtt = ((recvtime.GetMSW()&0xFFFF)<<16)|((recvtime.GetLSW()>>16)&0xFFFF);
	rtt -= RRinf.GetLastSRTimestamp();
	rtt -= RRinf.GetDelaySinceLastSR();

	double drtt = (((double)rtt)/65536.0);
	return RTPTime(drtt);
}

#ifdef RTPDEBUG
void RTPSourceData::Dump()
{
	std::cout << "Source data for SSRC:     " << ssrc << std::endl;
	std::cout << "    Active:               " << ((IsActive())?"Yes":"No") << std::endl;
	std::cout << "    Sender:               " << ((issender)?"Yes":"No") << std::endl;
	std::cout << "    CSRC:                 " << ((iscsrc)?"Yes":"No") << std::endl;
	std::cout << "    Received bye:         " << ((receivedbye)?"Yes":"No") << std::endl;
	std::cout << "    ProcessedInRTCP:      " << ((processedinrtcp)?"Yes":"No") << std::endl;
	std::cout << "    Timestamp unit:       " << timestampunit << std::endl;
	std::cout << "    RTP address:          ";
	if (!isrtpaddrset)
		std::cout << "Not set" << std::endl;
	else
	{
		if (rtpaddr == 0)
			std::cout << "Own session" << std::endl;
		else
			std::cout << rtpaddr->GetAddressString() << std::endl;
	}
	std::cout << "    RTCP address:         ";
	if (!isrtcpaddrset)
		std::cout << "Not set" << std::endl;
	else
	{
		if (rtcpaddr == 0)
			std::cout << "Own session" << std::endl;
		else
			std::cout << rtcpaddr->GetAddressString() << std::endl;
	}
	if (SRinf.HasInfo())
	{
		if (!SRprevinf.HasInfo())
		{
			std::cout << "    SR Info:" << std::endl;
			std::cout << "        NTP timestamp:    " << SRinf.GetNTPTimestamp().GetMSW() << ":" << SRinf.GetNTPTimestamp().GetLSW() << std::endl;
			std::cout << "        RTP timestamp:    " << SRinf.GetRTPTimestamp() << std::endl;
			std::cout << "        Packet count:     " << SRinf.GetPacketCount() << std::endl;
			std::cout << "        Octet count:      " << SRinf.GetByteCount() << std::endl;
			std::cout << "        Receive time:     " << SRinf.GetReceiveTime().GetSeconds() << std::endl;
		}	
		else
		{
			std::cout << "    SR Info:" << std::endl;
			std::cout << "        NTP timestamp:    " << SRinf.GetNTPTimestamp().GetMSW() << ":" << SRinf.GetNTPTimestamp().GetLSW()
				  << " (" << SRprevinf.GetNTPTimestamp().GetMSW() << ":" << SRprevinf.GetNTPTimestamp().GetLSW() << ")" << std::endl;
			std::cout << "        RTP timestamp:    " << SRinf.GetRTPTimestamp()
			          << " (" << SRprevinf.GetRTPTimestamp() << ")" << std::endl;
			std::cout << "        Packet count:     " << SRinf.GetPacketCount()
			          << " (" << SRprevinf.GetPacketCount() << ")" << std::endl;
			std::cout << "        Octet count:      " << SRinf.GetByteCount() 
			          << " (" << SRprevinf.GetByteCount() <<")" << std::endl;
			std::cout << "        Receive time:     " << SRinf.GetReceiveTime().GetSeconds()
			          << " (" << SRprevinf.GetReceiveTime().GetSeconds() << ")" << std::endl;
		}
	}
	if (RRinf.HasInfo())
	{
		if (!RRprevinf.HasInfo())
		{
			std::cout << "    RR Info:" << std::endl;
			std::cout << "        Fraction lost:    " << RRinf.GetFractionLost() << std::endl;
			std::cout << "        Packets lost:     " << RRinf.GetPacketsLost() << std::endl;
			std::cout << "        Ext.High.Seq:     " << RRinf.GetExtendedHighestSequenceNumber() << std::endl;
			std::cout << "        Jitter:           " << RRinf.GetJitter() << std::endl;
			std::cout << "        LSR:              " << RRinf.GetLastSRTimestamp() << std::endl;
			std::cout << "        DLSR:             " << RRinf.GetDelaySinceLastSR() << std::endl;
			std::cout << "        Receive time:     " << RRinf.GetReceiveTime().GetSeconds() << std::endl;
		}
		else
		{
			std::cout << "    RR Info:" << std::endl;
			std::cout << "        Fraction lost:    " << RRinf.GetFractionLost() 
				  << " (" << RRprevinf.GetFractionLost() << ")" << std::endl;
			std::cout << "        Packets lost:     " << RRinf.GetPacketsLost() 
			          << " (" << RRprevinf.GetPacketsLost() << ")" << std::endl;
			std::cout << "        Ext.High.Seq:     " << RRinf.GetExtendedHighestSequenceNumber() 
			          << " (" << RRprevinf.GetExtendedHighestSequenceNumber() << ")" << std::endl;
			std::cout << "        Jitter:           " << RRinf.GetJitter() 
			          << " (" << RRprevinf.GetJitter() << ")" << std::endl;
			std::cout << "        LSR:              " << RRinf.GetLastSRTimestamp() 
			          << " (" << RRprevinf.GetLastSRTimestamp() << ")" << std::endl;
			std::cout << "        DLSR:             " << RRinf.GetDelaySinceLastSR() 
			          << " (" << RRprevinf.GetDelaySinceLastSR() << ")" << std::endl;
			std::cout << "        Receive time:     " << RRinf.GetReceiveTime().GetSeconds() 
			          << " (" << RRprevinf.GetReceiveTime().GetSeconds() <<")" << std::endl;
		}
	}
	std::cout << "    Stats:" << std::endl;
	std::cout << "        Sent data:        " << ((stats.HasSentData())?"Yes":"No") << std::endl;
	std::cout << "        Packets received: " << stats.GetNumPacketsReceived() << std::endl;
	std::cout << "        Seq. base:        " << stats.GetBaseSequenceNumber() << std::endl;
	std::cout << "        Ext.High.Seq:     " << stats.GetExtendedHighestSequenceNumber() << std::endl;
	std::cout << "        Jitter:           " << stats.GetJitter() << std::endl;
	std::cout << "        New packets:      " << stats.GetNumPacketsReceivedInInterval() << std::endl;	
	std::cout << "        Saved seq. nr.:   " << stats.GetSavedExtendedSequenceNumber() << std::endl;	
	std::cout << "        RTT:              " << INF_GetRoundtripTime().GetDouble() << " seconds" << std::endl;
	if (INF_GetEstimatedTimestampUnit() > 0)
		std::cout << "        Estimated:        " << (1.0/INF_GetEstimatedTimestampUnit()) << " samples per second" << std::endl;
	std::cout << "    SDES Info:" << std::endl;

	size_t len;
	char str[1024];
	uint8_t *val;
	
	if ((val = SDESinf.GetCNAME(&len)) != 0)
	{
		memcpy(str,val,len);
		str[len] = 0;
		std::cout << "        CNAME:            " << std::string(str) << std::endl;
	}
	if ((val = SDESinf.GetName(&len)) != 0)
	{
		memcpy(str,val,len);
		str[len] = 0;
		std::cout << "        Name:             " << std::string(str) << std::endl;
	}
	if ((val = SDESinf.GetEMail(&len)) != 0)
	{
		memcpy(str,val,len);
		str[len] = 0;
		std::cout << "        EMail:            " << std::string(str) << std::endl;
	}
	if ((val = SDESinf.GetPhone(&len)) != 0)
	{
		memcpy(str,val,len);
		str[len] = 0;
		std::cout << "        phone:            " << std::string(str) << std::endl;
	}
	if ((val = SDESinf.GetLocation(&len)) != 0)
	{
		memcpy(str,val,len);
		str[len] = 0;
		std::cout << "        Location:         " << std::string(str) << std::endl;
	}
	if ((val = SDESinf.GetTool(&len)) != 0)
	{
		memcpy(str,val,len);
		str[len] = 0;
		std::cout << "        Tool:             " << std::string(str) << std::endl;
	}	
	if ((val = SDESinf.GetNote(&len)) != 0)
	{
		memcpy(str,val,len);
		str[len] = 0;
		std::cout << "        Note:             " << std::string(str) << std::endl;
	}
#ifdef RTP_SUPPORT_SDESPRIV
	SDESinf.GotoFirstPrivateValue();
	uint8_t *pref;
	size_t preflen;
	while (SDESinf.GetNextPrivateValue(&pref,&preflen,&val,&len))
	{
		char prefstr[1024];
		memcpy(prefstr,pref,preflen);
		memcpy(str,val,len);
		prefstr[preflen] = 0;
		str[len] = 0;
		std::cout << "        Private:          " << std::string(prefstr) << ":" << std::string(str) << std::endl;
	}
#endif // RTP_SUPPORT_SDESPRIV
	if (byereason)
	{
		memcpy(str,byereason,byereasonlen);
		str[byereasonlen] = 0;
		std::cout << "    BYE Reason:           " << std::string(str) << std::endl;
	}
}

#endif // RTPDEBUG

} // end namespace