Implementation of real-time transmission based on Jrtplib library under Linux __linux

Source: Internet
Author: User
Tags error handling pack sessions

Implementation of real-time transmission based on Jrtplib library under Linux
RTP is a standard protocol and key technology for real-time streaming media transmission.
Real-time transport protocol (real-time transport PROTOCOL,PRT) is a network protocol for processing multimedia data streams on the Internet, which can be used in one-to-one (unicast, unicast) or one-to-many (multicast, multicast), the real-time transmission of Liu Media data is realized in the network environment. RTP usually uses UDP for the transmission of multimedia data, but can use other protocols, such as TCP or ATM, if needed.

Protocol analysis: Each RTP datagram consists of two parts of the head (header) and load (Payload), where the first 12 bytes of the head are fixed and the load can be audio or video data.

RTP is the best way to solve the problem of streaming media real-time transmission, in order to carry on the Linux platform real-time transmission programming, may consider uses some open source code the RTP storehouse, like LIBRTP, Jrtplib and so on. Jrtplib is an object-oriented RTP library that is fully compliant with RFC 1889 design and is a very good choice in many situations. Jrtplib is a RTP library implemented in C + +, which uses the socket mechanism to implement network communication so it can run on a variety of operating systems, such as Windows, Linux, FreeBSD, Solaris, Unix, and VxWorks.
The Use method and program realization of Jrtplib Library
(1) The use of Jrtplib functions
A, before using jrtplib for real-time streaming media data transfer, you should first generate an instance of the Rtpsession class to represent this RTP session, and then call the Create () method to initialize it. The Create () method of the Rtpsession class has only one parameter that indicates the port number to use for this RTP session.
Rtpsession Sess; Sess. Create (5000);

b, setting the appropriate timestamp unit is another important work to be done in the RTP session initialization process, which is achieved by invoking the Settimestampunit () method of the Rtpsession class, which also has only one parameter, representing the timestamp unit in seconds.
Sess. Settimestampunit (1.0/8000.0);

C, when the RTP session was successfully established, the next can start streaming media data real-time transmission. First you need to set the destination address of the data sent, the RTP protocol allows multiple destination addresses in the same session, which can be done by calling the Rtpsession class Adddestination (), Deletedestination (), and cleardestinations () method to complete. For example, the following statement indicates that a RTP session sends data to port 6000 on the local host:

unsigned long addr = Ntohl (inet_addr ("127.0.0.1"));
Sess. Adddestination (addr, 6000);

D, after all the destination addresses are specified, you can then invoke the Sendpacket () method of the Rtpsession class to send streaming media data to all destination addresses. Sendpacket () is an overloaded function provided by the Rtpsession class
For the same RTP session, the load type, identity, and timestamp increments are generally the same, and Jrtplib allows them to be set as the default parameters for the session, by calling the Setdefaultpayloadtype () of the Rtpsession class, Setdefaultmark () and the Setdefaulttimestampincrement () method to complete. The advantage of setting these default parameters for RTP sessions is that you can simplify the sending of data, for example, if you set the default parameters for RTP sessions:

Sess. Setdefaultpayloadtype (0);
Sess. Setdefaultmark (FALSE);
Sess. Setdefaulttimestampincrement (10);



You can then simply indicate the data you want to send and the length of the data when you send it:

Sess. Sendpacket (buffer, 5);


E, for streaming media data receiving end, first need to call the Rtpsession class Polldata () method to receive sent over RTP or RTCP datagram. Because multiple participants (sources) are allowed in the same RTP session, you can either traverse all the sources by invoking the Gotofirstsource () and Gotonextsource () methods of the Rtpsession class, or by calling the Rtpsession class's Goto Firstsourcewithdata () and Gotonextsourcewithdata () methods are used to traverse those sources that carry data. After detecting a valid data source from the RTP session, we can then call the Rtpsession class Getnextpacket () method to extract the RTP data, and when the RTP data received is processed, we must remember to release it in time.

The Jrtplib defines three reception modes for RTP datagrams, each of which specifies which RTP datagrams will be accepted, and which RTP datagrams will be rejected in each mode of reception. The following receive modes can be set by calling the Setreceivemode () method of the Rtpsession class:
? Receivemode_all default reception mode, all incoming RTP datagrams will be accepted;
? Receivemode_ignoresome except for certain senders, all incoming RTP datagrams will be accepted, and the rejected Senders list can be invoked by calling Addtoignorelist (), Deletefromignorelist (), and Clearignorelist () method to set up;
? Receivemode_acceptsome In addition to certain specific senders, all incoming RTP datagrams will be rejected, and the accepted list of senders can be invoked by calling Addtoacceptlist (), Deletefromacceptlist, and Clearacceptlist () method to set. The following is an example of a program using the third receive mode.
if (Sess. Gotofirstsourcewithdata ()) {
do {
Sess. Addtoacceptlist (Remoteip, allports,portbase);
Sess. Setreceivemode (Receivemode_acceptsome);

Rtppacket *pack;
Pack = Sess.            Getnextpacket (); Processing received data
Delete pack; }
while (Sess. Gotonextsourcewithdata ());
}


(2) Program flow chart
Send: Get the IP address and port number of the receiving end create RTP session specify RTP data receiver set RTP session default parameter send streaming media data
Receive: Get user-specified port number create RTP session set receive mode accept RTP data retrieve RTP data source get RTP datagram Delete RTP Datagram


Third, the environment builds up and compiles the method
Reference (1) Installation of Toolchain
First locate the xscale-arm-toolchain.tgz file, assuming that the package is placed under/tmp/
#cd/
#tar-zxvf/tmp/xscale-arm-toolchain.tgz
Then set the environment variable
#export Path=/usr/local/arm-linux/bin: $PATH
Finally, check to see if the Cross Compilation tool was successfully installed
#arm-linux-g++--version
See if the arm-linux-g++ version is displayed, and if so, the installation is successful.
(2) Cross-compilation and installation of Jrtplib Library
First download the latest source package from Jrtplib's website (HTTP://LUMUMBA.LUC.AC.BE/JORI/JRTPLIB/JRTPLIB.HTMLL), where Jrtplib-2.8.tar is used, assuming the downloaded source package is placed in the/ TMP, perform the following command to decompress it:
#cd/tmp
#tar-ZXVF Jrtplib-2.8.tar
Then configure and compile the Jrtplib
#cd jrtplib-2.8
#./configure cc=arm-linux-g++ Cross-compile=yes
modifying makefile Files
Change link command ld and AR to Arm-linux-ld and Arm-linux-ar
#make
Finally, you can complete the installation of Jrtplib by executing the following command:
#make Install
(3) Program compiling
A, configure the compilation environment
You can use export to configure it, or you can write a makefile method. Makefile is used here.
Writing Makefile&:
incl =-i/usr/local/include
Cflags =-pipe-o2-fno-strength-reduce
Lflags =/usr/local/lib/libjrtp.a-l/usr/x11r6/lib
LIBS =-lx11-lxext/usr/local/lib/libjrtp.a
CC = arm-linux-g++

main:main.o
$ (CC) $ (lflags) $ (incl)-o main MAIN.O $ (LIBS)
Main.o:main.cpp

Clean
Rm-f Main
Rm-f *.O

. Suffixes:.cpp
. CPP.O:
$ (CC)-C $ (cflags) $ (incl)-o $@ $</* $@ indicates the full name of the target.
/* $< represents the first dependent file name.
B, compiling
Suppose the send and receive programs are placed in the/tmp/send and/tmp/receive directories, respectively.
#cd/tmp/send
#make
#cd/tmp/receive
#make
Four, easy to make mistakes and pay attention to problems
Reference 1, unable to find some of the most basic of the standard header files.
The main reason is that the toolchain path is not installed right, to strictly follow the steps to install.
2, can not find the use of some of the Jrtplib library header files.
Under the Jrtplib installation directory, there is no other directory under the include path.
3, the recieve function receives the data packet not to be able to propose the data correctly.
Since each RTP datagram consists of two parts of the head (header) and load (Payload), using Getrawdata () is the data that returns the entire packet, including the type, format, serial number, time stamp of the transmission media, and whether additional data is available. The Getpayload () function returns the data that is sent. There must be a distinction between the two.
4, set Receivemode_acceptsome receive mode, run program receiver can not receive packets.
There is a problem with the IP address format. Iner_addr () and Ntohl () function to use the right, otherwise the parameters can not be passed in, accept the list of no value, of course, not receive packets.
5, compile pass, but the receiver can not receive data when testing.
The receiver firewall may not be closed. Run:
#iptables-F
It is also possible that the IP address is not set well. Run:
#ifocnfig eth0 *.*.*.* netmask *.*.*.*
6, the use of Jrtolib Library, in the program include the best place to add the path of the library. V. Procedures

Send
View plain print? #include  <stdio.h>   #include  <string.h>   #include   "Rtpsession.h "     //  error handling function    void checkerror (int err)    {     if  (err < 0)  {       char* errstr =  rtpgeterrorstring (Err);       printf ("error:%s//n",  errstr);        exit ( -1);     }  }      int  Main (INT&NBSP;ARGC,&NBSP;CHAR**&NBSP;ARGV)    {     RTPSession sess;      unsigned long destip;     int destport;      int portbase = 6000;     int status, index;     char buffer[128];        if  (argc != 3)  {       printf ("usage: ./sender destip destport//n");        return -1;     }         //  get the IP address and port number of the receiving end      destip = inet_addr (argv[1]);      if  (Destip == inaddr_none)  {       printf ("Bad ip  address specified.//n ");       return -1;      }     destip = ntohl (Destip);     destport = atoi ( ARGV[2]);        //  Create RTP session      status = sess. Create (portbase);     checkerror (status);        //  Specifies the RTP data receiver      status = sess. Adddestination (destip, destport);   &NBSP;&NBSp;checkerror (status);        //  Set RTP session default parameters      sess. Setdefaultpayloadtype (0);     sess. Setdefaultmark (False);     sess. Setdefaulttimestampincrement (a);        //  send streaming media data       index = 1;     do {       sprintf (buffer,  "%d: rtp packet",  index ++);       sess. Sendpacket (Buffer, strlen (buffer));       printf ("send packet !//n ");     } while (1);        return 0;  }   




Receive
View plain print? #include  <stdio.h>   #include   "Rtpsession.h"    #include   "Rtppacket.h"      //  error handling function    void checkerror (int err)    {     if  (err < 0)  {       char* errstr =  rtpgeterrorstring (Err);       printf ("error:%s//n",  errstr);        exit ( -1);     }  }      int  Main (INT&NBSP;ARGC,&NBSP;CHAR**&NBSP;ARGV)    {     RTPSession sess;      int localport,portbase;     int status;      unsigned long remoteip;     if  (argc != 4)  {       printf ("usage: ./sender localport//n");       return -1;     }         //  Get user-specified port number            remoteip = inet_addr (argv[1]);      localport = atoi (argv[2]);     portbase = atoi (argv[3 ];     //  Create RTP session      status = sess. Create (LocalPort);     checkerror (status);          / /rtpheader *rtphdr;     unsigned long timestamp1;      unsigned char * rawdata;     unsigned char temp[30];     int lengh ,i;     bool allports = 1;           sess. Addtoacceptlist (remoteip, allports,portbase);        &NBSP;&NBsp;   do {    //set receive mode             sess. Setreceivemode (receivemode_acceptsome);      sess. Addtoacceptlist (remoteip, allports,portbase);          //  Receive RTP data        status = sess. Polldata ();              //  retrieving RTP data source        if  (Sess. Gotofirstsourcewithdata ())  {         do {                        rtppacket* packet;           //  get RTP data             while  (packet = sess. Getnextpacket ())  != null)  {             printf ("got packet !/n");         timestamp1 = packet->gettimestamp ();      lengh=packet- >getpayloadlength ();      rawdata=packet->getpayload ();             for (i=0;i<lengh;i++) {          temp[i]=rawdata[i];     printf ("%c", Temp[i]);      }      temp[i]= '/0 ';      printf ("  timestamp: %d lengh =%d data:%s/n ", timestamp1,lengh,&temp);              //  Remove RTP datagram                     delete packet;           }    &NBSp;     } while  (Sess. Gotonextsourcewithdata ());       }     } while (1);         return 0;  }  

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.