/* ***************************************************************************+
 * ITX package (cnrg.itx) for telephony application programming.              *
 * Copyright (c) 1999  Cornell University, Ithaca NY.                         *
 * A copy of the license is distributed with this package.  Look in the docs  *
 * directory, filename GPL.  Contact information: bergmark@cs.cornell.edu     *
 ******************************************************************************/


package cnrg.itx.datax.devices;

/**
 * Class for implementing the factory that creates RTP packets for
 * sending over the network.
 */
class RTPPacketFactory
{
	/**
	 * Attribute for storing the RTP header for this factory. This RTP header
	 * can be initialized once and reused to create subsequent RTP packets.
	 * Only the sequence number and the timestamp need to be changed for each
	 * packet.
	 */
	private RTPHeader header;
	
	/**
	 * Attribute for storing a RTP packet for this factory. This RTP packet
	 * can be reused to make make a RTP byte array for each data packet.
	 */
	private RTPPacket packet;
	
	/**
	 * Attribute for storing the previous RTP packet's sequence number.
	 */
	private short sequence;
	
	/**
	 * Default constructor for the factory. This creates a default RTP header.
	 */
	public RTPPacketFactory()
	{
		// Make a random source ID that is 32 bits long(0xffffffff)
		int ssrc = (int)(Math.random()*256*256*256*256);
		
		// Create the default RTP header
		header = new RTPHeader(ssrc, RTPHeader.PCMA_8000);
		
		// Make the default RTP packet
		packet = new RTPPacket();
		
		// Initialize the sequence number to a 16 bit random value
		sequence = (short)(Math.random()*256*256);

	}
	
	/**
	 * Method to create an RTP packet from a data packet. This method will
	 * put in the required RTP header and insert the data after it.
	 * @param data the data to be sent as part of the RTP packet
	 * @return byte[] the RTP version of the packet
	 */
	public byte[] createRTPPacket(byte[] data)
	{
		// Get the lower 32 bits of the current time
		int timeStamp = (int) System.currentTimeMillis();
		
		// Initialize the header with the timestamp and the sequence number
		header.setTimeStamp(timeStamp);
		header.setSequence(sequence++);
		
		// Initialize the packe with the header and the data
		packet.setRTPHeader(header);
		packet.setData(data);
		
		return packet.toByteArray();
	}
	
	/**
	 * Method to retrieve the RTPPacket object from an RTP packet.
	 * @param rtpPacket the RTP packet byte array with the header
	 * @return RTPPacket the RTPPacket object
	 */
	public RTPPacket getRTPPacket(byte[] rtpPacket)
	{
		return new RTPPacket(rtpPacket);
	}
	
	/**
	 * Method to get the sequence number
	 * @return int the sequence number
	 */
	public int getSequenceNumber()
	{
		return (int) (0xffff & sequence);
	}
}
