Example #1
0
        /// <summary>
        /// set ourselves up, we are pretty dumb so need to be told who we're sending for
        /// and where to get our data from, and when to start sending..
        /// </summary>
        /// <remarks>
        /// It seems that we don't use maxFrameSize any more.  hmm.  Remove it?
        /// </remarks>
        public BufferPlayer(int streamID, int maxFrameSize, int maxFrameCount, int maxBufferSize)
        {
            Debug.Assert( maxBufferSize >= maxFrameSize ); // just for kicks...

            buffer = new BufferChunk( maxBufferSize );
            indices = new Index[maxFrameCount+1]; // Pri3: why is this "+1" here? (DO NOT REMOVE YET)

            this.populating = false;
            this.streamOutOfData = false;
            this.streamID = streamID;

            this.currentIndex = 0;
            this.indexCount = 0;
            this.startingTick = 0;

            canPopulate = new AutoResetEvent(false);

            // pool a thread to re-populate ourselves
            waitHandle = ThreadPool.RegisterWaitForSingleObject( 
                canPopulate,
                new WaitOrTimerCallback( InitiatePopulation ), 
                this, 
                -1, // never timeout to perform a population
                false );
        }
Example #2
0
 internal asyncReceiveState(MSR.LST.Net.Sockets.Socket sock, BufferChunk bufferChunk, Queue queue, ReceivedFromCallback receivedFromCallback)
 {
     this.sock = sock;
     this.bufferChunk = bufferChunk;
     this.queue = queue;
     this.receivedFromCallback = receivedFromCallback;
 }
Example #3
0
        /// <summary>
        /// This method creates as many checksum buffers as exist in the checksum array
        /// </summary>
        /// <param name="bytes">Array of buffer chunk that represents the data to encode</param>
        /// <param name="checksum">Contains 1 BufferChunk, which should be Reset() before calling</param>
        /// <returns>The checksum packet</returns>
        public void Encode(BufferChunk[] data, BufferChunk[] checksum)
        {
            ValidateObjectNotNull(data);
            ValidateObjectNotNull(checksum);
            ValidateNullData(data, 0);
            ValidateNullData(checksum, 0);
            ValidateChecksumPacketCount(checksum.Length);

            // Sort the BufferChunks from longest to shortest
            ActiveColumns(data, data.Length);

            // Add 2 bytes so the checksum packet can contain the length of the missing packet
            int xorDataLength = activeColumns[0].Length + 2;
            BufferChunk xorData = checksum[0];
            int index = xorData.Index;
            
            // Store the xor'd lengths of the data
            xorData += (ushort)(XORLength() ^ xorDataLength);
            xorData.Reset(index + 2, xorDataLength - 2);

            // Populate the checksum buffer (xorData)
            XORData(xorData, xorDataLength - 2);

            // Set xorData.Index back to 0
            xorData.Reset(index, xorDataLength);
        }
Example #4
0
 public void ReadDataFromBuffer(BufferChunk buffer)
 {
     Time = buffer.NextUInt64();
     TimeStamp = buffer.NextUInt32();
     PacketCount = buffer.NextUInt32();
     BytesSent = buffer.NextUInt32();
 }
Example #5
0
 public void WriteDataToBuffer(BufferChunk buffer)
 {
     buffer += Time;
     buffer += TimeStamp;
     buffer += PacketCount;
     buffer += BytesSent;
 }
        /// <summary>
        /// Encode the packets that are in the data BufferChunk array and place the 
        /// encoded result over GF16 in the checksum packets that are in 
        /// the result BufferChunk array. This method encode the size on the first 2
        /// bytes of the checksum packet and the data after that. Every checksum BufferChunk
        /// has the same size, which is the size of the largest BufferChunk in the data BufferChunk
        /// array, plus one if this BufferChunk doesn't end on a 16 bits boundary, plus
        /// two to store the encoded length 
        /// </summary>
        /// <param name="data">The data BufferChunk array (left part of the multiplication)</param>
        /// <param name="result"></param>
        /// <param name="encode">The encoding Vandermonde GF16 matrix (right part of the multiplication)</param>
        public static void EncodeRS(BufferChunk[] data, BufferChunk[] checksum, UInt16[,] encode)
        {
            // Get the length in byte of largest BufferChunk in the data BufferChunk array 
            // (which is an array of BufferChunk that could have different sizes)
            int maxDataLength = GetMaxLength(data);

            // The checksum packet as a even number of bytes so we can stay with GF16
            // and not have to use GF8 for the last byte when length odd
            int checksumNbRowsByte = maxDataLength;
            if ((maxDataLength & 1) == 1)
            {
                checksumNbRowsByte += 1;
            }

            // Add 2 more bytes to store the length
            checksumNbRowsByte += CFec.SIZE_OVERHEAD;

            // Encode the length of the data and place that on the first 2 bytes
            // of the checksum BufferChunk
            EncodeRSLength(data, checksum, encode);

            // Start to put encoded data at index + 2, because the 2 first bytes
            // of the checksum already contain the encoded size
            for (int i = 0; i < checksum.Length; i++)
            {
                BufferChunk bc = checksum[i];
                bc.Reset(bc.Index + CFec.SIZE_OVERHEAD, checksumNbRowsByte - CFec.SIZE_OVERHEAD);
                
                // Reset all of the checksum packets so they have no data
                // TODO - Temporary workaround for column based approach - JVE 7/6/2004
                bc.Clear();
            }

            // Place all the packets in a 16bits boundary to avoid byte operation
            // Important: This suppose that the memory reserved for all the bc passed in param 
            // to this method ends on a 16bits boundary (so at least one addition availabe byte 
            // when the last item is on a even address)
            Queue paddedData = new Queue();
            AddPadding(data, 0, paddedData);

            // Encode the data and place the encoded information in the checksum BufferChunk
            EncodeRSData(data, checksum, encode, maxDataLength);

            // Earlier, we changed the boundary of all data BufferChunk
            // that was not ending on a 16 bits boundary in order to have
            // better performance during the encoding. Now we need to 
            // restore the data to their original state to be clean.
            RemovePadding(paddedData);

            // Restore the BufferChunk index in the checksum checksum BufferChunk
            // to 0 to be clean. Earlier, We changed the index in order to encode 
            // the data after the encoding length.
            for (int i=0; i < checksum.Length; i++)
            {
                BufferChunk bc = checksum[i];
                bc.Reset(bc.Index - CFec.SIZE_OVERHEAD, checksumNbRowsByte);
            }
        }
        private void Run()
        {
            while (true)
            {
                Console.Out.WriteLine("Sending to address: " + ADDRESS);

                byte[] buffer = new byte[sizeof(uint)];
                BufferChunk packetBuffer = new BufferChunk(buffer);
                packetBuffer.SetUInt32(0, COOKIE);

                udpSender.Send(packetBuffer);

                Thread.Sleep(PERIOD);
            }
        }
        public HeartbeatServer(String addr, int port, uint cookie, int period, ushort ttl) {
            m_Period = period;
            m_Thread = null;
            m_Disposed = false;

            //Set up the send buffer
            byte[] buffer = new byte[sizeof(uint)];
            m_PacketBuffer = new BufferChunk(buffer);
            m_PacketBuffer.SetUInt32(0, cookie);

            //Create the Sender
            IPAddress ipaddr = IPAddress.Parse(addr);
            m_IpEp = new IPEndPoint(ipaddr, port);
            m_UdpSender = new UdpSender(m_IpEp, ttl);
        }
Example #9
0
        public static GDIPen UnpackGPen(BufferChunk chunk)
        {
            uint     penColor;
            PenStyle penStyle;
            Guid     uniqueID;
            int      penSize;

            penStyle = (PenStyle)chunk.NextInt32();
            penSize  = chunk.NextInt32();
            penColor = chunk.NextUInt32();
            uniqueID = UnpackGuid(chunk);

            GDIPen aPen = new GDIPen(PenType.Cosmetic, PenStyle.Solid, PenJoinStyle.Round, PenEndCap.Round, penColor, penSize, uniqueID);

            return(aPen);
        }
        public static void Pack(BufferChunk chunk, TRIVERTEX[] vertices)
        {
            int nVertices = vertices.Length;

            // Pack the vertices, starting with the length
            chunk += nVertices;
            for (int i = 0; i < nVertices; i++)
            {
                chunk += vertices[i].x;
                chunk += vertices[i].y;
                chunk += vertices[i].Alpha;
                chunk += vertices[i].Blue;
                chunk += vertices[i].Green;
                chunk += vertices[i].Red;
            }
        }
        /// <summary>
        /// Return the next sample, compressed or uncompressed as appropriate.
        /// </summary>
        /// <param name="sample">The bits</param>
        /// <param name="timestamp">Absolute timestamp in ticks</param>
        /// <param name="keyframe">True if this sample is compressed and is a video keyframe</param>
        /// <param name="newstream">True if this sample is uncompressed and
        /// is from a different stream than the previous sample (thus may have a different media type).</param>
        /// <returns>True if a valid sample is returned</returns>
        public bool GetNextSample(out BufferChunk sample, out long timestamp, out bool keyframe, out bool newstream)
        {
            BufferChunk frame;

            keyframe  = false;
            newstream = false;
            if (compressed)
            {
                for (int i = 0; i < streamPlayers.Length; i++)
                {
                    if (streamPlayers[i].GetNextFrame(out frame, out timestamp))
                    {
                        sample = ProfileUtility.FrameToSample(frame, out keyframe);
                        return(true);
                    }
                }
            }
            else
            {
                for (int i = 0; i < fileStreamPlayers.Length; i++)
                {
                    while (fileStreamPlayers[i].GetNextSample(out sample, out timestamp))
                    {
                        if (timestamp >= startTime) //skip past frames that may be returned due to the look behind.
                        {
                            currentFSPGuid = fileStreamPlayers[i].xGuid;
                            if (fileStreamPlayers[i].AudioMediaType != null)
                            {
                                currentChannels = fileStreamPlayers[i].AudioMediaType.WaveFormatEx.Channels;
                            }
                            //PRI3: instead of newstream, we could track the MT, and raise a flag only when it changes.
                            if (i != lastFSP)
                            {
                                newstream = true;
                            }
                            lastFSP = i;
                            return(true);
                        }
                    }
                }
            }

            sample    = null;
            timestamp = 0;
            return(false);
        }
        // Gradient Fills
        public override void DrawGradientRectangle(GradientRect gRect)
        {
            BufferChunk chunk = new BufferChunk(1024);

            chunk += GDI32.EMR_GRADIENTFILL;

            // Pack the vertices
            Pack(chunk, gRect.Vertices);

            // Pack the gradient mesh
            Pack(chunk, gRect.Boundary);

            // pack the mode
            chunk += (int)gRect.Direction;

            PackCommand(chunk);
        }
Example #13
0
        /// <summary>
        /// Converts 3 bytes into a big-endian integer
        /// </summary>
        /// <param name="data"></param>
        /// <returns>Big-endian formatted integer</returns>
        private static int ThreeBytesToInt(BufferChunk data)
        {
            int ret = 0;

            ret += (data.NextByte() << 1 * 8);
            ret += (data.NextByte() << 2 * 8);
            ret += (data.NextByte() << 3 * 8);

            // If the 8th bit of the second byte (what will be the 24th bit)
            // is turned on, the value is signed, so sign extend our integer
            if (((byte)(ret >> 1 * 8) & 0x80) == 0x80)
            {
                ret += 0xFF;
            }

            return(ret);
        }
Example #14
0
File: TMPlan.cs Project: x2v0/TM
        /// <summary>
        ///    Nexts the plan spot result.
        /// </summary>
        /// <param name="buf">The buf.</param>
        /// <returns>System.Nullable&lt;SpotResult&gt;.</returns>
        public static SpotResult?NextSpotResult(this BufferChunk buf)
        {
            var plan = new SpotResult();

            try {
                plan.id            = buf.NextInt32();
                plan.result_xangle = buf.NextFloat();
                plan.result_zangle = buf.NextFloat();
                plan.result_pcount = buf.NextFloat();
                plan.done          = buf.NextInt32();
            } catch {
                //plan.id = -1; //
                return(null);
            }

            return(plan);
        }
    // Gradient Fills
    public override void GradientRectangle(TRIVERTEX[] pVertex, GRADIENT_RECT[] pMesh, uint dwMode)
    {
        BufferChunk chunk = new BufferChunk(1024);

        chunk += GDI32.EMR_GRADIENTFILL;

        // Pack the vertices
        Pack(chunk, pVertex);

        // Pack the gradient mesh
        Pack(chunk, pMesh);

        // pack the mode
        chunk += dwMode;

        PackCommand(chunk);
    }
Example #16
0
        /// <summary>
        /// Accept a raw presentation frame.  Deserialize and Demux to handler for the particular presentation format.
        /// </summary>
        /// <param name="bc"></param>
        public void ProcessFrame(BufferChunk frame)
        {
            BinaryFormatter bf    = new BinaryFormatter();
            Object          rtobj = null;

            try
            {
                MemoryStream ms = new MemoryStream((byte[])frame);
                rtobj = bf.Deserialize(ms);
            }
            catch (Exception e)
            {
                Debug.WriteLine("frameToSlide: exception deserializing message. size=" + frame.Length.ToString() +
                                " exception=" + e.ToString());
                return;
            }

            switch (format)
            {
            case PresenterWireFormatType.CPNav:
            {
                acceptCPNavFrame(rtobj);
                break;
            }

            case PresenterWireFormatType.CPCapability:
            {
                acceptCPCapabilityFrame(rtobj);
                break;
            }

            case PresenterWireFormatType.RTDocument:
            {
                acceptRTDocFrame(rtobj);
                break;
            }

            case PresenterWireFormatType.CP3: {
                acceptCP3Frame(rtobj);
                break;
            }

            default:
                break;
            }
        }
Example #17
0
        private void WritePropertyToBuffer(Rtcp.SDESType type, byte[] data, BufferChunk buffer)
        {
            if (data != null)
            {
                // Type
                buffer += (byte)type;

                // Length
                buffer += (byte)data.Length;

                // Data
                if (data.Length != 0)
                {
                    buffer += data;
                }
            }
        }
        public HeartbeatServer(String addr, int port, uint cookie, int period, ushort ttl)
        {
            m_Period   = period;
            m_Thread   = null;
            m_Disposed = false;

            //Set up the send buffer
            byte[] buffer = new byte[sizeof(uint)];
            m_PacketBuffer = new BufferChunk(buffer);
            m_PacketBuffer.SetUInt32(0, cookie);

            //Create the Sender
            IPAddress ipaddr = IPAddress.Parse(addr);

            m_IpEp      = new IPEndPoint(ipaddr, port);
            m_UdpSender = new UdpSender(m_IpEp, ttl);
        }
Example #19
0
File: TMPlan.cs Project: x2v0/TM
        /// <summary>
        ///    Nexts the Spot.
        /// </summary>
        /// <param name="buf">The buffer chunk.</param>
        /// <returns>Spot.</returns>
        public static Spot?NextSpot(this BufferChunk buf)
        {
            var plan = new Spot();

            try {
                plan.id     = buf.NextInt32();
                plan.xangle = buf.NextFloat();
                plan.zangle = buf.NextFloat();
                plan.energy = buf.NextFloat();
                plan.pcount = buf.NextFloat();
            } catch {
                //plan.id = -1; //
                return(null);
            }

            return(plan);
        }
Example #20
0
        /// <summary>
        /// Decoder: This method takes an array of BufferChunk in parameter with the data
        /// and checksum received and returns the missing packets. Because it
        /// is based on XOR, it can recover only from one packet lost. This method
        /// is very similar than encoder, but differ in the validation part.
        /// </summary>
        /// <param name="bytes">Array of buffer chunk that represents the packets where
        /// you might have lost a packet</param>
        /// <param name="nbChecksumPackets">Should be always set to 1</param>
        /// <returns>The missing packet</returns>
        public void Decode(BufferChunk[] data, int nbChecksumPackets, BufferChunk[] recovery)
        {
            ValidateObjectNotNull(data);
            ValidateObjectNotNull(data[data.Length - 1]); // Checksum packet can't be null
            ValidateChecksumPacketCount(nbChecksumPackets);
            ValidateNullData(data, 1);

            // Sort the BufferChunks from longest to shortest
            ActiveColumns(data, data.Length - 1);

            int xorDataLength = XORLength() ^ data[data.Length - 1].NextUInt16();

            BufferChunk xorData = recovery[0];

            xorData.Reset(xorData.Index, xorDataLength);
            XORData(xorData, xorDataLength);
        }
Example #21
0
File: TMPacket.cs Project: x2v0/TM
        /// <summary>
        ///    Initializes a new instance of the <see cref="Packet" /> class.
        /// </summary>
        public Packet(EServerType server_type, EPacketType type, byte cmd)
        {
            BufferChunk.SetNetworking();
            Header = new PacketHeader(server_type);

            Header.type          = (byte)type;
            Header.value         = cmd;
            Header.packet_number = PacketNumber++;
            Header.datalength    = 1;
            var len = PacketHeader.Length;

            len += Header.datalength;
            Data = new BufferChunk((int)len);
            Data.Add(Header);

            AddChecksumm();
        }
        private void ReceivePackets()
        {
            BufferChunk bc = null;

            while (true)
            {
                try
                {
                    bc = GetBuffer();
                    EndPoint ep;

                    rtpNetworkListener.ReceiveFrom(bc, out ep);
                    receivedPackets.Enqueue(new object[] { bc, ep });
                    newPacket.Set();

                    unchecked { pcPackets++; }
                }
                catch (PoolExhaustedException e)
                {
                    LogEvent(e.ToString(), EventLogEntryType.Error, (int)RtpEL.ID.UnboundedGrowth);
                    return; // Exit the thread gracefully
                }
                catch (System.Net.Sockets.SocketException e)
                {
                    ReturnBuffer(bc);

                    // Something other than - No data received before timeout
                    if (e.ErrorCode != 10060)
                    {
                        Object[] args = new Object[] { this, new RtpEvents.HiddenSocketExceptionEventArgs((RtpSession)rtpSession, e) };
                        EventThrower.QueueUserWorkItem(new RtpEvents.RaiseEvent(RtpEvents.RaiseHiddenSocketExceptionEvent), args);

                        LogEvent(e.ToString(), EventLogEntryType.Error, (int)RtpEL.ID.Error);
                    }
                }
                catch (Exception e)
                {
                    if (!(e is ThreadAbortException))
                    {
                        ReturnBuffer(bc);
                        LogEvent(e.ToString(), EventLogEntryType.Error, (int)RtpEL.ID.Error);
                    }
                }
            }
        }
Example #23
0
        private void ReadPrivatePropertyFromBuffer(BufferChunk buffer)
        {
            byte totalLength  = buffer.NextByte();
            byte prefixLength = buffer.NextByte();
            int  dataLength   = totalLength - prefixLength - 1;

            // The cast to byte[] does a copy
            byte[] prefix = (byte[])buffer.NextBufferChunk(prefixLength);
            byte[] data   = null;

            if (dataLength > 0)
            {
                // The cast to byte[] does a copy
                data = (byte[])buffer.NextBufferChunk(dataLength);
            }

            privs[prefix] = data;
        }
Example #24
0
        /// <summary>
        /// Receive a packet into a BufferChunk.  This method is preferred over receiving into a byte[] because you can allocate a large
        /// byte[] in one BufferChunk and continously receiving into the buffer without recreating byte[]s and dealing with the memory allocation
        /// overhead that causes.
        ///
        /// No int bytes received is returned because the bytes received is stored in BufferChunk.Length.
        /// </summary>
        /// <param name="packetBuffer">BufferChunk</param>
        /// <example>
        /// ...
        /// MulticastUdpListener mcListener = new MulticastUdpListener(endPoint);
        ///
        /// // Allocate a 2K buffer to hold the incoming packet
        /// BufferChunk packetBuffer = new BufferChunk(2000);
        ///
        /// mcListener.Receive(packetBuffer);
        ///
        /// mcListener.Displose();
        /// mcListener = null;
        /// ...
        /// </example>
        public void Receive(BufferChunk packetBuffer)
        {
            if (disposed)
            {
                throw new ObjectDisposedException(Strings.MulticastUdpListenerAlreadyDisposed);
            }

            sock.Receive(packetBuffer);
#if FaultInjection
            if (dropPacketsReceivedPercent > 0)
            {
                while (rnd.Next(0, 100) < dropPacketsReceivedPercent)
                {
                    sock.Receive(packetBuffer);
                }
            }
#endif
        }
Example #25
0
        // Generalized bit block transfer
        public override void PixBlt(PixelArray pixBuff, int x, int y)
        {
            // Create a buffer
            // It has to be big enough for the bitmap data, as well as the x,y, and command
            int         dataSize = pixBuff.BytesPerRow * pixBuff.Height;
            BufferChunk chunk    = new BufferChunk(dataSize + 128);

            // now put the basic command and simple components in
            chunk += GDI32.EMR_BITBLT;
            ChunkUtils.Pack(chunk, x, y);
            ChunkUtils.Pack(chunk, pixBuff.Width, pixBuff.Height);
            chunk += dataSize;

            // Finally, copy in the data
            chunk.CopyFrom(pixBuff.PixelData, dataSize);

            SendCommand(chunk);
        }
        // Generalized bit block transfer

        // Can transfer from any device context to this one.
        public override void BitBlt(int x, int y, PixelBuffer pixBuff)
        {
            // Create a buffer
            // It has to be big enough for the bitmap data, as well as the x,y, and command
            int         dataSize = pixBuff.Pixels.Stride * pixBuff.Pixels.Height;
            BufferChunk chunk    = new BufferChunk(dataSize + 128);

            // now put the basic command and simple components in
            chunk += GDI32.EMR_BITBLT;
            Pack(chunk, x, y);
            Pack(chunk, pixBuff.Pixels.Width, pixBuff.Pixels.Height);
            chunk += dataSize;

            // Finally, copy in the data
            chunk.CopyFrom(pixBuff.Pixels.Data, dataSize);

            PackCommand(chunk);
        }
Example #27
0
        /// <summary>
        /// Creates a venue with IPAddress 234.*.*.* where each * is randomly generated.  Extremely useful
        /// in the case where a venue server is inaccessible.
        /// </summary>
        public Venue CreateRandomMulticastVenue(string name, Image icon)
        {
            IPEndPoint endPoint       = null;
            bool       trafficInVenue = true;

            while (trafficInVenue)
            {
                #region Randomly choose the Venue's IP address
                Random rnd        = new Random();
                int    randomaddr = 234;
                randomaddr = randomaddr * 256 + rnd.Next(1, 2 ^ 8 - 1);
                randomaddr = randomaddr * 256 + rnd.Next(1, 2 ^ 8 - 1);
                randomaddr = randomaddr * 256 + rnd.Next(1, 2 ^ 8 - 1);
                endPoint   = new IPEndPoint(IPAddress.HostToNetworkOrder(randomaddr), 5004);
                #endregion
                #region Detect whether there is already traffic in the venue, if so change the IP address
                BufferChunk bc          = new BufferChunk(MSR.LST.Net.Rtp.Rtp.MAX_PACKET_SIZE);
                UdpListener udpListener = new UdpListener(endPoint, venueInUseTimeout);
                try
                {
                    udpListener.Receive(bc);
                }
                catch (System.Net.Sockets.SocketException e)
                {
                    if (e.ErrorCode == 10060)
                    {
                        trafficInVenue = false;
                    }
                    else
                    {
                        throw;
                    }
                }
                finally
                {
                    udpListener.Dispose();
                }
                #endregion
            }

            VenueData venueData = new VenueData(name, endPoint, 5, VenueType.Custom, icon);

            return(AddCustomVenue(venueData));
        }
Example #28
0
        public override void DrawPath(IPen aPen, GPath aPath)
        {
            BufferChunk chunk = new BufferChunk(aPath.Vertices.Length * 8 + 128);

            chunk += GDI32.EMR_POLYDRAW;

            ChunkUtils.Pack(chunk, aPath.Vertices);


            for (int i = 0; i < aPath.Vertices.Length; i++)
            {
                chunk += aPath.Commands[i];
            }

            // Pack the pen
            ChunkUtils.Pack(chunk, aPen);

            SendCommand(chunk);
        }
Example #29
0
        public bool GetNextSample(out BufferChunk sample, out long time)
        {
            sample = null;
            const int SAMPLE_SIZE = 4096;

            sample = Mix(SAMPLE_SIZE, out time);

            if (refTime == long.MinValue)
            {
                refTime = time;
            }

            if (sample == null)
            {
                return(false);
            }

            return(true);
        }
Example #30
0
        /// <summary>
        /// Same as Receive, but you also get an EndPoint containing the sender of the packet.
        /// </summary>
        /// <param name="packetBuffer">BufferChunk</param>
        /// <param name="endPoint">EndPoint</param>
        /// <example>
        /// ...
        /// MulticastUdpListener mcListener = new MulticastUdpListener(endPoint);
        ///
        /// // Allocate a 2K buffer to hold the incoming packet
        /// BufferChunk packetBuffer = new BufferChunk(2000);
        ///
        /// // Allocate a structure to hold the incoming endPoint
        /// EndPoint endPoint;
        ///
        /// mcListener.ReceiveFrom(packetBuffer, endPoint);
        ///
        /// mcListener.Displose();
        /// mcListener = null;
        /// ...
        /// </example>
        public void ReceiveFrom(BufferChunk packetBuffer, out EndPoint endPoint)
        {
            if (disposed)
            {
                throw new ObjectDisposedException(Strings.MulticastUdpListenerAlreadyDisposed);
            }

            endPoint = new IPEndPoint(externalInterface, 0);
            sock.ReceiveFrom(packetBuffer, ref endPoint);
#if FaultInjection
            if (dropPacketsReceivedPercent > 0)
            {
                while (rnd.Next(0, 100) < dropPacketsReceivedPercent)
                {
                    sock.ReceiveFrom(packetBuffer, ref endPoint);
                }
            }
#endif
        }
Example #31
0
        /// <summary>
        /// Send an arbitrarily large set of data contained in a BufferChunk.
        /// </summary>
        public void Send(BufferChunk frame)
        {
            if (disposed)
            {
                throw new ObjectDisposedException("RtpSender already disposed");
            }

            if (frame.Length == 0)
            {
                throw new IndexOutOfRangeException("frame.Length should be > 0, otherwise we'd send a packet with no data.");
            }

            unchecked { ts += tsIncrement; }
            this.frame.TimeStamp = ts;

            this.frame.Data = frame;

            Send();
        }
Example #32
0
        /// <summary>
        /// Given a byte[] (in the form of a BufferChunk) containing a MediaType received from WM Interop, and an
        /// allocated instance of MediaType, fill in the MediaType from the byte[].  This is just the
        /// payload-independant part.
        /// </summary>
        /// <param name="mt"></param>
        /// <param name="bc"></param>
        public static void ReconstituteBaseMediaType(MediaType mt, BufferChunk bc)
        {
            Guid g = NextGuid(bc);

            mt.MajorType    = MediaType.MajorTypeGuidToEnum(g);
            mt.mt.majortype = g;
            g                      = NextGuid(bc);
            mt.SubType             = MediaType.SubTypeGuidToEnum(g);
            mt.mt.subtype          = g;
            mt.FixedSizeSamples    = (NextInt32(bc) == 0)?false:true;
            mt.TemporalCompression = (NextInt32(bc) == 0)?false:true;
            mt.SampleSize          = NextInt32(bc);
            g                      = NextGuid(bc);
            mt.FormatType          = MediaType.FormatTypeGuidToEnum(g);
            mt.mt.formattype       = g;
            IntPtr punk     = (IntPtr)NextInt32(bc);
            int    cbformat = NextInt32(bc);
            IntPtr pbformat = (IntPtr)NextInt32(bc);             //This not a valid pointer in this context.
        }
Example #33
0
        /// <summary>
        /// Return the raw bitmap representing the current presentation state
        /// </summary>
        /// <param name="frame"></param>
        public void GetCurrentFrame(out BufferChunk frame)
        {
            frame = null;

            if ((currentSlide.IsSet) && (slideImages.ContainsKey(currentSlide.GetStringHashCode())))
            {
                frame = ((SlideImage)slideImages[currentSlide.GetStringHashCode()]).GenerateFrame(currentSlide.Size, currentSlide.BGColor, this.exportWidth, this.exportHeight);
            }
            else
            {
                //If we don't have a current slide, return a blank frame.
                if (nullSlide == null)
                {
                    nullSlide = new SlideImage();
                }

                frame = nullSlide.GenerateFrame(1.0, Color.PapayaWhip, this.exportWidth, this.exportHeight);
            }
        }
Example #34
0
        /// <summary>
        /// Write an audio sample.  Sample time is in ticks.
        /// </summary>
        /// <param name="sampleSize"></param>
        /// <param name="inBuf"></param>
        /// <param name="sampleTime">in Ticks</param>
        /// <returns></returns>
        public bool WriteAudio(uint sampleSize, BufferChunk inBuf, ulong sampleTime)
        {
            INSSBuffer sample;
            IntPtr     sampleBuf = IntPtr.Zero;

            //Debug.WriteLine("WMWriter.WriteAudio: time=" + sampleTime.ToString());
            //return true;
            //	+ " size=" + sampleSize.ToString() +
            // " audio bytes " + inBuf[345].ToString() + " " +
            //	inBuf[346].ToString() + " " + inBuf[347].ToString() + " " + inBuf[348].ToString());

            try
            {
                lock (this)
                {
                    writer.AllocateSample(sampleSize, out sample);
                    sample.GetBuffer(out sampleBuf);
                    Marshal.Copy(inBuf.Buffer, inBuf.Index, sampleBuf, (int)sampleSize);
                    sample.SetLength(sampleSize);
                    writer.WriteSample(audioInput, sampleTime, 0, sample);
                    //Debug.WriteLine("Wrote audio. time=" + sampleTime.ToString());
                    Marshal.ReleaseComObject(sample);
                    lastWriteTime = sampleTime;
                }
            }
            catch (Exception e)
            {
                //Debug.WriteLine("Exception while writing audio: " +
                //	"audioInput=" + videoInput.ToString() +
                //	" sampleTime=" + sampleTime.ToString() +
                //	" sampleSize=" + sampleSize.ToString());

                Debug.WriteLine("Exception while writing audio: " + e.ToString());
                eventLog.WriteEntry("Exception while writing audio: " + e.ToString(), EventLogEntryType.Error, 1000);
                return(false);
            }
            //Debug.WriteLine("Audio write succeeded " +
            //		"audioInput=" + videoInput.ToString() +
            //		" sampleTime=" + sampleTime.ToString() +
            //		" sampleSize=" + sampleSize.ToString());
            return(true);
        }
Example #35
0
        /// <summary>
        /// Allocates the storage used by the buffer.  After this method call
        /// the buffer is ready to be started.
        /// </summary>
        /// <param name="mt"></param>
        /// <returns></returns>
        public bool Create()
        {
            Debug.Assert(myMediaType != null);

            UW.CSE.MDShow.MediaTypeWaveFormatEx wf = myMediaType.ToMediaTypeWaveFormatEx();
            uint bytesPerSec = wf.WaveFormatEx.AvgBytesPerSec;

            currentChannels = wf.WaveFormatEx.Channels;

            if ((bytesPerSec == 0) || (SIZE_IN_SECONDS == 0))
            {
                return(false);
            }

            //Use about 1/4 second dummy audio sample to correct for lost audio data, or to resync.
            // This has to be evenly divisible by the BlockAlign value which we assume to be 2 or 4.
            // If we assume 4, it works for 2 as well.
            SilenceSize = (uint)(bytesPerSec / 16) * 4;

            Buffer        = new BufferChunk((int)bytesPerSec * SIZE_IN_SECONDS);
            Buffer.Length = (int)bytesPerSec * SIZE_IN_SECONDS;

            PresTime    = new ulong[SIZE_IN_SECONDS];
            QuietBuffer = new byte[SilenceSize];

            AddAudio       = 0;
            SkipAudio      = 0;
            SampleSize     = bytesPerSec;
            SampleCount    = SIZE_IN_SECONDS;
            WriteOffset    = 0;
            ReadOffset     = 0;
            SamplesReady   = 0;
            BufferSize     = (uint)bytesPerSec * SIZE_IN_SECONDS;
            BufferPos      = 0;
            LeftoverBytes  = 0;
            samplesWritten = 0;
            streamStopTime = 0;
            bytesBuffered  = 0;
            started        = false;
            sampleReceived = false;
            return(true);
        }
Example #36
0
        /// <summary>
        /// Take the DirectShow header off the frame and return the remainder.
        /// Also indicate whether the keyframe flag is set.
        /// </summary>
        /// <param name="frame"></param>
        /// <returns></returns>
        public static BufferChunk FrameToSample(BufferChunk frame, out bool keyframe)
        {
            short       headerSize = frame.NextInt16();        //first short tells us the header size
            BufferChunk header     = null;

            header = frame.NextBufferChunk(headerSize);

            AM_SAMPLE2_PROPERTIES amsp = ReconstituteSampleProperties(header);

            if ((amsp.dwSampleFlags & 1) > 0)
            {
                keyframe = true;
            }
            else
            {
                keyframe = false;
            }
            //Debug.WriteLine("FrameToSample returning sample of size=" + frame.Length);
            return(frame);
        }
Example #37
0
        /// <summary>
        /// Send an arbitrarily large set of data contained in a BufferChunk.
        /// </summary>
        public void Send(BufferChunk chunk)
        {
            if (disposed)
            {
                throw new ObjectDisposedException(Strings.RtpSenderAlreadyDisposed);
            }

            if (chunk.Length == 0)
            {
                throw new IndexOutOfRangeException(Strings.FrameLengthShouldBePositive);
            }

            unchecked { ts += tsIncrement; }
            this.frame.TimeStamp = ts;

            // The data gets packetized in this step
            this.frame.Data = chunk;

            Send();
        }
Example #38
0
        /// <summary>
        /// Fill in the video-specific parts of the MediaType from the data in the BufferChunk.
        /// Also return the compression data which is the remaining bytes at the end of the byte[].
        /// </summary>
        /// <param name="mt"></param>
        /// <param name="bc"></param>
        /// <param name="compressionData"></param>
        public static void ReconstituteVideoFormat(MediaTypeVideoInfo mt, BufferChunk bc, out byte[] compressionData)
        {
            VIDEOINFOHEADER vi;
            RECT            s;

            s.left    = NextInt32(bc);
            s.top     = NextInt32(bc);
            s.right   = NextInt32(bc);
            s.bottom  = NextInt32(bc);
            vi.Source = s;
            RECT t;

            t.left             = NextInt32(bc);
            t.top              = NextInt32(bc);
            t.right            = NextInt32(bc);
            t.bottom           = NextInt32(bc);
            vi.Target          = t;
            vi.BitRate         = (uint)NextInt32(bc);
            vi.BitErrorRate    = (uint)NextInt32(bc);
            vi.AvgTimePerFrame = bc.NextUInt64();
            BITMAPINFOHEADER bih;

            bih.Size          = (uint)NextInt32(bc);
            bih.Width         = NextInt32(bc);
            bih.Height        = NextInt32(bc);
            bih.Planes        = (ushort)NextInt16(bc);
            bih.BitCount      = (ushort)NextInt16(bc);
            bih.Compression   = (uint)NextInt32(bc);
            bih.SizeImage     = (uint)NextInt32(bc);
            bih.XPelsPerMeter = NextInt32(bc);
            bih.YPelsPerMeter = NextInt32(bc);
            bih.ClrUsed       = (uint)NextInt32(bc);
            bih.ClrImportant  = (uint)NextInt32(bc);
            vi.BitmapInfo     = bih;
            mt.VideoInfo      = vi;
            compressionData   = new byte[bc.Length];
            for (int i = 0; i < compressionData.Length; i++)
            {
                compressionData[i] = bc.NextByte();
            }
        }
Example #39
0
        /// <summary>
        /// Converts member data into buffer
        /// </summary>
        /// <param name="packet"></param>
        public override void WriteDataToBuffer(BufferChunk buffer)
        {
            // Add SSRCs
            foreach(uint ssrc in ssrcs)
            {
                buffer += ssrc;
            }

            // Add reason
            if(reason != null)
            {
                buffer += (byte)reason.Length;
                buffer += reason;
            }

            // Update Header
            Header.ItemCount = ssrcs.Count;
        }
Example #40
0
        public override void ReadDataFromBuffer(BufferChunk buffer)
        {
            SSRC = buffer.NextUInt32();
            name = (byte[])buffer.NextBufferChunk(4);

            if(buffer.Length != 0)
            {
                data = (byte[])buffer.NextBufferChunk(buffer.Length);
            }
        }
Example #41
0
        public override void WriteDataToBuffer(BufferChunk buffer)
        {
            buffer += SSRC;
            buffer += (BufferChunk)name;

            // Data is not required per RFC 3550 
            if(data != null)
            {
                buffer += (BufferChunk)data;
            }
        }
Example #42
0
 // Allocate the storage to receive data into off the wire
 public CompoundPacket()
 {
     buffer = new BufferChunk(size);
 }
Example #43
0
 /// <summary>
 /// Calls the base class ReceiveFrom.  Performs an efficient conversion from BufferChunk.
 /// </summary>
 /// <param name="bufferChunk">BufferChunk</param>
 /// <param name="endPoint">ref EndPoint</param>
 /// <example>
 /// Socket sock = new MSR.LST.Net.Sockets.Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
 /// sock.ReceiveFrom(bufferChunk, ref endPoint);
 /// </example>
 public void ReceiveFrom(BufferChunk bufferChunk, ref EndPoint endPoint)
 {
     bufferChunk.Length = base.ReceiveFrom(bufferChunk.Buffer, 0, bufferChunk.Buffer.Length, SocketFlags.None, ref endPoint);
 }
Example #44
0
 /// <summary>
 /// Calls the base class Receive.  Performs an efficient conversion from BufferChunk.
 /// </summary>
 /// <param name="bufferChunk">BufferChunk</param>
 /// <param name="socketFlags">SocketFlags</param>
 /// <example>
 /// Socket sock = new MSR.LST.Net.Sockets.Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
 /// sock.Receive(bufferChunk, SocketFlags.None);
 /// </example>
 public void Receive(BufferChunk bufferChunk, SocketFlags socketFlags)
 {
     bufferChunk.Length = base.Receive(bufferChunk.Buffer, 0, bufferChunk.Buffer.Length, socketFlags);
 }
Example #45
0
 /// <summary>
 /// Calls the base class Send.  Performs an efficient conversion from BufferChunk.
 /// </summary>
 /// <param name="bufferChunk">BufferChunk to send</param>
 /// <param name="socketFlags">SocketFlags</param>
 /// <returns>int bytes sent</returns>
 /// <example>
 /// Socket sock = new MSR.LST.Net.Sockets.Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
 /// sock.Send(bufferChunk, SocketFlags.None);
 /// </example>
 public int Send(BufferChunk bufferChunk, SocketFlags socketFlags)
 {
     return base.Send(bufferChunk.Buffer, bufferChunk.Index, bufferChunk.Length, socketFlags);
 }
Example #46
0
        public override void ReadDataFromBuffer(BufferChunk buffer)
        {
            // Make sure ItemCount and Data length agree
            if(Header.Length * 4 != Rtp.SSRC_SIZE + SenderReport.SIZE + 
                ReceiverReport.SIZE * Header.ItemCount)
            {
                Debug.Assert(false, "Header length and item count disagree!");
                throw new RtcpPacketException("Header length and item count disagree!");
            }

            // Read ssrc
            SSRC = buffer.NextUInt32();

            // Parse SenderReport
            sr.ReadDataFromBuffer(buffer);

            // Process Reports
            if(Header.ItemCount > 0)
            {
                receiverReports = new ArrayList();

                for(int rrCount = 0; rrCount < Header.ItemCount; rrCount++)
                {
                    ReceiverReport rr = new ReceiverReport();
                    rr.ReadDataFromBuffer(buffer);

                    receiverReports.Add(rr);
                }
            }
        }
Example #47
0
        /// <summary>
        /// Adds padding to make sure buffer ends on a 32 bit boundary
        /// </summary>
        /// <param name="cbBuffer">Size of buffer in bytes</param>
        protected static int AddPadding(BufferChunk buffer)
        {
            // We use the negative to take the 2's complement
            // and & 3 to retain the first 2 bits (0-3).
            int padding = GetNeededPadding(buffer.Length);
                
            if(padding > 0)
            {
                buffer += new byte[padding];
            }

            return padding;
        }
Example #48
0
        /// <summary>
        /// Converts the first 4 bytes of the buffer into member variables
        /// </summary>
        /// <param name="buffer"></param>
        public void ReadDataFromBuffer(BufferChunk buffer)
        {
            int version = buffer[0] >> 6;
            
            if(version != Rtp.VERSION)
            {
                throw new RtcpHeaderException(string.Format("Invalid version: {0}, current: {1}", 
                    version, Rtp.VERSION));
            }

            Padding = Convert.ToBoolean(buffer[0] & PADDING_MASK);
            ItemCount = buffer[0] & ITEMCOUNT_MASK;
            PacketType = buffer[1];
            Length = buffer.GetInt16(2);
        }
Example #49
0
        /// <summary>
        /// Converts member data to byte[]
        /// </summary>
        /// <param name="buffer"></param>
        public void WriteDataToBuffer(BufferChunk buffer)
        {
            // "Clear" the byte by setting the Version
            // 2 (10) becomes 128 (10000000) when you shift it into place in the header
            buffer[0] = Rtp.VERSION << 6;

            // Padding
            if(Padding == true)
            {
                buffer[0] |= PADDING_MASK;
            }

            // ItemCount
            buffer[0] += (byte)(ItemCount); // Add in the new value

            // PacketType
            buffer[1] = PacketType;

            // Length
            buffer.SetInt16(2, Length);
        }
Example #50
0
        /// <summary>
        /// Constructor which converts buffer into member variables
        /// Expects buffer to be 4 bytes long
        /// </summary>
        /// <param name="buffer">Data to be manipulated</param>
        public RtcpHeader(BufferChunk buffer)
        {
            if(buffer.Length != SIZE)
            {
                throw new RtcpHeaderException(string.Format("Invalid buffer length: {0}, must be: {1}",
                    buffer.Length, RtcpHeader.SIZE));
            }

            ReadDataFromBuffer(buffer);
        }
Example #51
0
 public CompoundPacket(BufferChunk buffer)
 {
     this.buffer = buffer;
     ParseBuffer();
 }
Example #52
0
        public override void WriteDataToBuffer(BufferChunk buffer)
        {
            // Add Reporter SSRC
            buffer += SSRC;

            // Add all the reports
            foreach(ReceiverReport rr in receiverReports)
            {
                rr.WriteDataToBuffer(buffer);
            }

            // Update Header
            Header.ItemCount = receiverReports.Count;
        }
Example #53
0
 /// <summary>
 /// Calls the base class Send.  Performs an efficient conversion from BufferChunk.
 /// </summary>
 /// <param name="bufferChunk">BufferChunk to send.</param>
 /// <returns>int bytes sent</returns>
 /// <example>
 /// Socket sock = new MSR.LST.Net.Sockets.Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
 /// sock.Send(bufferChunk);
 /// </example>
 public int Send(BufferChunk bufferChunk)
 {
     return Send(bufferChunk, SocketFlags.None);
 }
Example #54
0
        public override void ReadDataFromBuffer(BufferChunk buffer)
        {
            // Make sure ItemCount and Data length agree
            if(Header.Length * 4 != Header.ItemCount * ReceiverReport.SIZE + Rtp.SSRC_SIZE)
            {
                Debug.Assert(false, "Header length and item count disagree!");
                throw new RtcpPacketException("Header length and item count disagree!");
            }

            // Store Reporter SSRC
            SSRC = buffer.NextUInt32();

            // Process Reports
            for(int rrCount = 0; rrCount < Header.ItemCount; rrCount++)
            {
                ReceiverReport rr = new ReceiverReport();
                rr.ReadDataFromBuffer(buffer);

                receiverReports.Add(rr);
            }
        }
Example #55
0
 /// <summary>
 /// Calls the base class SendTo.  Performs an efficient conversion from BufferChunk.
 /// </summary>
 /// <param name="bufferChunk">BufferChunk</param>
 /// <param name="endPoint">EndPoint</param>
 /// <returns>int bytes sent</returns>
 /// <example>
 /// Socket sock = new MSR.LST.Net.Sockets.Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
 /// sock.SendTo(bufferChunk, endPoint);
 /// </example>
 public int SendTo(BufferChunk bufferChunk, EndPoint endPoint)
 {
     return SendTo(bufferChunk.Buffer, bufferChunk.Index, bufferChunk.Length, SocketFlags.None, endPoint);
 }
Example #56
0
 /// <summary>
 /// This method is called to return buffers to the bufferPool
 /// </summary>
 /// <param name="buffer"></param>
 private void ReturnBuffer(BufferChunk buffer)
 {
     buffer.Reset();
     bufferPool.Push(buffer);
 }
Example #57
0
 /// <summary>
 /// Calls the base class Receive.  Performs an efficient conversion from BufferChunk.
 /// </summary>
 /// <param name="bufferChunk">BufferChunk</param>
 /// <example>
 /// Socket sock = new MSR.LST.Net.Sockets.Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
 /// sock.Receive(bufferChunk);
 /// </example>
 public void Receive(BufferChunk bufferChunk)
 {
     Receive(bufferChunk, SocketFlags.None);
 }
Example #58
0
 private void HandleInvalidPacket(BufferChunk packet, IPEndPoint src, string exception)
 {
     rtpSession.RaiseInvalidPacketEvent(string.Format("First byte: {0}, Source IP: {1}, " +
         "Exception: {2}", packet.NextByte(), src, exception));
 }
Example #59
0
 public IAsyncResult BeginReceiveFrom(BufferChunk bufferChunk, ref EndPoint endPoint, AsyncCallback callback, object state)
 {
     return base.BeginReceiveFrom(bufferChunk.Buffer, 0, bufferChunk.Buffer.Length, SocketFlags.None, ref endPoint, callback, state);
 }
Example #60
0
        public override void WriteDataToBuffer(BufferChunk buffer)
        {
            // Add the SSRC
            buffer += SSRC;

            // Add the Sender Report
            sr.WriteDataToBuffer(buffer);

            // Add the receiver reports
            int reportCount = 0;

            if(receiverReports != null)
            {
                foreach(ReceiverReport rr in receiverReports)
                {
                    rr.WriteDataToBuffer(buffer);
                }

                reportCount = receiverReports.Count;
            }

            // Update Header
            Header.ItemCount = reportCount;
        }