package com.beem.project.beem.jingle;

import jlibrtp.Participant;
import jlibrtp.RTPSession;

import org.jivesoftware.smackx.jingle.JingleSession;
import org.jivesoftware.smackx.jingle.media.JingleMediaSession;
import org.jivesoftware.smackx.jingle.media.PayloadType;
import org.jivesoftware.smackx.jingle.nat.TransportCandidate;
import org.sipdroid.media.RtpStreamReceiver;
import org.sipdroid.media.RtpStreamSender;
import org.sipdroid.media.codecs.CodecManager;
import org.sipdroid.net.SipdroidSocket;

import android.content.Context;
import android.util.Log;

/**
 * Manage microphone RTP session.
 * @author nikita
 */
public class RTPAudioSession extends JingleMediaSession {
	
	private RtpStreamSender mSender=null;
	private RtpStreamReceiver mReceiver=null;

	private RTPSession rtpSession;

	/**
	 * constructor.
	 * @param payloadType the payload typ used
	 * @param remote the remote transport info
	 * @param local the local tranport info
	 * @param mediaLocator don't know
	 * @param jingleSession the current jingle session
	 * @param ctx 
	 */
	public RTPAudioSession(final PayloadType pt, final TransportCandidate remote,
			final TransportCandidate local, final String mediaLocator, final JingleSession jingleSession, Context ctx) {
		super(pt, remote, local, mediaLocator, jingleSession);
		
		prepareRtpSession(local.getPort(), remote.getIp(), remote.getPort());
		Log.d("AUDIO", String.format("payload type : %s ipdest %s port dest %d port src %d",pt.getName(), remote.getIp(), remote.getPort(), local.getPort()));
		
		mSender = new RtpStreamSender(CodecManager.getCodecByRtpName(pt.getName()), rtpSession);

		mReceiver = new RtpStreamReceiver(CodecManager.getCodecByRtpName(pt.getName()), rtpSession, ctx);
	}

	@Override
	public void initialize() {
		// TODO Auto-generated method stub

	}

	@Override
	public void setTrasmit(boolean active) {
	}

	@Override
	public void startReceive() {
		if (mReceiver != null) {
			mReceiver.start();
		}
	}

	@Override
	public void startTrasmit() {
		if (mSender != null) {
			mSender.start();
		}
		rtpSession.RTPSessionRegister(mReceiver, null, null);
	}

	@Override
	public void stopReceive() {
		if (mReceiver != null) {
			mReceiver.halt();
			mReceiver = null;
		}
		rtpSession.endSession();
	}

	@Override
	public void stopTrasmit() {
		if (mSender != null) {
			mSender.halt();
			mSender = null;
		}
	}
	
	private void prepareRtpSession(int src_port, String dest_addr, int dest_port) {
		SipdroidSocket rtpSocket = null;
		SipdroidSocket rtcpSocket = null;

		try {
			rtpSocket = new SipdroidSocket(src_port);
			rtcpSocket = new SipdroidSocket(src_port + 1);
		} catch (Exception e) {
		}
		rtpSession = new RTPSession(rtpSocket, rtcpSocket);
		Participant p = new Participant(dest_addr,dest_port, dest_port + 1);
		rtpSession.addParticipant(p);
		rtpSession.naivePktReception(true);
		rtpSession.packetBufferBehavior(3);
	}
}
