NewReceiveStreamEvent exception

Hello everybody
I'm unable to create DataSink, but the the datasource(ds) and dest(medialocator) is perfectly creating.
The below code is been used
stream = ((NewReceiveStreamEvent)evt).getReceiveStream();
DataSource ds = stream.getDataSource();
MediaLocator dest = new MediaLocator("file://e:/abc/rtp/test/temp.wav");
DataSink filewriter = null;
filewriter = Manager.createDataSink(ds,dest);
filewriter.open();
its giving the datasink exception
thanks in advance

insert "filewirter.start()"
you should wirte the content about the exception

Similar Messages

  • Why receiver is stopped

    i am creating rtp mixer .
    for that i have made a program which receive rtp stream and then transmit it .
    The problem with this code is that it first create receiver(it is a player) from the received rtp stream but receiver is stopped when treansmitter
    (it is a processor) is created.
    Earlier i was creaing the playe and processor from the same dataSourc so i thought it was creating problem . so i created transmitter (processor)
    from the cloned dataSource . but the problem reamain as it was
    what is the reason for this.
    please help me because i am already late in this project .
    very very thank u.
    my code is :
    import java.awt.*;
    import java.io.IOException;
    import java.net.*;
    import java.awt.event.*;
    import java.util.ArrayList;
    import java.util.Vector;
    import javax.media.*;
    import javax.media.rtp.*;
    import javax.media.rtp.event.*;
    import javax.media.rtp.rtcp.SourceDescription;
    import javax.media.control.TrackControl;
    import javax.media.protocol.DataSource;
    import javax.media.protocol.*;
    public class AVReceive implements ReceiveStreamListener, SessionListener,
              ControllerListener {
         String session[];
         static RTPManager mgrs;
         Vector playerWindows = null;
         static ArrayList list = new ArrayList();
         private Processor processor = null;
         String result = null;
         DataSource mds;
         private Integer stateLock = new Integer(0);
         DataSource dataOutput;
         public static int incr = 0;
         public static int inc;
         DataSource cloneableDataSource = null;
    DataSource clonedDataSource = null;
         private boolean failed = false;
         boolean dataReceived = false;
         DataSource ds = null;
         Object dataSync = new Object();
         protected boolean initialize() {
              try {
                   InetAddress ipAddr;
                   SessionAddress localAddr = new SessionAddress();
                   SessionAddress destAddr;
                   playerWindows = new Vector();
                   mgrs = (RTPManager) RTPManager.newInstance();
                   mgrs.addSessionListener(this);
                   mgrs.addReceiveStreamListener(this);
                   localAddr = new SessionAddress(InetAddress.getLocalHost(), 5004);
                   mgrs.initialize(localAddr);
                   destAddr = new SessionAddress(InetAddress.getLocalHost(), 20000);
                   mgrs.addTarget(destAddr);
              } catch (Exception e) {
                   System.err.println("Cannot create the RTP Session: "
                             + e.getMessage());
                   return false;
              return true;
         public boolean isDone() {
              return playerWindows.size() == 0;
         protected void close() {
              for (int i = 0; i < playerWindows.size(); i++) {
                   try {
                        ((PlayerWindow) playerWindows.elementAt(i)).close();
                   } catch (Exception e) {
              playerWindows.removeAllElements();
              if (mgrs != null) {
                   mgrs.removeTargets("Closing session from AVReceive");
                   mgrs.dispose();
                   mgrs = null;
         PlayerWindow find(Player p) {
              for (int i = 0; i < playerWindows.size(); i++) {
                   PlayerWindow pw = (PlayerWindow) playerWindows.elementAt(i);
                   if (pw.player == p)
                        return pw;
              return null;
         PlayerWindow find(ReceiveStream strm) {
              for (int i = 0; i < playerWindows.size(); i++) {
                   PlayerWindow pw = (PlayerWindow) playerWindows.elementAt(i);
                   if (pw.stream == strm)
                        return pw;
              return null;
         public synchronized void update(SessionEvent evt) {
              if (evt instanceof NewParticipantEvent) {
                   Participant p = ((NewParticipantEvent) evt).getParticipant();
                   System.out.println(" A new participant has just joined: "
                             + p.getCNAME());
         public synchronized void update(ReceiveStreamEvent evt) {
              Participant participant = evt.getParticipant();
              ReceiveStream stream = evt.getReceiveStream();
              if (evt instanceof NewReceiveStreamEvent) {
                   try {
                        stream = ((NewReceiveStreamEvent) evt).getReceiveStream();
                        if (stream != null)
                             System.out.println(" - Recevied new RTP stream");
                        ds = stream.getDataSource();
              Player p = javax.media.Manager.createPlayer(ds);
                        if (p == null) {
                             System.out.println("can not create player");
                             return;
                        System.out.println("player is created ");
                        p.addControllerListener(this);
                        p.realize();
                        synchronized (dataSync) {
                             dataSync.notifyAll();
                        inc++;
                        PlayerWindow pw = new PlayerWindow(p, stream, inc);
                        playerWindows.addElement(pw);
                   } catch (Exception e) {
                        System.err.println("NewReceiveStreamEvent exception "
                                  + e.getMessage());
                        return;
              } else if (evt instanceof StreamMappedEvent) {
                   if (stream != null && stream.getDataSource() != null) {
                        System.out.println(" has now been identified as sent by: "
                                  + participant.getCNAME());
                        incr++;
                        try {
                             Vector sourceDescriptions = stream.getParticipant()
                                       .getSourceDescription();
                                                 for (int i = 0; i < sourceDescriptions.size(); i++) {
                                  SourceDescription description = (SourceDescription) sourceDescriptions
                                            .get(i);
                                  if (description.getType() == SourceDescription.SOURCE_DESC_CNAME) {
                                       String ip[] = description.getDescription().split(
                        } catch (Exception e) {
                             System.out.println(" exception is " + e);
                        System.out.println(" creating transmitter ");
                        createProcessor();
                        processor.start();
                        PlayerWindow pw = new PlayerWindow(processor);
                        playerWindows.addElement(pw);
                        pw.initialize1();
                        pw.setVisible(true);
                        createTransmitter();
              } else if (evt instanceof ByeEvent) {
                   System.err.println(" - Got \"bye\" from: "
                             + participant.getCNAME());
                   PlayerWindow pw = find(stream);
                   if (pw != null) {
                        pw.close();
                        playerWindows.removeElement(pw);
         private String createProcessor() {
    cloneableDataSource
    = Manager.createCloneableDataSource(ds);
              try {
                   processor = javax.media.Manager.createProcessor(cloneableDataSource);
              } catch (NoProcessorException npe) {
                   return "Couldn't create processor";
              } catch (IOException ioe) {
                   return "IOException creating processor";
              boolean result = waitForState(processor, Processor.Configured);
              if (result == false)
                   return "Couldn't configure processor";
              TrackControl[] tracks = processor.getTrackControls();
              if (tracks == null || tracks.length < 1)
                   return "Couldn't find tracks in processor";
              ContentDescriptor cd = new ContentDescriptor(ContentDescriptor.RAW_RTP);
              processor.setContentDescriptor(cd);
              Format supported[];
              Format chosen;
              boolean atLeastOneTrack = false;
              for (int i = 0; i < tracks.length; i++) {
                   if (tracks.isEnabled()) {
                        supported = tracks[i].getSupportedFormats();
                        if (supported.length > 0) {
                             chosen = supported[0];
                             tracks[i].setFormat(chosen);
                             System.err
                                       .println("Track " + i + " is set to transmit as:");
                             System.err.println(" " + chosen);
                             atLeastOneTrack = true;
                        } else
                             tracks[i].setEnabled(false);
                   } else
                        tracks[i].setEnabled(false);
              if (!atLeastOneTrack)
                   return "Couldn't set any of the tracks to a valid RTP format";
              result = waitForState(processor, Controller.Realized);
              if (result == false)
                   return "Couldn't realize processor";
              dataOutput = processor.getDataOutput();
              System.out.println("dataoutput is " + dataOutput);
              return null;
         private void createTransmitter() {
              System.out.println("inside transmitter");
              PushBufferDataSource pbds = (PushBufferDataSource) dataOutput;
              PushBufferStream pbss[] = pbds.getStreams();
              System.out.println(" length of stream "+pbss.length);
              SessionAddress localAddr, destAddr1, destAddr2;
              InetAddress ipAddr1, ipAddr2;
              SendStream sendStream;
              int port = 0;
              SourceDescription srcDesList[];
              try {
                   sendStream = mgrs.createSendStream(dataOutput, 0);
                   System.out.println(" send stream is " + sendStream);
                   sendStream.start();
              } catch (Exception e) {
                   e.getMessage();
         Integer getStateLock() {
              return stateLock;
         void setFailed() {
              failed = true;
         private synchronized boolean waitForState(Processor p, int state) {
              p.addControllerListener(new StateListener());
              failed = false;
              System.out.println("inside configuring");
              if (state == Processor.Configured) {
                   System.out.println(" ok 4 ");
                   p.configure();
              } else if (state == Processor.Realized) {
                   p.realize();
              while (p.getState() < state && !failed) {
                   synchronized (getStateLock()) {
                        try {
                             getStateLock().wait();
                        } catch (InterruptedException ie) {
                             return false;
              System.out.println(" ok 3 ");
              if (failed)
                   return false;
              else
                   return true;
         public synchronized void controllerUpdate(ControllerEvent ce) {
              Player p = (Player) ce.getSourceController();
              if (p == null)
                   return;
              if (ce instanceof RealizeCompleteEvent) {
                   synchronized (dataSync) {
                        dataSync.notifyAll();
                   System.out.println(" player has been realized");
                   PlayerWindow pw = find(p);
                   if (pw == null) {
                        System.err.println("Internal error!");
                        System.exit(-1);
                   pw.initialize();
                   pw.setVisible(true);
                   p.start();
              if (ce instanceof ControllerErrorEvent) {
                   p.removeControllerListener(this);
                   PlayerWindow pw = find(p);
                   if (pw != null) {
                        pw.close();
                        playerWindows.removeElement(pw);
         class StateListener implements ControllerListener {
              public void controllerUpdate(ControllerEvent ce) {
                   if (ce instanceof ControllerClosedEvent) {
                        setFailed();
                   if (ce instanceof ControllerEvent) {
                        synchronized (getStateLock()) {
                        getStateLock().notifyAll();
         class PlayerWindow extends Frame implements ActionListener {
              public int inc;
              PlayerWindow() {
              Player player;
              ReceiveStream stream;
              PlayerWindow(Player p, ReceiveStream strm, int inc) {
                   player = p;
                   stream = strm;
                   this.inc = inc;
              PlayerWindow(Player p) {
                   player = p;
              public void initialize() {
                   add(new PlayerPanel(player, inc));
              public void initialize1() {
                   add(new PlayerPanel1(player, inc));
              public void close() {
                   player.close();
                   setVisible(false);
                   dispose();
              public void addNotify() {
                   super.addNotify();
                   pack();
              public void actionPerformed(ActionEvent e) {
                   if (e.getActionCommand() == "stop1") {
                        PlayerWindow pw = find(stream);
                        if (pw != null) {
                             pw.close();
                             playerWindows.removeElement(pw);
         class PlayerPanel extends Panel {
              Component vc, cc;
              PlayerPanel(Player p, int inc) {
                   setLayout(new BorderLayout());
                   if ((cc = p.getControlPanelComponent()) != null)
                        add("South", cc);
                   System.out.println("increment is " + inc);
                   Integer in = new Integer(inc);
                   Button counter = new Button("receiver" + in.toString());
                   Button stop1 = new Button("stop1");
                   add("Center", stop1);
                   add("North", counter);
                   PlayerWindow pw = find(p);
                   stop1.addActionListener(pw);
              public Dimension getPreferredSize() {
                   int w = 0, h = 200;
                   if (cc != null) {
                        Dimension size = cc.getPreferredSize();
                        if (w == 0)
                             w = size.width * 2;
                        h += size.height;
                   return new Dimension(w, h);
         class PlayerPanel1 extends Panel {
              Component vc, cc;
              PlayerPanel1(Player p, int inc) {
                   setLayout(new BorderLayout());
                   if ((cc = p.getControlPanelComponent()) != null)
                        add("South", cc);
                   System.out.println("increment is " + inc);
                   Integer in = new Integer(inc);
                   Button counter = new Button("transmitter" + in.toString());
                   Button stop1 = new Button("start");
                   add("Center", stop1);
                   add("North", counter);
                   PlayerWindow pw = find(p);
                   stop1.addActionListener(pw);
              public Dimension getPreferredSize() {
                   int w = 0, h = 200;
                   if (cc != null) {
                        Dimension size = cc.getPreferredSize();
                        if (w == 0)
                             w = size.width * 2;
                        h += size.height;
                   return new Dimension(w, h);
         public static void main(String argv[]) {
              AVReceive avReceive1 = new AVReceive();
              if (!avReceive1.initialize()) {
                   System.err.println("Failed to initialize the sessions.");
                   System.exit(-1);
              try {
                   while (true)
                        Thread.sleep(1000);
              } catch (Exception e) {

    hi jcparques
    thank for ur response .
    but i m not able to see ur code .
    so please allow me to see ur code.
    i have sent request to join ur project but i got denied reply.
    so accept my request.
    thank u.

  • JMF How to stream rtp from udp packet

    I implemented an rtsp client and use the client to setup two rtp session(audio, vedio). But when I use the example pramgram "AVReceive3" to stream the udp packet, it doesn't work.
    When the AVReceive3 receive the udp packet from the rtp port, it will call the update(ReceiveStreamEvent evt) function, and the event type is StreamMappedEvent, and the call to evt.getReceiveStream().getDataSource() return null.
    I thought the first event should be NewReceiveStreamEvent. Please help to solve the problem.
    What's rtp packet will cause the event StreamMappedEvent.
    Following is the code of AVReceive3.java:
    * AVReceive3.java
    * Created on 2007&#24180;10&#26376;30&#26085;, &#19979;&#21320;4:11
    * To change this template, choose Tools | Template Manager
    * and open the template in the editor.
    package PlayerTest;
    import java.io.*;
    import java.awt.*;
    import java.net.*;
    import java.awt.event.*;
    import java.util.Vector;
    import javax.media.*;
    import javax.media.rtp.*;
    import javax.media.rtp.event.*;
    import javax.media.rtp.rtcp.*;
    import javax.media.protocol.*;
    import javax.media.protocol.DataSource;
    import javax.media.format.AudioFormat;
    import javax.media.format.VideoFormat;
    import javax.media.Format;
    import javax.media.format.FormatChangeEvent;
    import javax.media.control.BufferControl;
    * AVReceive3 to receive RTP transmission using the RTPConnector.
    public class AVReceive3 extends Thread implements ReceiveStreamListener, SessionListener,
    ControllerListener
    String sessions[] = null;
    RTPManager mgrs[] = null;
    Vector playerWindows = null;
    boolean dataReceived = false;
    Object dataSync = new Object();
    public AVReceive3(String sessions[])
    this.sessions = sessions;
    public void run()
    initialize();
    public boolean initialize() {
    try {
    mgrs = new RTPManager[sessions.length];
    playerWindows = new Vector();
    SessionLabel session;
    // Open the RTP sessions.
    for (int i = 0; i < sessions.length; i++) {
    // Parse the session addresses.
    try {
    session = new SessionLabel(sessions);
    } catch (IllegalArgumentException e) {
    System.err.println("Failed to parse the session address given: " + sessions[i]);
    return false;
    System.err.println(" - Open RTP session for: addr: " + session.addr + " port: " + session.port + " ttl: " + session.ttl);
    mgrs[i] = (RTPManager) RTPManager.newInstance();
    mgrs[i].addSessionListener(this);
    mgrs[i].addReceiveStreamListener(this);
    // Initialize the RTPManager with the RTPSocketAdapter
    mgrs[i].initialize(new RTPSocketAdapter(
    InetAddress.getByName(session.addr),
    session.port, session.ttl));
    // You can try out some other buffer size to see
    // if you can get better smoothness.
    BufferControl bc = (BufferControl)mgrs[i].getControl("javax.media.control.BufferControl");
    if (bc != null)
    bc.setBufferLength(350);
    } catch (Exception e){
    System.err.println("Cannot create the RTP Session: " + e.getMessage());
    return false;
    // Wait for data to arrive before moving on.
    long then = System.currentTimeMillis();
    long waitingPeriod = 30000; // wait for a maximum of 30 secs.
    try{
    synchronized (dataSync) {
    while (!dataReceived &&
    System.currentTimeMillis() - then < waitingPeriod) {
    if (!dataReceived)
    System.err.println(" - Waiting for RTP data to arrive");
    dataSync.wait(1000);
    } catch (Exception e) {}
    if (!dataReceived) {
    System.err.println("No RTP data was received.");
    close();
    return false;
    return true;
    public boolean isDone() {
    return playerWindows.size() == 0;
    * Close the players and the session managers.
    protected void close() {
    for (int i = 0; i < playerWindows.size(); i++) {
    try {
    ((PlayerWindow)playerWindows.elementAt(i)).close();
    } catch (Exception e) {}
    playerWindows.removeAllElements();
    // close the RTP session.
    for (int i = 0; i < mgrs.length; i++) {
    if (mgrs[i] != null) {
    mgrs[i].removeTargets( "Closing session from AVReceive3");
    mgrs[i].dispose();
    mgrs[i] = null;
    PlayerWindow find(Player p) {
    for (int i = 0; i < playerWindows.size(); i++) {
    PlayerWindow pw = (PlayerWindow)playerWindows.elementAt(i);
    if (pw.player == p)
    return pw;
    return null;
    PlayerWindow find(ReceiveStream strm) {
    for (int i = 0; i < playerWindows.size(); i++) {
    PlayerWindow pw = (PlayerWindow)playerWindows.elementAt(i);
    if (pw.stream == strm)
    return pw;
    return null;
    * SessionListener.
    public synchronized void update(SessionEvent evt) {
    if (evt instanceof NewParticipantEvent) {
    Participant p = ((NewParticipantEvent)evt).getParticipant();
    System.err.println(" - A new participant had just joined: " + p.getCNAME());
    * ReceiveStreamListener
    public synchronized void update( ReceiveStreamEvent evt) {
    System.out.println("\nReceive an receiveStreamEvent:"+evt.toString());
    RTPManager mgr = (RTPManager)evt.getSource();
    Participant participant = evt.getParticipant(); // could be null.
    ReceiveStream stream = evt.getReceiveStream(); // could be null.
    System.out.println("The RTPManager is:");
    if (evt instanceof RemotePayloadChangeEvent) {
    System.err.println(" - Received an RTP PayloadChangeEvent.");
    System.err.println("Sorry, cannot handle payload change.");
    System.exit(0);
    else if (evt instanceof NewReceiveStreamEvent) {
    try {
    stream = ((NewReceiveStreamEvent)evt).getReceiveStream();
    DataSource ds = stream.getDataSource();
    // Find out the formats.
    RTPControl ctl = (RTPControl)ds.getControl("javax.media.rtp.RTPControl");
    if (ctl != null){
    System.err.println(" - Recevied new RTP stream: " + ctl.getFormat());
    } else
    System.err.println(" - Recevied new RTP stream");
    if (participant == null)
    System.err.println(" The sender of this stream had yet to be identified.");
    else {
    System.err.println(" The stream comes from: " + participant.getCNAME());
    // create a player by passing datasource to the Media Manager
    Player p = javax.media.Manager.createPlayer(ds);
    if (p == null)
    return;
    p.addControllerListener(this);
    p.realize();
    PlayerWindow pw = new PlayerWindow(p, stream);
    playerWindows.addElement(pw);
    pw.setVisible(true);
    // Notify intialize() that a new stream had arrived.
    synchronized (dataSync) {
    dataReceived = true;
    dataSync.notifyAll();
    } catch (Exception e) {
    System.err.println("NewReceiveStreamEvent exception " + e.getMessage());
    return;
    else if (evt instanceof StreamMappedEvent) {
    if (stream != null)
    if(stream.getDataSource()!=null)
    DataSource ds = stream.getDataSource();
    // Find out the formats.
    RTPControl ctl = (RTPControl)ds.getControl("javax.media.rtp.RTPControl");
    System.err.println(" - The previously unidentified stream ");
    if (ctl != null)
    System.err.println(" " + ctl.getFormat());
    System.err.println(" had now been identified as sent by: " + participant.getCNAME());
    else if (evt instanceof ByeEvent) {
    System.err.println(" - Got \"bye\" from: " + participant.getCNAME());
    PlayerWindow pw = find(stream);
    if (pw != null) {
    pw.close();
    playerWindows.removeElement(pw);
    * ControllerListener for the Players.
    public synchronized void controllerUpdate(ControllerEvent ce) {
    Player p = (Player)ce.getSourceController();
    if (p == null)
    return;
    // Get this when the internal players are realized.
    if (ce instanceof RealizeCompleteEvent) {
    PlayerWindow pw = find(p);
    if (pw == null) {
    // Some strange happened.
    System.err.println("Internal error!");
    System.exit(-1);
    pw.initialize();
    pw.setVisible(true);
    p.start();
    if (ce instanceof ControllerErrorEvent) {
    p.removeControllerListener(this);
    PlayerWindow pw = find(p);
    if (pw != null) {
    pw.close();
    playerWindows.removeElement(pw);
    System.err.println("AVReceive3 internal error: " + ce);
    * A utility class to parse the session addresses.
    class SessionLabel {
    public String addr = null;
    public int port;
    public int ttl = 1;
    SessionLabel(String session) throws IllegalArgumentException {
    int off;
    String portStr = null, ttlStr = null;
    if (session != null && session.length() > 0) {
    while (session.length() > 1 && session.charAt(0) == '/')
    session = session.substring(1);
    // Now see if there's a addr specified.
    off = session.indexOf('/');
    if (off == -1) {
    if (!session.equals(""))
    addr = session;
    } else {
    addr = session.substring(0, off);
    session = session.substring(off + 1);
    // Now see if there's a port specified
    off = session.indexOf('/');
    if (off == -1) {
    if (!session.equals(""))
    portStr = session;
    } else {
    portStr = session.substring(0, off);
    session = session.substring(off + 1);
    // Now see if there's a ttl specified
    off = session.indexOf('/');
    if (off == -1) {
    if (!session.equals(""))
    ttlStr = session;
    } else {
    ttlStr = session.substring(0, off);
    if (addr == null)
    throw new IllegalArgumentException();
    if (portStr != null) {
    try {
    Integer integer = Integer.valueOf(portStr);
    if (integer != null)
    port = integer.intValue();
    } catch (Throwable t) {
    throw new IllegalArgumentException();
    } else
    throw new IllegalArgumentException();
    if (ttlStr != null) {
    try {
    Integer integer = Integer.valueOf(ttlStr);
    if (integer != null)
    ttl = integer.intValue();
    } catch (Throwable t) {
    throw new IllegalArgumentException();
    * GUI classes for the Player.
    class PlayerWindow extends Frame {
    Player player;
    ReceiveStream stream;
    PlayerWindow(Player p, ReceiveStream strm) {
    player = p;
    stream = strm;
    public void initialize() {
    add(new PlayerPanel(player));
    public void close() {
    player.close();
    setVisible(false);
    dispose();
    public void addNotify() {
    super.addNotify();
    pack();
    * GUI classes for the Player.
    class PlayerPanel extends Panel {
    Component vc, cc;
    PlayerPanel(Player p) {
    setLayout(new BorderLayout());
    if ((vc = p.getVisualComponent()) != null)
    add("Center", vc);
    if ((cc = p.getControlPanelComponent()) != null)
    add("South", cc);
    public Dimension getPreferredSize() {
    int w = 0, h = 0;
    if (vc != null) {
    Dimension size = vc.getPreferredSize();
    w = size.width;
    h = size.height;
    if (cc != null) {
    Dimension size = cc.getPreferredSize();
    if (w == 0)
    w = size.width;
    h += size.height;
    if (w < 160)
    w = 160;
    return new Dimension(w, h);
    public static void main(String argv[]) {
    //if (argv.length == 0)
    // prUsage();
    String sessions[]= new String[] {"127.0.0.1/6670","127.0.0.1/6672"};
    AVReceive3 avReceive = new AVReceive3(sessions);
    if (!avReceive.initialize()) {
    System.err.println("Failed to initialize the sessions.");
    System.exit(-1);
    // Check to see if AVReceive3 is done.
    try {
    while (!avReceive.isDone())
    Thread.sleep(1000);
    } catch (Exception e) {}
    System.err.println("Exiting AVReceive3");
    static void prUsage() {
    System.err.println("Usage: AVReceive3 <session> <session> ");
    System.err.println(" <session>: <address>/<port>/<ttl>");
    System.exit(0);
    }// end of AVReceive3
    Following is the code of RTPSocketAdapter.java:
    * RTPSocketAdapter.java
    * Created on 2007&#24180;10&#26376;30&#26085;, &#19979;&#21320;4:13
    * To change this template, choose Tools | Template Manager
    * and open the template in the editor.
    package PlayerTest;
    import java.io.IOException;
    import java.net.InetAddress;
    import java.net.DatagramSocket;
    import java.net.MulticastSocket;
    import java.net.DatagramPacket;
    import java.net.SocketException;
    import javax.media.protocol.DataSource;
    import javax.media.protocol.PushSourceStream;
    import javax.media.protocol.ContentDescriptor;
    import javax.media.protocol.SourceTransferHandler;
    import javax.media.rtp.RTPConnector;
    import javax.media.rtp.OutputDataStream;
    * An implementation of RTPConnector based on UDP sockets.
    public class RTPSocketAdapter implements RTPConnector {
    DatagramSocket dataSock;
    DatagramSocket ctrlSock;
    InetAddress addr;
    int port;
    SockInputStream dataInStrm = null;
    SockInputStream ctrlInStrm = null;
    SockOutputStream dataOutStrm = null;
    SockOutputStream ctrlOutStrm = null;
    public RTPSocketAdapter(InetAddress addr, int port) throws IOException {
    this(addr, port, 1);
    public RTPSocketAdapter(InetAddress addr, int port, int ttl) throws IOException {
    try {
    if (addr.isMulticastAddress()) {
    dataSock = new MulticastSocket(port);
    ctrlSock = new MulticastSocket(port+1);
    ((MulticastSocket)dataSock).joinGroup(addr);
    ((MulticastSocket)dataSock).setTimeToLive(ttl);
    ((MulticastSocket)ctrlSock).joinGroup(addr);
    ((MulticastSocket)ctrlSock).setTimeToLive(ttl);
    } else {
    dataSock = new DatagramSocket(port, InetAddress.getLocalHost());
    ctrlSock = new DatagramSocket(port+1, InetAddress.getLocalHost());
    } catch (SocketException e) {
    throw new IOException(e.getMessage());
    this.addr = addr;
    this.port = port;
    * Returns an input stream to receive the RTP data.
    public PushSourceStream getDataInputStream() throws IOException {
    if (dataInStrm == null) {
    dataInStrm = new SockInputStream(dataSock, addr, port);
    dataInStrm.start();
    return dataInStrm;
    * Returns an output stream to send the RTP data.
    public OutputDataStream getDataOutputStream() throws IOException {
    if (dataOutStrm == null)
    dataOutStrm = new SockOutputStream(dataSock, addr, port);
    return dataOutStrm;
    * Returns an input stream to receive the RTCP data.
    public PushSourceStream getControlInputStream() throws IOException {
    if (ctrlInStrm == null) {
    ctrlInStrm = new SockInputStream(ctrlSock, addr, port+1);
    ctrlInStrm.start();
    return ctrlInStrm;
    * Returns an output stream to send the RTCP data.
    public OutputDataStream getControlOutputStream() throws IOException {
    if (ctrlOutStrm == null)
    ctrlOutStrm = new SockOutputStream(ctrlSock, addr, port+1);
    return ctrlOutStrm;
    * Close all the RTP, RTCP streams.
    public void close() {
    if (dataInStrm != null)
    dataInStrm.kill();
    if (ctrlInStrm != null)
    ctrlInStrm.kill();
    dataSock.close();
    ctrlSock.close();
    * Set the receive buffer size of the RTP data channel.
    * This is only a hint to the implementation. The actual implementation
    * may not be able to do anything to this.
    public void setReceiveBufferSize( int size) throws IOException {
    dataSock.setReceiveBufferSize(size);
    * Get the receive buffer size set on the RTP data channel.
    * Return -1 if the receive buffer size is not applicable for
    * the implementation.
    public int getReceiveBufferSize() {
    try {
    return dataSock.getReceiveBufferSize();
    } catch (Exception e) {
    return -1;
    * Set the send buffer size of the RTP data channel.
    * This is only a hint to the implementation. The actual implementation
    * may not be able to do anything to this.
    public void setSendBufferSize( int size) throws IOException {
    dataSock.setSendBufferSize(size);
    * Get the send buffer size set on the RTP data channel.
    * Return -1 if the send buffer size is not applicable for
    * the implementation.
    public int getSendBufferSize() {
    try {
    return dataSock.getSendBufferSize();
    } catch (Exception e) {
    return -1;
    * Return the RTCP bandwidth fraction. This value is used to
    * initialize the RTPManager. Check RTPManager for more detauls.
    * Return -1 to use the default values.
    public double getRTCPBandwidthFraction() {
    return -1;
    * Return the RTCP sender bandwidth fraction. This value is used to
    * initialize the RTPManager. Check RTPManager for more detauls.
    * Return -1 to use the default values.
    public double getRTCPSenderBandwidthFraction() {
    return -1;
    * An inner class to implement an OutputDataStream based on UDP sockets.
    class SockOutputStream implements OutputDataStream {
    DatagramSocket sock;
    InetAddress addr;
    int port;
    public SockOutputStream(DatagramSocket sock, InetAddress addr, int port) {
    this.sock = sock;
    this.addr = addr;
    this.port = port;
    public int write(byte data[], int offset, int len) {
    try {
    sock.send(new DatagramPacket(data, offset, len, addr, port));
    } catch (Exception e) {
    return -1;
    return len;
    * An inner class to implement an PushSourceStream based on UDP sockets.
    class SockInputStream extends Thread implements PushSourceStream {
    DatagramSocket sock;
    InetAddress addr;
    int port;
    boolean done = false;
    boolean dataRead = false;
    SourceTransferHandler sth = null;
    public SockInputStream(DatagramSocket sock, InetAddress addr, int port) {
    this.sock = sock;
    this.addr = addr;
    this.port = port;
    public int read(byte buffer[], int offset, int length) {
    DatagramPacket p = new DatagramPacket(buffer, offset, length, addr, port);
    try {
    sock.receive(p);
    } catch (IOException e) {
    return -1;
    synchronized (this) {
    dataRead = true;
    notify();
    System.out.println("RTPSocketAdapter receive RTP packet from port:"+port);
    System.out.println("The received RTP packet:"+new String(buffer));
    return p.getLength();
    public synchronized void start() {
    super.start();
    if (sth != null) {
    dataRead = true;
    notify();
    public synchronized void kill() {
    done = true;
    notify();
    public int getMinimumTransferSize() {
    return 2 * 1024; // twice the MTU size, just to be safe.
    public synchronized void setTransferHandler(SourceTransferHandler sth) {
    this.sth = sth;
    dataRead = true;
    notify();
    // Not applicable.
    public ContentDescriptor getContentDescriptor() {
    return null;
    // Not applicable.
    public long getContentLength() {
    return LENGTH_UNKNOWN;
    // Not applicable.
    public boolean endOfStream() {
    return false;
    // Not applicable.
    public Object[] getControls() {
    return new Object[0];
    // Not applicable.
    public Object getControl(String type) {
    return null;
    * Loop and notify the transfer handler of new data.
    public void run() {
    while (!done) {
    synchronized (this) {
    while (!dataRead && !done) {
    try {
    wait();
    } catch (InterruptedException e) { }
    dataRead = false;
    if (sth != null && !done) {
    sth.transferData(this);
    Thanks.

    The error of No format has been registered for RTP Payload type 96
    is caused by the dynamic payload mapping, when I add the dynamic mapping between dynamic payload and format. The Player cann't work yet. I think it because JMF doesn't support the format of my clips. For example:
    video: a=rtpmap:96 H263-2000/90000
    audio:a=rtpmap:97 MP4A-LATM/12000/1
    Is there some available plugin to support these format?
    Thanks

  • AV3 question

    hi friends:
    I am been looking into AVTransmit2.java, AVReceive2.java and AVTransmit3, AVReceive3
    can your tell me what is the input and output of this function
    where can I change to transmit and receive my DataSource
    and Then presenting them
    AVTransmit2.java:
    * @(#)AVTransmit2.java     1.4 01/03/13
    * Copyright (c) 1999-2001 Sun Microsystems, Inc. All Rights Reserved.
    * Sun grants you ("Licensee") a non-exclusive, royalty free, license to use,
    * modify and redistribute this software in source and binary code form,
    * provided that i) this copyright notice and license appear on all copies of
    * the software; and ii) Licensee does not utilize the software in a manner
    * which is disparaging to Sun.
    * This software is provided "AS IS," without a warranty of any kind. ALL
    * EXPRESS OR IMPLIED CONDITIONS, REPRESENTATIONS AND WARRANTIES, INCLUDING ANY
    * IMPLIED WARRANTY OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE OR
    * NON-INFRINGEMENT, ARE HEREBY EXCLUDED. SUN AND ITS LICENSORS SHALL NOT BE
    * LIABLE FOR ANY DAMAGES SUFFERED BY LICENSEE AS A RESULT OF USING, MODIFYING
    * OR DISTRIBUTING THE SOFTWARE OR ITS DERIVATIVES. IN NO EVENT WILL SUN OR ITS
    * LICENSORS BE LIABLE FOR ANY LOST REVENUE, PROFIT OR DATA, OR FOR DIRECT,
    * INDIRECT, SPECIAL, CONSEQUENTIAL, INCIDENTAL OR PUNITIVE DAMAGES, HOWEVER
    * CAUSED AND REGARDLESS OF THE THEORY OF LIABILITY, ARISING OUT OF THE USE OF
    * OR INABILITY TO USE SOFTWARE, EVEN IF SUN HAS BEEN ADVISED OF THE
    * POSSIBILITY OF SUCH DAMAGES.
    * This software is not designed or intended for use in on-line control of
    * aircraft, air traffic, aircraft navigation or aircraft communications; or in
    * the design, construction, operation or maintenance of any nuclear
    * facility. Licensee represents and warrants that it will not use or
    * redistribute the Software for such purposes.
    import java.awt.*;
    import java.io.*;
    import java.net.InetAddress;
    import javax.media.*;
    import javax.media.protocol.*;
    import javax.media.protocol.DataSource;
    import javax.media.format.*;
    import javax.media.control.TrackControl;
    import javax.media.control.QualityControl;
    import javax.media.rtp.*;
    import javax.media.rtp.rtcp.*;
    import com.sun.media.rtp.*;
    public class AVTransmit2 {
        // Input MediaLocator
        // Can be a file or http or capture source
        private MediaLocator locator;
        private String ipAddress;
        private int portBase;
        private Processor processor = null;
        private RTPManager rtpMgrs[];
        private DataSource dataOutput = null;
        public AVTransmit2(MediaLocator locator,
                    String ipAddress,
                    String pb,
                    Format format) {
         this.locator = locator;
         this.ipAddress = ipAddress;
         Integer integer = Integer.valueOf(pb);
         if (integer != null)
             this.portBase = integer.intValue();
         * Starts the transmission. Returns null if transmission started ok.
         * Otherwise it returns a string with the reason why the setup failed.
        public synchronized String start() {
         String result;
         // Create a processor for the specified media locator
         // and program it to output JPEG/RTP
         result = createProcessor();
         if (result != null)
             return result;
         // Create an RTP session to transmit the output of the
         // processor to the specified IP address and port no.
         result = createTransmitter();
         if (result != null) {
             processor.close();
             processor = null;
             return result;
         // Start the transmission
         processor.start();
         return null;
         * Stops the transmission if already started
        public void stop() {
         synchronized (this) {
             if (processor != null) {
              processor.stop();
              processor.close();
              processor = null;
              for (int i = 0; i < rtpMgrs.length; i++) {
                  rtpMgrs.removeTargets( "Session ended.");
              rtpMgrs[i].dispose();
    private String createProcessor() {
         if (locator == null)
         return "Locator is null";
         DataSource ds;
         DataSource clone;
         try {
         ds = javax.media.Manager.createDataSource(locator);
         } catch (Exception e) {
         return "Couldn't create DataSource";
         // Try to create a processor to handle the input media locator
         try {
         processor = javax.media.Manager.createProcessor(ds);
         } catch (NoProcessorException npe) {
         return "Couldn't create processor";
         } catch (IOException ioe) {
         return "IOException creating processor";
         // Wait for it to configure
         boolean result = waitForState(processor, Processor.Configured);
         if (result == false)
         return "Couldn't configure processor";
         // Get the tracks from the processor
         TrackControl [] tracks = processor.getTrackControls();
         // Do we have atleast one track?
         if (tracks == null || tracks.length < 1)
         return "Couldn't find tracks in processor";
         // Set the output content descriptor to RAW_RTP
         // This will limit the supported formats reported from
         // Track.getSupportedFormats to only valid RTP formats.
         ContentDescriptor cd = new ContentDescriptor(ContentDescriptor.RAW_RTP);
         processor.setContentDescriptor(cd);
         Format supported[];
         Format chosen;
         boolean atLeastOneTrack = false;
         // Program the tracks.
         for (int i = 0; i < tracks.length; i++) {
         Format format = tracks[i].getFormat();
         if (tracks[i].isEnabled()) {
              supported = tracks[i].getSupportedFormats();
              // We've set the output content to the RAW_RTP.
              // So all the supported formats should work with RTP.
              // We'll just pick the first one.
              if (supported.length > 0) {
              if (supported[0] instanceof VideoFormat) {
                   // For video formats, we should double check the
                   // sizes since not all formats work in all sizes.
                   chosen = checkForVideoSizes(tracks[i].getFormat(),
                                       supported[0]);
              } else
                   chosen = supported[0];
              tracks[i].setFormat(chosen);
              System.err.println("Track " + i + " is set to transmit as:");
              System.err.println(" " + chosen);
              atLeastOneTrack = true;
              } else
              tracks[i].setEnabled(false);
         } else
              tracks[i].setEnabled(false);
         if (!atLeastOneTrack)
         return "Couldn't set any of the tracks to a valid RTP format";
         // Realize the processor. This will internally create a flow
         // graph and attempt to create an output datasource for JPEG/RTP
         // audio frames.
         result = waitForState(processor, Controller.Realized);
         if (result == false)
         return "Couldn't realize processor";
         // Set the JPEG quality to .5.
         setJPEGQuality(processor, 0.5f);
         // Get the output data source of the processor
         dataOutput = processor.getDataOutput();
         return null;
    * Use the RTPManager API to create sessions for each media
    * track of the processor.
    private String createTransmitter() {
         // Cheated. Should have checked the type.
         PushBufferDataSource pbds = (PushBufferDataSource)dataOutput;
         PushBufferStream pbss[] = pbds.getStreams();
         rtpMgrs = new RTPManager[pbss.length];
         SessionAddress localAddr, destAddr;
         InetAddress ipAddr;
         SendStream sendStream;
         int port;
         SourceDescription srcDesList[];
         for (int i = 0; i < pbss.length; i++) {
         try {
              rtpMgrs[i] = RTPManager.newInstance();     
              // The local session address will be created on the
              // same port as the the target port. This is necessary
              // if you use AVTransmit2 in conjunction with JMStudio.
              // JMStudio assumes - in a unicast session - that the
              // transmitter transmits from the same port it is receiving
              // on and sends RTCP Receiver Reports back to this port of
              // the transmitting host.
              port = portBase + 2*i;
              ipAddr = InetAddress.getByName(ipAddress);
              localAddr = new SessionAddress( InetAddress.getLocalHost(),
                                  port);
              destAddr = new SessionAddress( ipAddr, port);
              rtpMgrs[i].initialize( localAddr);
              rtpMgrs[i].addTarget( destAddr);
              System.err.println( "Created RTP session: " + ipAddress + " " + port);
              sendStream = rtpMgrs[i].createSendStream(dataOutput, i);          
              sendStream.start();
         } catch (Exception e) {
              return e.getMessage();
         return null;
    * For JPEG and H263, we know that they only work for particular
    * sizes. So we'll perform extra checking here to make sure they
    * are of the right sizes.
    Format checkForVideoSizes(Format original, Format supported) {
         int width, height;
         Dimension size = ((VideoFormat)original).getSize();
         Format jpegFmt = new Format(VideoFormat.JPEG_RTP);
         Format h263Fmt = new Format(VideoFormat.H263_RTP);
         if (supported.matches(jpegFmt)) {
         // For JPEG, make sure width and height are divisible by 8.
         width = (size.width % 8 == 0 ? size.width :
                        (int)(size.width / 8) * 8);
         height = (size.height % 8 == 0 ? size.height :
                        (int)(size.height / 8) * 8);
         } else if (supported.matches(h263Fmt)) {
         // For H.263, we only support some specific sizes.
         if (size.width < 128) {
              width = 128;
              height = 96;
         } else if (size.width < 176) {
              width = 176;
              height = 144;
         } else {
              width = 352;
              height = 288;
         } else {
         // We don't know this particular format. We'll just
         // leave it alone then.
         return supported;
         return (new VideoFormat(null,
                        new Dimension(width, height),
                        Format.NOT_SPECIFIED,
                        null,
                        Format.NOT_SPECIFIED)).intersects(supported);
    * Setting the encoding quality to the specified value on the JPEG encoder.
    * 0.5 is a good default.
    void setJPEGQuality(Player p, float val) {
         Control cs[] = p.getControls();
         QualityControl qc = null;
         VideoFormat jpegFmt = new VideoFormat(VideoFormat.JPEG);
         // Loop through the controls to find the Quality control for
         // the JPEG encoder.
         for (int i = 0; i < cs.length; i++) {
         if (cs[i] instanceof QualityControl &&
              cs[i] instanceof Owned) {
              Object owner = ((Owned)cs[i]).getOwner();
              // Check to see if the owner is a Codec.
              // Then check for the output format.
              if (owner instanceof Codec) {
              Format fmts[] = ((Codec)owner).getSupportedOutputFormats(null);
              for (int j = 0; j < fmts.length; j++) {
                   if (fmts[j].matches(jpegFmt)) {
                   qc = (QualityControl)cs[i];
                   qc.setQuality(val);
                   System.err.println("- Setting quality to " +
                             val + " on " + qc);
                   break;
              if (qc != null)
              break;
    * Convenience methods to handle processor's state changes.
    private Integer stateLock = new Integer(0);
    private boolean failed = false;
    Integer getStateLock() {
         return stateLock;
    void setFailed() {
         failed = true;
    private synchronized boolean waitForState(Processor p, int state) {
         p.addControllerListener(new StateListener());
         failed = false;
         // Call the required method on the processor
         if (state == Processor.Configured) {
         p.configure();
         } else if (state == Processor.Realized) {
         p.realize();
         // Wait until we get an event that confirms the
         // success of the method, or a failure event.
         // See StateListener inner class
         while (p.getState() < state && !failed) {
         synchronized (getStateLock()) {
              try {
              getStateLock().wait();
              } catch (InterruptedException ie) {
              return false;
         if (failed)
         return false;
         else
         return true;
    * Inner Classes
    class StateListener implements ControllerListener {
         public void controllerUpdate(ControllerEvent ce) {
         // If there was an error during configure or
         // realize, the processor will be closed
         if (ce instanceof ControllerClosedEvent)
              setFailed();
         // All controller events, send a notification
         // to the waiting thread in waitForState method.
         if (ce instanceof ControllerEvent) {
              synchronized (getStateLock()) {
              getStateLock().notifyAll();
    * Sample Usage for AVTransmit2 class
    public static void main(String [] args) {
         // We need three parameters to do the transmission
         // For example,
         // java AVTransmit2 file:/C:/media/test.mov 129.130.131.132 42050
         /*if (args.length < 3) {
         prUsage();
         Format fmt = null;
         int i = 0;
         // Create a audio transmit object with the specified params.
         //AVTransmit2 at = new AVTransmit2(new MediaLocator(args[i]), args[i+1], args[i+2], fmt);
         AVTransmit2 at = new AVTransmit2(new MediaLocator("file:/C:/sample.mp3"), "172.24.30.58","8088",fmt);
         // Start the transmission
         String result = at.start();
         // result will be non-null if there was an error. The return
         // value is a String describing the possible error. Print it.
         if (result != null) {
         System.err.println("Error : " + result);
         System.exit(0);
         System.err.println("Start transmission for 60 seconds...");
         // Transmit for 60 seconds and then close the processor
         // This is a safeguard when using a capture data source
         // so that the capture device will be properly released
         // before quitting.
         // The right thing to do would be to have a GUI with a
         // "Stop" button that would call stop on AVTransmit2
         try {
         Thread.currentThread().sleep(60000);
         } catch (InterruptedException ie) {
         // Stop the transmission
         at.stop();
         System.err.println("...transmission ended.");
         System.exit(0);
    static void prUsage() {
         System.err.println("Usage: AVTransmit2 <sourceURL> <destIP> <destPortBase>");
         System.err.println(" <sourceURL>: input URL or file name");
         System.err.println(" <destIP>: multicast, broadcast or unicast IP address for the transmission");
         System.err.println(" <destPortBase>: network port numbers for the transmission.");
         System.err.println(" The first track will use the destPortBase.");
         System.err.println(" The next track will use destPortBase + 2 and so on.\n");
         System.exit(0);
    AVReceive2.java/*
    * @(#)AVReceive2.java     1.3 01/03/13
    * Copyright (c) 1999-2001 Sun Microsystems, Inc. All Rights Reserved.
    * Sun grants you ("Licensee") a non-exclusive, royalty free, license to use,
    * modify and redistribute this software in source and binary code form,
    * provided that i) this copyright notice and license appear on all copies of
    * the software; and ii) Licensee does not utilize the software in a manner
    * which is disparaging to Sun.
    * This software is provided "AS IS," without a warranty of any kind. ALL
    * EXPRESS OR IMPLIED CONDITIONS, REPRESENTATIONS AND WARRANTIES, INCLUDING ANY
    * IMPLIED WARRANTY OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE OR
    * NON-INFRINGEMENT, ARE HEREBY EXCLUDED. SUN AND ITS LICENSORS SHALL NOT BE
    * LIABLE FOR ANY DAMAGES SUFFERED BY LICENSEE AS A RESULT OF USING, MODIFYING
    * OR DISTRIBUTING THE SOFTWARE OR ITS DERIVATIVES. IN NO EVENT WILL SUN OR ITS
    * LICENSORS BE LIABLE FOR ANY LOST REVENUE, PROFIT OR DATA, OR FOR DIRECT,
    * INDIRECT, SPECIAL, CONSEQUENTIAL, INCIDENTAL OR PUNITIVE DAMAGES, HOWEVER
    * CAUSED AND REGARDLESS OF THE THEORY OF LIABILITY, ARISING OUT OF THE USE OF
    * OR INABILITY TO USE SOFTWARE, EVEN IF SUN HAS BEEN ADVISED OF THE
    * POSSIBILITY OF SUCH DAMAGES.
    * This software is not designed or intended for use in on-line control of
    * aircraft, air traffic, aircraft navigation or aircraft communications; or in
    * the design, construction, operation or maintenance of any nuclear
    * facility. Licensee represents and warrants that it will not use or
    * redistribute the Software for such purposes.
    import java.io.*;
    import java.awt.*;
    import java.net.*;
    import java.awt.event.*;
    import java.util.Vector;
    import javax.media.*;
    import javax.media.rtp.*;
    import javax.media.rtp.event.*;
    import javax.media.rtp.rtcp.*;
    import javax.media.protocol.*;
    import javax.media.protocol.DataSource;
    import javax.media.format.AudioFormat;
    import javax.media.format.VideoFormat;
    import javax.media.Format;
    import javax.media.format.FormatChangeEvent;
    import javax.media.control.BufferControl;
    * AVReceive2 to receive RTP transmission using the new RTP API.
    public class AVReceive2 implements ReceiveStreamListener, SessionListener,
         ControllerListener
    String sessions[] = null;
    RTPManager mgrs[] = null;
    Vector playerWindows = null;
    boolean dataReceived = false;
    Object dataSync = new Object();
    public AVReceive2(String sessions[]) {
         this.sessions = sessions;
    protected boolean initialize() {
    try {
         InetAddress ipAddr;
         SessionAddress localAddr = new SessionAddress();
         SessionAddress destAddr;
         mgrs = new RTPManager[sessions.length];
         playerWindows = new Vector();
         SessionLabel session;
         // Open the RTP sessions.
         for (int i = 0; i < sessions.length; i++) {
              // Parse the session addresses.
              try {
              session = new SessionLabel(sessions[i]);
              } catch (IllegalArgumentException e) {
              System.err.println("Failed to parse the session address given: " + sessions[i]);
              return false;
              System.err.println(" - Open RTP session for: addr: " + session.addr + " port: " + session.port + " ttl: " + session.ttl);
              mgrs[i] = (RTPManager) RTPManager.newInstance();
              mgrs[i].addSessionListener(this);
              mgrs[i].addReceiveStreamListener(this);
              ipAddr = InetAddress.getByName(session.addr);
              if( ipAddr.isMulticastAddress()) {
              // local and remote address pairs are identical:
              localAddr= new SessionAddress( ipAddr,
                                  session.port,
                                  session.ttl);
              destAddr = new SessionAddress( ipAddr,
                                  session.port,
                                  session.ttl);
              } else {
              localAddr= new SessionAddress( InetAddress.getLocalHost(),
                             session.port);
    destAddr = new SessionAddress( ipAddr, session.port);
              mgrs[i].initialize( localAddr);
              // You can try out some other buffer size to see
              // if you can get better smoothness.
              BufferControl bc = (BufferControl)mgrs[i].getControl("javax.media.control.BufferControl");
              if (bc != null)
              bc.setBufferLength(350);
              mgrs[i].addTarget(destAddr);
    } catch (Exception e){
    System.err.println("Cannot create the RTP Session: " + e.getMessage());
    return false;
         // Wait for data to arrive before moving on.
         long then = System.currentTimeMillis();
         long waitingPeriod = 30000; // wait for a maximum of 30 secs.
         try{
         synchronized (dataSync) {
              while (!dataReceived &&
                   System.currentTimeMillis() - then < waitingPeriod) {
              if (!dataReceived)
                   System.err.println(" - Waiting for RTP data to arrive...");
              dataSync.wait(1000);
         } catch (Exception e) {}
         if (!dataReceived) {
         System.err.println("No RTP data was received.");
         close();
         return false;
    return true;
    public boolean isDone() {
         return playerWindows.size() == 0;
    * Close the players and the session managers.
    protected void close() {
         for (int i = 0; i < playerWindows.size(); i++) {
         try {
              ((PlayerWindow)playerWindows.elementAt(i)).close();
         } catch (Exception e) {}
         playerWindows.removeAllElements();
         // close the RTP session.
         for (int i = 0; i < mgrs.length; i++) {
         if (mgrs[i] != null) {
    mgrs[i].removeTargets( "Closing session from AVReceive2");
    mgrs[i].dispose();
              mgrs[i] = null;
    PlayerWindow find(Player p) {
         for (int i = 0; i < playerWindows.size(); i++) {
         PlayerWindow pw = (PlayerWindow)playerWindows.elementAt(i);
         if (pw.player == p)
              return pw;
         return null;
    PlayerWindow find(ReceiveStream strm) {
         for (int i = 0; i < playerWindows.size(); i++) {
         PlayerWindow pw = (PlayerWindow)playerWindows.elementAt(i);
         if (pw.stream == strm)
              return pw;
         return null;
    * SessionListener.
    public synchronized void update(SessionEvent evt) {
         if (evt instanceof NewParticipantEvent) {
         Participant p = ((NewParticipantEvent)evt).getParticipant();
         System.err.println(" - A new participant had just joined: " + p.getCNAME());
    * ReceiveStreamListener
    public synchronized void update( ReceiveStreamEvent evt) {
         RTPManager mgr = (RTPManager)evt.getSource();
         Participant participant = evt.getParticipant();     // could be null.
         ReceiveStream stream = evt.getReceiveStream(); // could be null.
         if (evt instanceof RemotePayloadChangeEvent) {
         System.err.println(" - Received an RTP PayloadChangeEvent.");
         System.err.println("Sorry, cannot handle payload change.");
         System.exit(0);
         else if (evt instanceof NewReceiveStreamEvent) {
         try {
              stream = ((NewReceiveStreamEvent)evt).getReceiveStream();
              DataSource ds = stream.getDataSource();
              // Find out the formats.
              RTPControl ctl = (RTPControl)ds.getControl("javax.media.rtp.RTPControl");
              if (ctl != null){
              System.err.println(" - Recevied new RTP stream: " + ctl.getFormat());
              } else
              System.err.println(" - Recevied new RTP stream");
              if (participant == null)
              System.err.println(" The sender of this stream had yet to be identified.");
              else {
              System.err.println(" The stream comes from: " + participant.getCNAME());
              // create a player by passing datasource to the Media Manager
              Player p = javax.media.Manager.createPlayer(ds);
              if (p == null)
              return;
              p.addControllerListener(this);
              p.realize();
              PlayerWindow pw = new PlayerWindow(p, stream);
              playerWindows.addElement(pw);
              // Notify intialize() that a new stream had arrived.
              synchronized (dataSync) {
              dataReceived = true;
              dataSync.notifyAll();
         } catch (Exception e) {
              System.err.println("NewReceiveStreamEvent exception " + e.getMessage());
              return;
         else if (evt instanceof StreamMappedEvent) {
         if (stream != null && stream.getDataSource() != null) {
              DataSource ds = stream.getDataSource();
              // Find out the formats.
              RTPControl ctl = (RTPControl)ds.getControl("javax.media.rtp.RTPControl");
              System.err.println(" - The previously unidentified stream ");
              if (ctl != null)
              System.err.println(" " + ctl.getFormat());
              System.err.println(" had now been identified as sent by: " + participant.getCNAME());
         else if (evt instanceof ByeEvent) {
         System.err.println(" - Got \"bye\" from: " + participant.getCNAME());
         PlayerWindow pw = find(stream);
         if (pw != null) {
              pw.close();
              playerWindows.removeElement(pw);
    * ControllerListener for the Players.
    public synchronized void controllerUpdate(ControllerEvent ce) {
         Player p = (Player)ce.getSourceController();
         if (p == null)
         return;
         // Get this when the internal players are realized.
         if (ce instanceof RealizeCompleteEvent) {
         PlayerWindow pw = find(p);
         if (pw == null) {
              // Some strange happened.
              System.err.println("Internal error!");
              System.exit(-1);
         pw.initialize();
         pw.setVisible(true);
         p.start();
         if (ce instanceof ControllerErrorEvent) {
         p.removeControllerListener(this);
         PlayerWindow pw = find(p);
         if (pw != null) {
              pw.close();     
              playerWindows.removeElement(pw);
         System.err.println("AVReceive2 internal error: " + ce);
    * A utility class to parse the session addresses.
    class SessionLabel {
         public String addr = null;
         public int port;
         public int ttl = 1;
         SessionLabel(String session) throws IllegalArgumentException {
         int off;
         String portStr = null, ttlStr = null;
         if (session != null && session.length() > 0) {
              while (session.length() > 1 && session.charAt(0) == '/')
              session = session.substring(1);
              // Now see if there's a addr specified.
              off = session.indexOf('/');
              if (off == -1) {
              if (!session.equals(""))
                   addr = session;
              } else {
              addr = session.substring(0, off);
              session = session.substring(off + 1);
              // Now see if there's a port specified
              off = session.indexOf('/');
              if (off == -1) {
                   if (!session.equals(""))
                   portStr = session;
              } else {
                   portStr = session.substring(0, off);
                   session = session.substring(off + 1);
                   // Now see if there's a ttl specified
                   off = session.indexOf('/');
                   if (off == -1) {
                   if (!session.equals(""))
                        ttlStr = session;
                   } else {
                   ttlStr = session.substring(0, off);
         if (addr == null)
              throw new IllegalArgumentException();
         if (portStr != null) {
              try {
              Integer integer = Integer.valueOf(portStr);
              if (integer != null)
                   port = integer.intValue();
              } catch (Throwable t) {
              throw new IllegalArgumentException();
         } else
              throw new IllegalArgumentException();
         if (ttlStr != null) {
              try {
              Integer integer = Integer.valueOf(ttlStr);
              if (integer != null)
                   ttl = integer.intValue();
              } catch (Throwable t) {
              throw new IllegalArgumentException();
    * GUI classes for the Player.
    class PlayerWindow extends Frame {
         Player player;
         ReceiveStream stream;
         PlayerWindow(Player p, ReceiveStream strm) {
         player = p;
         stream = strm;
         public void initialize() {
         add(new PlayerPanel(player));
         public void close() {
         player.close();
         setVisible(false);
         dispose();
         public void addNotify() {
         super.addNotify();
         pack();
    * GUI classes for the Player.
    class PlayerPanel extends Panel {
         Component vc, cc;
         PlayerPanel(Player p) {
         setLayout(new BorderLayout());
         if ((vc = p.getVisualComponent()) != null)
              add("Center", vc);
         if ((cc = p.getControlPanelComponent()) != null)
              add("South", cc);
         public Dimension getPreferredSize() {
         int w = 0, h = 0;
         if (vc != null) {
              Dimension size = vc.getPreferredSize();
              w = size.width;
              h = size.height;
         if (cc != null) {
              Dimension size = cc.getPreferredSize();
              if (w == 0)
              w = size.width;
              h += size.height;
         if (w < 160)
              w = 160;
         return new Dimension(w, h);
    public static void main(String argv[]) {
         // if (argv.length == 0)
         // prUsage();
         String[] sessions = {"172.24.30.58/8080/1"} ;
         AVReceive2 avReceive = new AVReceive2(sessions);
         if (!avReceive.initialize()) {
         System.err.println("Failed to initialize the sessions.");
         System.exit(-1);
         // Check to see if AVReceive2 is done.
         try {
         while (!avReceive.isDone())
              Thread.sleep(1000);
         } catch (Exception e) {}
         System.err.println("Exiting AVReceive2");
    static void prUsage() {
         System.err.println("Usage: AVReceive2 <session> <session> ...");
         System.err.println(" <session>: <address>/<port>/<ttl>");
         System.exit(0);
    }// end of AVReceive2
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                             

    Question is ancient, and answered by experience.

  • AVReceiver2 only received two ReceiveStreamEvents

    Hi, I am new to JMF. I tailed the AVReceiver2 but it can only receive two ReceiveStreamEvents, one is NewReceiveStreamEvent and the other, StreamMappedEvent as I ran and traced the code. Below is the code.
    JMF gurus, thanks in advance for your help.
    import java.io.*;
    import java.awt.*;
    import java.net.*;
    import java.util.Vector;
    import javax.media.*;
    import javax.media.rtp.*;
    import javax.media.rtp.event.*;
    import javax.media.protocol.*;
    import javax.media.format.AudioFormat;
    import javax.media.format.VideoFormat;
    import javax.media.Format;
    import javax.media.control.BufferControl;
    import javax.media.control.MpegAudioControl;
    import javax.media.control.FrameRateControl;
    import org.apache.log4j.Logger;
    public class Receiver implements ReceiveStreamListener, SessionListener, ControllerListener {
         private static final Logger logger =
                 Logger.getLogger(Receiver.class);
        private RTPManager recvMgrs[] = null;
        private static boolean bye=false;
        boolean dataReceived = false;   
        Socket socketRTPReceiver=null;
        Socket socketRTCPReceiver=null;
        private String localAddr = null;
        private int localPort;
        private String remoteAddr = null;
        private int remotePort;
        private int ttl;
        private long timeStamp = 0;
        public Receiver (int localPort, String remoteAddr, int remotePort, int ttl, int AVOpt) {         
             this.localPort = localPort;
             this.remoteAddr = remoteAddr;
             this.remotePort = remotePort;
             this.ttl = ttl;         
             //generate a single RTP manager only for audio stream,
             if ((AVOpt == 0) || (AVOpt == 1)) //either audio only or video only
                  recvMgrs = new RTPManager[1];
             else if (AVOpt == 2) //receive both audio and video
                  recvMgrs = new RTPManager[2];
        private boolean initilaize () {
             InetAddress ipAddr;
             SessionAddress localAddr = new SessionAddress();
             SessionAddress destAddr;
             if (recvMgrs == null)
                  return false;
             try {
                  for (int i= 0; i<recvMgrs.length; i++) {              
                       recvMgrs[i] = (RTPManager) RTPManager.newInstance();
                       recvMgrs.addSessionListener(this);
                   recvMgrs[i].addReceiveStreamListener(this);
                   ipAddr = InetAddress.getByName(getRemoteAddr());
                   localAddr= new SessionAddress( InetAddress.getLocalHost(),
                        getLocalPort());
                   destAddr = new SessionAddress( ipAddr, getRemotePort());
                   logger.debug("======== ====== detsAddr = " + getRemoteAddr() + "remotePort = " + getRemotePort());               
                   logger.debug("======== ====== localAddr = " + InetAddress.getLocalHost() + "localPort = " + getLocalPort());
                   recvMgrs[i].initialize( localAddr);
                   // You can try out some other buffer size to see
                   // if you can get better smoothness.
                   BufferControl bc = (BufferControl)recvMgrs[i].getControl("javax.media.control.BufferControl");
                   if (bc != null)
                        bc.setBufferLength(350);
                   recvMgrs[i].addTarget(destAddr);
         } catch (Exception e){
              logger.error("Cannot create the RTP Session: " + e.getMessage());
              return false;
    return true;
    public void start () {
         if (! initilaize())
              logger.fatal("cannot start the Receiver.initialize()");
    public void stop () {
         // close the RTP session.
         logger.debug("========= Stop the receiver now ......");
         for (int i = 0; i < recvMgrs.length; i++) {
              if (recvMgrs[i] != null) {
                   recvMgrs[i].removeReceiveStreamListener(this);
                   recvMgrs[i].removeSessionListener(this);
                   recvMgrs[i].removeTargets( "Closing session from Receiver");
                   recvMgrs[i].dispose();
                   recvMgrs[i] = null;
    public synchronized void update(SessionEvent evt)
    if (evt instanceof NewParticipantEvent)
    Participant p = ((NewParticipantEvent) evt).getParticipant();
    logger.info("A new participant had just joined: " + p.getCNAME());
    public synchronized void update(ReceiveStreamEvent evt)
    Participant participant = evt.getParticipant(); // could be null.
    ReceiveStream stream = evt.getReceiveStream(); // could be null.
    if (evt instanceof RemotePayloadChangeEvent)
    logger.warn("Received an RTP PayloadChangeEvent," +
    " not supported cannot handle payload change.");
         //TBA: close this session
         //close();
    else if (evt instanceof NewReceiveStreamEvent)
         logger.debug("receiving a new ReceiveStreamEvent .....!");
    try
    stream = ((NewReceiveStreamEvent) evt).getReceiveStream();
    DataSource ds = stream.getDataSource();
    // Find out the formats.
    RTPControl ctl =
    (RTPControl) ds.getControl("javax.jmf.rtp.RTPControl");
    if (ctl != null)
    logger.info("Recevied new RTP stream: " + ctl.getFormat());
    else {
    logger.info("Recevied new RTP stream");
    if (participant == null)
    logger.info("The sender of this stream" +
    "had yet to be identified.");
    else
    logger.info("The stream comes from: " +
    participant.getCNAME());
    catch (Exception e)
    logger.warn("NewReceiveStreamEvent exception ", e);
    return;
    else if (evt instanceof StreamMappedEvent)
         logger.debug ("receiving StreammappedEvent ....");
    if (stream != null && stream.getDataSource() != null)
    DataSource ds = stream.getDataSource();
    // Find out the formats.
    RTPControl ctl =
    (RTPControl) ds.getControl("javax.jmf.rtp.RTPControl");
    logger.info("The previously unidentified stream ");
    if (ctl != null)
    logger.info(": " + ctl.getFormat());
    logger.info(" had now been identified as sent by: "
    + participant.getCNAME());
    else if (evt instanceof ByeEvent)
    logger.info("Got \"bye\" from: " + participant.getCNAME());
    public synchronized void controllerUpdate(ControllerEvent ce)
         logger.debug ("receiving controlUpdate ..........");
         return;      

    I changed the code with threading model and RTPConnectionAdapter as below. almost same as avReceiver2 or avReceiver3. Once the code starts, it is in the a while-loop, sleeping, then printing a log. So, I can know the thread is alive and wait for any new streamEvent from update(), I hope. Unfortuantely, from the log of RTPConnectionAdaptor, the UDP socket kept receiving datagram packets from the network(I confirmed from SockInputStream.read() and SockInputStream.run()), but the Receiver thread still only received two ReceiverStreamEvents. It is very frustrated. Could anyone explain what is going wrong in the code? Thanks in advance,
    public class Receiver extends Thread implements ReceiveStreamListener, SessionListener, ControllerListener {
         private static final Logger logger =
                 Logger.getLogger(Receiver.class);
        private RTPManager recvMgrs[] = null;
        private static boolean bye=false;
        private String localAddr = null;
        private int localPort;
        private String remoteAddr = null;
        private int remotePort;
        private int ttl;
        private long timeStamp = 0;
        public Receiver (int localPort, String remoteAddr, int remotePort, int ttl, int AVOpt) {         
             this.localPort = localPort;
             this.remoteAddr = remoteAddr;
             this.remotePort = remotePort;
             this.ttl = ttl;         
             //generate a single RTP manager only for audio stream,
             if ((AVOpt == 0) || (AVOpt == 1)) //either audio only or video only
                  recvMgrs = new RTPManager[1];
             else if (AVOpt == 2) //receive both audio and video
                  recvMgrs = new RTPManager[2];
            initilaize ();
         running = true;
        private boolean initilaize () {
             InetAddress ipAddr;
             SessionAddress localAddr = new SessionAddress();
             SessionAddress destAddr;
             if (recvMgrs == null)
                  return false;
             try {
                  for (int i= 0; i<recvMgrs.length; i++) {              
                       recvMgrs[i] = (RTPManager) RTPManager.newInstance();
                       recvMgrs.addSessionListener(this);
                   recvMgrs[i].addReceiveStreamListener(this);
                   ipAddr = InetAddress.getByName(getRemoteAddr());
                   localAddr= new SessionAddress( InetAddress.getLocalHost(),
                        getLocalPort());
                   destAddr = new SessionAddress( ipAddr, getRemotePort());
                   logger.debug("======== ====== detsAddr = " + getRemoteAddr() + "remotePort = " + getRemotePort());               
                   logger.debug("======== ====== localAddr = " + InetAddress.getLocalHost() + "localPort = " + getLocalPort());
                   recvMgrs[i].initialize(new RTPSocketAdapter(InetAddress.getLocalHost(), getLocalPort(), ttl));
                   // You can try out some other buffer size to see
                   // if you can get better smoothness.
                   BufferControl bc = (BufferControl)recvMgrs[i].getControl("javax.media.control.BufferControl");
                   if (bc != null)
                        bc.setBufferLength(350);
                   recvMgrs[i].addTarget(destAddr);
         } catch (Exception e){
              logger.error("Cannot create the RTP Session: " + e.getMessage());
              return false;
    return true;
    public void halt () {
         running = false;
    public void run () {
              while (running) {
                   logger.debug ("get into running-while loop ....1111");               
                   sleep(3000);
              close();
    public void close () {
         // close the RTP session.
         logger.debug("========= Stop the receiver now ......");
         for (int i = 0; i < recvMgrs.length; i++) {
              if (recvMgrs[i] != null) {
                   recvMgrs[i].removeReceiveStreamListener(this);
                   recvMgrs[i].removeSessionListener(this);
                   recvMgrs[i].removeTargets( "Closing session from Receiver");
                   recvMgrs[i].dispose();
                   recvMgrs[i] = null;
    public synchronized void update(SessionEvent evt)
    if (evt instanceof NewParticipantEvent)
    Participant p = ((NewParticipantEvent) evt).getParticipant();
    logger.info("A new participant had just joined: " + p.getCNAME());
    public synchronized void update(ReceiveStreamEvent evt)
    Participant participant = evt.getParticipant(); // could be null.
    ReceiveStream stream = evt.getReceiveStream(); // could be null.
    if (evt instanceof RemotePayloadChangeEvent)
    logger.warn("Received an RTP PayloadChangeEvent," +
    " not supported cannot handle payload change.");
         //TBA: close this session
         //close();
    else if (evt instanceof NewReceiveStreamEvent)
         logger.debug("receiving a new ReceiveStreamEvent .....!");
    try
    stream = ((NewReceiveStreamEvent) evt).getReceiveStream();
    DataSource ds = stream.getDataSource();
    // Find out the formats.
    RTPControl ctl =
    (RTPControl) ds.getControl("javax.jmf.rtp.RTPControl");
    if (ctl != null)
    logger.info("Recevied new RTP stream: " + ctl.getFormat());
    else {
    logger.info("Recevied new RTP stream");
    if (participant == null)
    logger.info("The sender of this stream" +
    "had yet to be identified.");
    else
    logger.info("The stream comes from: " +
    participant.getCNAME());
    catch (Exception e)
    logger.warn("NewReceiveStreamEvent exception ", e);
    return;
    else if (evt instanceof StreamMappedEvent)
         logger.debug ("receiving StreammappedEvent ....");
    if (stream != null && stream.getDataSource() != null)
    DataSource ds = stream.getDataSource();
    // Find out the formats.
    RTPControl ctl =
    (RTPControl) ds.getControl("javax.jmf.rtp.RTPControl");
    logger.info("The previously unidentified stream ");
    if (ctl != null)
    logger.info(": " + ctl.getFormat());
    logger.info(" had now been identified as sent by: "
    + participant.getCNAME());
    else if (evt instanceof ByeEvent)
    logger.info("Got \"bye\" from: " + participant.getCNAME());
    public synchronized void controllerUpdate(ControllerEvent ce)
         logger.debug ("receiving controlUpdate ..........");
         return;      

  • Connecting view button to player! help

    hi! I have posted my codes for Client and ClientChoice.
    in the actionlistener event of the ClientChoice(gui) have i have called the Client class where the player is found and where connection is made to the server. the error i get is that the .class of the Client is:
    mainCl(java.lang.String[]) in Client cannot be applied to (java.lang.String,java.lang.String)          cl.mainCl(a,b);
    can anyone help me ! am i doing the right thing or someway else plz help me......i have a week on that and i'm being late. here are the code:
    //Client.java
    //package ana;
    import java.io.*;
    import java.awt.*;
    import java.net.*;
    import java.awt.event.*;
    import java.util.Vector;
    import javax.media.*;
    import javax.media.rtp.*;
    import javax.media.rtp.event.*;
    import javax.media.rtp.rtcp.*;
    import javax.media.protocol.*;
    import javax.media.protocol.DataSource;
    import javax.media.format.AudioFormat;
    import javax.media.format.VideoFormat;
    import javax.media.Format;
    import javax.media.format.FormatChangeEvent;
    import javax.media.control.BufferControl;
    * Client to receive RTP transmission using the RTPConnector.
    public class Client implements ReceiveStreamListener, SessionListener,
         ControllerListener
    String sessions[] = null;
    RTPManager mgrs[] = null;
    Vector playerWindows = null;
    boolean dataReceived = false;
    Object dataSync = new Object();
    public Client(String sessions[]) {
         this.sessions = sessions;
    public Client(String a, String b)
         }//constructor
    protected boolean initialize() {
    try {
         mgrs = new RTPManager[sessions.length];
         playerWindows = new Vector();
         SessionLabel session;
         // Open the RTP sessions.
         for (int i = 0; i < sessions.length; i++) {
              // Parse the session addresses.
              try {
              session = new SessionLabel(sessions);
              } catch (IllegalArgumentException e) {
              System.err.println("Failed to parse the session address given: " + sessions[i]);
              return false;
              System.err.println(" - Open RTP session for: addr: " + session.addr + " port: " + session.port + " ttl: " + session.ttl);
              mgrs[i] = (RTPManager) RTPManager.newInstance();
              mgrs[i].addSessionListener(this);
              mgrs[i].addReceiveStreamListener(this);
              // Initialize the RTPManager with the RTPSocketAdapter
              mgrs[i].initialize(new RTPSocketAdapter(
                             InetAddress.getByName(session.addr),
                             session.port, session.ttl));
              // You can try out some other buffer size to see
              // if you can get better smoothness.
              BufferControl bc = (BufferControl)mgrs[i].getControl("javax.media.control.BufferControl");
              if (bc != null)
              bc.setBufferLength(350);
    } catch (Exception e){
    System.err.println("Cannot create the RTP Session: " + e.getMessage());
    return false;
         // Wait for data to arrive before moving on.
         long then = System.currentTimeMillis();
         long waitingPeriod = 30000; // wait for a maximum of 30 secs.
         try{
         synchronized (dataSync) {
              while (!dataReceived &&
                   System.currentTimeMillis() - then < waitingPeriod) {
              if (!dataReceived)
                   System.err.println(" - Waiting for RTP data to arrive...");
              dataSync.wait(1000);
         } catch (Exception e) {}
         if (!dataReceived) {
         System.err.println("No RTP data was received.");
         close();
         return false;
    return true;
    public boolean isDone() {
         return playerWindows.size() == 0;
    * Close the players and the session managers.
    protected void close() {
         for (int i = 0; i < playerWindows.size(); i++) {
         try {
              ((PlayerWindow)playerWindows.elementAt(i)).close();
         } catch (Exception e) {}
         playerWindows.removeAllElements();
         // close the RTP session.
         for (int i = 0; i < mgrs.length; i++) {
         if (mgrs[i] != null) {
    mgrs[i].removeTargets( "Closing session from AVReceive3");
    mgrs[i].dispose();
              mgrs[i] = null;
    PlayerWindow find(Player p) {
         for (int i = 0; i < playerWindows.size(); i++) {
         PlayerWindow pw = (PlayerWindow)playerWindows.elementAt(i);
         if (pw.player == p)
              return pw;
         return null;
    PlayerWindow find(ReceiveStream strm) {
         for (int i = 0; i < playerWindows.size(); i++) {
         PlayerWindow pw = (PlayerWindow)playerWindows.elementAt(i);
         if (pw.stream == strm)
              return pw;
         return null;
    * SessionListener.
    public synchronized void update(SessionEvent evt) {
         if (evt instanceof NewParticipantEvent) {
         Participant p = ((NewParticipantEvent)evt).getParticipant();
         System.err.println(" - A new participant had just joined: " + p.getCNAME());
    * ReceiveStreamListener
    public synchronized void update( ReceiveStreamEvent evt) {
         RTPManager mgr = (RTPManager)evt.getSource();
         Participant participant = evt.getParticipant();     // could be null.
         ReceiveStream stream = evt.getReceiveStream(); // could be null.
         if (evt instanceof RemotePayloadChangeEvent) {
         System.err.println(" - Received an RTP PayloadChangeEvent.");
         System.err.println("Sorry, cannot handle payload change.");
         System.exit(0);
         else if (evt instanceof NewReceiveStreamEvent) {
         try {
              stream = ((NewReceiveStreamEvent)evt).getReceiveStream();
              DataSource ds = stream.getDataSource();
              // Find out the formats.
              RTPControl ctl = (RTPControl)ds.getControl("javax.media.rtp.RTPControl");
              if (ctl != null){
              System.err.println(" - Recevied new RTP stream: " + ctl.getFormat());
              } else
              System.err.println(" - Recevied new RTP stream");
              if (participant == null)
              System.err.println(" The sender of this stream had yet to be identified.");
              else {
              System.err.println(" The stream comes from: " + participant.getCNAME());
              // create a player by passing datasource to the Media Manager
              Player p = javax.media.Manager.createPlayer(ds);
              if (p == null)
              return;
              p.addControllerListener(this);
              p.realize();
              PlayerWindow pw = new PlayerWindow(p, stream);
              playerWindows.addElement(pw);
              // Notify intialize() that a new stream had arrived.
              synchronized (dataSync) {
              dataReceived = true;
              dataSync.notifyAll();
         } catch (Exception e) {
              System.err.println("NewReceiveStreamEvent exception " + e.getMessage());
              return;
         else if (evt instanceof StreamMappedEvent) {
         if (stream != null && stream.getDataSource() != null) {
              DataSource ds = stream.getDataSource();
              // Find out the formats.
              RTPControl ctl = (RTPControl)ds.getControl("javax.media.rtp.RTPControl");
              System.err.println(" - The previously unidentified stream ");
              if (ctl != null)
              System.err.println(" " + ctl.getFormat());
              System.err.println(" had now been identified as sent by: " + participant.getCNAME());
         else if (evt instanceof ByeEvent) {
         System.err.println(" - Got \"bye\" from: " + participant.getCNAME());
         PlayerWindow pw = find(stream);
         if (pw != null) {
              pw.close();
              playerWindows.removeElement(pw);
    * ControllerListener for the Players.
    public synchronized void controllerUpdate(ControllerEvent ce) {
         Player p = (Player)ce.getSourceController();
         if (p == null)
         return;
         // Get this when the internal players are realized.
         if (ce instanceof RealizeCompleteEvent) {
         PlayerWindow pw = find(p);
         if (pw == null) {
              // Some strange happened.
              System.err.println("Internal error!");
              System.exit(-1);
         pw.initialize();
         pw.setVisible(true);
         p.start();
         if (ce instanceof ControllerErrorEvent) {
         p.removeControllerListener(this);
         PlayerWindow pw = find(p);
         if (pw != null) {
              pw.close();
              playerWindows.removeElement(pw);
              //p.close(); //i added to know if player close when click
         System.err.println("Client internal error: " + ce);
    * A utility class to parse the session addresses.
    class SessionLabel {
         public String addr = null;
         public int port;
         public int ttl = 1;
         SessionLabel(String session) throws IllegalArgumentException {
         int off;
         String portStr = null, ttlStr = null;
         if (session != null && session.length() > 0) {
              while (session.length() > 1 && session.charAt(0) == '/')
              session = session.substring(1);
              // Now see if there's a addr specified.
              off = session.indexOf('/');
              if (off == -1) {
              if (!session.equals(""))
                   addr = session;
              } else {
              addr = session.substring(0, off);
              session = session.substring(off + 1);
              // Now see if there's a port specified
              off = session.indexOf('/');
              if (off == -1) {
                   if (!session.equals(""))
                   portStr = session;
              } else {
                   portStr = session.substring(0, off);
                   session = session.substring(off + 1);
                   // Now see if there's a ttl specified
                   off = session.indexOf('/');
                   if (off == -1) {
                   if (!session.equals(""))
                        ttlStr = session;
                   } else {
                   ttlStr = session.substring(0, off);
         if (addr == null)
              throw new IllegalArgumentException();
         if (portStr != null) {
              try {
              Integer integer = Integer.valueOf(portStr);
              if (integer != null)
                   port = integer.intValue();
              } catch (Throwable t) {
              throw new IllegalArgumentException();
         } else
              throw new IllegalArgumentException();
         if (ttlStr != null) {
              try {
              Integer integer = Integer.valueOf(ttlStr);
              if (integer != null)
                   ttl = integer.intValue();
              } catch (Throwable t) {
              throw new IllegalArgumentException();
    * GUI classes for the Player.
    class PlayerWindow extends Frame {
         Player player;
         ReceiveStream stream;
         PlayerWindow(Player p, ReceiveStream strm) {
         player = p;
         stream = strm;
         public void initialize() {
         add(new PlayerPanel(player));
         public void close() {
         player.close();
         setVisible(false);
         dispose();
         public void addNotify() {
         super.addNotify();
         pack();
    * GUI classes for the Player.
    class PlayerPanel extends Panel {
         Component vc, cc;
         PlayerPanel(Player p) {
         setLayout(new BorderLayout());
         if ((vc = p.getVisualComponent()) != null)
              add("Center", vc);
         if ((cc = p.getControlPanelComponent()) != null)
              add("South", cc);
         public Dimension getPreferredSize() {
         int w = 0, h = 0;
         if (vc != null) {
              Dimension size = vc.getPreferredSize();
              w = size.width;
              h = size.height;
         if (cc != null) {
              Dimension size = cc.getPreferredSize();
              if (w == 0)
              w = size.width;
              h += size.height;
         if (w < 160)
              w = 160;
         return new Dimension(w, h);
    public static void mainCl(String argv[])
         if (argv.length == 0)
         prUsage();
         Client avReceive = new Client(argv);
         if (!avReceive.initialize()) {
         System.err.println("Failed to initialize the sessions.");
         System.exit(-1);
         // Check to see if Client is done.
         try {
         while (!avReceive.isDone())
              Thread.sleep(1000);
         } catch (Exception e) {}
         System.err.println("Exiting Client");
    static void prUsage() {
         System.err.println("Usage: Client <session> <session> ...");
         System.err.println(" <session>: <address>/<port>/<ttl>");
         System.exit(0);
    }// end of Client
    //package ana;
    import javax.swing.*;
    import javax.swing.UIManager;
    import java.awt.*;
    import java.awt.event.*;
    public class ClientChoice
         public static void main(String args[])
              try
                             UIManager.setLookAndFeel(UIManager.getCrossPlatformLookAndFeelClassName());
                        catch(Exception e)
         }//main
         JFrame frame=new JFrame("--- New Line Movie ---");
         //Create the menu bar
         JMenuBar menuBar;
         JMenu menu;
         menuBar = new JMenuBar();
         //Build the file menu in the menu bar
         menu = new JMenu("File");
         menu.setMnemonic(KeyEvent.VK_F);
         menuBar.add(menu);
         JMenuItem menuItem= new JMenuItem("Exit",KeyEvent.VK_X);
         menuItem.addActionListener(new ActionListener()
              public void actionPerformed(ActionEvent e)
                        System.exit(0);
         menu.add(menuItem);
         //Build help menu in the menu bar.
         menu = new JMenu("Help");
         menu.setMnemonic(KeyEvent.VK_H);
         menuBar.add(menu);
         JMenuItem help_item=new JMenuItem("Help Topics",KeyEvent.VK_T);
         menu.add(help_item);
         JMenuItem about_item=new JMenuItem("About Us");
         menu.add(about_item);
         frame.setJMenuBar(menuBar);
              ImageIcon icon=new ImageIcon("images/potter.jpg","");
              JButton clickmovie=new JButton(icon);
              //final JLabel latest=new JLabel("<html><caption>Harry Potter</caption></html>");
              //clickmovie.add(latest);
              final JLabel welcome1=new JLabel("<html><font color=blue face=arial size=3><strong>New Line Movie</strong> gives you the possibility to view your favorite movies.<br>You can choose your category of movies below and click on any movie to get more information about it. <br>Latest News about new movies are also available. ENJOY!!!</font></html>");
              frame.getContentPane().add(welcome1,BorderLayout.EAST);
              final JLabel copyright=new JLabel("<html><font color=blue face=arial size=3><p align=center>&copy Copyright 2004</p></font></html>");
              //frame.getContentPane().add(copyright,BorderLayout.EAST);
              JPanel actionPanel=new JPanel();
              JPanel cartoonPanel=new JPanel();
              JPanel comedyPanel=new JPanel();
              JPanel fictionPanel=new JPanel();
              JPanel mainPanel=new JPanel();
              mainPanel.setLayout(new GridLayout(2,1,5,5));
              mainPanel.setBorder(BorderFactory.createEmptyBorder(5,5,5,5));
              mainPanel.add(actionPanel);
              mainPanel.add(cartoonPanel);
              mainPanel.add(comedyPanel);
              mainPanel.add(fictionPanel);
              //mainPanel.add(copyright);
              actionPanel.setBorder(BorderFactory.createCompoundBorder(BorderFactory.createTitledBorder("Action"),BorderFactory.createEmptyBorder(5,5,5,5)));
              cartoonPanel.setBorder(BorderFactory.createCompoundBorder(BorderFactory.createTitledBorder("Cartoon"),BorderFactory.createEmptyBorder(5,5,5,5)));
              comedyPanel.setBorder(BorderFactory.createCompoundBorder(BorderFactory.createTitledBorder("Comedy"),BorderFactory.createEmptyBorder(5,5,5,5)));
              fictionPanel.setBorder(BorderFactory.createCompoundBorder(BorderFactory.createTitledBorder("Science Fiction"),BorderFactory.createEmptyBorder(5,5,5,5)));
              frame.getContentPane().add(mainPanel,BorderLayout.SOUTH);
              frame.getContentPane().add(clickmovie,BorderLayout.WEST);
              // Create combo box with action movies choices
              final JComboBox actionChoices;
              String[] actionmovie={"-Select a movie-","X-Men","Spiderman"};
              actionChoices=new JComboBox(actionmovie);
              actionChoices.setSelectedIndex(0);
              actionPanel.add(actionChoices);
              actionChoices.addActionListener(new ActionListener()
                   public void actionPerformed(ActionEvent e)
                        JComboBox cb = (JComboBox)e.getSource();
                        String act = (String)cb.getSelectedItem();
                        if(act=="X-Men")
                             JFrame action_xmen= new JFrame("--- New Line Movie: X-Men --- ");
                   action_xmen.setSize(400,350);
                   JPanel main=new JPanel();
                   main.setLayout(new GridLayout(2,1,5,5));
                             main.setBorder(BorderFactory.createEmptyBorder(5,5,5,5));
                             ImageIcon icon_men=new ImageIcon("images/x-men.jpg","");
                   JButton clickmovie_men=new JButton(icon_men);
                   final JLabel xmen_overview=new JLabel("<html><font color=blue face=arial size=3><b>Title:</b></font> <font color=black><strong>X-Men 2 </strong></font> <br><br><font color=blue face=arial size=3><b>Starring:</b> Hugh JACKMAN and Halle BARRY<br><br><b>Story:</b> The time has come for those who are different to stand united. <br><br>A military officer with a link to Wolverine's mysterious past conspires <br><br>to eradicate the mutant population for once and all. In order to defeat <br><br>this new menace, the X-men will be forced to join forces with Magneto. <br><br><b>Duration:</b> 1hr45min </font></html>");
                   final JLabel copyright=new JLabel("<html><font color=blue face=arial size=3><p align=center>&copy Copyright 2004</p></font></html>");
                             action_xmen.getContentPane().add(copyright,BorderLayout.SOUTH);
                   JButton view=new JButton("View");
                   view.setLayout(new BoxLayout(view,BoxLayout.X_AXIS));
                                            view.add(Box.createHorizontalGlue());
                             view.add(Box.createRigidArea(new Dimension(30,0)));
                   view.setMinimumSize(new Dimension(20,100));
                   view.setPreferredSize(new Dimension(20,100));
                   view.setMaximumSize(new Dimension(Short.MAX_VALUE,Short.MAX_VALUE));
                   view.setMnemonic('v');
                   view.addActionListener(new ActionListener()
                                  public void actionPerformed(ActionEvent e)
                                            String a="172.22.45.44/42050";
                                            String b="172.22.45.44/42052";
                                            String argv=a+b;
                                            Client cl= new Client(a,b);
                                            cl.mainCl(a,b);
                                            //this is the code i added so that on clicking the view button
                                            //the client is automatically connected to the server and the player
                                            //plays on the current machine
                   main.add(clickmovie_men);
                             main.add(view);
                             //action_xmen.getContentPane().add(view,BorderLayout.SOUTH);
                   action_xmen.getContentPane().add(main,BorderLayout.WEST);
                   action_xmen.getContentPane().add(xmen_overview,BorderLayout.EAST);
                   action_xmen.show();
                        else if(act=="Spiderman")
                             JFrame action_spider= new JFrame("--- New Line Movie: Spiderman --- ");
                             action_spider.setSize(400,350);
                   action_spider.show();
              //Create combo box with cartoon movies choices
              JComboBox cartoonChoices=null;
              String[] cartoonmovie={"-Select a movie-","Le Roi Lion"};
              cartoonChoices=new JComboBox(cartoonmovie);
              cartoonChoices.setSelectedIndex(0);
              cartoonPanel.add(cartoonChoices);
              //cartoonChoices.addActionListener();
              //Create combo box with comedy movies choices
              JComboBox comedyChoices=null;
              String[] comedymovie={"-Select a movie-"};
              comedyChoices=new JComboBox(comedymovie);
              comedyChoices.setSelectedIndex(0);
              comedyPanel.add(comedyChoices);
              //comedyChoices.addActionListener();
              //Create combo box with fiction movies choices
              JComboBox fictionChoices=null;
              String[] fictionmovie={"-Select a movie-","ET"};
              fictionChoices=new JComboBox(fictionmovie);
              fictionChoices.setSelectedIndex(0);
              fictionPanel.add(fictionChoices);
              //fictionChoices.addActionListener();
              frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
              frame.pack();
              frame.setVisible(true);
    //Implement player function here
    }//end of ClientChoice

    You are passing two String objects to a method that accepts an String array.
    try this to get rid of one error.
    Client cl = new Client(a, b);
    String[] c = {a,b};
    Client.mainCl(c);

  • Do any one kown how to encoder pcm to alaw if you use jmf?

    I'm have the problem about it how to encoder pcm to alaw?
    I find some code about it, but not work in jmf.
    A friend in forum tell me write it by myself , because jmf not support for alaw.
    But i'm new about this, so i want whether somebody could help me if you have the same code about this.
    code like this:
    capture.java
    * support : locator, datasource
    public class Capture extends MainFrame {
        private static final long serialVersionUID = 1L;
        private Processor cp = null;
        private Boolean isMix = false;
        private Boolean isUlaw = false;
        private MainFrame mf = null;
        public Capture(MainFrame mf, boolean useVideo) {
            this.isMix = useVideo;
            this.mf = mf;
        public Capture(MainFrame mf) {
            this.mf = mf;
        public Capture(boolean useVideo) {
            this.isMix = false;
        //get video MediaLocator
        public MediaLocator getVideoLocator() {
            MediaLocator VideoLocator = null;
            Vector VideoCaptureList = null;
            CaptureDeviceInfo VideoCaptureDeviceInfo = null;
            VideoFormat videoFormat = new VideoFormat(VideoFormat.YUV);
            VideoCaptureList = CaptureDeviceManager.getDeviceList(videoFormat);
            if (VideoCaptureList.size() > 0) {
                VideoCaptureDeviceInfo = (CaptureDeviceInfo) VideoCaptureList.elementAt(0);
                VideoLocator = VideoCaptureDeviceInfo.getLocator();
            } else {
    //--- Search video device
                VideoCaptureList = (Vector) CaptureDeviceManager.getDeviceList(null).clone();
                Enumeration getEnum = VideoCaptureList.elements();
                while (getEnum.hasMoreElements()) {
                    VideoCaptureDeviceInfo = (CaptureDeviceInfo) getEnum.nextElement();
                    String name = VideoCaptureDeviceInfo.getName();
                    if (name.startsWith("vfw:")) {
                        CaptureDeviceManager.removeDevice(VideoCaptureDeviceInfo);
                int nDevices = 0;
                for (int i = 0; i < 10; i++) {
                    String name = com.sun.media.protocol.vfw.VFWCapture.capGetDriverDescriptionName(i);
                    if (name != null && name.length() > 1) {
                        System.err.println("Found device" + name);
                        System.err.println("Querying device.Please wait....");
                        com.sun.media.protocol.vfw.VFWSourceStream.autoDetect(i);
                        nDevices++;
                VideoCaptureDeviceInfo = (CaptureDeviceInfo) CaptureDeviceManager.getDeviceList(videoFormat).elementAt(0);
                VideoLocator = VideoCaptureDeviceInfo.getLocator();
            return VideoLocator;
        //get audio MediaLocator
        public MediaLocator getAudioLocator() {
            MediaLocator AudioLocator = null;
            Vector AudioCaptureList = null;
            CaptureDeviceInfo AudioCaptureDeviceInfo = null;
            AudioFormat audioFormat = new AudioFormat(AudioFormat.LINEAR);
            AudioCaptureList = CaptureDeviceManager.getDeviceList(audioFormat);
            if (AudioCaptureList.size() > 0) {
                AudioCaptureDeviceInfo = (CaptureDeviceInfo) AudioCaptureList.elementAt(0);
                AudioLocator = AudioCaptureDeviceInfo.getLocator();
                System.out.println("get audio locator");
            } else {
                System.out.println("empty");
                AudioLocator = null;
            return AudioLocator;
        public DataSource getDataSource() {
            try {
                DataSource[] source = new DataSource[2];    //audio 0; video 1;
                source[0] = Manager.createDataSource(getAudioLocator());
                if (isMix) {
                    DataSource MixDataSource = null;
                    source[1] = Manager.createDataSource(getVideoLocator());
                    MixDataSource = Manager.createMergingDataSource(source);
                    return MixDataSource;
                } else {
                    return source[0];
            } catch (Exception ex) {
                System.out.println("---error0---" + ex);
                return null;
        public DataSource getDataSourceByProcessor() {
            StateHelper sh = null;
            DataSource OutDataSource = null;
            DataSource InputSource = null;
            InputSource = getDataSource();
            try {
                cp = Manager.createProcessor(InputSource);
            } catch (IOException ex) {
                System.out.println("---error1---" + ex);
            } catch (NoProcessorException ex) {
                System.out.println("---error2---" + ex);
            sh = new StateHelper(cp);
            if (!sh.configure(10000)) {
                System.out.println("Processor Configured Error!");
                System.exit(-1);
            ContentDescriptor cd = new ContentDescriptor(ContentDescriptor.RAW_RTP);
            cp.setContentDescriptor(cd);
            AudioFormat ulawFormat = new AudioFormat(AudioFormat.ULAW_RTP, 8000.0, 8, 1);
           // change encode to alaw here?
            TrackControl[] tracks = cp.getTrackControls();
            boolean encodingState = false;
            for (int i = 0; i < tracks.length; i++) {
                if (!encodingState && tracks[i] instanceof FormatControl) {
                    if (tracks.setFormat(ulawFormat) == null) {
    tracks[i].setEnabled(false);
    } else {
    encodingState = true;
    //---- ptime set
                   if (isUlaw) {
         try {
         System.out.println("Cambiando la lista de codecs...");
         Codec[] codec = new Codec[3];
         codec[0] = new com.ibm.media.codec.audio.rc.RCModule();
         codec[1] = new com.ibm.media.codec.audio.ulaw.JavaEncoder();
         //codec[2] = new com.ibm.media.codec.audio.ulaw.Packetizer();
         codec[2] = new com.sun.media.codec.audio.ulaw.Packetizer();
         ((com.sun.media.codec.audio.ulaw.Packetizer) codec[2]).setPacketSize(160);
         (tracks[i]).setCodecChain(codec);
         } catch (UnsupportedPlugInException ex) {
         } catch (NotConfiguredError ex) {
    } else {
    tracks[i].setEnabled(false);
    if (!encodingState) {
    System.out.println("Encode error");
    System.exit(-1);
    if (!sh.realize(10000)) {
    System.out.println("Processor Realized Error!");
    System.exit(-1);
    OutDataSource = cp.getDataOutput();
    return OutDataSource;
    //run
    public void start() {
    cp.start();
    //stop
    public void close() {
    cp.close();

    test.java (get outputDatasource form capture.java)
    package siphone.test;
    import java.io.IOException;
    import java.net.InetAddress;
    import javax.media.Format;
    import javax.media.Manager;
    import javax.media.Player;
    import javax.media.PlugInManager;
    import javax.media.control.BufferControl;
    import javax.media.format.UnsupportedFormatException;
    import javax.media.protocol.DataSource;
    import javax.media.protocol.PushBufferDataSource;
    import javax.media.protocol.PushBufferStream;
    import javax.media.rtp.InvalidSessionAddressException;
    import javax.media.rtp.Participant;
    import javax.media.rtp.RTPControl;
    import javax.media.rtp.RTPManager;
    import javax.media.rtp.ReceiveStream;
    import javax.media.rtp.ReceiveStreamListener;
    import javax.media.rtp.SendStream;
    import javax.media.rtp.SendStreamListener;
    import javax.media.rtp.SessionAddress;
    import javax.media.rtp.SessionListener;
    import javax.media.rtp.event.ByeEvent;
    import javax.media.rtp.event.NewParticipantEvent;
    import javax.media.rtp.event.NewReceiveStreamEvent;
    import javax.media.rtp.event.NewSendStreamEvent;
    import javax.media.rtp.event.ReceiveStreamEvent;
    import javax.media.rtp.event.RemotePayloadChangeEvent;
    import javax.media.rtp.event.SendStreamEvent;
    import javax.media.rtp.event.SessionEvent;
    import javax.media.rtp.rtcp.SourceDescription;
    import siphone.decode.AlawRtpDecoder;
    import siphone.device.Capture;
    import siphone.gui.MainFrame;
    * @author kaiser
    public class Dial implements SessionListener, ReceiveStreamListener, SendStreamListener {
        private String ip = null;
        private int TargetPort;
        private int LocalPort;
        private MainFrame mf = null;
        private Capture capture = null;
        private DataSource oDataSource = null;
        private RTPManager rtp = null;
        private SendStream stream = null;
        private Player play = null;
        private Boolean LogStatu = false;
        static private Format AlawRtpFormat;
        public Dial(String ip, String rport, int lport, MainFrame mf) {
            this.ip = ip;
            this.TargetPort = Integer.parseInt(rport);
            this.LocalPort = lport;
            this.mf = mf;
            capture = new Capture(false);
            oDataSource = capture.getDataSourceByProcessor();
        public static void main(String[] args) throws IOException {
            Dial dial = new Dial("192.168.200.40", "40000", 10000, null);
            dial.Init();
            System.in.read();
            dial.stop();
        public synchronized void Init() {
            PushBufferDataSource pushDataSource = (PushBufferDataSource) oDataSource;
            PushBufferStream pushStream[] = pushDataSource.getStreams();
            SessionAddress localAddress, targetAddress;
            try {
                rtp = RTPManager.newInstance();
                rtp.addReceiveStreamListener(this);
                rtp.addSendStreamListener(this);
                rtp.addSessionListener(this);
                //port: TargetPort or LocalPort;
                localAddress = new SessionAddress(InetAddress.getLocalHost(), TargetPort);
                targetAddress = new SessionAddress(InetAddress.getByName(ip), TargetPort);
                rtp.initialize(localAddress);
                rtp.addTarget(targetAddress);
                BufferControl bc = (BufferControl) rtp.getControl("javax.media.control.BufferControl");
                if (bc != null) {
                    bc.setBufferLength(100);
                stream = rtp.createSendStream(oDataSource, 0);
                stream.start();
                capture.start();
                System.out.println("voice starting...........\n");
            } catch (UnsupportedFormatException ex) {
                System.err.println("error0:\n" + ex);
            } catch (InvalidSessionAddressException ex) {
                System.err.println("error1:\n" + ex);
            } catch (IOException ex) {
                System.err.println("error2:\n" + ex);
        //stop
        public void stop() {
            capture.close();
            if (rtp != null) {
                rtp.removeTargets("close session");
                rtp.dispose();
                rtp = null;
            System.out.println("close session...........\n");
        public void update(SessionEvent evt) {
            if (evt instanceof NewParticipantEvent) {
                Participant sPart = ((NewParticipantEvent) evt).getParticipant();
                System.out.print("  - join: " + sPart.getCNAME());
        public void update(ReceiveStreamEvent rex) {
            ReceiveStream rStream = rex.getReceiveStream();
            Participant rPart = rex.getParticipant();
            if (rex instanceof NewReceiveStreamEvent) {
                try {
                    DataSource rData = rStream.getDataSource();
                    RTPControl rcl = (RTPControl) rData.getControl("javax.media.rtp.RTPControl");
                    if (rcl != null) {
                        System.out.print("  - receive RTPControl info | the AudioFormat: " + rcl.getFormat());
                    } else {
                        System.out.print("  - receive RTPControl info");
                    if (rPart == null) {
                        System.out.print(" UNKNOWN");
                    } else {
                        System.out.print("data form " + rPart.getCNAME());
                    play = Manager.createRealizedPlayer(rData);
                    if (play != null) {
                        play.start();
                } catch (Exception ex) {
                    System.out.print("NewReceiveStreamEvent Exception " + ex.getMessage());
                    return;
            } else if (rex instanceof ByeEvent) {
                System.out.print("  - receive bye message: " + rPart.getCNAME() + "   exit");
                stop();
                return;
    }Anyone can tell me how to do?
    Thank you very much!

  • Big problem with put the same received dataSource on two different panels

    Hello All!
    I have a big problem, but first what have I done:
    I am writting application that is based on AVReceiver2 and AVTransmit2 from Sun help.
    I have modified AVReceiver2 to only receive one stream - video stream.
    I show received video on scrollPane, but I want to show the same video on second scrollPane in the same time. I have read about cloning dataSource, but I don't know how to modify that code to make it work.
    This is my receiver class (logger is my own class that have listbox, so don't watch on it. This is not important):
    public class Po&#322;&#261;czenie implements ReceiveStreamListener, SessionListener,
         ControllerListener
        String session = null;
        RTPManager manager = null;
        public Player player1 = null;
        boolean dataReceived = false;
        Object dataSync = new Object();
        private Logger logger;
        private JPanel&#377;ród&#322;oPo&#322;&#261;czone panelOgólny;
        private JPanel&#377;ród&#322;oSzczegó&#322;y panelSzczegó&#322;y;
        private Date dataRozpocz&#281;cia;
        public Po&#322;&#261;czenie(String session, JPanel&#377;ród&#322;oSzczegó&#322;y panelSzczegó&#322;y, JPanel&#377;ród&#322;oPo&#322;&#261;czone panelOgólny, Logger logger) {
            this.session = session;
            this.logger = logger;
            this.panelOgólny = panelOgólny;
            this.panelSzczegó&#322;y = panelSzczegó&#322;y;
        public void Start()
            if (!initialize())
                System.err.println("Failed to initialize the sessions.");
                System.exit(-1);
                System.err.println("Odbiór rozpocz&#281;ty");
        public boolean initialize() {
            try {
             InetAddress ipAddr;
             SessionAddress localAddr = new SessionAddress();
             SessionAddress destAddr;
             SessionLabel sessionLabel;
             // Open the RTP sessions.
               // Parse the session addresses.
              try {
                  sessionLabel = new SessionLabel(session);
              } catch (IllegalArgumentException e) {
                  System.err.println("Failed to parse the session address given: " + session);
                  return false;
              System.err.println("  - Otwarcie sesji RTP: addr: " + sessionLabel.addr + " port: " + sessionLabel.port + " ttl: " + sessionLabel.ttl);
              manager = (RTPManager) RTPManager.newInstance();
              manager.addSessionListener(this);
              manager.addReceiveStreamListener(this);
              ipAddr = InetAddress.getByName(sessionLabel.addr);
              if( ipAddr.isMulticastAddress()) {
                  // local and remote address pairs are identical:
                  localAddr= new SessionAddress( ipAddr,
                                     sessionLabel.port,
                                     sessionLabel.ttl);
                  destAddr = new SessionAddress( ipAddr,
                                     sessionLabel.port,
                                     sessionLabel.ttl);
              } else {
                  localAddr= new SessionAddress( InetAddress.getLocalHost(),
                                          sessionLabel.port);
                        destAddr = new SessionAddress( ipAddr, sessionLabel.port);
              manager.initialize( localAddr);
              // You can try out some other buffer size to see
              // if you can get better smoothness.
              BufferControl bc = (BufferControl)manager.getControl("javax.media.control.BufferControl");
              if (bc != null)
                  bc.setBufferLength(350);
                  manager.addTarget(destAddr);
            } catch (Exception e){
                System.err.println("Cannot create the RTP Session: " + e.getMessage());
                return false;
         // Wait for data to arrive before moving on.
         long then = System.currentTimeMillis();
         long waitingPeriod = 30000;  // wait for a maximum of 30 secs.
         try{
             synchronized (dataSync) {
              while (!dataReceived &&
                   System.currentTimeMillis() - then < waitingPeriod) {
                  if (!dataReceived)
                   System.err.println("  - Oczekiwanie na transmisj&#281; danych...");
                  dataSync.wait(1000);
         } catch (Exception e) {}
         if (!dataReceived) {
             System.err.println("No RTP data was received.");
             close();
             return false;
            return true;
         * Close the players and the session managers.
        protected void close() {
             try {
                player1.close();
             } catch (Exception e) {}
         // close the RTP session.
             if (manager != null) {
                    manager.removeTargets( "Closing session from AVReceive2");
                    manager.dispose();
                    manager = null;
         * SessionListener.
        public synchronized void update(SessionEvent evt) {
         if (evt instanceof NewParticipantEvent) {
             Participant p = ((NewParticipantEvent)evt).getParticipant();
             System.err.println("  - Do&#322;&#261;czy&#322; nowy u&#380;ytkownik: " + p.getCNAME());
         * ReceiveStreamListener
        public synchronized void update( ReceiveStreamEvent evt) {
         RTPManager mgr = (RTPManager)evt.getSource();
         Participant participant = evt.getParticipant();     // could be null.
         ReceiveStream stream = evt.getReceiveStream();  // could be null.
         if (evt instanceof RemotePayloadChangeEvent) {
             System.err.println("  - Received an RTP PayloadChangeEvent.");
             System.err.println("Sorry, cannot handle payload change.");
             System.exit(0);
         else if (evt instanceof NewReceiveStreamEvent) {
             try {
              stream = ((NewReceiveStreamEvent)evt).getReceiveStream();
              DataSource ds = stream.getDataSource();
    //=========important thing:
                            DataSource cloneableDS = Manager.createCloneableDataSource( ds );
                            DataSource clonedDS = ((SourceCloneable)cloneableDS).createClone();
    //========
              // Find out the formats.
              RTPControl ctl = (RTPControl)ds.getControl("javax.media.rtp.RTPControl");
              if (ctl != null){
                  System.err.println("  - Recevied new RTP stream: " + ctl.getFormat());
              } else {
                  System.err.println("  - Recevied new RTP stream");
              if (participant == null)
                  System.err.println("      The sender of this stream had yet to be identified.");
              else {
                  System.err.println("      The stream comes from: " + participant.getCNAME());
              // create a player by passing datasource to the Media Manager
    //=====important thing:
                            player1 = javax.media.Manager.createPlayer(clonedDS);
    //=====
              if (player1 == null)
                  return;
              player1.addControllerListener(this);
              player1.realize();
              // Notify intialize() that a new stream had arrived.
              synchronized (dataSync) {
                  dataReceived = true;
                  dataSync.notifyAll();
             } catch (Exception e) {
              System.err.println("NewReceiveStreamEvent exception " + e.getMessage());
              return;
         else if (evt instanceof StreamMappedEvent) {
              if (stream != null && stream.getDataSource() != null) {
              DataSource ds = stream.getDataSource();
              // Find out the formats.
              RTPControl ctl = (RTPControl)ds.getControl("javax.media.rtp.RTPControl");
              System.err.println("  - The previously unidentified stream ");
              if (ctl != null)
                  System.err.println("      " + ctl.getFormat());
              System.err.println("      had now been identified as sent by: " + participant.getCNAME());
         else if (evt instanceof ByeEvent) {
              System.err.println("  - Got \"bye\" from: " + participant.getCNAME());
          player1.close();
            manager.dispose();
        }

    I wanted to show the same video stream on 2 panels at the same time. The panels are on 2 different Tabs of TabbedPane.
    So I done some kind of switch:
    - when user change tab, I change vievport from one panel to another. This works gr8, but I need to record some received video on the same time when user watch it.
    I find some code to record - this works on single machine, but now, when I have cloned dataSource I supposed to be able to record received video, but guess what: it doesn't work.
    Code of recording part:
               DataSource ds2; // I cloned this the same as I posted earlier
                PushBufferStream pbs;
         Vector camImgSize = new Vector();
         Vector camCapDevice = new Vector();
         Vector camCapFormat = new Vector();
         int camFPS;
         int camImgSel;
         Processor processor = null;
         DataSink datasink = null;
        public void record()
            fetchDeviceFormats();
              camImgSel=0;     // first format, or otherwise as desired
              camFPS = 30;     // framerate
              // Setup data source
              fetchDeviceDataSource();
              createPBDSource();
              createProcessor(ds2); // i'm using cloned datasource
              startCapture();
              try{Thread.sleep(20000);}catch(Exception e){}     // 20 seconds
              stopCapture();
         boolean fetchDeviceFormats()
              Vector deviceList = CaptureDeviceManager.getDeviceList(new VideoFormat(null));
              CaptureDeviceInfo CapDevice = null;
              Format CapFormat = null;
              String type = "N/A";
              CaptureDeviceInfo deviceInfo=null;boolean VideoFormatMatch=false;
              for(int i=0;i<deviceList.size();i++)
                   // search for video device
                   deviceInfo = (CaptureDeviceInfo)deviceList.elementAt(i);
                   if(deviceInfo.getName().indexOf("vfw:")<0)continue;
                   Format deviceFormat[] = deviceInfo.getFormats();
                   for (int f=0;f<deviceFormat.length;f++)
                        if(deviceFormat[f] instanceof RGBFormat)type="RGB";
                        if(deviceFormat[f] instanceof YUVFormat)type="YUV";
                        if(deviceFormat[f] instanceof JPEGFormat)type="JPG";
                        Dimension size = ((VideoFormat)deviceFormat[f]).getSize();
                        camImgSize.addElement(type+" "+size.width+"x"+size.height);
                        CapDevice = deviceInfo;
                        camCapDevice.addElement(CapDevice);
                        //System.out.println("Video device = " + deviceInfo.getName());
                        CapFormat = (VideoFormat)deviceFormat[f];
                        camCapFormat.addElement(CapFormat);
                        //System.out.println("Video format = " + deviceFormat[f].toString());
                        VideoFormatMatch=true;     // at least one
              if(VideoFormatMatch==false)
                   if(deviceInfo!=null)System.out.println(deviceInfo);
                   System.out.println("Video Format not found");
                   return false;
              return true;
         * Finds a camera and sets it up
         void fetchDeviceDataSource() //I test it on localhost so I don't change it
              CaptureDeviceInfo CapDevice = (CaptureDeviceInfo)camCapDevice.elementAt(camImgSel);
              System.out.println("Video device = " + CapDevice.getName());
              Format CapFormat = (Format)camCapFormat.elementAt(camImgSel);
              System.out.println("Video format = " + CapFormat.toString());
              try
                   // ensures 30 fps or as otherwise preferred, subject to available cam rates but this is frequency of windows request to stream
                   FormatControl formCont=((CaptureDevice)ds2).getFormatControls()[0];
                   VideoFormat formatVideoNew = new VideoFormat(null,null,-1,null,(float)camFPS);
                   formCont.setFormat(CapFormat.intersects(formatVideoNew));
              catch(Exception e){}
         * Gets a stream from the camera (and sets debug)
         void createPBDSource()
              try
                   pbs=((PushBufferDataSource)ds2).getStreams()[0];
              catch(Exception e){}
         public void createProcessor(DataSource datasource)
              FileTypeDescriptor ftd = new FileTypeDescriptor(FileTypeDescriptor.MSVIDEO);
              Format[] formats = new Format[] {new VideoFormat(VideoFormat.INDEO50)};
              ProcessorModel pm = new ProcessorModel(datasource, formats, ftd);
              try
                   processor = Manager.createRealizedProcessor(pm);
              catch(Exception me)
                   System.out.println(me);
                   // Make sure the capture devices are released
                   datasource.disconnect();
                   return;
         private void startCapture()
              // Get the processor's output, create a DataSink and connect the two.
              DataSource outputDS = processor.getDataOutput();
              try
                   MediaLocator ml = new MediaLocator("file:capture.avi");
                   datasink = Manager.createDataSink(outputDS, ml);
                   datasink.open();
                   datasink.start();
              }catch (Exception e)
                   System.out.println(e);
              processor.start();
              System.out.println("Started saving...");
         private void pauseCapture()
              processor.stop();
         private void resumeCapture()
              processor.start();
         private void stopCapture()
              // Stop the capture and the file writer (DataSink)
              processor.stop();
              processor.close();
              datasink.close();
              processor = null;
              System.out.println("Done saving.");
         }I run method record() from gui, after I received stream.
    IMPORTANT:
         on:           processor.close();
    I have an exception:
    Exception in thread "AWT-EventQueue-0" java.lang.NullPointerException
    at com.sun.media.multiplexer.video.AVIMux.writeFooter(AVIMux.java:827)
    at com.sun.media.multiplexer.BasicMux.close(BasicMux.java:142)
    at com.sun.media.BasicMuxModule.doClose(BasicMuxModule.java:172)
    at com.sun.media.PlaybackEngine.doClose(PlaybackEngine.java:872)
    at com.sun.media.BasicController.close(BasicController.java:261)
    at com.sun.media.BasicPlayer.doClose(BasicPlayer.java:229)
    at com.sun.media.BasicController.close(BasicController.java:261)
    at jmonitorserver.engine.Po&#322;&#261;czenie.stopCapture(Po&#322;&#261;czenie.java:684)
    And the video file have 0kb, even during recording
    datasource ds2 is not null.
    any idea?

  • Write(Export) the RTP Stream from a SIP Call to an audio file

    I am working on telephony system that need record each call to a file.
    I got the RTP Stream in ReceiveStreamEvent handler and start to record
    the problem is i got a file and play it but there are any sounds
    when i set FileTypeDescriptor.WAVE and AudioFormat.ULAW
    I try out the FileTypeDescriptor.WAVE and AudioFormat.IMA4_MS, i got a fixed size file with 60kb
    if the FileTypeDescriptor.MPEG_AUDIO and AudioFormat.MPEG, the processor cannot be realize,
    the thread is blocked!!
    Could anyone save me? thanks in advanced!
    =================================Code===================================================
    public void update(ReceiveStreamEvent evt){
    logger.debug("received a new incoming stream. " + evt);
    RTPManager mgr = (RTPManager) evt.getSource();
    Participant participant = evt.getParticipant(); // could be null.
    ReceiveStream stream = evt.getReceiveStream(); // could be null.
    if (evt instanceof NewReceiveStreamEvent)
    try
    stream = ( (NewReceiveStreamEvent) evt).getReceiveStream();
    DataSource ds = stream.getDataSource();
              recorder = new CallRecorderImpl(ds);
    recorder.start();
    catch (Exception e)
    logger.error("NewReceiveStreamEvent exception ", e);
    return;
    ========================================================================================
    this is the CallRecorderImpl Class
    public class CallRecorderImpl implements DataSinkListener, ControllerListener {
         private Processor processor = null;
         private DataSink dataSink = null;
         private DataSource source = null;
         private boolean bRecording = false;
         FileTypeDescriptor contentType = new FileTypeDescriptor(FileTypeDescriptor.WAVE);
         Format encoding = new AudioFormat(AudioFormat.IMA4_MS);
    MediaLocator dest = new MediaLocator("file:/c:/bar.wav");
         public CallRecorderImpl(DataSource ds) {
              this.source = ds;
         public void start() {
              try {
                   processor = Manager.createProcessor(source);
                   processor.addControllerListener(this);
                   processor.configure();
              } catch (Exception e) {
                   System.out.println("exception:" + e);
         public void stop() {
              try {
                   System.out.println("stopping");
                   this.dataSink.stop();
                   this.dataSink.close();
              } catch (Exception ep) {
                   ep.printStackTrace();
         public void controllerUpdate(ControllerEvent evt) {
              Processor pr = (Processor) evt.getSourceController();
              if (evt instanceof ConfigureCompleteEvent) {
                   System.out.println("ConfigureCompleteEvent");
                   processConfigured(pr);
              if (evt instanceof RealizeCompleteEvent) {
                   System.out.println("RealizeCompleteEvent");
                   processRealized(pr);
              if (evt instanceof ControllerClosedEvent) {
                   System.out.println("ControllerClosedEvent");
              if (evt instanceof EndOfMediaEvent) {
                   System.out.println("EndOfMediaEvent");
                   pr.stop();
              if (evt instanceof StopEvent) {
                   System.out.println("StopEvent");
                   pr.close();
                   try {
                        dataSink.stop();
                        dataSink.close();
                   } catch (Exception ee) {
                        ee.printStackTrace();
         public void dataSinkUpdate(DataSinkEvent event) {
              if (event instanceof EndOfStreamEvent) {
                   try {
                        System.out.println("EndOfStreamEvent");
                        dataSink.stop();
                        dataSink.close();
                        System.exit(1);
                   } catch (Exception e) {
         public void processConfigured(Processor p) {
              // Set the output content type
              p.setContentDescriptor(this.contentType);
              // Get the track control objects
              TrackControl track[] = p.getTrackControls();
              boolean encodingPossible = false;
              // Go through the tracks and try to program one of them
              // to output ima4 data.
              for (int i = 0; i < track.length; i++) {
              try {
                   track.setFormat(this.encoding);
                   encodingPossible = true;
              } catch (Exception e) {
                   track[i].setEnabled(false);
              if (!encodingPossible) {
                   System.out.println("cannot encode to " + this.encoding);
              return;
              p.realize();
         public void processRealized(Processor p) {
              System.out.println("Entered processRealized");
    DataSource source = p.getDataOutput();
    try {
         dataSink = Manager.createDataSink(source, dest);
         dataSink.open();
         dataSink.start();
         dataSink.addDataSinkListener(new DataSinkListener() {
                        public void dataSinkUpdate(DataSinkEvent e) {
                             if (e instanceof EndOfStreamEvent) {
                                  System.out.println("EndOfStreamEvent");
                                  dataSink.close();
    } catch (Exception e) {
         e.printStackTrace();
         return;
              p.start();
    ============================================

    Which shows that the output stream cannot be of that particulat format and descriptor.
    Look at this code
    import javax.swing.*;
    import javax.media.*;
    import java.net.*;
    import java.io.*;
    import javax.media.datasink.*;
    import javax.media.protocol.*;
    import javax.media.format.*;
    import javax.media.control.*;
    class Abc implements ControllerListener
         DataSource ds;
         DataSink sink;
         Processor pr;
         MediaLocator mc;
         public void maam() throws Exception
              mc=new MediaLocator("file:C:/Workspace/aaaaa.mpg");
              pr=Manager.createProcessor(new URL("file:G:/java files1/jmf/aa.mp3"));
              pr.addControllerListener(this);
              pr.configure();          
         public void controllerUpdate(ControllerEvent e)
              if(e instanceof ConfigureCompleteEvent)
                   System.out.println ("ConfigureCompleteEvent");
                             Processor p = (Processor)e.getSourceController();
                   System.out.println ("ConfigureCompleteEvent");
                         processConfigured(p);
              if(e instanceof RealizeCompleteEvent)
                   System.out.println ("RealizeCompleteEvent");
                           Processor p = (Processor)e.getSourceController();
                             processRealized(p);
              if(e instanceof ControllerClosedEvent)
                         System.out.println ("ControllerClosedEvent");
                     if(e instanceof EndOfMediaEvent)
                        System.out.println ("EndOfMediaEvent");
                        Processor p = (Processor)e.getSourceController();
                        p.stop();
                 if(e instanceof StopEvent)
                         System.out.println ("StopEvent");
                         Processor p = (Processor)e.getSourceController();
                         p.close();
                   try
                        sink.stop();
                        sink.close();
                   catch(Exception ee)
         public void processConfigured(Processor p)
              System.out.println("Entered processConfigured");
              p.setContentDescriptor (new FileTypeDescriptor (FileTypeDescriptor.MPEG_AUDIO));       
                /*    TrackControl track[] = p.getTrackControls ();
                 boolean encodingPossible = false;
                 for (int i = 0; i < track.length; i++)
                      try
                           track.setFormat (new VideoFormat (VideoFormat.MPEG));
                   encodingPossible = true;
                   catch (Exception e)
                   track[i].setEnabled (false);
         p.realize();
         public void processRealized(Processor p)
              pr=p;
              System.out.println("Entered processRealized");
              try
                   MediaLocator dest = new MediaLocator("file:C:/Workspace/ring1.mpg");
                   sink = Manager.createDataSink(p.getDataOutput(), dest);
              sink.addDataSinkListener(new DataSinkListener()
                        public void dataSinkUpdate(DataSinkEvent e)
                             if(e instanceof EndOfStreamEvent)
                        System.out.println ("EndOfStreamEvent");
                                  sink.close();
                   sink.open();
                   sink.start();
              catch(Exception eX)
              System.out.println("Just before start");
              p.start();
    /*     public void dataSinkUpdate(DataSinkEvent event)
              if(event instanceof EndOfStreamEvent)
                   try
                        System.out.println("EndOfStreamEvent");
                        dsk.stop();
                        dsk.close();
                        System.exit(1);
                   catch(Exception e)
    public class JMFCapture6
         public static void main(String args[]) throws Exception
              Abc a=new Abc();
              a.maam();

  • Attempting to write RTP stream to wave

    I have been working long and hard trying to figure out to save an RTP stream from a Cisco phone to a wave. I need the wave file to be in the format ULAW, 8khz, 8 bit mono.
    Through much research this is the code I come up with but I does not work. I states that I am trying to get a datasink for null when I try to create the filewriter datasink.
    I also have gotten the following error message with other version of the code below:
    newReceiveStreamEvent exception Cannot find a DataSink for: com.sun.media.protocol.rtp.DataSource@3680c1
    When I get the RTP stream I get the following as the format of the input stream:
    - Recevied new RTP stream: ULAW/rtp, 8000.0 Hz, 8-bit, Mono
    else if (evt instanceof NewReceiveStreamEvent) {
         try {
              stream = ((NewReceiveStreamEvent)evt).getReceiveStream();
    Format formats[] = new Format[1];
    formats[0] = new AudioFormat(AudioFormat.LINEAR,8000,8,1);
    FileTypeDescriptor outputType = new FileTypeDescriptor(FileTypeDescriptor.WAVE);
    DataSource ds = stream.getDataSource();
              // Find out the formats.
              RTPControl ctl = (RTPControl)ds.getControl("javax.media.rtp.RTPControl");
              if (ctl != null){
              System.err.println(" - Recevied new RTP stream: " + ctl.getFormat());
              } else
              System.err.println(" - Recevied new RTP stream");
              if (participant == null)
              System.err.println(" The sender of this stream had yet to be identified.");
              else {
              System.err.println(" The stream comes from: " + participant.getCNAME());
    ProcessorModel processorModel = new ProcessorModel(ds, formats, null);
    Processor processor = Manager.createRealizedProcessor(processorModel);
              processor.setContentDescriptor(new ContentDescriptor(ContentDescriptor.RAW_RTP));
    MediaLocator f = new MediaLocator("file:/C:/output.wav");
    DataSink filewriter = null;
    DataSource tempds = processor.getDataOutput();
    filewriter = Manager.createDataSink(tempds, f);
    filewriter.open();
    Edited by: phodat on Sep 16, 2010 10:17 PM
    Edited by: phodat on Sep 16, 2010 10:20 PM

    The content descriptor is designed to specify the output format, not the input format. The input format is specified by the DataSource automatically, and you set the content descriptor to whatever you want the output format to be. In this case, you'd want to set it to a WAV file.
    You'd then need to go through all of the Track objects on the processor and set their output format to the ULAW specifications as you want there.
    [http://www.cs.odu.edu/~cs778/spring04/lectures/jmfsolutions/examplesindex.html]
    There's actually an example program that exports RTP streams, you can probably use that code without modification to fit your needs.

  • Codes for audio video receiver class

    I am currently writting an audio and video receiver for my project based on AVReceive3, it works but i can only get Video only, everything seems to be normal, i dont see why i am not getting audio. My transmitter is working fine and sending both streams.
    If anyone can spot the error or mistake i a making, pleaase let me know as soon as possible.
    my email address is [email protected]
    public class AudVidReceive extends Frame implements ActionListener,ReceiveStreamListener,SessionListener,ControllerListener
    // Input MediaLocator
    // Can be a file or http or capture source
    private MediaLocator alocator;
    MediaLocator vlocator,vloct,aloct;
    private String ipAddress;
    private int portBase;
    Button transtop,transtart,recstop,recstart;
    Component controlPanel, visualComponent;
    //For Receiving Media Stream
    String sessions[] = null;
    SessionManager mgrs[] = null;
    Vector playerWindows = null;
    boolean dataReceived = false;
    Object dataSync = new Object();
    private Processor processor = null;
    Player player=null;
    Format fmt=null;
    private SessionManager rtpMgrs[];
    private DataSource dataOutput = null;
    DataSource ads=null;
    DataSource vds=null;
    DataSource source[];
    DataSource m=null;
    public AudVidReceive()
    super("Audio Video Receive");
    recstart=new Button("StartReceiving");
    //recstop=new Button("Stop Receiving");
    add(recstart);
    recstart.setBounds(80,250,100,30);
    recstart.addActionListener(this);
    setLayout(null);
    setSize(400,300);
    setVisible(true);
    //this.sessions=sessions;
    public void actionPerformed(ActionEvent e)
    Button b=(Button)e.getSource();
    String ac=e.getActionCommand();
    if(ac.equalsIgnoreCase("StartReceiving"))
    boolean flag;
    boolean st=initialize();
    if(!st)
    System.err.println("Failed to Realize the Sessions ");
    System.exit(-1);
    flag=isDone();
    try{
    while(!flag)
    Thread.sleep(1000);
    }catch(Exception e1)
    e1.printStackTrace();
    //Initialize the Session for Receiving the Incomming Stream
    protected boolean initialize() {
    try {
    InetAddress ipAddr;
    SessionAddress localAddr = new SessionAddress();
    SessionAddress destAddr;
    String sessions[]={"192.168.2.143/42060"};
    mgrs = new com.sun.media.rtp.RTPSessionMgr[sessions.length];
    playerWindows = new Vector();
    SessionLabel session;
    // Open the RTP sessions.
    for (int i = 0; i < sessions.length; i++) {
    // Parse the session addresses.
    try {
    session = new SessionLabel(sessions);
    } catch (IllegalArgumentException e) {
    System.err.println("Failed to parse the session address given: " + sessions[i]);
    return false;
    System.err.println(" - Open RTP session for: addr: " + session.addr + " port: " + session.port + " ttl: " + session.ttl);
    mgrs[i] = new com.sun.media.rtp.RTPSessionMgr();
    mgrs[i].addSessionListener(this);
    mgrs[i].addReceiveStreamListener(this);
    ipAddr = InetAddress.getByName(session.addr);
    destAddr = new SessionAddress(ipAddr, session.port,
    ipAddr, session.port+1);
    mgrs[i].initSession(localAddr, getSDES(mgrs[i]), .05, .25);
    // You can try out some other buffer size to see
    // if you can get better smoothness.
    BufferControl bc = (BufferControl)mgrs[i].getControl("javax.media.control.BufferControl");
    if (bc != null)
    bc.setBufferLength(350);
    mgrs[i].startSession(destAddr, session.ttl, null);
    } catch (Exception e){
    System.err.println("Cannot create the RTP Session: " + e.getMessage());
    return false;
    // Wait for data to arrive before moving on.
    long then = System.currentTimeMillis();
    long waitingPeriod = 120000; // wait for a maximum of 30 secs.
    try{
    synchronized (dataSync)
    while (!dataReceived && System.currentTimeMillis() - then < waitingPeriod) {
    if (!dataReceived)
    System.err.println(" - Waiting for RTP data to arrive...");
    dataSync.wait(1000);
    }catch (Exception e) {}
    if (!dataReceived) {
    System.err.println("No RTP data was received.");
    close();
    return false;
    return true;
    * Find out the host info.
    String cname = null;
    private SourceDescription[] getSDES(SessionManager mgr)
    SourceDescription[] desclist = new SourceDescription[3];
    if (cname == null)
    cname = mgr.generateCNAME();
    desclist[0] = new
    SourceDescription(SourceDescription.SOURCE_DESC_NAME,
    System.getProperty("user.name"),
    1,
    false);
    desclist[1] = new
    SourceDescription(SourceDescription.SOURCE_DESC_CNAME,
    cname,
    1,
    false);
    desclist[2] = new
    SourceDescription(SourceDescription.SOURCE_DESC_TOOL,
    "AVReceive powered by JMF",
    1,
    false);
    return desclist;
    //Check Player window sizing
    public boolean isDone() {
    return playerWindows.size() == 0;
    * Close the players and the session managers.
    protected void close()
    for (int i = 0; i < playerWindows.size(); i++)
    try {
    ((PlayerWindow)playerWindows.elementAt(i)).close();
    } catch (Exception e) {}
    playerWindows.removeAllElements();
    // close the RTP session.
    for (int i = 0; i < mgrs.length; i++) {
    if (mgrs[i] != null) {
    mgrs[i].closeSession("Closing session from AudVidReceive");
    mgrs[i] = null;
    //Find the player
    PlayerWindow find(Player p) {
    for (int i = 0; i < playerWindows.size(); i++) {
    PlayerWindow pw = (PlayerWindow)playerWindows.elementAt(i);
    if (pw.player == p)
    return pw;
    return null;
    //Find whether the Player is receiving the Stream
    PlayerWindow find(ReceiveStream strm) {
    for (int i = 0; i < playerWindows.size(); i++) {
    PlayerWindow pw = (PlayerWindow)playerWindows.elementAt(i);
    if (pw.stream == strm)
    return pw;
    return null;
    * SessionListener.
    public synchronized void update(SessionEvent evt) {
    if (evt instanceof NewParticipantEvent) {
    Participant p = ((NewParticipantEvent)evt).getParticipant();
    System.err.println(" - A new participant had just joined: " + p.getCNAME());
    * ReceiveStreamListener
    public synchronized void update( ReceiveStreamEvent evt) {
    SessionManager mgr = (SessionManager)evt.getSource();
    Participant participant = evt.getParticipant(); // could be null.
    ReceiveStream stream = evt.getReceiveStream(); // could be null.
    if (evt instanceof RemotePayloadChangeEvent) {
    System.err.println(" - Received an RTP PayloadChangeEvent.");
    System.err.println("Sorry, cannot handle payload change.");
    System.exit(0);
    else if (evt instanceof NewReceiveStreamEvent) {
    try {
    stream = ((NewReceiveStreamEvent)evt).getReceiveStream();
    DataSource ds = stream.getDataSource();
    // Find out the formats.
    RTPControl ctl = (RTPControl)ds.getControl("javax.media.rtp.RTPControl");
    if (ctl != null){
    System.err.println(" - Recevied new RTP stream: " + ctl.getFormat());
    } else
    System.err.println(" - Recevied new RTP stream");
    if (participant == null)
    System.err.println(" The sender of this stream had yet to be identified.");
    else {
    System.err.println(" The stream comes from: " + participant.getCNAME());
    // create a player by passing datasource to the Media Manager
    Player p = javax.media.Manager.createPlayer(ds);
    if (p == null)
    return;
    p.addControllerListener(this);
    p.realize();
    PlayerWindow pw = new PlayerWindow(p, stream);
    playerWindows.addElement(pw);
    // Notify intialize() that a new stream had arrived.
    synchronized (dataSync) {
    dataReceived = true;
    dataSync.notifyAll();
    } catch (Exception e) {
    System.err.println("NewReceiveStreamEvent exception " + e.getMessage());
    return;
    }//above catch closing if
    else if (evt instanceof StreamMappedEvent) {
    if (stream != null && stream.getDataSource() != null) {
    DataSource ds = stream.getDataSource();
    // Find out the formats.
    RTPControl ctl = (RTPControl)ds.getControl("javax.media.rtp.RTPControl");
    System.err.println(" - The previously unidentified stream ");
    if (ctl != null)
    System.err.println(" " + ctl.getFormat());
    System.err.println(" had now been identified as sent by: " + participant.getCNAME());
    else if (evt instanceof ByeEvent) {
    System.err.println(" - Got \"bye\" from: " + participant.getCNAME());
    PlayerWindow pw = find(stream);
    if (pw != null) {
    pw.close();
    playerWindows.removeElement(pw);
    }// end of this method
    * ControllerListener for the Players.
    public synchronized void controllerUpdate(ControllerEvent ce) {
    Player p = (Player)ce.getSourceController();
    if (p == null)
    return;
    // Get this when the internal players are realized.
    if (ce instanceof RealizeCompleteEvent) {
    PlayerWindow pw = find(p);
    if (pw == null) {
    // Some strange happened.
    System.err.println("Internal error!");
    System.exit(-1);
    pw.initialize();
    pw.setVisible(true);
    p.start();
    if (ce instanceof ControllerErrorEvent) {
    p.removeControllerListener(this);
    PlayerWindow pw = find(p);
    if (pw != null) {
    pw.close();
    playerWindows.removeElement(pw);
    System.err.println("AVReceive internal error: " + ce);
    * A utility class to parse the session addresses.
    class SessionLabel {
    public String addr = null;
    public int port;
    public int ttl = 1;
    SessionLabel(String session) throws IllegalArgumentException {
    int off;
    String portStr = null, ttlStr = null;
    if (session != null && session.length() > 0) {
    while (session.length() > 1 && session.charAt(0) == '/')
    session = session.substring(1);
    // Now see if there's a addr specified.
    off = session.indexOf('/');
    if (off == -1) {
    if (!session.equals(""))
    addr = session;
    } else {
    addr = session.substring(0, off);
    session = session.substring(off + 1);
    // Now see if there's a port specified
    off = session.indexOf('/');
    if (off == -1) {
    if (!session.equals(""))
    portStr = session;
    } else {
    portStr = session.substring(0, off);
    session = session.substring(off + 1);
    // Now see if there's a ttl specified
    off = session.indexOf('/');
    if (off == -1) {
    if (!session.equals(""))
    ttlStr = session;
    } else {
    ttlStr = session.substring(0, off);
    if (addr == null)
    throw new IllegalArgumentException();
    if (portStr != null) {
    try {
    Integer integer = Integer.valueOf(portStr);
    if (integer != null)
    port = integer.intValue();
    } catch (Throwable t) {
    throw new IllegalArgumentException();
    } else
    throw new IllegalArgumentException();
    if (ttlStr != null) {
    try {
    Integer integer = Integer.valueOf(ttlStr);
    if (integer != null)
    ttl = integer.intValue();
    } catch (Throwable t) {
    throw new IllegalArgumentException();
    * GUI classes for the Player.
    class PlayerWindow extends Frame {
    Player player;
    ReceiveStream stream;
    PlayerWindow(Player p, ReceiveStream strm) {
    player = p;
    stream = strm;
    public void initialize() {
    add(new PlayerPanel(player));
    public void close() {
    player.close();
    setVisible(false);
    dispose();
    public void addNotify() {
    super.addNotify();
    pack();
    * GUI classes for the Player.
    class PlayerPanel extends Panel {
    Component vc, cc;
    PlayerPanel(Player p) {
    setLayout(new BorderLayout());
    if ((vc = p.getVisualComponent()) != null)
    add("Center", vc);
    if ((cc = p.getControlPanelComponent()) != null)
    add("South", cc);
    public Dimension getPreferredSize() {
    int w = 0, h = 0;
    if (vc != null) {
    Dimension size = vc.getPreferredSize();
    w = size.width;
    h = size.height;
    if (cc != null) {
    Dimension size = cc.getPreferredSize();
    if (w == 0)
    w = size.width;
    h += size.height;
    if (w < 160)
    w = 160;
    return new Dimension(w, h);
    public static void main(String [] args) {
    Format fmt = null;
    int i = 0;
    AudVidReceive at1 = new AudVidReceive();
    System.err.println("Start Receiving incoming Streams ");
    try {
    Thread.currentThread().sleep(60000);
    } catch (InterruptedException ie) {
    ie.printStackTrace();

    I have to use RTP and RTSP for transferring the
    audio/video streams in real time.
    How I can sen and receive RTP packets.
    How can I make the RTP Player.
    What is the role of JMF in it.
    Please suggest me and provide me the codes if
    possible.
    Thanks alot
    shobhit vermaThere are two ways using which you can send and recieve packets using rtp. One without using the SessionManager and the other with.
    1.) Not using the SessionManager makes things easy for you but it offers very little flexibility to you. You can do this by just specifying a medialocator pointing to the specific url
    2.) Using the SessionManager is what is usually suggested. This process is more complex. First you have to instantiate a RTPSessionMgr to a SessionManager reference using which you can send and receive streams to and from the network. The process is more involved than this and is suggest you read some tutorials to get a better understanding, than me explaining to you the entire process.
    Message was edited by:
    qUesT_foR_knOwLeDge

  • Transmit and receive from the same ip address?

    Helpers:
    We 've been using transmit/Receive for a while, I read all the discussions. No one seem really know does the transmit send to a destination IP address and the destination receive from the same IP or the IP address the sender send from?
    like sender send from: java Transmitter 123.4.3.162 5000
    receiver receive from: java Receive 123.4.3.162 5000
    or sender send from: java Transmitter 123.4.3.162 5000
    receiver receive from: java Receive 10.118.5.162 5000
    I think the frist one is correct, does anyone has clear idea and experience about it.
    Desperate coder!

    Receiver code is as follows
    import java.io.*;
    import java.awt.*;
    import java.net.*;
    import java.awt.event.*;
    import java.util.Vector;
    import javax.media.*;
    import javax.media.rtp.*;
    import javax.media.rtp.event.*;
    import javax.media.rtp.rtcp.*;
    import javax.media.protocol.*;
    import javax.media.protocol.DataSource;
    import javax.media.format.AudioFormat;
    import javax.media.format.VideoFormat;
    import javax.media.Format;
    import javax.media.format.FormatChangeEvent;
    import javax.media.control.BufferControl;
    public class AVReceive2 implements ReceiveStreamListener, SessionListener,ControllerListener
    String sessions[] = null;
    RTPManager mgrs[] = null;
    Vector playerWindows = null;
    boolean dataReceived = false;
    Object dataSync = new Object();
    public AVReceive2(String sessions[])
              this.sessions = sessions;
    protected boolean initialize()
    try
              InetAddress ipAddr;
         SessionAddress localAddr = new SessionAddress();
              SessionAddress destAddr;
              mgrs = new RTPManager[sessions.length];
              playerWindows = new Vector();
              SessionLabel session;
              for (int i = 0; i < sessions.length; i++)
                   try
         session = new SessionLabel(sessions);
              catch (IllegalArgumentException e)
         System.err.println("Failed to parse the session address given: " + sessions[i]);
                        return false;
    System.err.println(" - Open RTP session for: addr: " + session.addr + " port: " + session.port + " ttl: " + session.ttl);
         mgrs[i] = (RTPManager) RTPManager.newInstance();
         mgrs[i].addSessionListener(this);
         mgrs[i].addReceiveStreamListener(this);
         ipAddr = InetAddress.getByName(session.addr);
              if( ipAddr.isMulticastAddress())
    // local and remote address pairs are identical:
    localAddr= new SessionAddress( ipAddr,session.port,session.ttl);
    destAddr = new SessionAddress( ipAddr,session.port,session.ttl);
                        else
    localAddr= new SessionAddress( InetAddress.getLocalHost(),session.port);
    destAddr = new SessionAddress( ipAddr, session.port);
              mgrs[i].initialize( localAddr);
    BufferControl bc = (BufferControl)mgrs[i].getControl("javax.media.control.BufferControl");
                        if (bc != null)
              bc.setBufferLength(350);
                   mgrs[i].addTarget(destAddr);
              catch (Exception e)
    System.err.println("Cannot create the RTP Session: " + e.getMessage());
    return false;
         long then = System.currentTimeMillis();
    long waitingPeriod = 30000; // wait for a maximum of 30 secs.
              try
              synchronized (dataSync)
    while (!dataReceived && System.currentTimeMillis() - then < waitingPeriod)
                        if (!dataReceived)
                                  System.err.println(" - Waiting for RTP data to arrive...");
                        dataSync.wait(1000);
              catch (Exception e) {}
              if (!dataReceived)
    System.err.println("No RTP data was received.");
              close();
              return false;
    return true;
    public boolean isDone()
              return playerWindows.size() == 0;
    protected void close()
              for (int i = 0; i < playerWindows.size(); i++)
              try
         ((PlayerWindow)playerWindows.elementAt(i)).close();
              catch (Exception e) {}
              playerWindows.removeAllElements();
         // close the RTP session.
              for (int i = 0; i < mgrs.length; i++)
              if (mgrs[i] != null)
    mgrs[i].removeTargets( "Closing session from AVReceive2");
    mgrs[i].dispose();
                        mgrs[i] = null;
    PlayerWindow find(Player p)
              for (int i = 0; i < playerWindows.size(); i++)
              PlayerWindow pw = (PlayerWindow)playerWindows.elementAt(i);
              if (pw.player == p)
                        return pw;
              return null;
    PlayerWindow find(ReceiveStream strm)
              for (int i = 0; i < playerWindows.size(); i++)
              PlayerWindow pw = (PlayerWindow)playerWindows.elementAt(i);
              if (pw.stream == strm)
                        return pw;
              return null;
    public synchronized void update(SessionEvent evt)
              if (evt instanceof NewParticipantEvent)
         Participant p = ((NewParticipantEvent)evt).getParticipant();
    System.err.println(" - A new participant had just joined: " + p.getCNAME());
    public synchronized void update( ReceiveStreamEvent evt)
         RTPManager mgr = (RTPManager)evt.getSource();
    Participant participant = evt.getParticipant();     // could be null.
    ReceiveStream stream = evt.getReceiveStream(); // could be null.
              if (evt instanceof RemotePayloadChangeEvent)
    System.err.println(" - Received an RTP PayloadChangeEvent.");
    System.err.println("Sorry, cannot handle payload change.");
              System.exit(0);
              else
              if (evt instanceof NewReceiveStreamEvent)
              try {
    stream = ((NewReceiveStreamEvent)evt).getReceiveStream();
    DataSource ds = stream.getDataSource();
              // Find out the formats.
    RTPControl ctl = (RTPControl)ds.getControl("javax.media.rtp.RTPControl");
                        if (ctl != null)
    System.err.println(" - Recevied new RTP stream: " + ctl.getFormat());
                        else
    System.err.println(" - Recevied new RTP stream");
                        if (participant == null)
    System.err.println(" The sender of this stream had yet to be identified.");
                        else
    System.err.println(" The stream comes from: " + participant.getCNAME());
    // create a player by passing datasource to the Media Manager
    Player p = javax.media.Manager.createPlayer(ds);
                        if (p == null)
                        return;
                   p.addControllerListener(this);
                        p.realize();
         PlayerWindow pw = new PlayerWindow(p, stream);
         playerWindows.addElement(pw);
                   synchronized (dataSync)
                        dataReceived = true;
                        dataSync.notifyAll();
              catch (Exception e)
         System.err.println("NewReceiveStreamEvent exception " + e.getMessage());
                        return;
              else
              if (evt instanceof StreamMappedEvent)
                   if (stream != null && stream.getDataSource() != null)
                        DataSource ds = stream.getDataSource();
              // Find out the formats.
    RTPControl ctl = (RTPControl)ds.getControl("javax.media.rtp.RTPControl");
         System.err.println(" - The previously unidentified stream ");
                        if (ctl != null)
         System.err.println(" " + ctl.getFormat());
         System.err.println(" had now been identified as sent by: " + participant.getCNAME());
              else
              if (evt instanceof ByeEvent)
    System.err.println(" - Got \"bye\" from: " + participant.getCNAME());
              PlayerWindow pw = find(stream);
              if (pw != null)
                        pw.close();
              playerWindows.removeElement(pw);
    public synchronized void controllerUpdate(ControllerEvent ce)
              Player p = (Player)ce.getSourceController();
              if (p == null)
              return;
         // Get this when the internal players are realized.
              if (ce instanceof RealizeCompleteEvent)
              PlayerWindow pw = find(p);
              if (pw == null)
              // Some strange happened.
              System.err.println("Internal error!");
                        System.exit(-1);
              pw.initialize();
              pw.setVisible(true);
              p.start();
              if (ce instanceof ControllerErrorEvent)
              p.removeControllerListener(this);
              PlayerWindow pw = find(p);
              if (pw != null)
                        pw.close();
              playerWindows.removeElement(pw);
         System.err.println("AVReceive2 internal error: " + ce);
    class SessionLabel
              public String addr = null;
              public int port;
              public int ttl = 1;
    SessionLabel(String session) throws IllegalArgumentException
              int off;
              String portStr = null, ttlStr = null;
              if (session != null && session.length() > 0)
         while (session.length() > 1 && session.charAt(0) == '/')
              session = session.substring(1);
              // Now see if there's a addr specified.
                        off = session.indexOf('/');
                        if (off == -1)
                        if (!session.equals(""))
                   addr = session;
                        else
              addr = session.substring(0, off);
              session = session.substring(off + 1);
              // Now see if there's a port specified
              off = session.indexOf('/');
                        if (off == -1)
                        if (!session.equals(""))
                        portStr = session;
                             else
              portStr = session.substring(0, off);
              session = session.substring(off + 1);
              // Now see if there's a ttl specified
                                  off = session.indexOf('/');
                                  if (off == -1)
                                  if (!session.equals(""))
                                            ttlStr = session;
                   else
              ttlStr = session.substring(0, off);
              if (addr == null)
         throw new IllegalArgumentException();
              if (portStr != null)
                        try {
              Integer integer = Integer.valueOf(portStr);
                        if (integer != null)
                                  port = integer.intValue();
              catch (Throwable t)
              throw new IllegalArgumentException();
              else
              throw new IllegalArgumentException();
              if (ttlStr != null)
                        try {
              Integer integer = Integer.valueOf(ttlStr);
                        if (integer != null)
                   ttl = integer.intValue();
                        catch (Throwable t)
              throw new IllegalArgumentException();
    class PlayerWindow extends Frame {
         Player player;
         ReceiveStream stream;
         PlayerWindow(Player p, ReceiveStream strm) {
         player = p;
         stream = strm;
         public void initialize() {
         add(new PlayerPanel(player));
         public void close() {
         player.close();
         setVisible(false);
         dispose();
         public void addNotify() {
         super.addNotify();
         pack();
    class PlayerPanel extends Panel {
         Component vc, cc;
         PlayerPanel(Player p) {
         setLayout(new BorderLayout());
         if ((vc = p.getVisualComponent()) != null)
              add("Center", vc);
         if ((cc = p.getControlPanelComponent()) != null)
              add("South", cc);
         public Dimension getPreferredSize() {
         int w = 0, h = 0;
         if (vc != null) {
              Dimension size = vc.getPreferredSize();
              w = size.width;
              h = size.height;
         if (cc != null) {
              Dimension size = cc.getPreferredSize();
              if (w == 0)
              w = size.width;
              h += size.height;
         if (w < 160)
              w = 160;
         return new Dimension(w, h);
    public static void main(String args[])
              String[] argv = new String[2];
              argv[0] = "100.210.0.220/42050";
              argv[1] = "100.210.0.220/4002";
              AVReceive2 avReceive = new AVReceive2(argv);
              if (!avReceive.initialize())
         System.err.println("Failed to initialize the sessions.");
              System.exit(-1);
              try {
              while (!avReceive.isDone())
                        Thread.sleep(1000);
              } catch (Exception e) {}
              System.err.println("Exiting AVReceive2");

  • About transmitting audio by RTP

    Hi, there,
    I want to create a simple application that transfers audio online through RTP. both the sender machine and receiver machine have public ip address. I tried JMStudio and AVTransmit2/AVReceiver2 without success till now! it drives me crazy. I really don't know what's wrong here. is there anyone really make it work?
    even I can see the receiver machine keep receiving data through the port I specify to transfer data(the port is 22224), the JMStudio or AVReceiver2 on receiver machine just waiting for data, also I can see the statistic of JMStudio on sender machine reports transfer successful and the data keeping transferred. I also tried to use broadcast way, that is, changing the last part of sender's ip address to 255, still no luck! the receiver can't receive any data!
    since I use Ubuntu, there is no firewall, no port is blocked. I can access from receiver to sender or vice versa using SSH. I don't think there is any connection problem, also I can see the receiver keeping receive data.
    I transfer a mp3 file through RTP session. I installed mp3 plugin on both receiver machine and sender machine. I can play it using JMStudio on both receiver machine and sender machine locally.
    could anyone kindly let me know how I should do, or if there is any very very simple java program to transfer anything using RTP on internet? could you please tell me your configuration if you happen to make it work?
    any hint will great appreciate!
    Sam

    if you have a microphone in your pc, AVTranmit2 and AVReceive2 command should be:
    on your own pc:
    java AVTransmit2 dsound:// targetIP 42050
    on target pc:
    java AVReceive2 yourIP/42050
    since the same port cannot be used simutaneously by two applications(avreceive2 and avtransmit2), the above command can only be used on two different pcs (your pc and target pc).
    if you wanna execute AVReceive2 and AVTransmit2 on the same pc, you have to modify the source codes. I have done that.
    commond
    java AVTransmit2 dsound:// yourip 42050 42100
    java AVReceive2 yourip/42050 yourip/42100
    the modified source files are as follows:
    /*****************AVReceive2.java**********************************/
    * @(#)AVReceive2.java     1.3 01/03/13
    * Copyright (c) 1999-2001 Sun Microsystems, Inc. All Rights Reserved.
    * Sun grants you ("Licensee") a non-exclusive, royalty free, license to use,
    * modify and redistribute this software in source and binary code form,
    * provided that i) this copyright notice and license appear on all copies of
    * the software; and ii) Licensee does not utilize the software in a manner
    * which is disparaging to Sun.
    * This software is provided "AS IS," without a warranty of any kind. ALL
    * EXPRESS OR IMPLIED CONDITIONS, REPRESENTATIONS AND WARRANTIES, INCLUDING ANY
    * IMPLIED WARRANTY OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE OR
    * NON-INFRINGEMENT, ARE HEREBY EXCLUDED. SUN AND ITS LICENSORS SHALL NOT BE
    * LIABLE FOR ANY DAMAGES SUFFERED BY LICENSEE AS A RESULT OF USING, MODIFYING
    * OR DISTRIBUTING THE SOFTWARE OR ITS DERIVATIVES. IN NO EVENT WILL SUN OR ITS
    * LICENSORS BE LIABLE FOR ANY LOST REVENUE, PROFIT OR DATA, OR FOR DIRECT,
    * INDIRECT, SPECIAL, CONSEQUENTIAL, INCIDENTAL OR PUNITIVE DAMAGES, HOWEVER
    * CAUSED AND REGARDLESS OF THE THEORY OF LIABILITY, ARISING OUT OF THE USE OF
    * OR INABILITY TO USE SOFTWARE, EVEN IF SUN HAS BEEN ADVISED OF THE
    * POSSIBILITY OF SUCH DAMAGES.
    * This software is not designed or intended for use in on-line control of
    * aircraft, air traffic, aircraft navigation or aircraft communications; or in
    * the design, construction, operation or maintenance of any nuclear
    * facility. Licensee represents and warrants that it will not use or
    * redistribute the Software for such purposes.
    import java.io.*;
    import java.awt.*;
    import java.net.*;
    import java.awt.event.*;
    import java.util.Vector;
    import javax.media.*;
    import javax.media.rtp.*;
    import javax.media.rtp.event.*;
    import javax.media.rtp.rtcp.*;
    import javax.media.protocol.*;
    import javax.media.protocol.DataSource;
    import javax.media.format.AudioFormat;
    import javax.media.format.VideoFormat;
    import javax.media.Format;
    import javax.media.format.FormatChangeEvent;
    import javax.media.control.BufferControl;
    * AVReceive2 to receive RTP transmission using the new RTP API.
    public class AVReceive2 implements ReceiveStreamListener, SessionListener,
         ControllerListener
    String sessions[] = null;
    RTPManager mgrs[] = null;
    Vector playerWindows = null;
    boolean dataReceived = false;
    Object dataSync = new Object();
    public AVReceive2(String sessions[]) {
         this.sessions = sessions;
    protected boolean initialize() {
    try {
         InetAddress ipAddr;
         SessionAddress localAddr = new SessionAddress();
         SessionAddress destAddr;
         mgrs = new RTPManager[sessions.length];
         playerWindows = new Vector();
         SessionLabel session;
         // Open the RTP sessions.
         for (int i = 0; i < sessions.length; i++) {
              // Parse the session addresses.
              try {
              session = new SessionLabel(sessions);
              } catch (IllegalArgumentException e) {
              System.err.println("Failed to parse the session address given: " + sessions[i]);
              return false;
              System.err.println(" - Open RTP session for: addr: " + session.addr + " port: " + session.port + " ttl: " + session.ttl);
              mgrs[i] = (RTPManager) RTPManager.newInstance();
              mgrs[i].addSessionListener(this);
              mgrs[i].addReceiveStreamListener(this);
              ipAddr = InetAddress.getByName(session.addr);
              if( ipAddr.isMulticastAddress()) {
              // local and remote address pairs are identical:
              localAddr= new SessionAddress( ipAddr,
                                  session.port,
                                  session.ttl);
              destAddr = new SessionAddress( ipAddr,
                                  session.port,
                                  session.ttl);
              } else {
              localAddr= new SessionAddress( InetAddress.getLocalHost(),
                        42100+2*i);
                             //session.port);
    destAddr = new SessionAddress( ipAddr,
              42050+2*i);
              //session.port);
              mgrs[i].initialize( localAddr);
              // You can try out some other buffer size to see
              // if you can get better smoothness.
              BufferControl bc = (BufferControl)mgrs[i].getControl("javax.media.control.BufferControl");
              if (bc != null)
              bc.setBufferLength(350);
              mgrs[i].addTarget(destAddr);
    } catch (Exception e){
    System.err.println("Cannot create the RTP Session: " + e.getMessage());
    return false;
         // Wait for data to arrive before moving on.
         long then = System.currentTimeMillis();
         long waitingPeriod = 30000; // wait for a maximum of 30 secs.
         try{
         synchronized (dataSync) {
              while (!dataReceived &&
                   System.currentTimeMillis() - then < waitingPeriod) {
              if (!dataReceived)
                   System.err.println(" - Waiting for RTP data to arrive...");
              dataSync.wait(1000);
         } catch (Exception e) {}
         if (!dataReceived) {
         System.err.println("No RTP data was received.");
         close();
         return false;
    return true;
    public boolean isDone() {
         return playerWindows.size() == 0;
    * Close the players and the session managers.
    protected void close() {
         for (int i = 0; i < playerWindows.size(); i++) {
         try {
              ((PlayerWindow)playerWindows.elementAt(i)).close();
         } catch (Exception e) {}
         playerWindows.removeAllElements();
         // close the RTP session.
         for (int i = 0; i < mgrs.length; i++) {
         if (mgrs[i] != null) {
    mgrs[i].removeTargets( "Closing session from AVReceive2");
    mgrs[i].dispose();
              mgrs[i] = null;
    PlayerWindow find(Player p) {
         for (int i = 0; i < playerWindows.size(); i++) {
         PlayerWindow pw = (PlayerWindow)playerWindows.elementAt(i);
         if (pw.player == p)
              return pw;
         return null;
    PlayerWindow find(ReceiveStream strm) {
         for (int i = 0; i < playerWindows.size(); i++) {
         PlayerWindow pw = (PlayerWindow)playerWindows.elementAt(i);
         if (pw.stream == strm)
              return pw;
         return null;
    * SessionListener.
    public synchronized void update(SessionEvent evt) {
         if (evt instanceof NewParticipantEvent) {
         Participant p = ((NewParticipantEvent)evt).getParticipant();
         System.err.println(" - A new participant had just joined: " + p.getCNAME());
    * ReceiveStreamListener
    public synchronized void update( ReceiveStreamEvent evt) {
         RTPManager mgr = (RTPManager)evt.getSource();
         Participant participant = evt.getParticipant();     // could be null.
         ReceiveStream stream = evt.getReceiveStream(); // could be null.
         if (evt instanceof RemotePayloadChangeEvent) {
         System.err.println(" - Received an RTP PayloadChangeEvent.");
         System.err.println("Sorry, cannot handle payload change.");
         System.exit(0);
         else if (evt instanceof NewReceiveStreamEvent) {
         try {
              stream = ((NewReceiveStreamEvent)evt).getReceiveStream();
              DataSource ds = stream.getDataSource();
              // Find out the formats.
              RTPControl ctl = (RTPControl)ds.getControl("javax.media.rtp.RTPControl");
              if (ctl != null){
              System.err.println(" - Recevied new RTP stream: " + ctl.getFormat());
              } else
              System.err.println(" - Recevied new RTP stream");
              if (participant == null)
              System.err.println(" The sender of this stream had yet to be identified.");
              else {
              System.err.println(" The stream comes from: " + participant.getCNAME());
              // create a player by passing datasource to the Media Manager
              Player p = javax.media.Manager.createPlayer(ds);
              if (p == null)
              return;
              p.addControllerListener(this);
              p.realize();
              PlayerWindow pw = new PlayerWindow(p, stream);
              playerWindows.addElement(pw);
              // Notify intialize() that a new stream had arrived.
              synchronized (dataSync) {
              dataReceived = true;
              dataSync.notifyAll();
         } catch (Exception e) {
              System.err.println("NewReceiveStreamEvent exception " + e.getMessage());
              return;
         else if (evt instanceof StreamMappedEvent) {
         if (stream != null && stream.getDataSource() != null) {
              DataSource ds = stream.getDataSource();
              // Find out the formats.
              RTPControl ctl = (RTPControl)ds.getControl("javax.media.rtp.RTPControl");
              System.err.println(" - The previously unidentified stream ");
              if (ctl != null)
              System.err.println(" " + ctl.getFormat());
              System.err.println(" had now been identified as sent by: " + participant.getCNAME());
         else if (evt instanceof ByeEvent) {
         System.err.println(" - Got \"bye\" from: " + participant.getCNAME());
         PlayerWindow pw = find(stream);
         if (pw != null) {
              pw.close();
              playerWindows.removeElement(pw);
    * ControllerListener for the Players.
    public synchronized void controllerUpdate(ControllerEvent ce) {
         Player p = (Player)ce.getSourceController();
         if (p == null)
         return;
         // Get this when the internal players are realized.
         if (ce instanceof RealizeCompleteEvent) {
         PlayerWindow pw = find(p);
         if (pw == null) {
              // Some strange happened.
              System.err.println("Internal error!");
              System.exit(-1);
         pw.initialize();
         pw.setVisible(true);
         p.start();
         if (ce instanceof ControllerErrorEvent) {
         p.removeControllerListener(this);
         PlayerWindow pw = find(p);
         if (pw != null) {
              pw.close();     
              playerWindows.removeElement(pw);
         System.err.println("AVReceive2 internal error: " + ce);
    * A utility class to parse the session addresses.
    class SessionLabel {
         public String addr = null;
         public int port;
         public int ttl = 1;
         SessionLabel(String session) throws IllegalArgumentException {
         int off;
         String portStr = null, ttlStr = null;
         if (session != null && session.length() > 0) {
              while (session.length() > 1 && session.charAt(0) == '/')
              session = session.substring(1);
              // Now see if there's a addr specified.
              off = session.indexOf('/');
              if (off == -1) {
              if (!session.equals(""))
                   addr = session;
              } else {
              addr = session.substring(0, off);
              session = session.substring(off + 1);
              // Now see if there's a port specified
              off = session.indexOf('/');
              if (off == -1) {
                   if (!session.equals(""))
                   portStr = session;
              } else {
                   portStr = session.substring(0, off);
                   session = session.substring(off + 1);
                   // Now see if there's a ttl specified
                   off = session.indexOf('/');
                   if (off == -1) {
                   if (!session.equals(""))
                        ttlStr = session;
                   } else {
                   ttlStr = session.substring(0, off);
         if (addr == null)
              throw new IllegalArgumentException();
         if (portStr != null) {
              try {
              Integer integer = Integer.valueOf(portStr);
              if (integer != null)
                   port = integer.intValue();
              } catch (Throwable t) {
              throw new IllegalArgumentException();
         } else
              throw new IllegalArgumentException();
         if (ttlStr != null) {
              try {
              Integer integer = Integer.valueOf(ttlStr);
              if (integer != null)
                   ttl = integer.intValue();
              } catch (Throwable t) {
              throw new IllegalArgumentException();
    * GUI classes for the Player.
    class PlayerWindow extends Frame {
         Player player;
         ReceiveStream stream;
         PlayerWindow(Player p, ReceiveStream strm) {
         player = p;
         stream = strm;
         public void initialize() {
         add(new PlayerPanel(player));
         public void close() {
         player.close();
         setVisible(false);
         dispose();
         public void addNotify() {
         super.addNotify();
         pack();
    * GUI classes for the Player.
    class PlayerPanel extends Panel {
         Component vc, cc;
         PlayerPanel(Player p) {
         setLayout(new BorderLayout());
         if ((vc = p.getVisualComponent()) != null)
              add("Center", vc);
         if ((cc = p.getControlPanelComponent()) != null)
              add("South", cc);
         public Dimension getPreferredSize() {
         int w = 0, h = 0;
         if (vc != null) {
              Dimension size = vc.getPreferredSize();
              w = size.width;
              h = size.height;
         if (cc != null) {
              Dimension size = cc.getPreferredSize();
              if (w == 0)
              w = size.width;
              h += size.height;
         if (w < 160)
              w = 160;
         return new Dimension(w, h);
    public static void main(String argv[]) {
         if (argv.length == 0)
         prUsage();
         AVReceive2 avReceive = new AVReceive2(argv);
         if (!avReceive.initialize()) {
         System.err.println("Failed to initialize the sessions.");
         System.exit(-1);
         // Check to see if AVReceive2 is done.
         try {
         while (!avReceive.isDone())
              Thread.sleep(1000);
         } catch (Exception e) {}
         System.err.println("Exiting AVReceive2");
    static void prUsage() {
         System.err.println("Usage: AVReceive2 <session> <session> ...");
         System.err.println(" <session>: <address>/<port>/<ttl>");
         System.exit(0);
    }// end of AVReceive2
    /****************************AVTransmit2.java****************************/
    * @(#)AVTransmit2.java     1.4 01/03/13
    * Copyright (c) 1999-2001 Sun Microsystems, Inc. All Rights Reserved.
    * Sun grants you ("Licensee") a non-exclusive, royalty free, license to use,
    * modify and redistribute this software in source and binary code form,
    * provided that i) this copyright notice and license appear on all copies of
    * the software; and ii) Licensee does not utilize the software in a manner
    * which is disparaging to Sun.
    * This software is provided "AS IS," without a warranty of any kind. ALL
    * EXPRESS OR IMPLIED CONDITIONS, REPRESENTATIONS AND WARRANTIES, INCLUDING ANY
    * IMPLIED WARRANTY OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE OR
    * NON-INFRINGEMENT, ARE HEREBY EXCLUDED. SUN AND ITS LICENSORS SHALL NOT BE
    * LIABLE FOR ANY DAMAGES SUFFERED BY LICENSEE AS A RESULT OF USING, MODIFYING
    * OR DISTRIBUTING THE SOFTWARE OR ITS DERIVATIVES. IN NO EVENT WILL SUN OR ITS
    * LICENSORS BE LIABLE FOR ANY LOST REVENUE, PROFIT OR DATA, OR FOR DIRECT,
    * INDIRECT, SPECIAL, CONSEQUENTIAL, INCIDENTAL OR PUNITIVE DAMAGES, HOWEVER
    * CAUSED AND REGARDLESS OF THE THEORY OF LIABILITY, ARISING OUT OF THE USE OF
    * OR INABILITY TO USE SOFTWARE, EVEN IF SUN HAS BEEN ADVISED OF THE
    * POSSIBILITY OF SUCH DAMAGES.
    * This software is not designed or intended for use in on-line control of
    * aircraft, air traffic, aircraft navigation or aircraft communications; or in
    * the design, construction, operation or maintenance of any nuclear
    * facility. Licensee represents and warrants that it will not use or
    * redistribute the Software for such purposes.
    import java.awt.*;
    import java.io.*;
    import java.net.InetAddress;
    import javax.media.*;
    import javax.media.protocol.*;
    import javax.media.protocol.DataSource;
    import javax.media.format.*;
    import javax.media.control.TrackControl;
    import javax.media.control.QualityControl;
    import javax.media.rtp.*;
    import javax.media.rtp.rtcp.*;
    import com.sun.media.rtp.*;
    public class AVTransmit2 {
    // Input MediaLocator
    // Can be a file or http or capture source
    private MediaLocator locator;
    private String ipAddress;
    // private int portBase;
         private int localPortBase;
         private int remotePortBase;
    private Processor processor = null;
    private RTPManager rtpMgrs[];
    private DataSource dataOutput = null;
    public AVTransmit2(MediaLocator locator,
                   String ipAddress,
                   String localPB,
                   String remotePB,
                   Format format) {
    Integer int1 = Integer.valueOf(remotePB);
    if(int1 != null)
         this.remotePortBase = int1.intValue();
         this.locator = locator;
         this.ipAddress = ipAddress;
         Integer int2 = Integer.valueOf(localPB);
         if (int2 != null)
         this.localPortBase = int2.intValue();
    * Starts the transmission. Returns null if transmission started ok.
    * Otherwise it returns a string with the reason why the setup failed.
    public synchronized String start() {
         String result;
         // Create a processor for the specified media locator
         // and program it to output JPEG/RTP
         result = createProcessor();
         if (result != null)
         return result;
         // Create an RTP session to transmit the output of the
         // processor to the specified IP address and port no.
         result = createTransmitter();
         if (result != null) {
         processor.close();
         processor = null;
         return result;
         // Start the transmission
         processor.start();
         return null;
    * Stops the transmission if already started
    public void stop() {
         synchronized (this) {
         if (processor != null) {
              processor.stop();
              processor.close();
              processor = null;
              for (int i = 0; i < rtpMgrs.length; i++) {
              rtpMgrs[i].removeTargets( "Session ended.");
              rtpMgrs[i].dispose();
    private String createProcessor() {
         if (locator == null)
         return "Locator is null";
         DataSource ds;
         DataSource clone;
         try {
         ds = javax.media.Manager.createDataSource(locator);
         } catch (Exception e) {
         return "Couldn't create DataSource";
         // Try to create a processor to handle the input media locator
         try {
         processor = javax.media.Manager.createProcessor(ds);
         } catch (NoProcessorException npe) {
         return "Couldn't create processor";
         } catch (IOException ioe) {
         return "IOException creating processor";
         // Wait for it to configure
         boolean result = waitForState(processor, Processor.Configured);
         if (result == false)
         return "Couldn't configure processor";
         // Get the tracks from the processor
         TrackControl [] tracks = processor.getTrackControls();
         // Do we have atleast one track?
         if (tracks == null || tracks.length < 1)
         return "Couldn't find tracks in processor";
         // Set the output content descriptor to RAW_RTP
         // This will limit the supported formats reported from
         // Track.getSupportedFormats to only valid RTP formats.
         ContentDescriptor cd = new ContentDescriptor(ContentDescriptor.RAW_RTP);
         processor.setContentDescriptor(cd);
         Format supported[];
         Format chosen;
         boolean atLeastOneTrack = false;
         // Program the tracks.
         for (int i = 0; i < tracks.length; i++) {
         Format format = tracks[i].getFormat();
         if (tracks[i].isEnabled()) {
              supported = tracks[i].getSupportedFormats();
              // We've set the output content to the RAW_RTP.
              // So all the supported formats should work with RTP.
              // We'll just pick the first one.
              if (supported.length > 0) {
              if (supported[0] instanceof VideoFormat) {
                   // For video formats, we should double check the
                   // sizes since not all formats work in all sizes.
                   chosen = checkForVideoSizes(tracks[i].getFormat(),
                                       supported[0]);//select the first supported format for convenice
              } else
                   chosen = supported[0];
              tracks[i].setFormat(chosen);
              System.err.println("Track " + i + " is set to transmit as:");
              System.err.println(" " + chosen);
              atLeastOneTrack = true;
              } else
              tracks[i].setEnabled(false);
         } else
              tracks[i].setEnabled(false);
         if (!atLeastOneTrack)
         return "Couldn't set any of the tracks to a valid RTP format";
         // Realize the processor. This will internally create a flow
         // graph and attempt to create an output datasource for JPEG/RTP
         // audio frames.
         result = waitForState(processor, Controller.Realized);
         if (result == false)
         return "Couldn't realize processor";
         // Set the JPEG quality to .5.
         setJPEGQuality(processor, 0.5f);//no effect if not JPEG format
         // Get the output data source of the processor
         dataOutput = processor.getDataOutput();
         return null;
    * Use the RTPManager API to create sessions for each media
    * track of the processor.
    private String createTransmitter() {
         // Cheated. Should have checked the type.
         PushBufferDataSource pbds = (PushBufferDataSource)dataOutput;
         PushBufferStream pbss[] = pbds.getStreams();
         rtpMgrs = new RTPManager[pbss.length];
         SessionAddress localAddr, destAddr;
         InetAddress ipAddr;
         SendStream sendStream;
         int localPort;
         int remotePort;
         SourceDescription srcDesList[];
         for (int i = 0; i < pbss.length; i++) {
         try {
              rtpMgrs[i] = RTPManager.newInstance();     
              // The local session address will be created on the
              // same port as the the target port. This is necessary
              // if you use AVTransmit2 in conjunction with JMStudio.
              // JMStudio assumes - in a unicast session - that the
              // transmitter transmits from the same port it is receiving
              // on and sends RTCP Receiver Reports back to this port of
              // the transmitting host.
              localPort = localPortBase + 2*i;
              remotePort = remotePortBase + 2*i;
              ipAddr = InetAddress.getByName(ipAddress);
              localAddr = new SessionAddress( InetAddress.getLocalHost(),
                                  localPort);
              destAddr = new SessionAddress( ipAddr, remotePort);
              rtpMgrs[i].initialize( localAddr);
              rtpMgrs[i].addTarget( destAddr);
              System.err.println( "Created RTP session ("+pbss[i].getFormat().getClass() + "):"+localAddr.getControlHostAddress()
                        +":"+localAddr.getDataPort()+"->"+destAddr.getControlHostAddress()+":"+ destAddr.getDataPort());
              sendStream = rtpMgrs[i].createSendStream(dataOutput, i);     
              sendStream.start();
         } catch (Exception e) {
              return e.getMessage();
         return null;
    * For JPEG and H263, we know that they only work for particular
    * sizes. So we'll perform extra checking here to make sure they
    * are of the right sizes.
    Format checkForVideoSizes(Format original, Format supported) {
         int width, height;
         Dimension size = ((VideoFormat)original).getSize();
         Format jpegFmt = new Format(VideoFormat.JPEG_RTP);
         Format h263Fmt = new Format(VideoFormat.H263_RTP);
         if (supported.matches(jpegFmt)) {
         // For JPEG, make sure width and height are divisible by 8.
         width = (size.width % 8 == 0 ? size.width :
                        (int)(size.width / 8) * 8);
         height = (size.height % 8 == 0 ? size.height :
                        (int)(size.height / 8) * 8);
         } else if (supported.matches(h263Fmt)) {
         // For H.263, we only support some specific sizes.
         if (size.width < 128) {
              width = 128;
              height = 96;
         } else if (size.width < 176) {
              width = 176;
              height = 144;
         } else {
              width = 352;
              height = 288;
         } else {
         // We don't know this particular format. We'll just
         // leave it alone then.
         return supported;
         return (new VideoFormat(null,
                        new Dimension(width, height),
                        Format.NOT_SPECIFIED,
                        null,
                        Format.NOT_SPECIFIED)).intersects(supported);
    * Setting the encoding quality to the specified value on the JPEG encoder.
    * 0.5 is a good default.
    void setJPEGQuality(Player p, float val) {
         Control cs[] = p.getControls();
         QualityControl qc = null;
         VideoFormat jpegFmt = new VideoFormat(VideoFormat.JPEG);
         // Loop through the controls to find the Quality control for
         // the JPEG encoder.
         for (int i = 0; i < cs.length; i++) {
         if (cs[i] instanceof QualityControl &&
              cs[i] instanceof Owned) {
              Object owner = ((Owned)cs[i]).getOwner();
              // Check to see if the owner is a Codec.
              // Then check for the output format.
              if (owner instanceof Codec) {
              Format fmts[] = ((Codec)owner).getSupportedOutputFormats(null);
              for (int j = 0; j < fmts.length; j++) {
                   if (fmts[j].matches(jpegFmt)) {
                   qc = (QualityControl)cs[i];
                   qc.setQuality(val);
                   System.err.println("- Setting quality to " +
                             val + " on " + qc);
                   break;
              if (qc != null)
              break;
    * Convenience methods to handle processor's state changes.
    private Integer stateLock = new Integer(0);
    private boolean failed = false;
    Integer getStateLock() {
         return stateLock;
    void setFailed() {
         failed = true;
    private boolean waitForState(Processor p, int state) {
         p.addControllerListener(new StateListener());
         failed = false;
         // Call the required method on the processor
         if (state == Processor.Configured) {
         p.configure();
         } else if (state == Processor.Realized) {
         p.realize();
         // Wait until we get an event that confirms the
         // success of the method, or a failure event.
         // See StateListener inner class
         while (p.getState() < state && !failed) {
         synchronized (getStateLock()) {
              try {
              getStateLock().wait();
              } catch (InterruptedException ie) {
              return false;
         if (failed)
         return false;
         else
         return true;
    * Inner Classes
    class StateListener implements ControllerListener {
         public void controllerUpdate(ControllerEvent ce) {
         // If there was an error during configure or
         // realize, the processor will be closed
         if (ce instanceof ControllerClosedEvent)
              setFailed();
         // All controller events, send a notification
         // to the waiting thread in waitForState method.
         if (ce instanceof ControllerEvent) {
              synchronized (getStateLock()) {
              getStateLock().notifyAll();
    * Sample Usage for AVTransmit2 class
    public static void main(String [] args) {
         // We need three parameters to do the transmission
         // For example,
         // java AVTransmit2 file:/C:/media/test.mov 129.130.131.132 42050
         if (args.length < 3) {
         prUsage();
         Format fmt = null;
         int i = 0;
         MediaLocator ml = new MediaLocator(args[i]);
         // Create a audio transmit object with the specified params.
         AVTransmit2 at = new AVTransmit2(ml,
                             args[i+1], args[i+2], args[i+3], fmt);
         // Start the transmission
         String result = at.start();
         // result will be non-null if there was an error. The return
         // value is a String describing the possible error. Print it.
         if (result != null) {
         System.err.println("Error : " + result);
         System.exit(0);
         System.err.println("Start transmission for 60 seconds...");
         // Transmit for 60 seconds and then close the processor
         // This is a safeguard when using a capture data source
         // so that the capture device will be properly released
         // before quitting.
         // The right thing to do would be to have a GUI with a
         // "Stop" button that would call stop on AVTransmit2
         try {
         Thread.currentThread().sleep(60000);
         } catch (InterruptedException ie) {
         // Stop the transmission
         at.stop();
         System.err.println("...transmission ended.");
         System.exit(0);
    static void prUsage() {
         System.err.println("Usage: AVTransmit2 <sourceURL> <destIP> <destPortBase>");
         System.err.println(" <sourceURL>: input URL or file name");
         System.err.println(" <destIP>: multicast, broadcast or unicast IP address for the transmission");
         System.err.println(" <destPortBase>: network port numbers for the transmission.");
         System.err.println(" The first track will use the destPortBase.");
         System.err.println(" The next track will use destPortBase + 2 and so on.\n");
         System.exit(0);
    if you have any further problems, it's my pleasure to discuss with you.
    [email protected]

  • How to solve the problem "cannot create a datasink for **(datasource)"

    There is a forums that can send and receive RTP streams, and it can play on the client. Now I want to save it. I write the code according to the jmf2_0-guide, how ever it always throws the exception "cannot create a datasink for **(datasource)". The datasource is the RTP stream received from the server. Is there anything wrong with the data source or anything else?
    here is the code:
    public synchronized void update( ReceiveStreamEvent evt){
    if(evt instanceof NewReceiveStreamEvent){
    try{
    stream = ((NewReceiveStreamEvent)evt).getReceiveStream();
    DataSource ds = stream.getDataSource();
    MediaLocator f = new MediaLocator("file://foo.au");
    Manager.createDataSink(ds, f);
    RTPControl ctl = (RTPControl)ds.getControl("javax.media.rtp.RTPControl");
    if (ctl != null) {
         System.err.println(" - Recevied new RTP stream: " + ctl.getFormat());
         } else {
         System.err.println(" - Recevied new RTP stream");
         if (participant == null) {
         System.err.println(" The sender of this stream had yet to be identified.");
         } else {
         System.err.println(" The stream comes from: " + participant.getCNAME());
         // create a player by passing datasource to the Media Manager
         Player p = javax.media.Manager.createPlayer(ds);
         if (p == null) {
         return;
         p.addControllerListener(this);
         p.realize();
         PlayerWindow pw = new PlayerWindow(p, stream);
         playerWindows.addElement(pw);
         // Notify intialize() that a new stream had arrived.
         synchronized (dataSync) {
         dataReceived = true;
         dataSync.notifyAll();
         } catch (Exception e) {
         System.err.println("NewReceiveStreamEvent exception " + e.getMessage());
         return;
    Does any one know how to solve this problem? How to save or how to create a datasink? Please help! Thank you!!

    The complete error message:
    NewReceiveStreamEvent exception Cannot find a DataSink for: com.sun.media.protocol.rtp.DataSource@4741d6

  • A simple client

    hello,
    I was wondering if anyone had or if there is a simple client application out there which connects to a server and plays the rtp stream. I already have the server ready to go and I was hopeing I could find an easy client to use to display the video. I am currently using JMStudio as the client which turns out to be a bit ugly. Are there alternatives?

    import java.io.*;
    import java.awt.*;
    import java.net.*;
    import java.awt.event.*;
    import java.util.Vector;
    import javax.media.*;
    import javax.media.rtp.*;
    import javax.media.rtp.event.*;
    import javax.media.rtp.rtcp.*;
    import javax.media.protocol.*;
    import javax.media.protocol.DataSource;
    import javax.media.format.AudioFormat;
    import javax.media.format.VideoFormat;
    import javax.media.Format;
    import javax.media.format.FormatChangeEvent;
    import javax.media.control.BufferControl;
    import javax.media.datasink.DataSinkListener;
    import javax.media.datasink.DataSinkEvent;
    * AVReceive2 to receive RTP transmission using the new RTP API.
    public class AVReceive2 implements ReceiveStreamListener, SessionListener,DataSinkListener,
         ControllerListener
    String sessions[] = null;
    RTPManager mgrs[] = null;
    Vector playerWindows = null;
    javax.media.DataSink datasink=null;
    boolean dataReceived = false;
    Object dataSync = new Object();
    public AVReceive2(String sessions[]) {
    System.out.println("Reached in");
         this.sessions = sessions;
    protected boolean initialize() {
    try {
         InetAddress ipAddr;
         SessionAddress localAddr = new SessionAddress();
         SessionAddress destAddr;
         mgrs = new RTPManager[sessions.length];
         playerWindows = new Vector();
         SessionLabel session;
         // Open the RTP sessions.
         for (int i = 0; i < sessions.length; i++) {
              // Parse the session addresses.
              try {
              session = new SessionLabel(sessions);
              } catch (IllegalArgumentException e) {
              System.err.println("Failed to parse the session address given: " + sessions[i]);
              return false;
              System.err.println(" - Open RTP session for: addr: " + session.addr + " port: " + session.port + " ttl: " + session.ttl);
              mgrs[i] = (RTPManager) RTPManager.newInstance();
              mgrs[i].addSessionListener(this);
              mgrs[i].addReceiveStreamListener(this);
              ipAddr = InetAddress.getByName(session.addr);
              if( ipAddr.isMulticastAddress()) {
              // local and remote address pairs are identical:
              localAddr= new SessionAddress( ipAddr,
                                  session.port,
                                  session.ttl);
              destAddr = new SessionAddress( ipAddr,
                                  session.port,
                                  session.ttl);
              } else {
              localAddr= new SessionAddress( InetAddress.getLocalHost(),
                             session.port);
    destAddr = new SessionAddress( ipAddr, session.port);
              mgrs[i].initialize( localAddr);
              // You can try out some other buffer size to see
              // if you can get better smoothness.
              BufferControl bc = (BufferControl)mgrs[i].getControl("javax.media.control.BufferControl");
              if (bc != null)
              bc.setBufferLength(350);
              mgrs[i].addTarget(destAddr);
    } catch (Exception e){
    System.err.println("Cannot create the RTP Session: " + e.getMessage());
    return false;
         // Wait for data to arrive before moving on.
         long then = System.currentTimeMillis();
         long waitingPeriod = 30000; // wait for a maximum of 30 secs.
         try{
         synchronized (dataSync) {
              while (!dataReceived &&
                   System.currentTimeMillis() - then < waitingPeriod) {
              if (!dataReceived)
                   System.err.println(" - Waiting for RTP data to arrive...");
              dataSync.wait(1000);
         } catch (Exception e) {}
         if (!dataReceived) {
         System.err.println("No RTP data was received.");
         close();
         return false;
    return true;
    public boolean isDone() {
         return playerWindows.size() == 0;
    * Close the players and the session managers.
    protected void close() {
         for (int i = 0; i < playerWindows.size(); i++) {
         try {
              ((PlayerWindow)playerWindows.elementAt(i)).close();
         } catch (Exception e) {}
         playerWindows.removeAllElements();
         // close the RTP session.
         for (int i = 0; i < mgrs.length; i++) {
         if (mgrs[i] != null) {
    mgrs[i].removeTargets( "Closing session from AVReceive2");
    mgrs[i].dispose();
              mgrs[i] = null;
    PlayerWindow find(Player p) {
    System.out.println("In Find with player");
         for (int i = 0; i < playerWindows.size(); i++) {
         PlayerWindow pw = (PlayerWindow)playerWindows.elementAt(i);
         if (pw.player == p)
              return pw;
         return null;
    PlayerWindow find(ReceiveStream strm) {
         for (int i = 0; i < playerWindows.size(); i++) {
         PlayerWindow pw = (PlayerWindow)playerWindows.elementAt(i);
         System.out.println("In Find");
              if (strm!=null){
         if (pw.stream == strm)
              return pw;
         return null;
    * SessionListener.
    public synchronized void update(SessionEvent evt) {
    SessionManager sess = (SessionManager)evt.getSessionManager();
    System.out.println("In Session Event");
         if (evt instanceof NewParticipantEvent) {
         Participant p = ((NewParticipantEvent)evt).getParticipant();
         System.err.println(" - A new participant had just joined: " + p.getCNAME());
         /* try{
    javax.media.protocol.DataSource dsource =(javax.media.protocol.DataSource) stream.getDataSource();
    System.out.println(stream);
    System.out.println(dsource);
    // System.out.println(dsource.getContentType());
    //dsource.connect();
    MediaLocator f = new MediaLocator("file://C:/foo.mp3");
    DataSink dSink= Manager.createDataSink(dsource, f);
    dSink.open();
    dSink.start();
    } catch (Exception e) {
    System.err.println("newReceiveStreamEvent exception "
    + e.getMessage());
    return;
    * ReceiveStreamListener
    public synchronized void update( ReceiveStreamEvent evt) {
    System.out.println("In Rece Event");
         RTPManager mgr = (RTPManager)evt.getSource();
         Participant participant = evt.getParticipant();     // could be null.
         ReceiveStream stream = evt.getReceiveStream(); // could be null.
         if (evt instanceof RemotePayloadChangeEvent) {
         System.err.println(" - Received an RTP PayloadChangeEvent.");
         System.err.println("Sorry, cannot handle payload change.");
         System.exit(0);
         else if (evt instanceof NewReceiveStreamEvent) {
    System.out.println("In New Rece Event");
         try {
              stream = ((NewReceiveStreamEvent)evt).getReceiveStream();
              DataSource ds = stream.getDataSource();
              // Find out the formats.
              RTPControl ctl = (RTPControl)ds.getControl("javax.media.rtp.RTPControl");
              if (ctl != null){
              System.err.println(" - Recevied new RTP stream: " + ctl.getFormat());
              } else
              System.err.println(" - Recevied new RTP stream");
              if (participant == null)
              System.err.println(" The sender of this stream had yet to be identified.");
              else {
              System.err.println(" The stream comes from: " + participant.getCNAME());
              // create a player by passing datasource to the Media Manager
              Player p = javax.media.Manager.createPlayer(ds);
              ///Code By Ritesh
              try{
    MediaLocator f = new MediaLocator("rtp://10.10.205.24:49150/audio/1");
    datasink= Manager.createDataSink(ds, f);
    datasink.open();
    datasink.start();
    datasink.addDataSinkListener(this);
    //dSink.
    } catch (Exception e) {
    System.err.println("newReceiveStreamEvent exception "
    + e.getMessage());
              //End of code by Ritesh
         if (p == null)
              return;
              p.addControllerListener(this);
              p.realize();
              PlayerWindow pw = new PlayerWindow(p, stream);
              playerWindows.addElement(pw);
    // Code By Ritesh
    //Participant part = stream.getParticipant();
    // get the ReceiveStream datasource
              // Notify intialize() that a new stream had arrived.
              synchronized (dataSync) {
              dataReceived = true;
              dataSync.notifyAll();
         } catch (Exception e) {
              System.err.println("NewReceiveStreamEvent exception " + e.getMessage());
              return;
         else if (evt instanceof StreamMappedEvent) {
         if (stream != null && stream.getDataSource() != null) {
              DataSource ds = stream.getDataSource();
              // Find out the formats.
              RTPControl ctl = (RTPControl)ds.getControl("javax.media.rtp.RTPControl");
              System.err.println(" - The previously unidentified stream ");
              if (ctl != null)
              System.err.println(" " + ctl.getFormat());
              System.err.println(" had now been identified as sent by: " + participant.getCNAME());
         else if (evt instanceof ByeEvent) {
         System.err.println(" - Got \"bye\" from: " + participant.getCNAME());
         PlayerWindow pw = find(stream);
         if (pw != null) {
              pw.close();
              playerWindows.removeElement(pw);
    //Data Sink Object
    public void dataSinkUpdate(DataSinkEvent event){
    System.out.println("Data Sink Event");
    * ControllerListener for the Players.
    public synchronized void controllerUpdate(ControllerEvent ce) {
         Player p = (Player)ce.getSourceController();
         if (p == null)
         return;
         // Get this when the internal players are realized.
         if (ce instanceof RealizeCompleteEvent) {
         PlayerWindow pw = find(p);
         if (pw == null) {
              // Some strange happened.
              System.err.println("Internal error!");
              System.exit(-1);
         pw.initialize();
         pw.setVisible(true);
         p.start();
         if (ce instanceof ControllerErrorEvent) {
         p.removeControllerListener(this);
         PlayerWindow pw = find(p);
         if (pw != null) {
              pw.close();     
              playerWindows.removeElement(pw);
         System.err.println("AVReceive2 internal error: " + ce);
    * A utility class to parse the session addresses.
    class SessionLabel {
         public String addr = null;
         public int port;
         public int ttl = 1;
         SessionLabel(String session) throws IllegalArgumentException {
         int off;
         String portStr = null, ttlStr = null;
         if (session != null && session.length() > 0) {
              while (session.length() > 1 && session.charAt(0) == '/')
              session = session.substring(1);
              // Now see if there's a addr specified.
              off = session.indexOf('/');
              if (off == -1) {
              if (!session.equals(""))
                   addr = session;
              } else {
              addr = session.substring(0, off);
              session = session.substring(off + 1);
              // Now see if there's a port specified
              off = session.indexOf('/');
              if (off == -1) {
                   if (!session.equals(""))
                   portStr = session;
              } else {
                   portStr = session.substring(0, off);
                   session = session.substring(off + 1);
                   // Now see if there's a ttl specified
                   off = session.indexOf('/');
                   if (off == -1) {
                   if (!session.equals(""))
                        ttlStr = session;
                   } else {
                   ttlStr = session.substring(0, off);
         if (addr == null)
              throw new IllegalArgumentException();
         if (portStr != null) {
              try {
              Integer integer = Integer.valueOf(portStr);
              if (integer != null)
                   port = integer.intValue();
              } catch (Throwable t) {
              throw new IllegalArgumentException();
         } else
              throw new IllegalArgumentException();
         if (ttlStr != null) {
              try {
              Integer integer = Integer.valueOf(ttlStr);
              if (integer != null)
                   ttl = integer.intValue();
              } catch (Throwable t) {
              throw new IllegalArgumentException();
    * GUI classes for the Player.
    class PlayerWindow extends Frame {
         Player player;
         ReceiveStream stream;
         PlayerWindow(Player p, ReceiveStream strm) {
         player = p;
         stream = strm;
         public void initialize() {
         add(new PlayerPanel(player));
         public void close() {
         player.close();
         setVisible(false);
         dispose();
         public void addNotify() {
         super.addNotify();
         pack();
    * GUI classes for the Player.
    class PlayerPanel extends Panel {
         Component vc, cc;
         PlayerPanel(Player p) {
         setLayout(new BorderLayout());
         if ((vc = p.getVisualComponent()) != null)
              add("Center", vc);
         if ((cc = p.getControlPanelComponent()) != null)
              add("South", cc);
         public Dimension getPreferredSize() {
         int w = 0, h = 0;
         if (vc != null) {
              Dimension size = vc.getPreferredSize();
              w = size.width;
              h = size.height;
         if (cc != null) {
              Dimension size = cc.getPreferredSize();
              if (w == 0)
              w = size.width;
              h += size.height;
         if (w < 160)
              w = 160;
         return new Dimension(w, h);
    public static void main(String argv[]) {
         if (argv.length == 0)
         prUsage();
         AVReceive2 avReceive = new AVReceive2(argv);
         if (!avReceive.initialize()) {
         System.err.println("Failed to initialize the sessions.");
         System.exit(-1);
         // Check to see if AVReceive2 is done.
         try {
         while (!avReceive.isDone())
              Thread.sleep(1000);
         } catch (Exception e) {}
         System.err.println("Exiting AVReceive2");
    static void prUsage() {
         System.err.println("Usage: AVReceive2 <session> <session> ...");
         System.err.println(" <session>: <address>/<port>/<ttl>");
         System.exit(0);
    }// end of AVReceive2

Maybe you are looking for