Revision: 15048
Author: oleg.kulikoff
Date: Fri Nov  5 02:26:07 2010
Log: Issue 1382:        Silence suppression handling
http://code.google.com/p/mobicents/source/detail?r=15048

Added:
/trunk/servers/media/core/server-impl/src/main/java/org/mobicents/media/server/impl/rtp/SilenceDetector.java
Modified:
/trunk/servers/media/core/server-impl/src/main/java/org/mobicents/media/server/impl/rtp/ReceiveStream.java /trunk/servers/media/core/server-impl/src/main/java/org/mobicents/media/server/impl/rtp/RtpFactory.java /trunk/servers/media/core/server-impl/src/main/java/org/mobicents/media/server/impl/rtp/RtpSocketImpl.java /trunk/servers/media/core/server-impl/src/main/java/org/mobicents/media/server/impl/rtp/SendStream.java

=======================================
--- /dev/null
+++ /trunk/servers/media/core/server-impl/src/main/java/org/mobicents/media/server/impl/rtp/SilenceDetector.java Fri Nov 5 02:26:07 2010
@@ -0,0 +1,33 @@
+/**
+ * Implements jitter buffer.
+ *
+ * A jitter buffer temporarily stores arriving packets in order to minimize
+ * delay variations. If packets arrive too late then they are discarded. A
+ * jitter buffer may be mis-configured and be either too large or too small.
+ *
+ * If a jitter buffer is too small then an excessive number of packets may be + * discarded, which can lead to call quality degradation. If a jitter buffer is + * too large then the additional delay can lead to conversational difficulty.
+ *
+ * A typical jitter buffer configuration is 30mS to 50mS in size. In the case of + * an adaptive jitter buffer then the maximum size may be set to 100-200mS. Note
+ * that if the jitter buffer size exceeds 100mS then the additional delay
+ * introduced can lead to conversational difficulty.
+ *
+ * @author Oleg Kulikov
+ * @author amit bhayani
+ */
+package org.mobicents.media.server.impl.rtp;
+
+import org.mobicents.media.Buffer;
+
+/**
+ *
+ * @author kulikov
+ */
+public class SilenceDetector {
+    public boolean isSilenceDetected(Buffer buffer) {
+ return (buffer.getFlags() & Buffer.FLAG_SILENCE) == Buffer.FLAG_SILENCE;
+    }
+
+}
=======================================
--- /trunk/servers/media/core/server-impl/src/main/java/org/mobicents/media/server/impl/rtp/ReceiveStream.java Thu Oct 14 20:19:46 2010 +++ /trunk/servers/media/core/server-impl/src/main/java/org/mobicents/media/server/impl/rtp/ReceiveStream.java Fri Nov 5 02:26:07 2010
@@ -17,6 +17,7 @@
  */
 package org.mobicents.media.server.impl.rtp;

+import java.io.IOException;
 import java.util.ArrayList;
 import org.mobicents.media.Buffer;
 import org.mobicents.media.Format;
@@ -51,6 +52,10 @@
     //The SSRC used for Reception Report in RTCP
     private final long ssrc = System.currentTimeMillis();

+    /** silence detected in milliseconds */
+    private int silence;
+    private int RTP_TIMEOUT = 5000;
+
     /** Creates a new instance of ReceiveStream */
public ReceiveStream(RtpSocketImpl rtpSocket, int jitter, AVProfile formatConfig) {
         super("ReceiveStream");
@@ -199,9 +204,13 @@
         //reading next packet from jitter buffer
         RtpPacket packet = jitterBuffer.read(timestamp);
         if (packet == null) {
-            buffer.setFlags(Buffer.FLAG_DISCARD);
+            buffer.setFlags(Buffer.FLAG_SILENCE);
             buffer.setDuration(DEFAULT_POLL_PERIOD);
+            //increment silence duration
+            silence += DEFAULT_POLL_PERIOD;
         } else if (packet.getPayloadType() == mainstream) {
+            //clean silence
+            this.silence = 0;
             buffer.setData(packet.getPayload());
             buffer.setOffset(0);
             buffer.setTimeStamp(timestamp);
@@ -220,13 +229,30 @@
                 codec.process(buffer);
             }
         } else if (packet.getPayloadType() == dtmf) {
+            //clean silence
+            this.silence = 0;
             dtmfConverter.process(packet, buffer);
             buffer.setTimeStamp(timestamp);
         } else {
+            //clean silence
+            this.silence = 0;
             buffer.setFlags(Buffer.FLAG_DISCARD);
             buffer.setDuration(DEFAULT_POLL_PERIOD);
         }

+        //check total silence
+        if (silence > RTP_TIMEOUT) {
+            if (!this.rtpSocket.isSilenceSuppressed()) {
+                //TODO: precreate exception
+ this.rtpSocket.notify(new IOException("RTP channel is broken"));
+            } else {
+                //check last rtp received report
+                if (this.rtpSocket.rtcpExpired()) {
+                    //TODO: precreate exception
+ this.rtpSocket.notify(new IOException("RTP channel is broken"));
+                }
+            }
+        }
         if (logger.isTraceEnabled()) {
             logger.trace("Receive " + buffer);
         }
=======================================
--- /trunk/servers/media/core/server-impl/src/main/java/org/mobicents/media/server/impl/rtp/RtpFactory.java Thu Oct 14 20:19:46 2010 +++ /trunk/servers/media/core/server-impl/src/main/java/org/mobicents/media/server/impl/rtp/RtpFactory.java Fri Nov 5 02:26:07 2010
@@ -86,6 +86,8 @@
     /** Logger instance */
     private transient Logger logger = Logger.getLogger(RtpFactory.class);

+    private boolean silenceSuppression = false;
+
     /**
      * Creates RTP Factory instance
      */
@@ -310,6 +312,14 @@
         return null;
     }

+    public void setSilenceSuppression(boolean value) {
+        this.silenceSuppression = value;
+    }
+
+    public boolean isSilenceSuppressed() {
+        return this.silenceSuppression;
+    }
+
     /**
      * Gets list of assigned codecs.
      *
@@ -367,7 +377,7 @@
throw new ResourceUnavailableException("Receiver is not running");
         }

- RtpSocketImpl rtpSocket = new RtpSocketImpl(this, getCodecs(media), media); + RtpSocketImpl rtpSocket = new RtpSocketImpl(this, getCodecs(media), media, silenceSuppression);
         return rtpSocket;
     }

=======================================
--- /trunk/servers/media/core/server-impl/src/main/java/org/mobicents/media/server/impl/rtp/RtpSocketImpl.java Thu Oct 14 20:19:46 2010 +++ /trunk/servers/media/core/server-impl/src/main/java/org/mobicents/media/server/impl/rtp/RtpSocketImpl.java Fri Nov 5 02:26:07 2010
@@ -53,36 +53,34 @@
  * @author Oleg Kulikov
  */
 public class RtpSocketImpl implements RtpSocket {
-
-    private static int GEN = 1;
-    private String id;
-
-       // After every 5000 ms RTCP report will be sent
-       public static final int RTCP_MIN_TIME = 5000;
-
- // If there is no RTP or RTCP received till RTCP_CUT_OFF_TIME, notify listener to take appropriate action
-       public static final int RTCP_CUT_OFF_TIME = 2 * RTCP_MIN_TIME;
-
+
+    private static int GEN = 1;
+    private String id;
+    // After every 5000 ms RTCP report will be sent
+    public static final int RTCP_MIN_TIME = 5000;
+
+    //If there is no RTP or RTCP received till RTCP_CUT_OFF_TIME, notify
+    //listener to take appropriate action
+    public static final int RTCP_CUT_OFF_TIME = 2 * RTCP_MIN_TIME;
+
     /** Media type */
-    protected MediaType mediaType;
+    protected MediaType mediaType;

     //RTP local address and port pair
-    private DatagramSocket rtpSocket;
-    private DatagramChannel rtpChannel;
-
-       //RTCP local address and port pair
-       private DatagramSocket rtcpSocket;
-       private DatagramChannel rtcpChannel;
-
-    private String localAddress;
+    private DatagramSocket rtpSocket;
+    private DatagramChannel rtpChannel;
+
+    //RTCP local address and port pair
+    private DatagramSocket rtcpSocket;
+    private DatagramChannel rtcpChannel;
+    private String localAddress;

     //remote address and port pair
-    protected InetSocketAddress rtpRemoteAddress = null;
-
+    protected InetSocketAddress rtpRemoteAddress = null;
     protected InetSocketAddress rtcpRemoteAddress = null;
-
+
     //jitter in milliseconds. default value is 60ms
-    private int jitter = 60;
+    private int jitter = 60;

     //media streams
     private ReceiveStream receiveStream;
@@ -90,12 +88,12 @@

     //factory instance
     private RtpFactory factory = null;
+
     //listener instance
-    private RtpSocketListener listener;
+    private RtpSocketListener listener;

     //the default format map between rtp payload and format
-    private AVProfile avProfile = new AVProfile();
-
+    private AVProfile avProfile = new AVProfile();
     //collection of codecs
     protected Collection<Codec> codecs;

@@ -106,41 +104,35 @@
//this values are valid after negotiation and till this socket will be released
     private Format format;
     private int payloadId;
-
+
     private SelectionKey rtpSelection;
     private SelectionKey rtcpSelection;

     protected boolean registered = false;
-
-    private ByteBuffer sendBuffer = ByteBuffer.allocateDirect(8192);
+    private ByteBuffer sendBuffer = ByteBuffer.allocateDirect(8192);

     //statistics
     private int rtpPacketsSent;
     private int rtpPacketsReceived;
-
-       private int rtcpPacketsSent;
-       private int rtcpPacketsReceived;
-
-       private long rtcpOctetSent;
-       private long rtcpOctetReceived;
-
-       private long lastRtcpPackReceivedTimeStamp;
-       private long lastRtcpSenderRprtReceivedTimeStamp;
-
-       /**
- * Expected packets calculated on every RTCP transmission timeout and used as previous expected packets on next
-        * transmission timeout for calculation of Fraction
-        */
-       private int intervalExpectedRtpPackets;
-
-       /**
- * Actual received packets calculated on every transmission timeout and used as previous actual received packets on
-        * next transmission timeout for calculation of Fraction
-        */
-       private int intervalReceivedRtpPackets;
-
-       private RtcpSenderReport lastRtcpSenderReport = null;
-
+    private int rtcpPacketsSent;
+    private int rtcpPacketsReceived;
+    private long rtcpOctetSent;
+    private long rtcpOctetReceived;
+    private long lastRtcpPackReceivedTimeStamp;
+    private long lastRtcpSenderRprtReceivedTimeStamp;
+
+    /**
+ * Expected packets calculated on every RTCP transmission timeout and used as previous expected packets on next
+     * transmission timeout for calculation of Fraction
+     */
+    private int intervalExpectedRtpPackets;
+
+    /**
+ * Actual received packets calculated on every transmission timeout and used as previous actual received packets on
+     * next transmission timeout for calculation of Fraction
+     */
+    private int intervalReceivedRtpPackets;
+    private RtcpSenderReport lastRtcpSenderReport = null;
     private volatile boolean isClosed = false;

     /**
@@ -152,14 +144,8 @@
      *  as prefferedPort for all future binds
      */
     private int rtpPreferredPort;
-
     private int rtcpPreferredPort;
-
-    /**
- * The time stamp when last RTP Packet was sent from this. Used for creation of RTCP SR
-     */
-    //private long lastRtpPackSentTimeStamp;
-
+
     /**
      * The reference to last RTP Packet sent. Used for creation of RTCP SR
      */
@@ -170,13 +156,13 @@
     private byte[] rtcpPacketRawData = new byte[8192];

     private RtcpSendStream rtcpSendStream = null;
-
     private RtpPacketHandler rtpPacketHandler = null;
     private RtcpPacketHandler rtcpPacketHandler = null;

     private LocalTask rtcpSenderWorker;
-
     private String cname;
+
+    private boolean silenceSuppression;

     /**
      * Creates a new instance of RtpSocket
@@ -186,33 +172,33 @@
      * @param rtpMap
      *            RTP payloads list.
      */
- public RtpSocketImpl(RtpFactory factory, Collection<Codec> codecs, MediaType media) throws IOException, ResourceUnavailableException {
-
+ public RtpSocketImpl(RtpFactory factory, Collection<Codec> codecs, MediaType media, boolean silenceSuppression) throws IOException, ResourceUnavailableException {
         this.id = this.genID();
-
         this.mediaType = media;
-
         this.clock = factory.getClock(media);
-
         this.factory = factory;
-        //this.timer = factory.getTimer();
+
+        //assigns default preconfgured value for silence suppression
+        this.silenceSuppression = silenceSuppression;
+
+
         this.codecs = codecs;
         this.avProfile = factory.getAVProfile().clone();

         jitter = factory.getJitter();
-
+
         sendStream = new SendStream(this, this.avProfile);
receiveStream = new ReceiveStream(this, factory.getJitter(), this.avProfile);

         this.localAddress = factory.getBindAddress();
- this.cname = "MMS-" + id + "-" + mediaType.getName() + "@" + localAddress;
-
+ this.cname = "MMS-" + id + "-" + mediaType.getName() + "@" + localAddress;
+
         this.rtcpSendStream = new RtcpSendStream(this);
-
+
         this.rtpPacketHandler = new RtpPacketHandler(this);
         this.rtcpPacketHandler = new RtcpPacketHandler(this);
-
-    }
+    }
+

     /**
      * Generates unique identifier for this connection.
@@ -238,15 +224,15 @@

         rtpSocket = rtpChannel.socket();
     }
-
+
     private void openRtcpChannel() throws IOException {
-               rtcpChannel = DatagramChannel.open();
-               rtcpChannel.configureBlocking(false);
-
-               rtcpSocket = rtcpChannel.socket();
-    }
-
-    private void closeRtpSocket(){
+        rtcpChannel = DatagramChannel.open();
+        rtcpChannel.configureBlocking(false);
+
+        rtcpSocket = rtcpChannel.socket();
+    }
+
+    private void closeRtpSocket() {
         try {
             if (rtpChannel != null) {
                 rtpChannel.close();
@@ -259,8 +245,8 @@
         } catch (IOException e) {
         }
     }
-
-    private void closeRtcpSocket(){
+
+    private void closeRtcpSocket() {
         try {
             if (rtcpChannel != null) {
                 rtcpChannel.close();
@@ -272,8 +258,8 @@
             }
         } catch (IOException e) {
         }
-    }
-
+    }
+
     /**
      * Binds Datagram to the address sprecified.
      *
@@ -284,14 +270,14 @@
         //disbale closed flag if was set
         this.isClosed = false;
         boolean portCycled = false;
-        this.rtpPreferredPort = factory.getNextEvenPort();
+        this.rtpPreferredPort = factory.getNextEvenPort();
         this.rtcpPreferredPort = factory.getNextOddPort();
-
+
         int initialPort = this.rtpPreferredPort;
-
+
         //opening RTP channel
         openRtpChannel();
-
+
         //binding socket to the first available port.
         while (!rtpSocket.isBound()) {
             try {
@@ -301,59 +287,59 @@
             } catch (SocketException e) {
                 //port is in use? let's try another
                 this.rtpPreferredPort = this.factory.getNextEvenPort();
-
-                if(this.rtpPreferredPort <= initialPort){
-                       portCycled = true;
-                }
-
-                if(portCycled && this.rtpPreferredPort > initialPort){
- //At this point one full cycle of ports are scanned and there are no free ports. Better to exit
-                       break;
+
+                if (this.rtpPreferredPort <= initialPort) {
+                    portCycled = true;
+                }
+
+                if (portCycled && this.rtpPreferredPort > initialPort) {
+ //At this point one full cycle of ports are scanned and there are no free ports. Better to exit
+                    break;
                 }
                 continue;
             }
         }//while loop
-
+
         //RTP socket still not bound? throw exception
         if (!rtpSocket.isBound()) {
             rtpChannel.close();
             throw new ResourceUnavailableException();
         }
-
+
         initialPort = this.rtcpPreferredPort;
         portCycled = false;
-
+
         //Opening RTCP channel
         openRtcpChannel();
-
-        while(!rtcpSocket.isBound()){
-               try{
- InetSocketAddress address = new InetSocketAddress(localAddress, this.rtcpPreferredPort);
-                       rtcpSocket.bind(address);
-               }  catch (SocketException e) {
-                       //Port is not free. let's try another
-                       this.rtcpPreferredPort = this.factory.getNextOddPort();
-
-
-                if(this.rtcpPreferredPort <= initialPort){
-                       portCycled = true;
-                }
-
-                if(portCycled && this.rtcpPreferredPort > initialPort){
- //At this point one full cycle of ports are scanned and there are no free ports. Better to exit
-                       break;
-                }
-               }
-        }
-
+
+        while (!rtcpSocket.isBound()) {
+            try {
+ InetSocketAddress address = new InetSocketAddress(localAddress, this.rtcpPreferredPort);
+                rtcpSocket.bind(address);
+            } catch (SocketException e) {
+                //Port is not free. let's try another
+                this.rtcpPreferredPort = this.factory.getNextOddPort();
+
+
+                if (this.rtcpPreferredPort <= initialPort) {
+                    portCycled = true;
+                }
+
+                if (portCycled && this.rtcpPreferredPort > initialPort) {
+ //At this point one full cycle of ports are scanned and there are no free ports. Better to exit
+                    break;
+                }
+            }
+        }
+
         //RTCP socket still not bound? throw exception
         if (!rtcpSocket.isBound()) {
             rtcpChannel.close();
             this.closeRtpSocket();
             throw new ResourceUnavailableException();
-        }
-    }
-
+        }
+    }
+
     /**
      * Registers this socket usign specified selector.
      *
@@ -365,8 +351,7 @@
rtcpSelection = rtcpChannel.register(selector, SelectionKey.OP_READ, this.rtcpPacketHandler);
         registered = true;
     }
-
-
+
     /**
      * Gets the currently used format.
      *
@@ -427,6 +412,23 @@
         sendStream.setDtmf(dtmf);
     }

+    /**
+     * Modifies silence suppression flag.
+     *
+     * @param value the new value for flag.
+     */
+    public void setSilenceSuppression(boolean value) {
+        this.silenceSuppression = value;
+    }
+
+    /**
+     * Indicates the status of silence suppression algorithm.
+     *
+     * @return true if silence suppression is enabled.
+     */
+    public boolean isSilenceSuppressed() {
+        return this.silenceSuppression;
+    }
     /**
      * Gets address to which this socked is bound.
      *
@@ -508,7 +510,7 @@
     public int getPacketsReceived() {
         return rtpPacketsReceived;
     }
-
+
     /**
      * Gets the number of sent packets
      *
@@ -517,8 +519,8 @@
     public int getPacketsSent() {
         return rtpPacketsSent;
     }
-
-       /**
+
+    /**
      * Closes this socket and resets its streams;
      * This method is called by RtpSocket user.
      *
@@ -544,37 +546,37 @@
         //disable format and payload
         this.format = null;
         this.payloadId = -1;
-
+
         //clean stats
         rtpPacketsSent = 0;
         rtpPacketsReceived = 0;
-
+
         this.closeRtpSocket();
-
-        if(rtcpSelection != null){
-               rtcpSelection.cancel();
-        }
-
+
+        if (rtcpSelection != null) {
+            rtcpSelection.cancel();
+        }
+
         this.lastRtcpPackReceivedTimeStamp = 0;
         this.rtcpOctetReceived = 0;
         this.rtcpPacketsReceived = 0;
-
+
         this.rtcpOctetSent = 0;
         this.rtcpOctetReceived = 0;
-
+
         this.intervalExpectedRtpPackets = 0;
         this.intervalReceivedRtpPackets = 0;
-
+
         this.lastRtpPackSent = null;
-
+
         this.rtcpSendStream.reset();
         this.closeRtcpSocket();
     }
-
+
     public boolean isClosed() {
         return this.isClosed;
     }
-
+
     /**
      * Gets the currently assigned listener.
      *
@@ -605,14 +607,14 @@
         rtpRemoteAddress = new InetSocketAddress(address, port);
         rtpChannel.connect(rtpRemoteAddress);

-        rtcpRemoteAddress = new InetSocketAddress(address, port+1);
+        rtcpRemoteAddress = new InetSocketAddress(address, port + 1);
         rtcpChannel.connect(rtcpRemoteAddress);
-
+
         factory.registerQueue.offer(this);
-
-               // Add RtcpSendStream to scheduler to send RTCP Report every 5 
secs
+
+        // Add RtcpSendStream to scheduler to send RTCP Report every 5 secs
         this.rtcpSenderWorker = scheduler.execute(rtcpSendStream);
-
+
     }

     /**
@@ -623,24 +625,24 @@
     public SendStream getSendStream() {
         return sendStream;
     }
-
-       private void send(RtcpPacket rtcpPacket) {
-               // TODO optimize the RTCPPacket to use the ByteBuffer directly
-               int length = rtcpPacket.encode(rtcpPacketRawData, 0);
-
-               this.rtcpPacketsSent += rtcpPacket.getNoOfPackets();
-               this.rtcpOctetSent += length;
-               // converting packet to binary array and sent to the remote 
address.
-               sendBuffer.clear();
-               sendBuffer.rewind();
-               sendBuffer.put(rtcpPacketRawData, 0, length);
-               sendBuffer.flip();
-               try {
-                       rtcpChannel.write(sendBuffer);
-               } catch (IOException e) {
-                       this.notify(e);
-               }
-       }
+
+    private void send(RtcpPacket rtcpPacket) {
+        // TODO optimize the RTCPPacket to use the ByteBuffer directly
+        int length = rtcpPacket.encode(rtcpPacketRawData, 0);
+
+        this.rtcpPacketsSent += rtcpPacket.getNoOfPackets();
+        this.rtcpOctetSent += length;
+ // converting packet to binary array and sent to the remote address.
+        sendBuffer.clear();
+        sendBuffer.rewind();
+        sendBuffer.put(rtcpPacketRawData, 0, length);
+        sendBuffer.flip();
+        try {
+            rtcpChannel.write(sendBuffer);
+        } catch (IOException e) {
+            this.notify(e);
+        }
+    }

     /**
      * Sends media data to remote peer.
@@ -654,11 +656,11 @@
     public void send(RtpPacket packet) throws IOException {
         //check state flag before sending
         if (!this.isClosed) {
-
-               //Reference to last RTP Packet Sent and time when it was sent
-               //this.lastRtpPackSentTimeStamp = scheduler.getTimestamp();
-               this.lastRtpPackSent = packet;
-
+
+            //Reference to last RTP Packet Sent and time when it was sent
+            //this.lastRtpPackSentTimeStamp = scheduler.getTimestamp();
+            this.lastRtpPackSent = packet;
+
             byte[] p = packet.toByteArray();
             send(p);
         }
@@ -676,8 +678,8 @@
         sendBuffer.rewind();
         sendBuffer.put(packet);
         sendBuffer.flip();
-        try{
-               rtpChannel.write(sendBuffer);
+        try {
+            rtpChannel.write(sendBuffer);
         } catch (IOException e) {
             this.notify(e);
         }
@@ -693,29 +695,29 @@
         receiveStream.process(rtpPacket);
         rtpPacketsReceived++;
     }
-
+
     public void receiveRtcp(RtcpPacket rtcpPacket) {
-
-       RtcpReceptionReportItem[] rtcpReceptionReports = null;
-
-       // Keep reference to timeStamp when last RTCP was received
-               this.lastRtcpPackReceivedTimeStamp = scheduler.getTimestamp();
-
-       this.rtcpOctetReceived += rtcpPacket.getPacketSize();
-       this.rtcpPacketsReceived += rtcpPacket.getNoOfPackets();
-
-       if(rtcpPacket.getRtcpSenderReport() != null){
-               this.lastRtcpSenderReport = rtcpPacket.getRtcpSenderReport();
- this.lastRtcpSenderRprtReceivedTimeStamp = this.lastRtcpPackReceivedTimeStamp;
-
- rtcpReceptionReports = this.lastRtcpSenderReport.getRtcpReceptionReports();
-       }
-
-       //if(rtcpReceptionReports != null){
- //TODO : sender may modify its transmissions based on the feedback. Define events to be fired for Listener
-       //}
-
-    }
+
+        RtcpReceptionReportItem[] rtcpReceptionReports = null;
+
+        // Keep reference to timeStamp when last RTCP was received
+        this.lastRtcpPackReceivedTimeStamp = scheduler.getTimestamp();
+
+        this.rtcpOctetReceived += rtcpPacket.getPacketSize();
+        this.rtcpPacketsReceived += rtcpPacket.getNoOfPackets();
+
+        if (rtcpPacket.getRtcpSenderReport() != null) {
+            this.lastRtcpSenderReport = rtcpPacket.getRtcpSenderReport();
+ this.lastRtcpSenderRprtReceivedTimeStamp = this.lastRtcpPackReceivedTimeStamp;
+
+ rtcpReceptionReports = this.lastRtcpSenderReport.getRtcpReceptionReports();
+        }
+
+    //if(rtcpReceptionReports != null){
+ //TODO : sender may modify its transmissions based on the feedback. Define events to be fired for Listener
+    //}
+
+    }

     /**
      * Notifies the listener that something goes wrong.
@@ -727,7 +729,14 @@
             listener.error(e);
         }
     }
-
+
+    public boolean rtcpExpired() {
+        long now = scheduler.getTimestamp();
+        if (now - this.lastRtcpPackReceivedTimeStamp > RTCP_CUT_OFF_TIME) {
+            return true;
+        }
+        return false;
+    }
     /**
      * Statistical method.
      *
@@ -736,7 +745,7 @@
     public long getBytesReceived() {
         return receiveStream.byteCount;
     }
-
+
     /**
      * Statistical method.
      *
@@ -745,167 +754,159 @@
     public long getBytesSent() {
         return sendStream.byteCount;
     }
-
-
-       public MediaType getMediaType() {
-               return mediaType;
-       }
-
-
-       class RtcpSendStream implements Task {
-
-               private RtpSocketImpl rtpSocketImpl = null;
-               private boolean initial = true;
-
-               RtcpSendStream(RtpSocketImpl rtpSocketImpl){
-                       this.rtpSocketImpl = rtpSocketImpl;
-               }
-
-               void reset(){
-                       this.initial = true;
-               }
-
-               public void cancel() {
-                       // TODO Auto-generated method stub
-
-               }
-
-               public boolean isActive() {
-                       return !isClosed;
-               }
-
-               public int perform() {
- // If for first time we will send the report after 2.5 seconds. After this every 5 seconds
-                       if (initial) {
-                               this.initial = false;
-                               return (RTCP_MIN_TIME / 2);
-                       }
-
-
-                       RtcpSenderReport rtcpSenderReport = null;
-                       RtcpReceptionReport rtcpReceptionReport = null;
-                       RtcpSdes rtcpSdes = null;
-                       // RtcpAppDefined rtcpAppDefined = null;
-
-                       long now = Server.scheduler.getTimestamp();
-                       // rtpSocketImpl.setLastRtcpPackSentTimeStamp(now);
-
-                       JitterBuffer jitBuff = receiveStream.getJitterBuffer();
-
-                       int expectedPackets = jitBuff.getExpectedPacketCount();
-                       int receivedPackets = 
rtpSocketImpl.getPacketsReceived();
-
-                       RtpPacket rtpPacket = lastRtpPackSent;
-
-                       if (rtpPacket != null) {
-                               long[] ntpTs = NtpTimeStampUtil.toNtpTime(now);
-
- rtcpSenderReport = new RtcpSenderReport(false, rtpPacket.getSyncSource(), ntpTs[0], ntpTs[1], rtpPacket - .getTimestamp(), rtpSocketImpl.getPacketsSent(), rtpSocketImpl.getBytesSent());
-
-                               rtcpSdes = new RtcpSdes(false);
-
- RtcpSdesItem rtcpSdesItem = new RtcpSdesItem(RtcpSdesItem.RTCP_SDES_CNAME, cname); - RtcpSdesChunk rtcpSdesChunk = new RtcpSdesChunk(rtpPacket.getSyncSource());
-                               rtcpSdesChunk.addRtcpSdesItem(rtcpSdesItem);
-
-                               rtcpSdes.addRtcpSdesChunk(rtcpSdesChunk);
-                       }
-
- // TODO If no RTP sent for time > 2T raise RTCPSendTimeout event. May be indicator that silence started? But - // do we need it? If needed and implemented we call rtcpSenderTimeout on listener
-               //if (listener != null) {
-               //    listener.rtcpSenderTimeout(this.rtpSocketImpl);
-               //}
-
-
-                       rtpPacket = jitBuff.getLastRtpPacketRecd();
-
-                       if(rtpPacket != null){
-                               int lost = expectedPackets - receivedPackets;
-
-                               int expected_interval = (expectedPackets - 
intervalExpectedRtpPackets);
-                               int received_interval = (receivedPackets - 
intervalReceivedRtpPackets);
-
-                               int lost_interval = expected_interval - 
received_interval;
-                               int fraction = 0;
-                               if (expected_interval == 0 || lost_interval <= 
0) {
-                                       fraction = 0;
-                               } else {
-                                       fraction = (lost_interval << 8) / 
expected_interval;
-                               }
-
-                               // The middle 32 bits out of 64 in the NTP 
timestamp (as explained in
-                               // Section 4) received as part of the most 
recent RTCP sender report
-                               // (SR) packet from source SSRC_n. If no SR has 
been received yet,
-                               // the field is set to zero.
-                               long lsr = 0;
-
-                               // The delay, expressed in units of 1/65536 
seconds, between
-                               // receiving the last SR packet from source 
SSRC_n and sending this
-                               // reception report block.
-                               long dsr = 0;
-
-                               if (lastRtcpSenderReport != null) {
-                                       lsr |= lastRtcpSenderReport.getNtpSec() 
& 0x0000FFFF;
-                                       lsr <<= 16;
-                                       lsr |= ((lastRtcpSenderReport.getNtpFrac() & 
0xFFFF0000) >> 16);
-
-                                       dsr = ((now - 
lastRtcpSenderRprtReceivedTimeStamp) * 65536) / 1000;
-                               }
-
- RtcpReceptionReportItem rtcpReceptionReportItem = new RtcpReceptionReportItem( - rtpPacket.getSyncSource(), fraction, lost, jitBuff.getSeqNoCycles(), rtpPacket.getSeqNumber(),
-                                                               (int) 
receiveStream.getInterArrivalJitter(), lsr, dsr);
-
-                               if (rtcpSenderReport == null) {
-                                       rtcpReceptionReport = new 
RtcpReceptionReport(false,
-                                                       
receiveStream.getSsrc());
-                                       rtcpReceptionReport
-                                                       
.addRtcpReceptionReportItem(rtcpReceptionReportItem);
-
-                                       rtcpSdes = new RtcpSdes(false);
-
-                                       RtcpSdesItem rtcpSdesItem = new 
RtcpSdesItem(
-                                                       
RtcpSdesItem.RTCP_SDES_CNAME, cname);
- RtcpSdesChunk rtcpSdesChunk = new RtcpSdesChunk(receiveStream.getSsrc());
-                                       
rtcpSdesChunk.addRtcpSdesItem(rtcpSdesItem);
-
-                                       
rtcpSdes.addRtcpSdesChunk(rtcpSdesChunk);
-                               } else {
-                                       rtcpSenderReport
-                                                       
.addRtcpReceptionReportItem(rtcpReceptionReportItem);
-                               }
-                       }
-
-                       // If no RTP and RTCP received for 2T fire 
RTCPReceiveTimeout event.
- // 1. This is useful when Connection is RECV_ONLY and far end is crashed. - // 2. If Connection is SEND_RECV and far end crashed, the RTPSocket will anyway throw error and this
-                       // Connection will be deleted
- // 3. If Connection is SEND_RECV and silence is ON on MMS side and far end crashed, even then this algo will
-                       // work. But if far end doesn't
- // have RTCP implemented, this algo will wrongly indicate ReceiverTimeout. This is punishment for not
-                       // implementing RTCP ;)
- if ((now - jitBuff.getLastRtpPackReceivedTimeStamp()) > RtpSocketImpl.RTCP_CUT_OFF_TIME - && (now - lastRtcpPackReceivedTimeStamp) > RtpSocketImpl.RTCP_CUT_OFF_TIME) {
-                       if (listener != null) {
-                           listener.rtcpReceiverTimeout(this.rtpSocketImpl);
-                       }
-                       }
-
- // set the reference to expected and received packets here, so they can be referenced on next transmission
-                       // timeout for calculation of Fraction
-                       intervalExpectedRtpPackets = expectedPackets;
-                       intervalReceivedRtpPackets = receivedPackets;
-
-                       RtcpPacket rtcpPacket = new RtcpPacket(rtcpSenderReport,
-                                       rtcpReceptionReport, rtcpSdes, null, 
null);
-
-                       send(rtcpPacket);
-
-
-                       return RTCP_MIN_TIME;
-               }
-
-       }
-}
+
+    public MediaType getMediaType() {
+        return mediaType;
+    }
+
+    class RtcpSendStream implements Task {
+
+        private RtpSocketImpl rtpSocketImpl = null;
+        private boolean initial = true;
+
+        RtcpSendStream(RtpSocketImpl rtpSocketImpl) {
+            this.rtpSocketImpl = rtpSocketImpl;
+        }
+
+        void reset() {
+            this.initial = true;
+        }
+
+        public void cancel() {
+            // TODO Auto-generated method stub
+        }
+
+        public boolean isActive() {
+            return !isClosed;
+        }
+
+        public int perform() {
+ // If for first time we will send the report after 2.5 seconds. After this every 5 seconds
+            if (initial) {
+                this.initial = false;
+                return (RTCP_MIN_TIME / 2);
+            }
+
+
+            RtcpSenderReport rtcpSenderReport = null;
+            RtcpReceptionReport rtcpReceptionReport = null;
+            RtcpSdes rtcpSdes = null;
+            // RtcpAppDefined rtcpAppDefined = null;
+
+            long now = Server.scheduler.getTimestamp();
+            // rtpSocketImpl.setLastRtcpPackSentTimeStamp(now);
+
+            JitterBuffer jitBuff = receiveStream.getJitterBuffer();
+
+            int expectedPackets = jitBuff.getExpectedPacketCount();
+            int receivedPackets = rtpSocketImpl.getPacketsReceived();
+
+            RtpPacket rtpPacket = lastRtpPackSent;
+
+            if (rtpPacket != null) {
+                long[] ntpTs = NtpTimeStampUtil.toNtpTime(now);
+
+ rtcpSenderReport = new RtcpSenderReport(false, rtpPacket.getSyncSource(), ntpTs[0], ntpTs[1], rtpPacket.getTimestamp(), rtpSocketImpl.getPacketsSent(), rtpSocketImpl.getBytesSent());
+
+                rtcpSdes = new RtcpSdes(false);
+
+ RtcpSdesItem rtcpSdesItem = new RtcpSdesItem(RtcpSdesItem.RTCP_SDES_CNAME, cname); + RtcpSdesChunk rtcpSdesChunk = new RtcpSdesChunk(rtpPacket.getSyncSource());
+                rtcpSdesChunk.addRtcpSdesItem(rtcpSdesItem);
+
+                rtcpSdes.addRtcpSdesChunk(rtcpSdesChunk);
+            }
+
+ // TODO If no RTP sent for time > 2T raise RTCPSendTimeout event. May be indicator that silence started? But + // do we need it? If needed and implemented we call rtcpSenderTimeout on listener
+            //if (listener != null) {
+            //    listener.rtcpSenderTimeout(this.rtpSocketImpl);
+            //}
+
+
+            rtpPacket = jitBuff.getLastRtpPacketRecd();
+
+            if (rtpPacket != null) {
+                int lost = expectedPackets - receivedPackets;
+
+ int expected_interval = (expectedPackets - intervalExpectedRtpPackets); + int received_interval = (receivedPackets - intervalReceivedRtpPackets);
+
+                int lost_interval = expected_interval - received_interval;
+                int fraction = 0;
+                if (expected_interval == 0 || lost_interval <= 0) {
+                    fraction = 0;
+                } else {
+                    fraction = (lost_interval << 8) / expected_interval;
+                }
+
+ // The middle 32 bits out of 64 in the NTP timestamp (as explained in + // Section 4) received as part of the most recent RTCP sender report + // (SR) packet from source SSRC_n. If no SR has been received yet,
+                // the field is set to zero.
+                long lsr = 0;
+
+ // The delay, expressed in units of 1/65536 seconds, between + // receiving the last SR packet from source SSRC_n and sending this
+                // reception report block.
+                long dsr = 0;
+
+                if (lastRtcpSenderReport != null) {
+                    lsr |= lastRtcpSenderReport.getNtpSec() & 0x0000FFFF;
+                    lsr <<= 16;
+ lsr |= ((lastRtcpSenderReport.getNtpFrac() & 0xFFFF0000) >> 16);
+
+ dsr = ((now - lastRtcpSenderRprtReceivedTimeStamp) * 65536) / 1000;
+                }
+
+ RtcpReceptionReportItem rtcpReceptionReportItem = new RtcpReceptionReportItem( + rtpPacket.getSyncSource(), fraction, lost, jitBuff.getSeqNoCycles(), rtpPacket.getSeqNumber(), + (int) receiveStream.getInterArrivalJitter(), lsr, dsr);
+
+                if (rtcpSenderReport == null) {
+                    rtcpReceptionReport = new RtcpReceptionReport(false,
+                            receiveStream.getSsrc());
+ rtcpReceptionReport.addRtcpReceptionReportItem(rtcpReceptionReportItem);
+
+                    rtcpSdes = new RtcpSdes(false);
+
+                    RtcpSdesItem rtcpSdesItem = new RtcpSdesItem(
+                            RtcpSdesItem.RTCP_SDES_CNAME, cname);
+ RtcpSdesChunk rtcpSdesChunk = new RtcpSdesChunk(receiveStream.getSsrc());
+                    rtcpSdesChunk.addRtcpSdesItem(rtcpSdesItem);
+
+                    rtcpSdes.addRtcpSdesChunk(rtcpSdesChunk);
+                } else {
+ rtcpSenderReport.addRtcpReceptionReportItem(rtcpReceptionReportItem);
+                }
+            }
+
+ // If no RTP and RTCP received for 2T fire RTCPReceiveTimeout event. + // 1. This is useful when Connection is RECV_ONLY and far end is crashed. + // 2. If Connection is SEND_RECV and far end crashed, the RTPSocket will anyway throw error and this
+            // Connection will be deleted
+ // 3. If Connection is SEND_RECV and silence is ON on MMS side and far end crashed, even then this algo will
+            // work. But if far end doesn't
+ // have RTCP implemented, this algo will wrongly indicate ReceiverTimeout. This is punishment for not
+            // implementing RTCP ;)
+ if ((now - jitBuff.getLastRtpPackReceivedTimeStamp()) > RtpSocketImpl.RTCP_CUT_OFF_TIME && (now - lastRtcpPackReceivedTimeStamp) > RtpSocketImpl.RTCP_CUT_OFF_TIME) {
+                if (listener != null) {
+                    listener.rtcpReceiverTimeout(this.rtpSocketImpl);
+                }
+            }
+
+ // set the reference to expected and received packets here, so they can be referenced on next transmission
+            // timeout for calculation of Fraction
+            intervalExpectedRtpPackets = expectedPackets;
+            intervalReceivedRtpPackets = receivedPackets;
+
+            RtcpPacket rtcpPacket = new RtcpPacket(rtcpSenderReport,
+                    rtcpReceptionReport, rtcpSdes, null, null);
+
+            send(rtcpPacket);
+
+
+            return RTCP_MIN_TIME;
+        }
+    }
+}
=======================================
--- /trunk/servers/media/core/server-impl/src/main/java/org/mobicents/media/server/impl/rtp/SendStream.java Fri Jun 25 05:30:54 2010 +++ /trunk/servers/media/core/server-impl/src/main/java/org/mobicents/media/server/impl/rtp/SendStream.java Fri Nov 5 02:26:07 2010
@@ -51,11 +51,14 @@

     protected long byteCount;

+    private SilenceDetector silenceDetector;
+
     public SendStream(RtpSocketImpl rtpSocket, AVProfile avProfile) {
         super("SendStream");
         this.rtpSocket = rtpSocket;
         this.formatConfig = avProfile;
         this.clock = rtpSocket.getClock();
+        this.silenceDetector = new SilenceDetector();
     }

     @Override
@@ -94,11 +97,19 @@
     }

     public void onMediaTransfer(Buffer buffer) throws IOException {
+        //TODO this block must be removed
+        //it does not depend from rtp clock
         RtpPacket packet = null;
         if (buffer.getFormat() == Format.RAW_RTP) {
             rtpSocket.send(buffer.getData());
             return;
         }
+
+        //check for silence
+ if (this.rtpSocket.isSilenceSuppressed() && silenceDetector.isSilenceDetected(buffer)) {
+            //suppress silence.
+            return;
+        }

         if (codec != null) {
             codec.process(buffer);

Reply via email to