void H264MediaSubsession::startStream(unsigned clientSessionId,
						void* streamToken,
						TaskFunc* rtcpRRHandler,
						void* rtcpRRHandlerClientData,
						unsigned short& rtpSeqNum,
						unsigned& rtpTimestamp,
						ServerRequestAlternativeByteHandler* serverRequestAlternativeByteHandler,
						void* serverRequestAlternativeByteHandlerClientData) {
	Log("-----[%d] %s .... calling\n", gettid(), __func__);
	DestinationTable::iterator it = fDestinationsHashTable.find(clientSessionId);
	if (it==fDestinationsHashTable.end())
	{
		Log("Rtsp session %u not found\n", clientSessionId);
		return;
	}
	MyDestinations* destinations = it->second;
	char* dest_addr = NULL;
	if(destinations != NULL)
	{
		dest_addr =  inet_ntoa(destinations->addr);
		Log("-----Session destionation is %s:%d\n", dest_addr, ntohs(destinations->rtpPort.num()));
	}

	VideoCodec::RTPMap rtpMap;
	rtpMap[rtpPayloadType] = m_Watcher->GetVideoCodec();
	//video.StartSending(clientSessionId,dest_addr,ntohs(destinations->rtpPort.num()),rtpMap);
	RTPSession *rtp = m_Watcher->StartSendingVideo(clientSessionId,dest_addr,ntohs(destinations->rtpPort.num()),rtpMap);
	rtp->SetRtcpRRHandler(rtcpRRHandler, rtcpRRHandlerClientData);
}
RTPSession *AudioStream::AddAudioWatcher(unsigned clientSessionId,char *sendAudioIp,int sendAudioPort,AudioCodec::RTPMap& rtpMap, AudioCodec::Type watcherCodec)
{
    Log(">Add Audio Watcher[%u, %s,%d]\n",clientSessionId, sendAudioIp,sendAudioPort);

    //Si tenemos video
    if (sendAudioPort==0) {
        Error("No video\n");
        return NULL;
    }

    Rtps::iterator it = rtps.find(clientSessionId);

    RTPSession* rtp = NULL;
    //Si no esta
    if (it == rtps.end()) {
        Error("Rtp not init\n");
        return NULL;
    }
    rtp = (*it).second;

    if(!rtp->Init())
    {
        delete rtp;
        Error("Rtp init error\n");
        return NULL;
    }


    //Iniciamos las sesiones rtp de envio
    if(!rtp->SetRemotePort(sendAudioIp,sendAudioPort))
    {
        delete rtp;
        Error("Rtp SetRemotePort error\n");
        return NULL;
    }

    rtp->SetSendingAudioRTPMap(rtpMap);

    //Set video codec
    if(!rtp->SetSendingAudioCodec(watcherCodec))
    {
        delete rtp;
        //Error
        Error("%s video codec not supported by peer\n",AudioCodec::GetNameFor(watcherCodec));
        return NULL;
    }

    rtps[clientSessionId] = rtp;

    //LOgeamos
    Log("<Add Audio Watcher success [%u]\n",clientSessionId);

    return rtp;
}
void CSenderDlg::OnSend() 
{
	CFileDialog  dlg(TRUE, NULL, NULL, OFN_HIDEREADONLY | OFN_OVERWRITEPROMPT, 
			"(*.*)|*.*|", NULL);
	if (dlg.DoModal() == IDOK)
	{
		m_SourceFile = dlg.GetPathName();	
	}
	source=fopen(m_SourceFile,"rb");
	if ( source == NULL )
	{
		AfxMessageBox("can't access the file");
	}
//#ifdef win32
 	
//#endif	
	size_t bufRead  = 0;
	Mark=true;
	BYTE buffer[bufsize];
	int t;
	
	
	t=sess.Create(5800);
	if(t!=0)AfxMessageBox("can't create");
	if(t==0){sen=true;}
	sess.SetMulticastTTL(1);	//設定multicast封包TTL
	sess.AddDestination(ntohl(inet_addr("127.0.0.1")),6900);	//指定傳送目的端
	//sess.AddDestination(ntohl(inet_addr("192.168.25.79")),6900);
	if(t!=0)AfxMessageBox("can't add destination");
	(void) fseek( source, 0, SEEK_SET );
		while(!feof(source))
		{
			bufRead = fread(buffer, sizeof(BYTE), bufsize, source ); 
			nPT=rand()%64+1;		
			nTSTAMP=rand()%1000+1;	

			//g_ACode.EncodeAudioData ((char*)buffer,bufsize,m_cBufOut,&iOut);
			//t=sess.SendPacket(m_cBufOut,iOut,nPT,Mark,nTSTAMP);	
			
			t=sess.SendPacket(buffer,bufsize,nPT,Mark,nTSTAMP);	
		    if(t!=0)AfxMessageBox("can't sending");
			Sleep(5);
			Mark=false;			
		}
		(void) fflush( source ); 
		(void) fclose( source ); 
		AfxMessageBox("send success");
	WSACleanup();
	
}
Beispiel #4
0
void* startsound(void *_ca)
{
	FILE *source=fopen("c://12pcm.wav","rb");
	if ( source == NULL )
	{
		cout<<"can't access the file"<<endl;
	}
//#ifdef win32
 	
//#endif	
	size_t bufRead  = 0;
	bool Mark=true;
	#define bufsize 1024
	BYTE buffer[bufsize];
	int t;
	RTPSession sess;
	
	t=sess.Create(5800);
	if(t!=0)cout<<"can't create"<<endl;
	bool sen;
	if(t==0){sen=true;}
	int nPT ;
	int nTSTAMP;
	sess.SetMulticastTTL(1);	//設定multicast封包TTL
	sess.AddDestination(ntohl(inet_addr("192.168.3.190")),portt);	//指定傳送目的端
	//sess.AddDestination(ntohl(inet_addr("192.168.25.79")),6900);
	if(t!=0) cout<<"can't add destination"<<endl;
	for (int jj=0;j<1000;j++) 
	{
	
	(void) fseek( source, 0, SEEK_SET );
		while(!feof(source))
		{
			bufRead = fread(buffer, sizeof(BYTE), bufsize, source ); 
			nPT=rand()%64+1;		
			nTSTAMP=rand()%1000+1;	
			t=sess.SendPacket(buffer,bufsize,nPT,Mark,nTSTAMP);	
		    if(t!=0)cout<<"can't sending"<<endl;
			Sleep(5);
			Mark=false;			
		}
	}
		(void) fflush( source ); 
		(void) fclose( source ); 
		cout<<("send success")<<endl;
	WSACleanup();
	return NULL;
}
Beispiel #5
0
/***********************************************************************************************************
**函数:Rtp_Lock
**功能:
**输入参数:
**返回值:
***********************************************************************************************************/
static int  RtpSetup( uint16_t portbase)
{
    int status;
	
    RTPUDPv4TransmissionParams transparams;
    RTPSessionParams sessparams;
    sessparams.SetOwnTimestampUnit(1.0/90000.0);
    sessparams.SetMaximumPacketSize(1200);
    transparams.SetPortbase(portbase);
    sess.SetDefaultPayloadType(PLOAD_TYPE);
    sess.SetDefaultMark(false);
    sess.SetDefaultTimestampIncrement(DefaultTimestampIncrement);
    status = sess.Create(sessparams,&transparams);
    checkerror(status);
    return status;
}
Beispiel #6
0
/***********************************************************************************************************
**函数:Rtp_Lock
**功能:
**输入参数:
**返回值:
***********************************************************************************************************/
static int SimpleRtpIsActive(void)
{
    int ret=false;
    Rtp_Lock();
    ret=sess.IsActive();
    Rtp_UnLock();
    return ret;
}
Beispiel #7
0
// Create a new RTP session.  If multicast is not being used then multicastIP
// should be set to an empty string.
static RTPSession createRtpSession(const std::string& multicastIP, 
                                   unsigned int port)
{
    RTPSession session;

    //if (setenv("LOGNAME", "video", 0) != 0) {
    //    throw std::runtime_error("Error setting LOGNAME environment variable");
    //}

    // Set up session params
    RTPSessionParams sessionparams;
    sessionparams.SetUsePollThread(false);
    sessionparams.SetMaximumPacketSize(1400);
    sessionparams.SetAcceptOwnPackets(true);
    sessionparams.SetOwnTimestampUnit(1.0f/900000.0f);
    sessionparams.SetResolveLocalHostname(false); 
    sessionparams.SetSessionBandwidth(9000000);
    sessionparams.SetReceiveMode(RTPTransmitter::AcceptAll);

    RTPUDPv4TransmissionParams transparams;
    transparams.SetPortbase(port);

    int status = session.Create(sessionparams, &transparams);
    if (status < 0) {
        throw std::runtime_error("Error creating RTP session");
    }

    // Join multicast groups if they are specified
    if (multicastIP.size() > 0) {
        if (!session.SupportsMulticasting()) {
            throw std::runtime_error("Multicast not supported!");
        } else {
            int joinip = ntohl(inet_addr(multicastIP.c_str())); 

            RTPIPv4Address joinaddr(joinip, port);
            int jstatus = session.JoinMulticastGroup(joinaddr);

            if (jstatus < 0) {
                throw std::runtime_error("Unable to join multicast group");
            }
        }
    }

    return session;
}
Beispiel #8
0
void* QTSSCallbacks::Easy_GetRTSPPushSessions()
{
	OSRefTable* reflectorSessionMap = QTSServerInterface::GetServer()->GetReflectorSessionMap();

	EasyMsgSCRTSPPushSessionListACK ack;
	ack.SetHeaderValue(EASY_TAG_VERSION, "1.0");
	ack.SetHeaderValue(EASY_TAG_CSEQ, "1");

	UInt32 uIndex= 0;
	OSMutexLocker locker(reflectorSessionMap->GetMutex());

	for (OSRefHashTableIter theIter(reflectorSessionMap->GetHashTable()); !theIter.IsDone(); theIter.Next())
	{
		OSRef* theRef = theIter.GetCurrent();
		ReflectorSession* theSession = (ReflectorSession*)theRef->GetObject();

		EasyDarwinRTSPSession session;
		session.index = uIndex;
		char* fullRequestURL = NULL;

		RTPSession* clientSession = (RTPSession*) theSession->GetBroadcasterSession();

		if(clientSession == NULL) continue;

		clientSession->GetValueAsString(qtssCliSesFullURL,0,&fullRequestURL);
		session.Url = fullRequestURL;
		session.Name = theSession->GetSessionName();
		session.numOutputs = theSession->GetNumOutputs();
		ack.AddSession(session);
		uIndex++;
	}  

	char count[16] = { 0 };
	sprintf(count,"%d", uIndex);
	ack.SetBodyValue(EASY_TAG_SESSION_COUNT, count);

	string msg = ack.GetMsg();

	UInt32 theMsgLen = strlen(msg.c_str());
	char* retMsg = new char[theMsgLen+1];
	retMsg[theMsgLen] = '\0';
	strncpy(retMsg, msg.c_str(), strlen(msg.c_str()));
	return (void*)retMsg;
}
void CSenderDlg::OnClose() 
{
	if(sen)
	{sess.Destroy();
		sen=false;
	}
	WSACleanup();
	OnOK();
	
}
void H264MediaSubsession::getStreamParameters(unsigned clientSessionId,
		      netAddressBits clientAddress,
		      Port const& clientRTPPort,
		      Port const& clientRTCPPort,
		      int tcpSocketNum,
		      unsigned char rtpChannelId,
		      unsigned char rtcpChannelId,
		      netAddressBits& destinationAddress,
		      u_int8_t& destinationTTL,
		      Boolean& isMulticast,
		      Port& serverRTPPort,
		      Port& serverRTCPPort,
		      void*& streamToken) {
	MyOnDemandMediaSubsession::getStreamParameters(clientSessionId,clientAddress,clientRTPPort,clientRTCPPort,tcpSocketNum,rtpChannelId,rtcpChannelId,destinationAddress,destinationTTL,isMulticast,serverRTPPort,serverRTCPPort,streamToken);
	RTPSession *rtp = m_Watcher->StartRecvingVideoRtcp(clientSessionId);
	serverRTPPort = rtp->GetLocalPort();
	serverRTCPPort = rtp->GetLocalPort() + 1;
	Log("-----%u:[%d] %s .... calling\n", clientSessionId, gettid(), __func__);
}
Beispiel #11
0
/***********************************************************************************************************
**函数:SimpleGetRtpPoll
**功能:
**输入参数:
**返回值:
***********************************************************************************************************/
int SimpleGetRtpPoll(void)
{
    int status;
    if(SimpleRtpIsActive()!=true)
    {
        return -1;
    }
    status = sess.Poll();
    checkerror(status);
    return status;
}
Beispiel #12
0
/***********************************************************************************************************
**函数:SimpleSetDefaultPayloadType
**功能:
**输入参数:
**返回值:
***********************************************************************************************************/
int SimpleSetDefaultPayloadType(uint8_t pt)
{
    if(SimpleRtpIsActive()!=true)
    {
        printf("rtp Session is error,%s ,%d\n",__FUNCTION__, __LINE__);
        return -1;
    }
    Rtp_Lock();
    sess.SetDefaultPayloadType(pt);
    Rtp_UnLock();
    return 0;
}
Beispiel #13
0
/***********************************************************************************************************
**函数:Rtp_Lock
**功能:
**输入参数:
**返回值:
***********************************************************************************************************/
int SimpleDeleteDestination(uint32_t ipaddr,uint16_t port)
{
    if(SimpleRtpIsActive()!=true)
    {
        printf("rtp Session is error,%s ,%d\n",__FUNCTION__, __LINE__);
        return -1;
    }
    Rtp_Lock();
    sess.DeleteDestination(ipaddr,port);
    Rtp_UnLock();
    return 0;
}
Beispiel #14
0
/***********************************************************************************************************
**函数:SimpleClearDestinations
**功能:
**输入参数:
**返回值:
***********************************************************************************************************/
int SimpleClearDestinations(void)
{
    if(SimpleRtpIsActive()!=true)
    {
        printf("rtp Session is error,%s ,%d\n",__FUNCTION__, __LINE__);
        return -1;
    }
    Rtp_Lock();
    sess.ClearDestinations();
    Rtp_UnLock();
    return 0;
}
Beispiel #15
0
/***********************************************************************************************************
**函数:SimpleIncrementTimestampDefault
**功能:
**输入参数:
**返回值:
***********************************************************************************************************/
int SimpleIncrementTimestampDefault()
{
    if(SimpleRtpIsActive()!=true)
    {
        printf("rtp Session  is error,%s ,%d\n",__FUNCTION__, __LINE__);
        return -1;
    }

    Rtp_Lock();
    sess.IncrementTimestampDefault();
    Rtp_UnLock();
    return 0;
}
int AudioStream::DeleteAudioWatcher(unsigned clientSessionId)
{
    Log(">DeleteAudioWatcher [%u]\n",clientSessionId);

    //El iterator
    Rtps::iterator it = rtps.find(clientSessionId);

    //Si no esta
    if (it == rtps.end())
        return Error("Rtps not found\n");

    RTPSession* rtp = (*it).second;

    rtps.erase(it);

    rtp->End();

    delete rtp;

    Log(">DeleteAudioWatcher [%u] success\n",clientSessionId);

    return 1;
}
Beispiel #17
0
/***********************************************************************************************************
**函数:Rtp_Lock
**功能:
**输入参数:
**返回值:
***********************************************************************************************************/
int SimpleAddDestination(uint32_t ipaddr, uint16_t destport)
{
    int status;
    if(SimpleRtpIsActive()!=true)
    {
        printf("rtp Session is error,%s ,%d\n",__FUNCTION__, __LINE__);
        return -1;
    }
    Rtp_Lock();
    RTPIPv4Address addr(ipaddr,destport);
    status = sess.AddDestination(addr);
    checkerror(status);
    Rtp_UnLock();
    return status;
}
void Java_cn_nickwar_MainActivity_nativeWorker(JNIEnv* env, jobject obj) {
	uint16_t portbase=8000,destport=9000;
	std::string ipstr="192.168.1.102";
	uint32_t destip=inet_addr(ipstr.c_str());
	int status,i,num;

	RTPSession session;
	RTPSessionParams sessionparams;
	RTPUDPv4TransmissionParams transparams;
	RTPIPv4Address addr;

	if (destip == INADDR_NONE) {
		__android_log_print(ANDROID_LOG_DEBUG, "pspm.native", "Bad IP address specified");
	}

	destip = ntohl(destip);

	num = 40;

	sessionparams.SetOwnTimestampUnit(1.0/10.0);
	sessionparams.SetAcceptOwnPackets(true);

	transparams.SetPortbase(portbase);

	addr.SetIP(destip);
	addr.SetPort(destport);

	status = session.Create(sessionparams,&transparams);

	if (status<0) {
		std::string tmp = "Create:";
		__android_log_print(ANDROID_LOG_DEBUG, "pspm.native", (tmp+RTPGetErrorString(status)).c_str());
	}
	status = session.AddDestination(addr);
	if (status<0) {
		std::string tmp = "AddDestination:";
		__android_log_print(ANDROID_LOG_DEBUG, "pspm.native", (tmp+RTPGetErrorString(status)).c_str());
	}

	while(!m_bExitApp)
	{
		session.BeginDataAccess();

		unsigned char *buff = NULL;
		if (session.GotoFirstSourceWithData())
		{
			do
			{
				RTPPacket *pack;
				while((pack = session.GetNextPacket()) !=NULL)
				{
					__android_log_print(ANDROID_LOG_DEBUG, "pspm.native", "got packet!\n");
					char message[26];
					sprintf(message, "got packet");
					jstring messageString = env->NewStringUTF(message);
					env->CallVoidMethod(obj, rtpresultFromJNI, messageString);

					if (NULL != env->ExceptionOccurred()) {
						//						break;
						continue;
					}
					if (pack->GetPayloadLength()>0) {
						buff = pack->GetPayloadData();
						__android_log_print(ANDROID_LOG_DEBUG, "pspm.native", "packt data:%s",buff);
					}
					session.DeletePacket(pack);
				}
			}
			while(session.GotoNextSourceWithData());
		}

		session.EndDataAccess();
		//
#ifndef RTP_SUPPORT_THREAD
		status = sess.Poll();
		if (status<0) {
			session.Destroy();
			return;
		}
#endif

		RTPTime::Wait(RTPTime(0,5000));
	}

	session.Destroy();
	return;
}
Beispiel #19
0
int main(int argc, char ** argv)
{
        
        uint16_t portbase,destport;
        uint32_t destip;  
        std:string ipstr;  //get the destiny ip from the std input stream
        
     //   NALU_t *n;


        printf("Please Enter:./test   framenum(500)\n");
        if(argc!=2)
        {
                printf("Please Enter:./test   framenum\n");
                exit(EXIT_FAILURE);
        }

        //dev_name=argv[1];

        frame_num=atoi(argv[1]);    //convert a string to an integer
        if(!frame_num)
                {
                        printf("frame_num should be over 0 frame\n");
                        exit(EXIT_FAILURE);
                }

        // @0506 here ,there is no need to test YUYV | YUV420 | tmpH264 , for Module Test        
        //openFiles();

//*****************************************************************************        

//****************** the capturing process *****************start*********
                printf("capture video begin\n");
        open_device();
        init_device();
        start_capturing();
        //fp = fopen(filename, "wa+"); //yuv422

        // ***********
        //alloc_image();
        //  ***********

        // ***********
        //open_x264file("test420.yuv");
        init_encoder();
        init_picture(yuv_size_2);
        //  ***********
        portbase = 33334;
        destport = 9000;
        //ipstr = "222.197.174.76";
        // @ 1204 change the ip to the LAN IP
        //ipstr = "202.115.11.128";
        ipstr = "192.168.5.155";
        destip = inet_addr(ipstr.c_str()); 
        //destip = ntohl(destip); ///************** very important **************
        destip = htonl(destip);

//********************** get the rtp parameter from std input stream ****above ***
        // @2 Setting basic parameter ----------------------------------
        RTPUDPv4TransmissionParams transparams;
        transparams.SetPortbase(portbase);


        RTPSessionParams sessparams;
        sessparams.SetOwnTimestampUnit(1.0/90000.0);

        status=sess.Create(sessparams,&transparams);
        checkerror(status);

        RTPIPv4Address addr(destip,destport);

        status = sess.AddDestination(addr);
        checkerror(status);

        sess.SetDefaultPayloadType(96);
        sess.SetDefaultMark(false);
        sess.SetDefaultTimestampIncrement(90000.0/10.0);  // frame rate control 10 / 25

        RTPTime delay(0.040);//RTPTime delay(0.040)
        //RTPTime::Wait(delay);
        RTPTime starttime=RTPTime::CurrentTime();

//         //  @3.0    Preparation for sending  NALU package----------------------------------------------------
//         char sendbuf[1500];
//         char *nalu_payload;
//         int size=0;
//         unsigned int timestamp_increase=0,ts_current=0;
//         OpenBitstreamFile("test.h264");

//         n=AllocNALU(8000000);// alloc memory for the <struct NALU>  n->maxSize = 8_000_000 = 8 MB
//         int start=false;

//         //****************************************************************

        mainloop(frame_num);   // **** capture frame *****
       // fclose(fp);
        stop_capturing();
        uninit_device();
        close_device();


        close_encoder();


                printf("capture video is over\n");
//****************** the capturing process ********************end ******


//****************** x264 encode ******************************* start ***
        // open_yuvfile(filename);
        // alloc_image();
        // swscale_start();     // ******  yuv422 -> I420 *******
        // swscale_close();

        // open_x264file(dst_filename);
        // init_encoder();
        // init_picture(yuv_size);
        // encode_frame();      // **** encode x264 format ***
        // close_encoder();
//****************** x264 encode ******************************* end ***

        /////---------------------------------------------------------------------------------------------------
                printf("encode x264 video is over\n");
                printf("Wait to jrtpsend....\n");


//******************  RTP send *********************** start **********
       // @1  Getting basic parameter -------------------------------
        // std::cout<<"Enter local portbase:"<<std::endl;
        // std::cin>>portbase;
        // std::cout<<std::endl;

        // std::cout << "Enter the destination IP address" << std::endl;
        // std::cin >> ipstr;
        // destip = inet_addr(ipstr.c_str());
        // if (destip == INADDR_NONE)
        // {
        //         std::cerr << "Bad IP address specified" << std::endl;
        //         return -1;
        // }
        // destip = ntohl(destip);

        // std::cout << "Enter the destination port" << std::endl;
        // std::cin >> destport;

//         portbase = 33333;
//         destport = 55555;
//         ipstr = "222.197.174.76";
//         destip = inet_addr(ipstr.c_str()); 

// //********************** get the rtp parameter from std input stream ****above ***
//         // @2 Setting basic parameter ----------------------------------
//         RTPUDPv4TransmissionParams transparams;
//         transparams.SetPortbase(portbase);


//         RTPSessionParams sessparams;
//         sessparams.SetOwnTimestampUnit(1.0/90000.0);

//         status=sess.Create(sessparams,&transparams);
//         checkerror(status);

//         RTPIPv4Address addr(destip,destport);

//         status = sess.AddDestination(addr);
//         checkerror(status);

//         sess.SetDefaultPayloadType(96);
//         sess.SetDefaultMark(false);
//         sess.SetDefaultTimestampIncrement(90000.0/10.0);

//         RTPTime delay(0.030);//RTPTime delay(0.040)
//         //RTPTime::Wait(delay);
//         RTPTime starttime=RTPTime::CurrentTime();

//         //  @3.0    Preparation for sending  NALU package----------------------------------------------------
//         char sendbuf[1500];
//         char *nalu_payload;
//         int size=0;
//         unsigned int timestamp_increase=0,ts_current=0;
//         OpenBitstreamFile("test.h264");

//         n=AllocNALU(8000000);// alloc memory for the <struct NALU>  n->maxSize = 8_000_000 = 8 MB
//         int start=false;
        //  NALU packages sending loop  ----------------------------------- 
        // while(!feof(bits))
        // {	
        //         size=GetAnnexbNALU(n);    // having original souce for this function
        //         if(size<4)
        //         {
        //                 printf("get nalu error!\n");
        //                 continue;
        //         }
        //         printf("size:%d\n",size);

        //         dump(n);
        //         if(!start)
        //         {
        //                  if(n->nal_unit_type==1||n->nal_unit_type==5||n->nal_unit_type==6||n->nal_unit_type==7)
        //                 {
        //                         printf("begin\n");
        //                         start=true;
        //                 }

        //         }

        //         if(n->len <= MAX_RTP_PKT_LENGTH)
        //         {
        //                 nalu_hdr=(NALU_HEADER *)&sendbuf[0];
        //                 nalu_hdr->F=n->forbidden_bit;
        //                 nalu_hdr->NRI=n->nal_reference_idc>>5;
        //                 nalu_hdr->TYPE=n->nal_unit_type;

        //                 nalu_payload=&sendbuf[1];
        //                 memcpy(nalu_payload,n->buf+1,n->len-1);
        //                 ts_current=ts_current+timestamp_increase;

        //                 if(n->nal_unit_type==1||n->nal_unit_type==5)
        //                 {
        //                         status=sess.SendPacket((void *)sendbuf,n->len,96,true,3600);
        //                 }

        //                 else
        //                 {
        //                         status=sess.SendPacket((void *)sendbuf,n->len,96,true,0);
        //                         continue;
        //                 }
        //                 checkerror(status);
        //         }

        //         else if(n->len > MAX_RTP_PKT_LENGTH)
        //         {
        //                 int k=0,l=0;
        //                 k=n->len/MAX_RTP_PKT_LENGTH;
        //                 l=n->len%MAX_RTP_PKT_LENGTH;
        //                 int t=0;

        //                 while(t<=k)
        //                 {
        //                         if(!t)//first pkt package
        //                         {
        //                                 memset(sendbuf,0,1500);
        //                                 fu_ind=(FU_INDICATOR *)&sendbuf[0];
        //                                 fu_ind->F=n->forbidden_bit;
        //                                 fu_ind->NRI=n->nal_reference_idc>>5;
        //                                 fu_ind->TYPE=28;//FU-A

        //                                 fu_hdr=(FU_HEADER *)&sendbuf[1];
        //                                 fu_hdr->E=0;
        //                                 fu_hdr->R=0;
        //                                 fu_hdr->S=1;
        //                                 fu_hdr->TYPE=n->nal_unit_type;

        //                                 nalu_payload=&sendbuf[2];
        //                                 memcpy(nalu_payload,n->buf+1,MAX_RTP_PKT_LENGTH);

        //                                 status=sess.SendPacket((void *)sendbuf,MAX_RTP_PKT_LENGTH+2,96,false,0);
        //                                 checkerror(status);
        //                                 t++;
        //                         }

        //                         else if(t==k)//last package
        //                         {
        //                                 memset(sendbuf,0,1500);
        //                                 fu_ind=(FU_INDICATOR *)&sendbuf[0];
        //                                 fu_ind->F=n->forbidden_bit;
        //                                 fu_ind->NRI=n->nal_reference_idc>>5;
        //                                 fu_ind->TYPE=28;//FU-A

        //                                 fu_hdr=(FU_HEADER *)&sendbuf[1];
        //                                 fu_hdr->R=0;
        //                                 fu_hdr->S=0;
        //                                 fu_hdr->E=1;
        //                                 fu_hdr->TYPE=n->nal_unit_type;

        //                                 nalu_payload=&sendbuf[2];
        //                                 memcpy(nalu_payload,n->buf+t*MAX_RTP_PKT_LENGTH+1,l-1);

        //                                 status=sess.SendPacket((void *)sendbuf,l+1,96,true,3600);
        //                                 checkerror(status);

        //                                 t++;

        //                         }

        //                         else if( (t<k) && (t!=0) ) //packageS  between the first and the last
        //                         {
        //                                 memset(sendbuf,0,1500);
        //                                 fu_ind=(FU_INDICATOR *)&sendbuf[0];
        //                                 fu_ind->F=n->forbidden_bit;
        //                                 fu_ind->NRI=n->nal_reference_idc>>5;
        //                                 fu_ind->TYPE=28;//FU-A

        //                                 fu_hdr=(FU_HEADER *)&sendbuf[1];
        //                                 fu_hdr->R=0;
        //                                 fu_hdr->S=0;
        //                                 fu_hdr->E=0;//E=1
        //                                 fu_hdr->TYPE=n->nal_unit_type;

        //                                 nalu_payload=&sendbuf[2];
        //                                 memcpy(nalu_payload,n->buf+t*MAX_RTP_PKT_LENGTH+1,MAX_RTP_PKT_LENGTH);
        //                                 status=sess.SendPacket((void *)sendbuf,MAX_RTP_PKT_LENGTH+2,96,false,0);
        //                                 checkerror(status);
        //                                 t++;
        //                         }
        //                 }

        //         }

        //         RTPTime::Wait(delay);//Wait(delay);
        //         RTPTime time=RTPTime::CurrentTime();
        //         time-=starttime;
        //         if(time>RTPTime(60.0))break;
        // }


        // //   @4   Finish   sending NALU package
        // printf("Mission over\n");
        // delay=RTPTime(10.0);
        // sess.BYEDestroy(delay,"Time's up",9);

        return 0;
}
Beispiel #20
0
int main(void)  
{  
    int status,i;  
    RTPSession s;  
    RTPSessionParams sessparams;  
    RTPUDPv4TransmissionParams transparams;  
    char blaai[100];  
      
    transparams.SetPortbase(10000);  
    sessparams.SetOwnTimestampUnit(1.0/8000.0);  
    sessparams.SetUsePollThread(true);  
    sessparams.SetMaximumPacketSize(10000);  
    status = s.Create(sessparams,&transparams);  
    s.SetLocalName((const uint8_t *)"Jori Liesenborgs",16);  
    s.SetLocalEMail((const uint8_t *)"*****@*****.**",20);  
    s.SetLocalNote((const uint8_t *)"Blaai",5);  
    s.SetNameInterval(3);  
    s.SetEMailInterval(5);  
    s.SetNoteInterval(2);  
  
    status = s.AddDestination(RTPIPv4Address(ntohl(inet_addr("192.168.2.115")),5000));  
    //status = s.AddDestination(RTPIPv4Address(ntohl(inet_addr("127.0.0.1")),7000));  
  
    int snd = open("/dev/dsp",O_RDWR);  
    int val;  
  
    val = 0;  
    status = ioctl(snd,SNDCTL_DSP_STEREO,&val);  
    val = 8;  
    status = ioctl(snd,SNDCTL_DSP_SAMPLESIZE,&val);  
    val = 8000;  
    status = ioctl(snd,SNDCTL_DSP_SPEED,&val);  
    val = 7 | (128<<16);  
    ioctl(snd,SNDCTL_DSP_SETFRAGMENT,&val);  
      
    i = 0;  
    while (i++ < 40000)  
    {  
        if (i == 1000)  
        {  
            //std::cout <<"Disabling note" << std::endl;  
            s.SetNoteInterval(0);  
        }  
        uint8_t data[PACKSIZE];   
        RTPTime t1 = RTPTime::CurrentTime();  
        status = read(snd,data,PACKSIZE);  
        RTPTime t2 = RTPTime::CurrentTime();  
        t2 -= t1;  
        printf("%d.%06d\n",t2.GetSeconds(),t2.GetMicroSeconds());  
        status = s.SendPacket(data,PACKSIZE,1,false,PACKSIZE);  
    }  
      
    close(snd);  
    printf("Destroying...\n");  
    s.BYEDestroy(RTPTime(10,0),(const uint8_t *)"Leaving session",16);  
    return 0;  
}  
	// This method does almost everything.
	void run(void) {
		// redefined from Thread.
		
		// Before using ccRTP you should learn something about other
		// CommonC++ classes. We need InetHostAddress...
		
		// Construct loopback address
		InetHostAddress local_ip;
		local_ip = "127.0.0.1";
		
		// Is that correct?
		if( ! local_ip ){  
			// this is equivalent to `! local_ip.isInetAddress()'
			cerr << ": IP address is not correct!" << endl;
			exit();
		}
		
		cout << local_ip.getHostname() << 
			" is going to transmit audio to perself through " <<
			local_ip << "..." << endl;
		
		// ____Here comes the real RTP stuff____
		
		// Construct the RTP socket.
		socket = new RTPSession(local_ip,TRANSMITTER_BASE);
		
		// Set up connection
		socket->setSchedulingTimeout(10000);
		if( !socket->addDestination(local_ip,RECEIVER_BASE) )
			cerr << "I could not connect.";
		
		socket->setPayloadFormat(StaticPayloadFormat(sptPCMU));

		socket->startRunning();
		cout << "The RTP queue service thread is ";
		if( socket->isActive() )
			cout << "active." << endl;
		else
			cerr << "not active." << endl;
		
		cout << "Transmitting " << PACKET_SIZE 
		     << " octects long packets "
		     << "every " << PERIOD << " milliseconds..." << endl;
		
		unsigned char buffer[PACKET_SIZE];
		int count=PACKET_SIZE;
		
		// This will be useful for periodic execution
		TimerPort::setTimer(PERIOD);
		
		setCancel(cancelImmediate);
		// This is the main loop, where packets are transmitted.
		for( int i = 0 ; (!sendingfile || count > 0) ; i++ ){
			
			count = ::read(audioinput,buffer,PACKET_SIZE);
			if( count > 0 ){				
				// send an RTP packet, providing timestamp,
				// payload type and payload.
				socket->putData(PACKET_SIZE*i,buffer,
						PACKET_SIZE);
			}
			cout << "." << flush;

			// Let's wait for the next cycle
			Thread::sleep(TimerPort::getTimer());
			TimerPort::incTimer(PERIOD);
		}
		cout << endl << "I have got no more data to send. " <<endl;
	}
int main(void)
{
	int packetsPerSecond = 100;
	MIPTime interval(1.0/(double)packetsPerSecond); // We'll use 10 millisecond intervals.
	MIPAverageTimer timer(interval);
	MIPOSCInput oscInput;
	MIPOSCEncoder oscEnc;
	MIPRTPOSCEncoder rtpEnc;
	MIPRTPComponent rtpComp;
	MIPRTPDecoder rtpDec;
	MIPRTPOSCDecoder rtpOSCDec;
	MIPOSCDecoder oscDec;
	MIPOSCOutput oscOutput;

	MyChain chain("OSC Sender");
	RTPSession rtpSession;
	bool returnValue;


	// Convert Messages to MIPOSCMessages
	returnValue = oscEnc.init();
	checkError(returnValue, oscEnc);

	// Initialize the RTP OSC encoder: this component will create
	// RTP messages which can be sent to the RTP component.

	returnValue = rtpEnc.init();
	checkError(returnValue, rtpEnc);

	// We'll initialize the RTPSession object which is needed by the
	// RTP component.

	RTPUDPv4TransmissionParams transmissionParams;
	RTPSessionParams sessionParams;
	int portBase = 60000;
	int status;

	transmissionParams.SetPortbase(portBase);
	sessionParams.SetOwnTimestampUnit(1.0/((double)packetsPerSecond));
	sessionParams.SetMaximumPacketSize(64000);
	sessionParams.SetAcceptOwnPackets(true);

	status = rtpSession.Create(sessionParams,&transmissionParams);
	checkError(status);

	// Instruct the RTP session to send data to ourselves.
	status = rtpSession.AddDestination(RTPIPv4Address(ntohl(inet_addr("127.0.0.1")),portBase));
	checkError(status);

	// Tell the RTP component to use this RTPSession object.
	returnValue = rtpComp.init(&rtpSession);
	checkError(returnValue, rtpComp);

	returnValue = rtpDec.init(false, 0, &rtpSession);
	checkError(returnValue, rtpDec);

	returnValue = rtpDec.setPacketDecoder(0, &rtpOSCDec);
	checkError(returnValue, rtpDec);

	returnValue = oscDec.init();
	checkError(returnValue, oscDec);

	// Next, we'll create the chain
	returnValue = chain.setChainStart(&timer);
	checkError(returnValue, chain);

	returnValue = chain.addConnection(&timer, &oscInput);
	checkError(returnValue, chain);

	returnValue = chain.addConnection(&oscInput, &oscEnc);
	checkError(returnValue, chain);

	returnValue = chain.addConnection(&oscEnc, &rtpEnc);
	checkError(returnValue, chain);

	returnValue = chain.addConnection(&rtpEnc, &rtpComp);
	checkError(returnValue, chain);

	returnValue = chain.addConnection(&rtpComp, &rtpDec);
	checkError(returnValue, chain);

	returnValue = chain.addConnection(&rtpDec, &oscDec, true);
	checkError(returnValue, chain);

	returnValue = chain.addConnection(&oscDec, &oscOutput);
	checkError(returnValue, chain);

	// Start the chain

	returnValue = chain.start();
	checkError(returnValue, chain);

	// We'll wait until enter is pressed

	int counter = 0;

	sleep(1);
	for(int i=0; i<4; i++) {
		lo_message m = lo_message_new();
		lo_message_add_int32(m,counter++);
		oscInput.push(m, "/testpfad");
		sleep(1);
	}
	getc(stdin);

	returnValue = chain.stop();
	checkError(returnValue, chain);

	rtpSession.Destroy();

	return 0;
}
int main(int argc, char** argv)
{
#if 0
	CRTPSender sender;
	string destip_str = "127.0.0.1";
	uint32_t dest_ip = inet_addr(destip_str.c_str());

	SetRTPParams(sender,dest_ip,DEST_PORT,BASE_PORT);
	sender.SetParamsForSendingH264();
#else
	RTPSession session;

	RTPSessionParams sessionparams;
	sessionparams.SetOwnTimestampUnit(1.0/90000.0);

	RTPUDPv4TransmissionParams transparams;
	transparams.SetPortbase(8000);

	int status = session.Create(sessionparams,&transparams);
	if (status < 0)
	{
		std::cerr << RTPGetErrorString(status) << std::endl;
		exit(-1);
	}

	uint8_t localip[]={127,0,0,1};
	RTPIPv4Address addr(localip,9000);

	status = session.AddDestination(addr);
	if (status < 0)
	{
		std::cerr << RTPGetErrorString(status) << std::endl;
		exit(-1);
	}

	session.SetDefaultPayloadType(96);
	session.SetDefaultMark(false);
	session.SetDefaultTimestampIncrement(90000.0 /25.0);




	RTPTime delay(0.040);
	RTPTime starttime = RTPTime::CurrentTime();

#endif

	NALU_HEADER		*nalu_hdr;
	FU_INDICATOR	*fu_ind;
	FU_HEADER		*fu_hdr;
	char sendbuf[1500];
	char* nalu_payload;
	unsigned int timestamp_increse=0,ts_current=0;

#define ddd
	OpenBitstreamFile("raw.264");//打开264文件,并将文件指针赋给bits,在此修改文件名实现打开别的264文件。
	NALU_t *n;
	n = AllocNALU(8000000);//为结构体nalu_t及其成员buf分配空间。返回值为指向nalu_t存储空间的指针
	bool start=false;
	while(!feof(bits))
	{
		int size=GetAnnexbNALU(n);//每执行一次,文件的指针指向本次找到的NALU的末尾,下一个位置即为下个NALU的起始码0x000001
		if(size<4)
		{
			printf("get nul error!\n");
			continue;
		}
		dump(n);//输出NALU长度和TYPE
		if(!start)
		{
			if(n->nal_unit_type==5||n->nal_unit_type==6||
					n->nal_unit_type==7||n->nal_unit_type==7)
			{
				printf("begin\n");
				start=true;
			}
		}
		//将编码数据写入文件t
		//fwrite(pNals[i].p_payload, 1, pNals[i].i_payload, pFile);
		//发送编码文件
#if 1
		//	当一个NALU小于MAX_RTP_PKT_LENGTH字节的时候,采用一个单RTP包发送
			if(n->len<=MAX_RTP_PKT_LENGTH)
			{
				//printf("ddd0\n");
				//session.SetDefaultMark(false);
				//设置NALU HEADER,并将这个HEADER填入sendbuf[12]
				nalu_hdr =(NALU_HEADER*)&sendbuf[0]; //将sendbuf[12]的地址赋给nalu_hdr,之后对nalu_hdr的写入就将写入sendbuf中;
				nalu_hdr->F=n->forbidden_bit;
				nalu_hdr->NRI=n->nal_reference_idc>>5;//有效数据在n->nal_reference_idc的第6,7位,需要右移5位才能将其值赋给nalu_hdr->NRI。
				nalu_hdr->TYPE=n->nal_unit_type;

				nalu_payload=&sendbuf[1];//同理将sendbuf[13]赋给nalu_payload
				memcpy(nalu_payload,n->buf+1,n->len-1);//去掉nalu头的nalu剩余内容写入sendbuf[13]开始的字符串。
				ts_current=ts_current+timestamp_increse;

				//status = session.SendPacket((void *)sendbuf,n->len);
				if(n->nal_unit_type==1 || n->nal_unit_type==5)
				{
					status = session.SendPacket((void *)sendbuf,n->len,96,true,3600);
				}
				else
				{
						status = session.SendPacket((void *)sendbuf,n->len,96,true,0);\
						//如果是6,7类型的包,不应该延时;之前有停顿,原因这在这
						continue;
				}
				//发送RTP格式数据包并指定负载类型为96
				if (status < 0)
				{
					std::cerr << RTPGetErrorString(status) << std::endl;
					exit(-1);
				}

			}
			else if(n->len>MAX_RTP_PKT_LENGTH)
Beispiel #24
0
/***********************************************************************************************************
**函数:SimpleH264SendPacket
**功能:
**输入参数:
**返回值:
***********************************************************************************************************/
int SimpleH264SendPacket(unsigned char *val,uint32_t length)
{
    /*
    *val:为264的原始数据,包含0x00 0x00 0x00 0x01信息,
    */
    int status=0;
    uint32_t  TimestampIncrement;
	uint32_t send_length,valid_len=length-4;
	char NALU=val[4],*sendStartAddr=NULL;
	#define  MAX_STREAM_SLICE 1024
    if(SimpleRtpIsActive()!=true)
    {
        printf("rtp Session is error,%s ,%d\n",__FUNCTION__, __LINE__);
        return -1;
    }
    Rtp_Lock();
	TimestampIncrement=sess.GetDefaultTimestampIncrement();
    if(valid_len<=MAX_STREAM_SLICE)
    {
        status = sess.SendPacket((void *)&val[4],valid_len,PLOAD_TYPE,true,DefaultTimestampIncrement);
        checkerror(status);
    }
    else
    {
        int k=0,l=0,len=valid_len,pos=0;
        k=len/MAX_STREAM_SLICE;
        l=len%MAX_STREAM_SLICE;
        int t=0;
        while(t<=k)
        {
            if(t==0)
            {//发送第1包					
            	sendStartAddr=(char *)(val+4);//发送数据的起始地址
				sendStartAddr[pos-1]=(NALU&0x60)|28;//FU indicator
            	sendStartAddr[pos]=(NALU&0x1f)|0x80;//FU header
				send_length=MAX_STREAM_SLICE+1;//要发送数据的长度
                status = sess.SendPacket(sendStartAddr-1,send_length,PLOAD_TYPE,false,DefaultTimestampIncrement);
				checkerror(status);
                if(status<0)
                {
                    goto end;
                }
				pos+=MAX_STREAM_SLICE;
            }
            else if(k==t&&l!=0)
            {//最后一包
            	sendStartAddr[pos-2]=(NALU&0x60)|28;//FU indicator
            	sendStartAddr[pos-1]=(NALU&0x1f)|0x40;//FU header
				send_length=l+2;//要发送数据的长度
                status = sess.SendPacket(sendStartAddr+pos-2,send_length,PLOAD_TYPE,true,0);
                checkerror(status);
                if(status<0)
                {
                    goto end;
                }
				pos+=l;
            }
            else if(t<k&&0!=t)
            {//发送第2包-----倒数第2包
            	if(l==0&&t==k-1)
            	{
					sendStartAddr[pos-2]=(NALU&0x60)|28;//FU indicator
					sendStartAddr[pos-1]=(NALU&0x1f)|0x40;//FU header
				}
				else
				{
					sendStartAddr[pos-2]=(NALU&0x60)|28;//FU indicator
					sendStartAddr[pos-1]=(NALU&0x1f);//FU header
				}
				send_length=MAX_STREAM_SLICE+2;//要发送数据的长度
                status = sess.SendPacket(sendStartAddr+pos-2,send_length,PLOAD_TYPE,false,0);
                checkerror(status);
                if(status<0)
                {
                    goto end;
                }	
				pos+=MAX_STREAM_SLICE;
            }
			t++;
        }
    }
#ifndef RTP_SUPPORT_THREAD
    checkerror(status);
#endif
end:
    Rtp_UnLock();
    return status;
}
Beispiel #25
0
int main(int argc, char ** argv)
{
        
        uint16_t portbase,destport;
        uint32_t destip;  
        std:string ipstr;  //get the destiny ip from the std input stream
        
     //   NALU_t *n;


        printf("Please Enter:./test   framenum(500)\n");
        if(argc!=2)
        {
                printf("Please Enter:./test   framenum\n");
                exit(EXIT_FAILURE);
        }

        //dev_name=argv[1];

        frame_num=atoi(argv[1]);    //convert a string to an integer
        if(!frame_num)
                {
                        printf("frame_num should be over 0 frame\n");
                        exit(EXIT_FAILURE);
                }

        // @0506 here ,there is no need to test YUYV | YUV420 | tmpH264 , for Module Test        
        //openFiles();

//*****************************************************************************        

//****************** the capturing process *****************start*********
                printf("capture video begin\n");
        open_device();
        init_device();
        start_capturing();
        //fp = fopen(filename, "wa+"); //yuv422

        // ***********
        //alloc_image();
        //  ***********

        // ***********
        //open_x264file("test420.yuv");
        init_encoder();
        init_picture(yuv_size_2);
        //  ***********
        portbase = 33334;
        destport = 9000;
        //ipstr = "222.197.174.76";
        ipstr = "202.115.11.128";
        destip = inet_addr(ipstr.c_str()); 
        //destip = ntohl(destip); ///************** very important **************
        destip = htonl(destip);

//********************** get the rtp parameter from std input stream ****above ***
        // @2 Setting basic parameter ----------------------------------
        RTPUDPv4TransmissionParams transparams;
        transparams.SetPortbase(portbase);


        RTPSessionParams sessparams;
        sessparams.SetOwnTimestampUnit(1.0/90000.0);

        status=sess.Create(sessparams,&transparams);
        checkerror(status);

        RTPIPv4Address addr(destip,destport);

        status = sess.AddDestination(addr);
        checkerror(status);

        sess.SetDefaultPayloadType(96);
        sess.SetDefaultMark(false);
        sess.SetDefaultTimestampIncrement(90000.0/10.0);  // frame rate control 10 / 25

        RTPTime delay(0.040);//RTPTime delay(0.040)
        //RTPTime::Wait(delay);
        RTPTime starttime=RTPTime::CurrentTime();

//         //  @3.0    Preparation for sending  NALU package----------------------------------------------------
//         char sendbuf[1500];
//         char *nalu_payload;
//         int size=0;
//         unsigned int timestamp_increase=0,ts_current=0;
//         OpenBitstreamFile("test.h264");

//         n=AllocNALU(8000000);// alloc memory for the <struct NALU>  n->maxSize = 8_000_000 = 8 MB
//         int start=false;

//         //****************************************************************



//****************** the capturing process ********************end ******


//****************** x264 encode ******************************* start ***
        // open_yuvfile(filename);
        // alloc_image();
        // swscale_start();     // ******  yuv422 -> I420 *******
        // swscale_close();

        // open_x264file(dst_filename);
        // init_encoder();
        // init_picture(yuv_size);
        // encode_frame();      // **** encode x264 format ***
        // close_encoder();
//****************** x264 encode ******************************* end ***
//-----------------------------------------------------------
        //@1223--01
        struct timeval tpstart,tpend;
        float  timeuse;

        gettimeofday(&tpstart,NULL);        
///------ implement capture the pictures next line -----------------------------
        tmpFP264 = fopen("softEncodeH264.h264","wb");
        mainloop(frame_num);            // **** capture frame *****
        fclose(tmpFP264);
///-----------------------------------------------------------------------------
        gettimeofday(&tpend,NULL);
        timeuse=1000000 * (tpend.tv_sec-tpstart.tv_sec) + tpend.tv_usec - tpstart.tv_usec;
        timeuse/=1000000;
        printf("timeuse total Used Time( Second ):%f\n",timeuse);       
        //@1223--02
        //-----------------------------------------------------------

        stop_capturing();
        uninit_device();
        close_device();


        close_encoder();




        return 0;
}
Beispiel #26
0
	// This method does almost everything.
	void run(void){    
		// redefined from Thread.
		
		// Before using ccRTP you should learn something about other
		// CommonC++ classes. We need InetHostAddress...

		// Construct loopback address
		InetHostAddress local_ip;
		local_ip = "127.0.0.1";
		
		// Is that correct?
		if( ! local_ip ){  
		// this is equivalent to `! local_ip.isInetAddress()'
			cerr << ": IP address is not correct!" << endl;
			exit();
		}
		
		cout << local_ip.getHostname() << 
			" is going to listen to perself through " <<
			local_ip << "..." << endl;
		
		// ____Here comes the real RTP stuff____
		
		// Construct the RTP socket
		socket = new RTPSession(local_ip,RECEIVER_BASE,0);
		
		// Set up receiver's connection
		socket->setSchedulingTimeout(10000);  
		if( !socket->addDestination(local_ip,TRANSMITTER_BASE) )
			cerr << "The receiver could not connect.";
		
		// Let's check the queue (you should read the documentation
		// so that you know what the queue is for).
		socket->startRunning();
		cout << "The RTP queue is ";
		if( socket->isActive() )
			cout << "active." << endl;
		else
			cerr << "not active." << endl;
		
		cout << "Waiting for audio packets..." << endl;
		
		// This will be useful for periodic execution.
		TimerPort::setTimer(PERIOD);

		setCancel(cancelImmediate);
		// This is the main loop, where packets are sent and receipt.
		socket->setPayloadFormat(StaticPayloadFormat(sptPCMU));
		for( int i=0 ; true ; i++ ){
			const AppDataUnit* adu;
			do{
				adu = socket->getData(socket->getFirstTimestamp());
				if ( NULL == adu )
					Thread::sleep(5);
				else cout << ".";
			}while ( (NULL == adu) || (adu->getSize() <= 0) );

			
			// This is for buffering some packets at the
			// receiver side, since playing smoothly
			// without any reception buffer is almost
			// impossible.  Try commenting the two lines
			// below, or stop transmission and continue
			// later: you will probably hear noise or
			// cracks.  
			if (i==0)
				Thread::sleep(20);
			
			::write(audiooutput,adu->getData(),adu->getSize());

			cout << "." << flush;

			// Let's wait for the next cycle
			Thread::sleep(TimerPort::getTimer());
			TimerPort::incTimer(PERIOD);
		}

	} // end of run
Beispiel #27
0
int main(void)
{
#ifdef NEED_PA_INIT
	std::string errStr;

	if (!MIPPAInputOutput::initializePortAudio(errStr))
	{
		std::cerr << "Can't initialize PortAudio: " << errStr << std::endl;
		return -1;
	}
#endif // NEED_PA_INIT
#ifdef WIN32
	WSADATA dat;
	WSAStartup(MAKEWORD(2,2),&dat);
#endif // WIN32

	MIPTime interval(0.020); // We'll use 20 millisecond intervals.
	MIPAverageTimer timer(interval);
	MIPWAVInput sndFileInput;
	MIPSamplingRateConverter sampConv, sampConv2;
	MIPSampleEncoder sampEnc, sampEnc2, sampEnc3;
	MIPULawEncoder uLawEnc;
	MIPRTPULawEncoder rtpEnc;
	MIPRTPComponent rtpComp;
	MIPRTPDecoder rtpDec;
	MIPRTPULawDecoder rtpULawDec;
	MIPULawDecoder uLawDec;
	MIPAudioMixer mixer;
	MIPComponentAlias rtpCompAlias(&rtpComp);
	ToggleOutputComponent sndToggleComponent(&sndFileInput);
#ifdef MIPCONFIG_SUPPORT_WINMM
	MIPWinMMOutput sndCardOutput;
#else
#ifdef MIPCONFIG_SUPPORT_OSS
	MIPOSSInputOutput sndCardOutput;
#else
	MIPPAInputOutput sndCardOutput;
#endif
#endif
	MyChain chain("Sound file player");
	RTPSession rtpSession;
	bool returnValue;

	// We'll open the file 'soundfile.wav'.

	returnValue = sndFileInput.open("soundfile.wav", interval);
	checkError(returnValue, sndFileInput);
	
	// We'll convert to a sampling rate of 8000Hz and mono sound.
	
	int samplingRate = 8000;
	int numChannels = 1;

	returnValue = sampConv.init(samplingRate, numChannels);
	checkError(returnValue, sampConv);

	// Initialize the sample encoder: the RTP U-law audio encoder
	// expects native endian signed 16 bit samples.
	
	returnValue = sampEnc.init(MIPRAWAUDIOMESSAGE_TYPE_S16);
	checkError(returnValue, sampEnc);

	// Convert samples to U-law encoding
	returnValue = uLawEnc.init();
	checkError(returnValue, uLawEnc);

	// Initialize the RTP audio encoder: this component will create
	// RTP messages which can be sent to the RTP component.

	returnValue = rtpEnc.init();
	checkError(returnValue, rtpEnc);

	// We'll initialize the RTPSession object which is needed by the
	// RTP component.
	
	RTPUDPv4TransmissionParams transmissionParams;
	RTPSessionParams sessionParams;
	int portBase = 60000;
	int status;

	transmissionParams.SetPortbase(portBase);
	sessionParams.SetOwnTimestampUnit(1.0/((double)samplingRate));
	sessionParams.SetMaximumPacketSize(64000);
	sessionParams.SetAcceptOwnPackets(true);
	
	status = rtpSession.Create(sessionParams,&transmissionParams);
	checkError(status);

	// Instruct the RTP session to send data to ourselves.
	status = rtpSession.AddDestination(RTPIPv4Address(ntohl(inet_addr("127.0.0.1")),portBase));
	checkError(status);

	// Tell the RTP component to use this RTPSession object.
	returnValue = rtpComp.init(&rtpSession, 160); // 20ms at 8000Hz = 160 samples per RTP packet
	checkError(returnValue, rtpComp);
	
	// Initialize the RTP audio decoder.
	returnValue = rtpDec.init(true, 0, &rtpSession);
	checkError(returnValue, rtpDec);

	// Register the U-law decoder for payload type 0
	returnValue = rtpDec.setPacketDecoder(0,&rtpULawDec);
	checkError(returnValue, rtpDec);

	// Convert U-law encoded samples to linear encoded samples
	returnValue = uLawDec.init();
	checkError(returnValue, uLawDec);

	// Transform the received audio data to floating point format.
	returnValue = sampEnc2.init(MIPRAWAUDIOMESSAGE_TYPE_FLOAT);
	checkError(returnValue, sampEnc2);

	// We'll make sure that received audio frames are converted to the right
	// sampling rate.
	returnValue = sampConv2.init(samplingRate, numChannels);
	checkError(returnValue, sampConv2);

	// Initialize the mixer.
	returnValue = mixer.init(samplingRate, numChannels, interval);
	checkError(returnValue, mixer);

	// Initialize the soundcard output.
	returnValue = sndCardOutput.open(samplingRate, numChannels, interval);
	checkError(returnValue, sndCardOutput);

#ifdef MIPCONFIG_SUPPORT_WINMM
	// The WinMM output component uses signed little endian 16 bit samples.
	returnValue = sampEnc3.init(MIPRAWAUDIOMESSAGE_TYPE_S16LE);
#else
#ifdef MIPCONFIG_SUPPORT_OSS
	// The OSS component can use several encoding types. We'll ask
	// the component to which format samples should be converted.
	returnValue = sampEnc3.init(sndCardOutput.getRawAudioSubtype());
#else
	// The PortAudio output component uses signed 16 bit samples
	returnValue = sampEnc3.init(MIPRAWAUDIOMESSAGE_TYPE_S16);
#endif
#endif
	checkError(returnValue, sampEnc3);

	// Next, we'll create the chain
	returnValue = chain.setChainStart(&timer);
	checkError(returnValue, chain);

	returnValue = chain.addConnection(&timer, &sndToggleComponent);
	checkError(returnValue, chain);

	returnValue = chain.addConnection(&sndToggleComponent, &sampConv);
	checkError(returnValue, chain);

	returnValue = chain.addConnection(&sampConv, &sampEnc);
	checkError(returnValue, chain);

	returnValue = chain.addConnection(&sampEnc, &uLawEnc);
	checkError(returnValue, chain);
	
	returnValue = chain.addConnection(&uLawEnc, &rtpEnc);
	checkError(returnValue, chain);

	returnValue = chain.addConnection(&rtpEnc, &rtpComp);
	checkError(returnValue, chain);

	returnValue = chain.addConnection(&timer, &rtpCompAlias);
	checkError(returnValue, chain);
	
	returnValue = chain.addConnection(&rtpCompAlias, &rtpDec);
	checkError(returnValue, chain);

	// This is where the feedback chain is specified: we want
	// feedback from the mixer to reach the RTP audio decoder,
	// so we'll specify that over the links in between, feedback
	// should be transferred.

	returnValue = chain.addConnection(&rtpDec, &uLawDec, true);
	checkError(returnValue, chain);

	returnValue = chain.addConnection(&uLawDec, &sampEnc2, true);
	checkError(returnValue, chain);
	
	returnValue = chain.addConnection(&sampEnc2, &sampConv2, true);
	checkError(returnValue, chain);

	returnValue = chain.addConnection(&sampConv2, &mixer, true);
	checkError(returnValue, chain);

	returnValue = chain.addConnection(&mixer, &sampEnc3);
	checkError(returnValue, chain);

	returnValue = chain.addConnection(&sampEnc3, &sndCardOutput);
	checkError(returnValue, chain);
	
	// Start the chain

	returnValue = chain.start();
	checkError(returnValue, chain);

	// We'll wait until enter is pressed

	int num = 10;

	for (int i = 0 ; i < num ; i++)
	{
		std::cout << "iteration " << (i+1) << "/" << num << std::endl;
		std::cout << "Press enter for silence" << std::endl;

		getc(stdin);
		sndToggleComponent.lock();
		sndToggleComponent.setEnabled(false);
		sndToggleComponent.unlock();

		std::cout << "Press enter for sound" << std::endl;

		getc(stdin);
		sndToggleComponent.lock();
		sndToggleComponent.setEnabled(true);
		sndToggleComponent.unlock();
	}

	returnValue = chain.stop();
	checkError(returnValue, chain);

	rtpSession.Destroy();
	
	// We'll let the destructors of the other components take care
	// of their de-initialization.

	sndCardOutput.close(); // In case we're using PortAudio
#ifdef NEED_PA_INIT
	MIPPAInputOutput::terminatePortAudio();
#endif // NEED_PA_INIT

#ifdef WIN32
	WSACleanup();
#endif
	return 0;
}
Beispiel #28
0
int main(void)
{
	RTPSession sess;
	int portbase;
	unsigned long destip;
	int destport;
	char ipstr[256];
	int status;
	char dummybuffer[1024];
	struct timeval rttprev = {0,0},rtt,tv;
	int sock1,sock2;
	bool done;
	fd_set fdset;
	
        /*
           First, we'll ask for the necessary information
        */
		
	printf("Enter the local portbase\n");
	scanf("%d",&portbase);
	printf("\n");
	
	printf("Enter the destination IP address\n");
	scanf("%s",ipstr);
	destip = inet_addr(ipstr);
	if (destip == INADDR_NONE)
	{
		printf("Bad IP address specified\n");
		return -1;
	}
	
	// The inet_addr function returns a value in network byte order, but
	// we need the IP address in host byte order, so we use a call to
	// ntohl
	destip = ntohl(destip);
	
	printf("Enter the destination port\n");
	scanf("%d",&destport);
	
	/*
	   Now, we'll create a RTP session, set the destination, send some
	   packets and poll for incoming data.
	*/
	
	status = sess.Create(portbase);	
	checkerror(status);

	/* Get the sockets, so we can use them in a 'select' call */
	
	sess.GetRTPSocket(&sock1);
	sess.GetRTCPSocket(&sock2);
	
	status = sess.AddDestination(destip,destport);
	checkerror(status);

	printf("Press return to quit...\n");
	
	done = false;
	while (!done)
	{
		/* Just send something */
		
		status = sess.SendPacket("1234567890",10,0,false,10);
		checkerror(status);
		
		/* Wait for incoming data, or wait just one second */
		
		tv.tv_sec = 1;
		tv.tv_usec = 0;
		FD_ZERO(&fdset);
		FD_SET(sock1,&fdset);
		FD_SET(sock2,&fdset);
		FD_SET(0,&fdset); // check for keypress
			
		select(FD_SETSIZE,&fdset,NULL,NULL,&tv);
		if (FD_ISSET(0,&fdset))
			done = true;
		
		/* poll for incoming data */
		
		status = sess.PollData();
		
		/* check incoming packets */
		
		if (sess.GotoFirstSourceWithData())
		{
			do
			{
				RTPSourceData *srcdat;
				
				srcdat = sess.GetCurrentSourceInfo();
				srcdat->FlushPackets(); // we don't need the actual data
				
				rtt = srcdat->INF_GetRoundTripTime();
				if (rtt.tv_sec != 0 || rtt.tv_usec != 0)
				{
					if ((rtt.tv_sec != rttprev.tv_sec) || (rtt.tv_usec != rttprev.tv_usec))
					{
						double t;
					
						t = (double)rtt.tv_sec;
						t += ((double)rtt.tv_usec)/1000000.0;
						t *= 1000.0; // we want milliseconds;
						printf("rtt: %f ms\n",(float)t);
						rttprev = rtt;
					}
				}
			} while (sess.GotoNextSourceWithData());
		}
	}
	
	return 0;
}
Beispiel #29
0
// Thread function for RTP session.
static void* rtpSessionThread(void *arg)
{
    VideoStream* video = reinterpret_cast<VideoStream*>(arg);

    u_int8_t bigBuffer[MAX_FRAME_SIZE];

    unsigned int lastPacketTimestamp = 0;
    unsigned int currentIndex = 0;
    double last_time = 0;

    RTPSession session = createRtpSession(video->getMulticastIP(), 
                                          video->getPort());

    while (1) {
        session.Poll();

        // Distribute data from the session to connected clients if we've
        // got anything
        session.BeginDataAccess();

        if (session.GotoFirstSourceWithData()) {
            do {
                RTPPacket *packet = NULL;

                while ((packet = session.GetNextPacket()) != NULL) {
                    if ((packet->GetPayloadLength() > sizeof(bigBuffer)) || 
                        (packet->GetPayloadLength() == 0)) {
                        // Free the packet, we're not going to use it.
                        session.DeletePacket(packet);
                        continue; // Exit this level of the loop and drop it
                    }

                    // Check timestamps for new data.  A new timestamp means
                    // this is from a different time.
                    if (packet->GetTimestamp() != lastPacketTimestamp) {
                        video->decode((uint8_t*)&bigBuffer[0], currentIndex);

                        currentIndex = 0;
                        memset(&bigBuffer[0], 0, sizeof(bigBuffer));
                    } // End new timestamp optimization.


                    // Copy data into buffer
                    if (currentIndex + packet->GetPayloadLength() > sizeof(bigBuffer)) {
                        throw std::runtime_error("Frame buffer overflow");
                    }

                    memcpy(&bigBuffer[currentIndex], packet->GetPayloadData(),
                           packet->GetPayloadLength());
                    currentIndex += packet->GetPayloadLength();

                    // Mark our last timestamp
                    lastPacketTimestamp = packet->GetTimestamp();

                    // Free the packet.
                    session.DeletePacket(packet);
                } 
            } while (session.GotoNextSourceWithData()); 
        }

        session.EndDataAccess();
        RTPTime delay(0, 100); // 100usec

        // Update More Data
        bool moreData;
        session.WaitForIncomingData(delay, &moreData);
    }

    // Leave the session while sending BYE.
    RTPTime timeout(0.75f); //  Wait briefly.
    const char* reason = "Session Destroyed.";
    unsigned int reasonlen = strlen(reason);

    if (session.IsActive())
        session.BYEDestroy(timeout, reason, reasonlen);
}  
/****************************************
* RecAudio
*	Obtiene los packetes y los muestra
*****************************************/
int AudioStream::RecAudio()
{
    BYTE 		lost=0;
    int 		recBytes=0;
    struct timeval 	before;
    BYTE		data[512];
    WORD		playBuffer[512];
    DWORD		size=512;
    AudioCodec*	codec=NULL;
    AudioCodec::Type type;
    DWORD		timeStamp=0;
    DWORD		frameTime=0;
    DWORD		lastTime=0;

    Log(">RecAudio\n");

    //Inicializamos el tiempo
    gettimeofday(&before,NULL);

    //Empezamos a reproducir
    audioOutput->StartPlaying();

    //Mientras tengamos que capturar
    while(receivingAudio)
    {
        //POnemos el tam�o
        size=512;
        lost=0;

        //Obtenemos el paquete
        if (!rtp.GetAudioPacket((BYTE *)data,&size,&lost,&type,&timeStamp))
        {
            //Log(">Process audio error\n");
            switch (errno)
            {
            case 11:
            case 4:
            case 0:
                break;
            default:
                Log("Error obteniendo el packete [%d]\n",errno);
            }
            continue;
        }

        // add for rtsp watcher by liuhong start
        if (!muted) {
            Rtps::iterator iter;
            for(iter = rtps.begin(); iter != rtps.end(); iter++)
            {
                RTPSession *rtp = iter->second;
                int ret = rtp->ForwardPacket((BYTE *)data, size, 0, timeStamp);
                //Log(">Send audio to watcher %d %ld\n", ret, timeStamp);
            }
        }

        //Comprobamos el tipo
        if ((codec==NULL) || (type!=codec->type))
        {
            //Si habia uno nos lo cargamos
            if (codec!=NULL)
                delete codec;

            //Creamos uno dependiendo del tipo
            if ((codec = CreateAudioCodec(type))==NULL)
            {
                Log("Error creando nuevo codec de audio [%d]\n",type);
                continue;
            }
            // add for rtsp watcher by liuhong
            decodeCodec = type;
        }

        //Lo decodificamos
        int len = codec->Decode(data,size,playBuffer,512);

        //Obtenemos el tiempo del frame
        frameTime = timeStamp - lastTime;

        //Actualizamos el ultimo envio
        lastTime = timeStamp;

        //Check muted
        if (!muted)
            //Y lo reproducimos
            audioOutput->PlayBuffer((WORD *)playBuffer,len,frameTime);

        //Aumentamos el numero de bytes recividos
        recBytes+=size;
    }

    //Terminamos de reproducir
    audioOutput->StopPlaying();

    //Borramos el codec
    if (codec!=NULL)
        delete codec;

    //Salimos
    Log("<RecAudio\n");
    pthread_exit(0);
}