import java.net.*;
import java.io.*;
import java.awt.TextArea;

public class RTPReceiver extends Thread{
   private static final boolean Debug=true;
   InetAddress group;
   int         port;
   TextArea    msgBoard;
   MulticastSocket rtpRcvSock;
   static final int  MAXBUFLEN=268;    // 256+12
   static final int  RTPHDRLEN=12;
   byte [] buf;
   byte [] data;
   int   dataLen;
   DataInputStream in;
   DatagramPacket rcvPkt;
   
   public RTPReceiver(InetAddress g, int p, TextArea ta){
      group = g;
      port = p;
      msgBoard = ta;
      buf = new byte[MAXBUFLEN];
      rcvPkt = new DatagramPacket(buf, buf.length);
      try{
         rtpRcvSock = new MulticastSocket(port);
      }catch(IOException e){
         System.out.println("RTPReceiver: create socket-->"+e);
      }
   }
   
   public void run(){
      byte  b1, b2;
      byte [] msgbuf=null;
      int ssrc;
      short seq;
      String msg;
      
      try{
         rtpRcvSock.joinGroup(group);
      }catch(IOException e){
         System.out.println("RTPReceiver: joinGroup-->"+e);
      }
      while (true){
         try{
            rtpRcvSock.receive(rcvPkt);
         }catch(IOException e){
            System.out.println("RTPReceiver: receive-->"+e);
         }
         data = rcvPkt.getData();
         dataLen = rcvPkt.getLength() - RTPHDRLEN;
         in = new DataInputStream(new ByteArrayInputStream(data));
         try{
            // first two bytes
            b1 = in.readByte();
            b2 = in.readByte();
            
            // Sequence number
            seq = in.readShort();
            
            // Skip timestamp
            in.readInt();
            
            // SSRC
            ssrc = in.readInt();
            if (Debug){
               System.out.println("RTPReceiver.run: b1-->"+b1+", b2-->"+b2);
               System.out.println("                 seq-->"+seq+", ssrc-->"+ssrc);
               System.out.println("                 datalen-->"+dataLen);
            }
            
            // Read the message
            msgbuf = new byte[dataLen];
            in.readFully(msgbuf);
         }catch(IOException e){
            System.out.println("RTPReceiver: read-->"+e);
         }
         msg = new String(msgbuf);
         if (Debug){
            System.out.println("RTPReceiver.run: msg-->"+msg);
         }
         rcvPkt.setLength(MAXBUFLEN);
         msgBoard.append("\n"+msg);
      }
   }
   
   public void leave(){
      if (Debug){
         System.out.println("RTPReceiver.leave: leaving group...");
      }
      try{
         rtpRcvSock.leaveGroup(group);
      }catch(IOException e){
         System.out.println("RTPReceiver: leaveGroup-->"+e);
      }
   }
}      
