demuxer.cpp 10.3 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
/*******************************************************}
{                                                       }
{       File: demuxer.cpp                               }
{       Created by Tsviatko Jongov                      }
{       http://tsviatko.jongov.com                      }
{       Date : 25.01.2007                               }
{                                                       }
{       CMpeg2Demux class.                              }
{                                                       }
{*******************************************************/
#include "assert.h"
#include <stdio.h>
#include "demuxer.h"
#include "Pack_Header_Def.h"
#include "time.h"

#include <chrono>

#ifdef _WIN32
#include "Winsock2.h"
#pragma comment(lib, "ws2_32.lib")
#endif
#ifdef __linux__
#include "arpa/inet.h"
#endif

using namespace std;


static /*_inline*/ unsigned int asm_swap32(unsigned int x)
{
	return ntohl(x);
}

static /*_inline*/ unsigned short asm_swap16(unsigned short x) 
{
	return ntohs(x);
}

CMpeg2Demux::CMpeg2Demux()
: m_streamType(STREAM_TYPE_UNKNOWN)
,m_userdata(NULL)
,m_userdata2(NULL)
,m_lastiskeyfram(false)
{
	try
	{
		fBuffer = new CBuffer(1024 * 1024); 
		if (fBuffer == NULL)
		{
		}
		m_lastpts = 0;
		fReceiveFunction = 0;
		fReceiveFunction2 = 0;

		m_psvideo= new CBuffer(1024*50);
		m_esvideo= new CBuffer(1024*50);
		m_psaudio= new CBuffer(1024*50);
		m_esaudio= new CBuffer(1024*50);
	}
	catch (...)
	{
	}
};

CMpeg2Demux::~CMpeg2Demux()
{
	try
	{
		if (fBuffer != NULL)
		{	
			delete fBuffer;
			fBuffer = NULL;
		}

		if (NULL != m_psvideo)
		{
			delete m_psvideo;
			m_psvideo = NULL;
		}
		if (NULL != m_esvideo)
		{
			delete m_esvideo;
			m_esvideo = NULL;
		}
		if (NULL != m_psaudio)
		{
			delete m_psaudio;
			m_psaudio = NULL;
		}
		if (NULL != m_esaudio)
		{
			delete m_esaudio;
			m_esaudio = NULL;
		}
	}
	catch (...)
	{		
	}
};

int CMpeg2Demux::AddData(void * Data, int Size/*, DWORD pts*/)
{
	try
	{
		if ((Data == NULL) || (Size <= 0))
		{		
			return (-1);
		}

		/*m_timeStamp = pts;*/
		fBuffer->add((char *)Data, Size);
		if (!Demultiplex())
		{	
			return (-1);
		}

		return (0);	
	}
	catch (...)
	{			
		return (-1);
	}
}

void CMpeg2Demux::SetReceiveFunction(ReceiveFunction * func, void* userdata)
{	 
	try
	{	
		fReceiveFunction = func;
		m_userdata       = userdata;
	}
	catch (...)
	{		
	}
}

void CMpeg2Demux::SetReceiveFunction2(ReceiveFunction2 * func2, void* userdata2)
{
	fReceiveFunction2 = func2;
	m_userdata2       = userdata2;
}

uint64_t  GetLocalTimeOfMicroSecond()
{
	chrono::time_point<chrono::system_clock, chrono::microseconds> tpMicro
		= chrono::time_point_cast<chrono::microseconds>(chrono::system_clock::now());

	return tpMicro.time_since_epoch().count();
}

int CMpeg2Demux::Demultiplex()
{
	try
	{
    	unsigned char * PDW {};
    	unsigned int Code {};
		int Processed = 0;
    	int StreamID {};
    	int PES_packet_length {};
    	int PES_header_data_length {};
    	int Val {};

		if (fBuffer->len() <= 0)
		{
			return (0);
		}
		 
		PDW = (unsigned char *)fBuffer->head();
		while (fBuffer->len() - Processed > 140)
		{
			if ((*(unsigned int *)PDW & 0x00FFFFFF) != 0x00010000)
			{
				PDW++;
				Processed++;
				continue;
			}

			Code = asm_swap32(*(unsigned int *)PDW);
			StreamID = (Code & 0xFF);
			if (PACK_START_CODE != Code)
			{
				unsigned short pespacklen = asm_swap16(*(unsigned short *)(PDW + 4)) + 6;
				if (fBuffer->len() - Processed < pespacklen + 6)
				{
					break;
				}
			}

			if (PACK_START_CODE == Code)//前一个pspack完或下一个pspack开始
			{
				if (fReceiveFunction != NULL && m_esvideo->len())//视频es
				{
					PS_HEADER_tag* pshead = (PS_HEADER_tag*)m_psvideo->head();
					uint64_t pts = 0;
					pshead->getSystem_clock_reference_base(pts);
					pts = pts/90;
					int64_t localPts = GetLocalTimeOfMicroSecond();
					fReceiveFunction(m_streamType, m_esvideo->head(), m_esvideo->len(), pts, localPts, m_lastiskeyfram, m_userdata);
				}
				m_esvideo->fFirst = m_esvideo->len();
				m_esvideo->compact();

				if (fReceiveFunction != NULL && m_esaudio->len())//音频es
				{
					int64_t localPts = GetLocalTimeOfMicroSecond();
					fReceiveFunction(0xC0, m_esaudio->head(), m_esaudio->len(), m_lastpts, localPts, 0, m_userdata);
				}
				m_esaudio->fFirst = m_esaudio->len();
				m_esaudio->compact();

				if (fReceiveFunction2 != NULL && m_psvideo->len())//视频ps
				{
					fReceiveFunction2(STREAM_TYPE_VIDEO,m_psvideo->head(),m_psvideo->len(),m_lastpts,m_lastiskeyfram,m_userdata2);
				}
				m_psvideo->fFirst = m_psvideo->len();
				m_psvideo->compact();

				if (fReceiveFunction2 != NULL && m_psaudio->len())//音频
				{
					fReceiveFunction2(STREAM_TYPE_AUDIO,m_psaudio->head(),m_psaudio->len(),m_lastpts,0,m_userdata2);
				}
				m_psaudio->fFirst = m_psaudio->len();
				m_psaudio->compact();

				PS_HEADER_tag* ppshead = (PS_HEADER_tag*)PDW;
				unsigned long psheadlen = sizeof(PS_HEADER_tag) + ppshead->pack_stuffing_length;
				if (fBuffer->len() - Processed < (int)psheadlen)
				{
					break;
				}

				//
				m_lastiskeyfram = false;
				if ((*(unsigned int *)(PDW+psheadlen)&0x00FFFFFF) != 0x00010000)
				{
				}
				else
				{
					m_psvideo->add((char*)PDW,psheadlen);//ps头写入视频数据中
					PDW += psheadlen;
					Processed += psheadlen;
					continue;
				}
			}
			else if (SYSTEM_START_CODE == Code)//system_header
			{
				unsigned short pespacklen = asm_swap16(*(unsigned short *)(PDW + 4)) + 6;
				if ((*(unsigned int *)(PDW+pespacklen)&0x00FFFFFF) != 0x00010000)
				{
					printf("SYSTEM_START_CODE: Warning in CMpeg2Demux::Demultiplex - ((*PDW & 0x00FFFFFF) != 0x00010000).\n");
				}
				else
				{
					m_psvideo->add((char*)PDW,pespacklen);//ps头写入视频数据中
					PDW += pespacklen;
					Processed +=pespacklen;
					m_lastiskeyfram = true;
					continue;
				}
			}
			else if (PROGRAM_STREAM_MAP == StreamID)//psm
			{
				unsigned short pespacklen = asm_swap16(*(unsigned short *)(PDW + 4)) + 6;
				if ((*(unsigned int *)(PDW+pespacklen)&0x00FFFFFF) != 0x00010000)
				{
				}
				else
				{
					unsigned short program_stream_info_length;
					//unsigned short elementary_stream_map_length;
					unsigned short* plen = (unsigned short*)(PDW + 8);
					program_stream_info_length = ntohs(*plen);
					int test = *(PDW + 8 + program_stream_info_length + 5);//192
					//assert(*(PDW+8+program_stream_info_length+5) == 0xe0);

					//if(*(PDW + 8 + program_stream_info_length + 5) != 0xe0)
					//{
					//	continue;
					//}
					//printf("0xe0=%d, 0x1b=%d\n", *(PDW + 8 + program_stream_info_length + 5), *(PDW + 8 + program_stream_info_length + 4));
					if (m_pserror > 5 && (*(PDW + 8 + program_stream_info_length + 5) != 0xe0 && *(PDW + 8 + program_stream_info_length + 5) != 0xc0))//判断c0是为了兼容枢纽引擎名叫博士的垃圾小厂家
					{
						printf("--------------------------------2 error:{%d}\n", m_pserror);
						return -1;
					}
					if (*(PDW + 8 + program_stream_info_length + 5) != 0xe0 && *(PDW + 8 + program_stream_info_length + 5) != 0xc0)
					{
						//printf("--------------------------------1\n");
						++m_pserror;
						continue;
					}
					m_lastiskeyfram = true;
					if (*(PDW + 8 + program_stream_info_length + 4) == 0x1b || *(PDW + 8 + program_stream_info_length + 4) == 0x03)
					{
						m_streamType = VIDEO_TYPE_H264; // H264
					}
					else if (*(PDW + 8 + program_stream_info_length + 4) == 0x24)
					{
						m_streamType = VIDEO_TYPE_H265; // H265
					}
					else if (*(PDW+8+program_stream_info_length+4) == 0x10)
					{
						m_streamType = VIDEO_TYPE_MPEG4; // MPEG4
					}
					else
					{
						m_streamType = STREAM_TYPE_UNKNOWN;
					}
					m_pserror = 0;
					m_psvideo->add((char*)PDW,pespacklen);//ps头写入视频数据中
					PDW += pespacklen;
					Processed +=pespacklen;
					continue;
				}
			}
			else if (0xBD == StreamID)//私有数据
			{
				unsigned short pespacklen = asm_swap16(*(unsigned short *)(PDW + 4)) + 6;

				if ((*(unsigned int *)(PDW+pespacklen)&0x00FFFFFF) != 0x00010000)
				{
				}
				else
				{
					m_psvideo->add((char*)PDW,pespacklen);//ps头写入视频数据中
					PDW += pespacklen;
					Processed +=pespacklen;
					continue;
				}
			}

			if ((Code >= SYSTEM_START_CODE_MIN) &&
				(Code <= SYSTEM_START_CODE_MAX) &&
				(Code != PACK_START_CODE) &&
				(Code != SYSTEM_START_CODE) &&
				(StreamID != PROGRAM_STREAM_MAP) &&
				(StreamID != PADDING_STREAM) &&
				(StreamID != PRIVATE_STREAM_2) &&
				(StreamID != ECM_STREAM) &&
				(StreamID != EMM_STREAM) &&
				(StreamID != PROGRAM_STREAM_DIRECTORY) &&
				(StreamID != DSM_CC_STREAM) &&
				(StreamID != ITU_T_STREAM_E))
			{
				PES_packet_length = asm_swap16(*(unsigned short *)(PDW + 4));
				PES_header_data_length = *(PDW + 8);

				if (PES_packet_length == 0)
					PES_packet_length = fBuffer->len() - Processed/* - 4*/;
				else
					PES_packet_length += 6;

				if (fBuffer->len() - Processed >= PES_packet_length/* + 4*/)
				{
					PES_HEADER_tag* peshead = (PES_HEADER_tag*)PDW;
					uint64_t pts = 0;
					if (peshead->PTS_DTS_flags&0x3)
					{
						PTS_tag* ptstag = (PTS_tag*)(PDW + 9);
						ptstag->getPTS(pts);
						m_lastpts = pts/90;
					}

					Val = 6 + 3 + PES_header_data_length;

					if (0xE0 == StreamID)
					{
						m_esvideo->add((char*)PDW + Val, PES_packet_length - Val);
						m_psvideo->add((char*)PDW, PES_packet_length);
					}
					else if (0xC0 == StreamID)
					{
						if (PES_packet_length + 6 - Val > 0)
						{
							m_esaudio->add((char*)PDW + Val,PES_packet_length - Val);
						}
						else
						{
							m_esaudio->add((char*)PDW + Val,PES_packet_length - 19);
						}
						m_psaudio->add((char*)PDW,PES_packet_length+6);
					}

					fBuffer->fFirst += Processed + PES_packet_length;
					fBuffer->compact();

					Processed = 0;
					PDW = (unsigned char *)fBuffer->head();
				}
				else
				{
					break;
				}
			}
			else {
				PDW++;
				Processed++;
			}
		};

		if (Processed)
		{
           fBuffer->fFirst += Processed;
		   fBuffer->compact();
		   Processed = 0;
		}
		return (true);
	}
	catch (...)
	{
		return (-1);
	}
}