Beispiel #1
0
        /// <summary>
        /// Default constructor.
        /// </summary>
        /// <param name="session">RTP multimedia session.</param>
        public wfrm_RTP_Debug(RTP_MultimediaSession session)
        {
            if(session == null){
                throw new ArgumentNullException("session");
            }

            m_pSession = session;

            InitUI();

            m_pSession.Error += new EventHandler<LumiSoft.Net.ExceptionEventArgs>(m_pSession_Error);
            m_pSession.SessionCreated += new EventHandler<LumiSoft.Net.EventArgs<RTP_Session>>(m_pSession_SessionCreated);
            m_pSession.NewParticipant += new EventHandler<RTP_ParticipantEventArgs>(m_pSession_NewParticipant);
            m_pSession.LocalParticipant.SourceAdded += new EventHandler<RTP_SourceEventArgs>(Participant_SourceAdded);
            m_pSession.LocalParticipant.SourceRemoved += new EventHandler<RTP_SourceEventArgs>(Participant_SourceRemoved);

            m_pTimer = new Timer();
            m_pTimer.Interval = 1000;
            m_pTimer.Tick += new EventHandler(m_pTimer_Tick);
            m_pTimer.Enabled = true;

            TreeNode nodeParticipant = new TreeNode(session.LocalParticipant.CNAME);
            nodeParticipant.Tag = new RTP_ParticipantInfo(session.LocalParticipant);
            nodeParticipant.Nodes.Add("Sources");
            m_pParticipants.Nodes.Add(nodeParticipant);
        }
Beispiel #2
0
        /// <summary>
        /// Default constructor.
        /// </summary>
        /// <param name="session">Owner RTP multimedia session.</param>
        /// <param name="localEP">Local RTP end point.</param>
        /// <param name="clock">RTP media clock.</param>
        /// <exception cref="ArgumentNullException">Is raised when <b>localEP</b>, <b>localEP</b> or <b>clock</b> is null reference.</exception>
        internal RTP_Session(RTP_MultimediaSession session,RTP_Address localEP,RTP_Clock clock)
        {
            if(session == null){
                throw new ArgumentNullException("session");
            }
            if(localEP == null){
                throw new ArgumentNullException("localEP");
            }
            if(clock == null){
                throw new ArgumentNullException("clock");
            }

            m_pSession  = session;
            m_pLocalEP  = localEP;
            m_pRtpClock = clock;

            m_pLocalSources = new List<RTP_Source_Local>();
            m_pTargets = new List<RTP_Address>();
            m_pMembers = new Dictionary<uint,RTP_Source>();
            m_pSenders = new Dictionary<uint,RTP_Source>();
            m_pConflictingEPs = new Dictionary<string,DateTime>();
            m_pPayloads = new KeyValueCollection<int,Codec>();
            
            m_pUdpDataReceivers = new List<UDP_DataReceiver>();
            m_pRtpSocket = new Socket(localEP.IP.AddressFamily,SocketType.Dgram,ProtocolType.Udp);
            m_pRtpSocket.Bind(localEP.RtpEP);
            m_pRtcpSocket = new Socket(localEP.IP.AddressFamily,SocketType.Dgram,ProtocolType.Udp);
            m_pRtcpSocket.Bind(localEP.RtcpEP);
                        
            m_pRtcpTimer = new TimerEx();
            m_pRtcpTimer.Elapsed += new System.Timers.ElapsedEventHandler(delegate(object sender,System.Timers.ElapsedEventArgs e){
                SendRtcp();
            });
            m_pRtcpTimer.AutoReset = false;
        }
Beispiel #3
0
        /// <summary>
        /// Calling constructor.
        /// </summary>
        /// <param name="stack">Reference to SIP stack.</param>
        /// <param name="sender">Initial INVITE sender.</param>
        /// <param name="session">Call RTP multimedia session.</param>
        /// <exception cref="ArgumentNullException">Is raised when <b>stack</b>,<b>sender</b> or <b>session</b> is null reference.</exception>
        internal SIP_Call(SIP_Stack stack,SIP_RequestSender sender,RTP_MultimediaSession session)
        {
            if(stack == null){
                throw new ArgumentNullException("stack");
            }
            if(sender == null){
                throw new ArgumentNullException("sender");
            }
            if(session == null){
                throw new ArgumentNullException("session");
            }

            m_pStack                = stack;
            m_pInitialInviteSender  = sender;
            m_pRtpMultimediaSession = session;

            m_pTags = new Dictionary<string,object>();

            m_pInitialInviteSender.Completed += new EventHandler(delegate(object s,EventArgs e){
                m_pInitialInviteSender = null;

                if(this.State == SIP_CallState.Terminating){
                    SetState(SIP_CallState.Terminated);
                }
            });

            m_CallState = SIP_CallState.Calling;
        }
Beispiel #4
0
        private RTP_Session CreateRtpSession(RTP_MultimediaSession rtpMultimediaSession)
        {
            if (rtpMultimediaSession == null)
            {
                throw new ArgumentNullException("rtpMultimediaSession");
            }

            //--- Search RTP IP -------------------------------------------------------//
            IPAddress rtpIP = null;
            foreach (IPAddress ip in Dns.GetHostAddresses(""))
            {
                if (ip.AddressFamily == System.Net.Sockets.AddressFamily.InterNetwork)
                {
                    rtpIP = ip;
                    break;
                }
            }
            if (rtpIP == null)
            {
                throw new Exception("None of the network connection is available.");
            }
            //------------------------------------------------------------------------//

            // Search free ports for RTP session.
            for (int i = 0; i < 100; i += 2)
            {
                try
                {
                    return rtpMultimediaSession.CreateSession(new RTP_Address(rtpIP, m_RtpBasePort, m_RtpBasePort + 1), new RTP_Clock(1, 8000));
                }
                catch
                {
                    m_RtpBasePort += 2;
                }
            }

            return null;
        }
Beispiel #5
0
        private void Call(SIP_t_NameAddress from, SIP_t_NameAddress to)
        {
            if (from == null)
            {
                throw new ArgumentNullException("from");
            }
            if (to == null)
            {
                throw new ArgumentNullException("to");
            }

            #region Setup RTP session

            RTP_MultimediaSession rtpMultimediaSession = new RTP_MultimediaSession(RTP_Utils.GenerateCNAME());
            RTP_Session rtpSession = CreateRtpSession(rtpMultimediaSession);
            // Port search failed.
            if (rtpSession == null)
            {
                throw new Exception("Calling not possible, RTP session failed to allocate IP end points.");
            }

            if (m_IsDebug)
            {
                wfrm_RTP_Debug rtpDebug = new wfrm_RTP_Debug(rtpMultimediaSession);
                rtpDebug.Show();
            }

            #endregion

            #region Create SDP offer

            SDP_Message sdpOffer = new SDP_Message();
            sdpOffer.Version = "0";
            sdpOffer.Origin = new SDP_Origin("-", sdpOffer.GetHashCode(), 1, "IN", "IP4", System.Net.Dns.GetHostAddresses("")[0].ToString());
            sdpOffer.SessionName = "SIP Call";
            sdpOffer.Times.Add(new SDP_Time(0, 0));

            #region Add 1 audio stream

            SDP_MediaDescription mediaStream = new SDP_MediaDescription(SDP_MediaTypes.audio, 0, 1, "RTP/AVP", null);

            rtpSession.NewReceiveStream += delegate(object s, RTP_ReceiveStreamEventArgs e)
            {
                AudioOut_RTP audioOut = new AudioOut_RTP(m_pAudioOutDevice, e.Stream, m_pAudioCodecs);
                audioOut.Start();
                mediaStream.Tags["rtp_audio_out"] = audioOut;
            };

            if (!HandleNAT(mediaStream, rtpSession))
            {
                throw new Exception("Calling not possible, because of NAT or firewall restrictions.");
            }

            foreach (KeyValuePair<int, AudioCodec> entry in m_pAudioCodecs)
            {
                mediaStream.Attributes.Add(new SDP_Attribute("rtpmap", entry.Key + " " + entry.Value.Name + "/" + entry.Value.CompressedAudioFormat.SamplesPerSecond));
                mediaStream.MediaFormats.Add(entry.Key.ToString());
            }
            mediaStream.Attributes.Add(new SDP_Attribute("ptime", "20"));
            mediaStream.Attributes.Add(new SDP_Attribute("sendrecv", ""));
            mediaStream.Tags["rtp_session"] = rtpSession;
            mediaStream.Tags["audio_codecs"] = m_pAudioCodecs;
            sdpOffer.MediaDescriptions.Add(mediaStream);

            #endregion

            #endregion

            // Create INVITE request.
            SIP_Request invite = m_pStack.CreateRequest(SIP_Methods.INVITE, to, from);
            invite.ContentType = "application/sdp";
            invite.Data = sdpOffer.ToByte();

            SIP_RequestSender sender = m_pStack.CreateRequestSender(invite);

            // Create call.
            m_pCall = new SIP_Call(m_pStack, sender, rtpMultimediaSession);
            m_pCall.LocalSDP = sdpOffer;
            m_pCall.StateChanged += new EventHandler(m_pCall_StateChanged);

            bool finalResponseSeen = false;
            List<SIP_Dialog_Invite> earlyDialogs = new List<SIP_Dialog_Invite>();
            sender.ResponseReceived += delegate(object s, SIP_ResponseReceivedEventArgs e)
            {
                // Skip 2xx retransmited response.
                if (finalResponseSeen)
                {
                    return;
                }
                if (e.Response.StatusCode >= 200)
                {
                    finalResponseSeen = true;
                }

                try
                {
                    #region Provisional

                    if (e.Response.StatusCodeType == SIP_StatusCodeType.Provisional)
                    {
                        /* RFC 3261 13.2.2.1.
                            Zero, one or multiple provisional responses may arrive before one or
                            more final responses are received.  Provisional responses for an
                            INVITE request can create "early dialogs".  If a provisional response
                            has a tag in the To field, and if the dialog ID of the response does
                            not match an existing dialog, one is constructed using the procedures
                            defined in Section 12.1.2.
                        */
                        if (e.Response.StatusCode > 100 && e.Response.To.Tag != null)
                        {
                            earlyDialogs.Add((SIP_Dialog_Invite)e.GetOrCreateDialog);
                        }

                        // 180_Ringing.
                        if (e.Response.StatusCode == 180)
                        {
                            //m_pPlayer.Play(ResManager.GetStream("ringing.wav"), 10);

                            // We need BeginInvoke here, otherwise we block client transaction.
                            m_pStatusBar.BeginInvoke(new MethodInvoker(delegate()
                            {
                                m_pStatusBar.Items[0].Text = "Ringing";
                            }));
                        }
                    }

                    #endregion

                    #region Success

                    else if (e.Response.StatusCodeType == SIP_StatusCodeType.Success)
                    {
                        SIP_Dialog dialog = e.GetOrCreateDialog;

                        /* Exit all all other dialogs created by this call (due to forking).
                           That is not defined in RFC but, since UAC can send BYE to early and confirmed dialogs, 
                           all this is 100% valid.
                        */
                        foreach (SIP_Dialog_Invite d in earlyDialogs.ToArray())
                        {
                            if (!d.Equals(dialog))
                            {
                                d.Terminate("Another forking leg accepted.", true);
                            }
                        }

                        m_pCall.InitCalling(dialog, sdpOffer);

                        // Remote-party provided SDP.
                        if (e.Response.ContentType != null && e.Response.ContentType.ToLower().IndexOf("application/sdp") > -1)
                        {
                            try
                            {
                                // SDP offer. We sent offerless INVITE, we need to send SDP answer in ACK request.'
                                if (e.ClientTransaction.Request.ContentType == null || e.ClientTransaction.Request.ContentType.ToLower().IndexOf("application/sdp") == -1)
                                {
                                    // Currently we never do it, so it never happens. This is place holder, if we ever support it.
                                }
                                // SDP answer to our offer.
                                else
                                {
                                    // This method takes care of ACK sending and 2xx response retransmission ACK sending.
                                    HandleAck(m_pCall.Dialog, e.ClientTransaction);

                                    ProcessMediaAnswer(m_pCall, m_pCall.LocalSDP, SDP_Message.Parse(Encoding.UTF8.GetString(e.Response.Data)));
                                }
                            }
                            catch
                            {
                                m_pCall.Terminate("SDP answer parsing/processing failed.");
                            }
                        }
                        else
                        {
                            // If we provided SDP offer, there must be SDP answer.
                            if (e.ClientTransaction.Request.ContentType != null && e.ClientTransaction.Request.ContentType.ToLower().IndexOf("application/sdp") > -1)
                            {
                                m_pCall.Terminate("Invalid 2xx response, required SDP answer is missing.");
                            }
                        }

                        // Stop ringing.
                        m_pPlayer.Stop();
                    }

                    #endregion

                    #region Failure

                    else
                    {
                        /* RFC 3261 13.2.2.3.
                            All early dialogs are considered terminated upon reception of the non-2xx final response.
                        */
                        foreach (SIP_Dialog_Invite dialog in earlyDialogs.ToArray())
                        {
                            dialog.Terminate("All early dialogs are considered terminated upon reception of the non-2xx final response. (RFC 3261 13.2.2.3)", false);
                        }

                        // We need BeginInvoke here, otherwise we block client transaction while message box open.
                        if (m_pCall.State != SIP_CallState.Terminating)
                        {
                            this.BeginInvoke(new MethodInvoker(delegate()
                            {
                                m_pConnect.Image = global::PowerSDR.Properties.Resources.call;
                                connected = false;
                                MessageBox.Show("Calling failed: " + e.Response.StatusCode_ReasonPhrase, "Error:", MessageBoxButtons.OK, MessageBoxIcon.Error);
                            }));
                        }

                        // We need BeginInvoke here, otherwise we block client transaction.
                        m_pStatusBar.BeginInvoke(new MethodInvoker(delegate()
                        {
                            m_pStatusBar.Items[0].Text = "";
                        }));
                        // Stop calling or ringing.
                        m_pPlayer.Stop();

                        // Terminate call.
                        m_pCall.Terminate("Remote party rejected a call.", false);
                    }

                    #endregion
                }
                catch (Exception x)
                {
                    // We need BeginInvoke here, otherwise we block client transaction while message box open.
                    this.BeginInvoke(new MethodInvoker(delegate()
                    {
                        MessageBox.Show("Error: " + x.Message, "Error:", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    }));
                }
            };

            m_pStatusBar.Items[0].Text = "Calling";
            m_pStatusBar.Items[1].Text = "00:00:00";
            //m_pPlayer.Play(ResManager.GetStream("calling.wav"), 10);

            // Start calling.
            sender.Start();
        }
Beispiel #6
0
        /// <summary>
        /// Incoming call constructor.
        /// </summary>
        /// <param name="stack">Reference to SIP stack.</param>
        /// <param name="dialog">Reference SIP dialog.</param>
        /// <param name="session">Call RTP multimedia session.</param>
        /// <param name="localSDP">Local SDP.</param>
        /// <exception cref="ArgumentNullException">Is raised when <b>stack</b>,<b>dialog</b>,<b>session</b> or <b>localSDP</b> is null reference.</exception>
        internal SIP_Call(SIP_Stack stack, SIP_Dialog dialog, RTP_MultimediaSession session, SDP_Message localSDP)
        {
            if (stack == null)
            {
                throw new ArgumentNullException("stack");
            }
            if (dialog == null)
            {
                throw new ArgumentNullException("dialog");
            }
            if (session == null)
            {
                throw new ArgumentNullException("session");
            }
            if (localSDP == null)
            {
                throw new ArgumentNullException("localSDP");
            }

            m_pStack = stack;
            m_pDialog = (SIP_Dialog_Invite)dialog;
            m_pRtpMultimediaSession = session;
            m_pLocalSDP = localSDP;

            m_StartTime = DateTime.Now;
            m_pFlow = dialog.Flow;
            dialog.StateChanged += new EventHandler(m_pDialog_StateChanged);

            SetState(SIP_CallState.Active);

            // Start ping timer.
            m_pKeepAliveTimer = new TimerEx(40000);
            m_pKeepAliveTimer.Elapsed += new System.Timers.ElapsedEventHandler(m_pKeepAliveTimer_Elapsed);
            m_pKeepAliveTimer.Enabled = true;
        }
Beispiel #7
0
        private void ProcessMediaOffer(SIP_Dialog dialog, SIP_ServerTransaction transaction, RTP_MultimediaSession rtpMultimediaSession, SDP_Message offer, SDP_Message localSDP)
        {
            if (dialog == null)
            {
                throw new ArgumentNullException("dialog");
            }
            if (transaction == null)
            {
                throw new ArgumentNullException("transaction");
            }
            if (rtpMultimediaSession == null)
            {
                throw new ArgumentNullException("rtpMultimediaSession");
            }
            if (offer == null)
            {
                throw new ArgumentNullException("offer");
            }
            if (localSDP == null)
            {
                throw new ArgumentNullException("localSDP");
            }

            try
            {
                #region SDP basic validation

                // Version field must exist.
                if (offer.Version == null)
                {
                    transaction.SendResponse(m_pStack.CreateResponse(SIP_ResponseCodes.x500_Server_Internal_Error + ": Invalid SDP answer: Required 'v'(Protocol Version) field is missing.", transaction.Request));

                    return;
                }

                // Origin field must exist.
                if (offer.Origin == null)
                {
                    transaction.SendResponse(m_pStack.CreateResponse(SIP_ResponseCodes.x500_Server_Internal_Error + ": Invalid SDP answer: Required 'o'(Origin) field is missing.", transaction.Request));

                    return;
                }

                // Session Name field.

                // Check That global 'c' connection attribute exists or otherwise each enabled media stream must contain one.
                if (offer.Connection == null)
                {
                    for (int i = 0; i < offer.MediaDescriptions.Count; i++)
                    {
                        if (offer.MediaDescriptions[i].Connection == null)
                        {
                            transaction.SendResponse(m_pStack.CreateResponse(SIP_ResponseCodes.x500_Server_Internal_Error + ": Invalid SDP answer: Global or per media stream no: " + i + " 'c'(Connection) attribute is missing.", transaction.Request));

                            return;
                        }
                    }
                }

                #endregion

                // Re-INVITE media streams count must be >= current SDP streams.
                if (localSDP.MediaDescriptions.Count > offer.MediaDescriptions.Count)
                {
                    transaction.SendResponse(m_pStack.CreateResponse(SIP_ResponseCodes.x500_Server_Internal_Error + ": re-INVITE SDP offer media stream count must be >= current session stream count.", transaction.Request));

                    return;
                }

                bool audioAccepted = false;
                // Process media streams info.
                for (int i = 0; i < offer.MediaDescriptions.Count; i++)
                {
                    SDP_MediaDescription offerMedia = offer.MediaDescriptions[i];
                    SDP_MediaDescription answerMedia = (localSDP.MediaDescriptions.Count > i ? localSDP.MediaDescriptions[i] : null);

                    // Disabled stream.
                    if (offerMedia.Port == 0)
                    {
                        // Remote-party offered new disabled stream.
                        if (answerMedia == null)
                        {
                            // Just copy offer media stream data to answer and set port to zero.
                            localSDP.MediaDescriptions.Add(offerMedia);
                            localSDP.MediaDescriptions[i].Port = 0;
                        }
                        // Existing disabled stream or remote party disabled it.
                        else
                        {
                            answerMedia.Port = 0;

                            #region Cleanup active RTP stream and it's resources, if it exists

                            // Dispose existing RTP session.
                            if (answerMedia.Tags.ContainsKey("rtp_session"))
                            {
                                ((RTP_Session)offerMedia.Tags["rtp_session"]).Dispose();
                                answerMedia.Tags.Remove("rtp_session");
                            }

                            // Release UPnPports if any.
                            if (answerMedia.Tags.ContainsKey("upnp_rtp_map"))
                            {
                                try
                                {
                                    m_pUPnP.DeletePortMapping((UPnP_NAT_Map)answerMedia.Tags["upnp_rtp_map"]);
                                }
                                catch
                                {
                                }
                                answerMedia.Tags.Remove("upnp_rtp_map");
                            }
                            if (answerMedia.Tags.ContainsKey("upnp_rtcp_map"))
                            {
                                try
                                {
                                    m_pUPnP.DeletePortMapping((UPnP_NAT_Map)answerMedia.Tags["upnp_rtcp_map"]);
                                }
                                catch
                                {
                                }
                                answerMedia.Tags.Remove("upnp_rtcp_map");
                            }

                            #endregion
                        }
                    }
                    // Remote-party wants to communicate with this stream.
                    else
                    {
                        // See if we can support this stream.
                        if (!audioAccepted && CanSupportMedia(offerMedia))
                        {
                            // New stream.
                            if (answerMedia == null)
                            {
                                answerMedia = new SDP_MediaDescription(SDP_MediaTypes.audio, 0, 2, "RTP/AVP", null);
                                localSDP.MediaDescriptions.Add(answerMedia);
                            }

                            #region Build audio codec map with codecs which we support

                            Dictionary<int, AudioCodec> audioCodecs = GetOurSupportedAudioCodecs(offerMedia);
                            answerMedia.MediaFormats.Clear();
                            answerMedia.Attributes.Clear();
                            foreach (KeyValuePair<int, AudioCodec> entry in audioCodecs)
                            {
                                answerMedia.Attributes.Add(new SDP_Attribute("rtpmap", entry.Key + " " + entry.Value.Name + "/" + entry.Value.CompressedAudioFormat.SamplesPerSecond));
                                answerMedia.MediaFormats.Add(entry.Key.ToString());
                            }
                            answerMedia.Attributes.Add(new SDP_Attribute("ptime", "20"));
                            answerMedia.Tags["audio_codecs"] = audioCodecs;

                            #endregion

                            #region Create/modify RTP session

                            // RTP session doesn't exist, create it.
                            if (!answerMedia.Tags.ContainsKey("rtp_session"))
                            {
                                RTP_Session rtpSess = CreateRtpSession(rtpMultimediaSession);
                                // RTP session creation failed,disable this stream.
                                if (rtpSess == null)
                                {
                                    answerMedia.Port = 0;

                                    break;
                                }
                                answerMedia.Tags.Add("rtp_session", rtpSess);

                                rtpSess.NewReceiveStream += delegate(object s, RTP_ReceiveStreamEventArgs e)
                                {
                                    if (answerMedia.Tags.ContainsKey("rtp_audio_out"))
                                    {
                                        ((AudioOut_RTP)answerMedia.Tags["rtp_audio_out"]).Dispose();
                                    }

                                    AudioOut_RTP audioOut = new AudioOut_RTP(m_pAudioOutDevice, e.Stream, audioCodecs);
                                    audioOut.Start();
                                    answerMedia.Tags["rtp_audio_out"] = audioOut;
                                };

                                // NAT
                                if (!HandleNAT(answerMedia, rtpSess))
                                {
                                    // NAT handling failed,disable this stream.
                                    answerMedia.Port = 0;

                                    break;
                                }
                            }

                            RTP_StreamMode offerStreamMode = GetRtpStreamMode(offer, offerMedia);
                            if (offerStreamMode == RTP_StreamMode.Inactive)
                            {
                                answerMedia.SetStreamMode("inactive");
                            }
                            else if (offerStreamMode == RTP_StreamMode.Receive)
                            {
                                answerMedia.SetStreamMode("sendonly");
                            }
                            else if (offerStreamMode == RTP_StreamMode.Send)
                            {
                                answerMedia.SetStreamMode("recvonly");
                            }
                            else if (offerStreamMode == RTP_StreamMode.SendReceive)
                            {
                                answerMedia.SetStreamMode("sendrecv");
                            }

                            RTP_Session rtpSession = (RTP_Session)answerMedia.Tags["rtp_session"];
                            rtpSession.Payload = Convert.ToInt32(answerMedia.MediaFormats[0]);
                            rtpSession.StreamMode = GetRtpStreamMode(localSDP, answerMedia);
                            rtpSession.RemoveTargets();
                            if (GetSdpHost(offer, offerMedia) != "0.0.0.0")
                            {
                                rtpSession.AddTarget(GetRtpTarget(offer, offerMedia));
                            }
                            rtpSession.Start();

                            #endregion

                            #region Create/modify audio-in source

                            if (!answerMedia.Tags.ContainsKey("rtp_audio_in"))
                            {
                                AudioIn_RTP rtpAudioIn = new AudioIn_RTP(m_pAudioInDevice, 20, audioCodecs, rtpSession.CreateSendStream());
                                rtpAudioIn.Start();
                                answerMedia.Tags.Add("rtp_audio_in", rtpAudioIn);
                            }
                            else
                            {
                                ((AudioIn_RTP)answerMedia.Tags["rtp_audio_in"]).AudioCodecs = audioCodecs;
                            }

                            #endregion

                            audioAccepted = true;
                        }
                        // We don't accept this stream, so disable it.
                        else
                        {
                            // Just copy offer media stream data to answer and set port to zero.

                            // Delete exisiting media stream.
                            if (answerMedia != null)
                            {
                                localSDP.MediaDescriptions.RemoveAt(i);
                            }
                            localSDP.MediaDescriptions.Add(offerMedia);
                            localSDP.MediaDescriptions[i].Port = 0;
                        }
                    }
                }

                #region Create and send 2xx response

                SIP_Response response = m_pStack.CreateResponse(SIP_ResponseCodes.x200_Ok, transaction.Request, transaction.Flow);
                //response.Contact = SIP stack will allocate it as needed;
                response.ContentType = "application/sdp";
                response.Data = localSDP.ToByte();

                transaction.SendResponse(response);

                // Start retransmitting 2xx response, while ACK receives.
                Handle2xx(dialog, transaction);

                // REMOVE ME: 27.11.2010
                // Start retransmitting 2xx response, while ACK receives.
                //m_pInvite2xxMgr.Add(dialog,transaction);

                #endregion
            }
            catch (Exception x)
            {
                transaction.SendResponse(m_pStack.CreateResponse(SIP_ResponseCodes.x500_Server_Internal_Error + ": " + x.Message, transaction.Request));
            }
        }
Beispiel #8
0
        private void m_pStack_RequestReceived(object sender, SIP_RequestReceivedEventArgs e)
        {
            try
            {
                #region CANCEL

                if (e.Request.RequestLine.Method == SIP_Methods.CANCEL)
                {
                    SIP_ServerTransaction trToCancel = m_pStack.TransactionLayer.MatchCancelToTransaction(e.Request);

                    if (trToCancel != null)
                    {
                        trToCancel.Cancel();
                        e.ServerTransaction.SendResponse(m_pStack.CreateResponse(SIP_ResponseCodes.x200_Ok, e.Request));
                    }
                    else
                    {
                        e.ServerTransaction.SendResponse(m_pStack.CreateResponse(SIP_ResponseCodes.x481_Call_Transaction_Does_Not_Exist, e.Request));
                    }
                }

                #endregion

                #region BYE

                else if (e.Request.RequestLine.Method == SIP_Methods.BYE)
                {
                    // Currently we match BYE to dialog and it processes it,
                    // so BYE what reaches here doesnt match to any dialog.

                    e.ServerTransaction.SendResponse(m_pStack.CreateResponse(SIP_ResponseCodes.x481_Call_Transaction_Does_Not_Exist, e.Request));
                }

                #endregion

                #region INVITE

                else if (e.Request.RequestLine.Method == SIP_Methods.INVITE)
                {

                    #region Incoming call

                    if (e.Dialog == null)
                    {
                        #region Validate incoming call

                        // We don't accept more than 1 call at time.
                        if (connected || m_pCall != null)
                        {
                            e.ServerTransaction.SendResponse(m_pStack.CreateResponse(SIP_ResponseCodes.x600_Busy_Everywhere, e.Request));
                            return;
                        }

                        // We don't accept SDP offerless calls.
                        if (e.Request.ContentType == null || e.Request.ContentType.ToLower().IndexOf("application/sdp") == -1)
                        {
                            e.ServerTransaction.SendResponse(m_pStack.CreateResponse(SIP_ResponseCodes.x606_Not_Acceptable + 
                                ": We don't accpet SDP offerless calls.", e.Request));
                            return;
                        }

                        SDP_Message sdpOffer = SDP_Message.Parse(Encoding.UTF8.GetString(e.Request.Data));

                        // Check if we can accept any media stream.
                        bool canAccept = false;
                        foreach (SDP_MediaDescription media in sdpOffer.MediaDescriptions)
                        {
                            if (CanSupportMedia(media))
                            {
                                canAccept = true;

                                break;
                            }
                        }

                        if (!canAccept)
                        {
                            e.ServerTransaction.SendResponse(m_pStack.CreateResponse(SIP_ResponseCodes.x606_Not_Acceptable, e.Request));

                            return;
                        }

                        #endregion

                        // Send ringing to remote-party.
                        SIP_Response responseRinging = m_pStack.CreateResponse(SIP_ResponseCodes.x180_Ringing, e.Request, e.Flow);
                        responseRinging.To.Tag = SIP_Utils.CreateTag();
                        e.ServerTransaction.SendResponse(responseRinging);

                        SIP_Dialog_Invite dialog = (SIP_Dialog_Invite)m_pStack.TransactionLayer.GetOrCreateDialog(e.ServerTransaction, responseRinging);

                        // We need invoke here, otherwise we block SIP stack RequestReceived event while incoming call UI showed.
                        this.BeginInvoke(new MethodInvoker(delegate()
                        {
                            try
                            {
                                //m_pPlayer.Play(ResManager.GetStream("ringing.wav"), 20);

                                // Call accepted.
                                RTP_MultimediaSession rtpMultimediaSession = new RTP_MultimediaSession(RTP_Utils.GenerateCNAME());

                                // Build local SDP template
                                SDP_Message sdpLocal = new SDP_Message();
                                sdpLocal.Version = "0";
                                sdpLocal.Origin = new SDP_Origin("-", sdpLocal.GetHashCode(), 1, "IN", "IP4", 
                                    System.Net.Dns.GetHostAddresses("")[0].ToString());
                                sdpLocal.SessionName = "SIP Call";
                                sdpLocal.Times.Add(new SDP_Time(0, 0));

                                ProcessMediaOffer(dialog, e.ServerTransaction, rtpMultimediaSession, sdpOffer, sdpLocal);

                                // Create call.
                                m_pCall = new SIP_Call(m_pStack, dialog, rtpMultimediaSession, sdpLocal);
                                m_pCall.StateChanged += new EventHandler(m_pCall_StateChanged);
                                m_pCall_StateChanged(m_pCall, new EventArgs());

                                if (m_IsDebug)
                                {
                                    wfrm_RTP_Debug rtpDebug = new wfrm_RTP_Debug(m_pCall.RtpMultimediaSession);
                                    rtpDebug.Show();
                                }

                                connected = true;

                            }
                            catch (Exception x1)
                            {
                                MessageBox.Show("Error: " + x1.Message, "Error:", MessageBoxButtons.OK, MessageBoxIcon.Error);
                                connected = false;
                                m_pConnect.Image = global::PowerSDR.Properties.Resources.call;
                            }
                        }));
                    }

                    #endregion

                    #region Re-INVITE

                    else
                    {
                        try
                        {
                            // Remote-party provided SDP offer.
                            if (e.Request.ContentType != null && e.Request.ContentType.ToLower().IndexOf("application/sdp") > -1)
                            {
                                ProcessMediaOffer(m_pCall.Dialog, e.ServerTransaction, m_pCall.RtpMultimediaSession, 
                                    SDP_Message.Parse(Encoding.UTF8.GetString(e.Request.Data)), m_pCall.LocalSDP);

                                // Remote-party is holding a call.
                                if (IsRemotePartyHolding(SDP_Message.Parse(Encoding.UTF8.GetString(e.Request.Data))))
                                {
                                    // We need invoke here, we are running on thread pool thread.
                                    this.BeginInvoke(new MethodInvoker(delegate()
                                    {
                                        m_pStatusBar.Items[0].Text = "Remote party holding a call";
                                    }));

                                    //m_pPlayer.Play(ResManager.GetStream("onhold.wav"), 20);
                                }
                                // Call is active.
                                else
                                {
                                    // We need invoke here, we are running on thread pool thread.
                                    this.BeginInvoke(new MethodInvoker(delegate()
                                    {
                                        m_pStatusBar.Items[0].Text = "Call established";
                                    }));

                                    m_pPlayer.Stop();
                                }
                            }
                            // Error: Re-INVITE can't be SDP offerless.
                            else
                            {
                                e.ServerTransaction.SendResponse(m_pStack.CreateResponse(SIP_ResponseCodes.x500_Server_Internal_Error + 
                                    ": Re-INVITE must contain SDP offer.", e.Request));
                            }
                        }
                        catch (Exception x1)
                        {
                            e.ServerTransaction.SendResponse(m_pStack.CreateResponse(SIP_ResponseCodes.x500_Server_Internal_Error + 
                                ": " + x1.Message, e.Request));
                        }
                    }

                    #endregion
                }

                #endregion

                #region ACK

                else if (e.Request.RequestLine.Method == SIP_Methods.ACK)
                {
                    // Abandoned ACK, just skip it.
                }

                #endregion

                #region MESSAGE

                else if (e.Request.RequestLine.Method == SIP_Methods.MESSAGE)
                {
                    e.ServerTransaction.SendResponse(m_pStack.CreateResponse(SIP_ResponseCodes.x200_Ok, e.Request));
                    byte[] msg = e.Request.Data;
                    ASCIIEncoding buffer = new ASCIIEncoding();
                    string data = buffer.GetString(msg);
                    string answer = "";

                    if (debug && !console.ConsoleClosing)
                        console.Invoke(new DebugCallbackFunction(console.DebugCallback), data);

                    if (op_mode == VoIP_mode.Server)
                        answer = console.CAT_server_socket.ProcessData(msg, msg.Length);
                    else
                    {
                        if (console.CAT_client_socket.ProcessData(msg, msg.Length, out answer))
                            SendMessage(answer, "CAT");
                    }
                }

                #endregion

                #region Other

                else
                {
                    // ACK is response less method.
                    if (e.Request.RequestLine.Method != SIP_Methods.ACK)
                    {
                        e.ServerTransaction.SendResponse(m_pStack.CreateResponse(SIP_ResponseCodes.x501_Not_Implemented, e.Request));
                    }
                }

                #endregion
            }
            catch
            {
                e.ServerTransaction.SendResponse(m_pStack.CreateResponse(SIP_ResponseCodes.x500_Server_Internal_Error, e.Request));
            }
        }
Beispiel #9
0
        /// <summary>
        /// Cleans up any resources being used.
        /// </summary>
        public void Dispose()
        {
            if(m_IsDisposed){
                return;
            }
            m_IsDisposed = true;

            foreach(UDP_DataReceiver receiver in m_pUdpDataReceivers){
                receiver.Dispose();
            }
            m_pUdpDataReceivers = null;
            if(m_pRtcpTimer != null){
                m_pRtcpTimer.Dispose();
                m_pRtcpTimer = null;
            }
            m_pSession = null;
            m_pLocalEP = null;
            m_pTargets = null;
            foreach(RTP_Source_Local source in m_pLocalSources.ToArray()){
                source.Dispose();
            }
            m_pLocalSources = null;
            m_pRtcpSource = null;
            foreach(RTP_Source source in m_pMembers.Values){
                source.Dispose();
            }
            m_pMembers = null;
            m_pSenders = null;
            m_pConflictingEPs = null;
            m_pRtpSocket.Close();
            m_pRtpSocket = null;
            m_pRtcpSocket.Close();
            m_pRtcpSocket = null;
            m_pUdpDataReceivers = null;

            OnDisposed();

            this.Disposed = null;
            this.Closed = null;
            this.NewSendStream = null;
            this.NewReceiveStream = null;
        }
Beispiel #10
0
        private void Robot_FormClosed(object sender, FormClosedEventArgs e)
        {
            CloseFile();
            //audio stream
            m_IsRunning = false;
            if (m_pRtpSession != null)
            {
                m_pRtpSession.Close(null);
                m_pRtpSession = null;
            }
            if (m_pWaveOut != null)
            {
                m_pWaveOut.Dispose();
                m_pWaveOut = null;
            }
            if (m_pRecordStream != null)
            {
                m_pRecordStream.Dispose();
                m_pRecordStream = null;
            }
            //audio stream
            //Robot1.ActiveForm.Dispose();
            try
            {

                ThreadCheckStat.Abort();
                mjpegsmall.smallcamClose();
            }
            catch
            {
            }
        }
Beispiel #11
0
        //Battery Monitor
        //AUDIO STREAM OLD
        private void m_pToggleRun_Click(object sender, EventArgs e)
        {
            if (m_IsRunning)
            {
                m_IsRunning = false;
                m_IsSendingTest = false;

                m_pRtpSession.Dispose();
                m_pRtpSession = null;

                m_pWaveOut.Dispose();
                m_pWaveOut = null;

                if (m_pRecordStream != null)
                {
                    m_pRecordStream.Dispose();
                    m_pRecordStream = null;
                }

                m_pOutDevices.Enabled = true;
                m_pToggleRun.Text = "Start";
                m_pRecord.Enabled = true;
                m_pRecordFile.Enabled = true;
                m_pRecordFileBrowse.Enabled = true;
                m_pRemoteIP.Enabled = false;
                m_pRemotePort.Enabled = false;
                m_pCodec.Enabled = false;
                m_pToggleMic.Text = "Send";
                m_pToggleMic.Enabled = false;
                m_pSendTestSound.Enabled = false;
                m_pSendTestSound.Text = "Send";
                m_pPlayTestSound.Enabled = false;
                m_pPlayTestSound.Text = "Play";
            }
            else
            {
                if (m_pOutDevices.SelectedIndex == -1)
                {
                    MessageBox.Show(this, "Please select output device !", "Error:", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    return;
                }
                if (m_pRecord.Checked && m_pRecordFile.Text == "")
                {
                    MessageBox.Show(this, "Please specify record file !", "Error:", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    return;
                }

                if (m_pRecord.Checked)
                {
                    m_pRecordStream = File.Create(m_pRecordFile.Text);
                }

                m_IsRunning = true;

                m_pWaveOut = new AudioOut(AudioOut.Devices[m_pOutDevices.SelectedIndex], 8000, 16, 1);

                m_pRtpSession = new RTP_MultimediaSession(RTP_Utils.GenerateCNAME());
                // --- Debug -----
                //wfrm_RTP_Debug frmRtpDebug = new wfrm_RTP_Debug(m_pRtpSession);
                //frmRtpDebug.Show();
                //-----------------
                m_pRtpSession.CreateSession(new RTP_Address(IPAddress.Parse(m_pLocalIP.Text), (int)m_pLocalPort.Value, (int)m_pLocalPort.Value + 1), new RTP_Clock(0, 8000));
                m_pRtpSession.Sessions[0].AddTarget(new RTP_Address(IPAddress.Parse(m_pRemoteIP.Text), (int)m_pRemotePort.Value, (int)m_pRemotePort.Value + 1));
                m_pRtpSession.Sessions[0].NewSendStream += new EventHandler<RTP_SendStreamEventArgs>(m_pRtpSession_NewSendStream);
                m_pRtpSession.Sessions[0].NewReceiveStream += new EventHandler<RTP_ReceiveStreamEventArgs>(m_pRtpSession_NewReceiveStream);
                m_pRtpSession.Sessions[0].Payload = 8;
                m_pRtpSession.Sessions[0].Start();

                m_pOutDevices.Enabled = false;
                m_pToggleRun.Text = "Stop";
                m_pRecord.Enabled = false;
                m_pRecordFile.Enabled = false;
                m_pRecordFileBrowse.Enabled = false;
                m_pRemoteIP.Enabled = true;
                m_pRemotePort.Enabled = true;
                m_pCodec.Enabled = true;
                m_pToggleMic.Enabled = true;
                m_pSendTestSound.Enabled = true;
                m_pSendTestSound.Text = "Send";
                m_pPlayTestSound.Enabled = true;
                m_pPlayTestSound.Text = "Play";
            }
            m_pCodec.SelectedIndex = 0;
        }
Beispiel #12
0
        /// <summary>
        /// Is called when SIP stack has received request.
        /// </summary>
        /// <param name="sender">Sender.</param>
        /// <param name="e">Event data.</param>
        private void m_pStack_RequestReceived(object sender,SIP_RequestReceivedEventArgs e)
        {
            try{
                #region CANCEL

                if(e.Request.RequestLine.Method == SIP_Methods.CANCEL){
                    /* RFC 3261 9.2.
                        If the UAS did not find a matching transaction for the CANCEL
                        according to the procedure above, it SHOULD respond to the CANCEL
                        with a 481 (Call Leg/Transaction Does Not Exist).
                  
                        Regardless of the method of the original request, as long as the
                        CANCEL matched an existing transaction, the UAS answers the CANCEL
                        request itself with a 200 (OK) response.
                    */

                    SIP_ServerTransaction trToCancel = m_pStack.TransactionLayer.MatchCancelToTransaction(e.Request);
                    if(trToCancel != null){
                        trToCancel.Cancel();
                        e.ServerTransaction.SendResponse(m_pStack.CreateResponse(SIP_ResponseCodes.x200_Ok,e.Request));
                    }
                    else{
                        e.ServerTransaction.SendResponse(m_pStack.CreateResponse(SIP_ResponseCodes.x481_Call_Transaction_Does_Not_Exist,e.Request));
                    }
                }

                #endregion

                #region BYE

                else if(e.Request.RequestLine.Method == SIP_Methods.BYE){
                    /* RFC 3261 15.1.2.
                        If the BYE does not match an existing dialog, the UAS core SHOULD generate a 481
                        (Call/Transaction Does Not Exist) response and pass that to the server transaction.
                    */

                    // Currently we match BYE to dialog and it processes it,
                    // so BYE what reaches here doesnt match to any dialog.

                    e.ServerTransaction.SendResponse(m_pStack.CreateResponse(SIP_ResponseCodes.x481_Call_Transaction_Does_Not_Exist,e.Request));
                }

                #endregion

                #region INVITE

                else if(e.Request.RequestLine.Method == SIP_Methods.INVITE){

                    #region Incoming call

                    if(e.Dialog == null){
                        #region Validate incoming call

                        // We don't accept more than 1 call at time.
                        if(m_pIncomingCallUI != null || m_pCall != null){
                            e.ServerTransaction.SendResponse(m_pStack.CreateResponse(SIP_ResponseCodes.x600_Busy_Everywhere,e.Request));

                            return;
                        }

                        // We don't accept SDP offerless calls.
                        if(e.Request.ContentType == null || e.Request.ContentType.ToLower().IndexOf("application/sdp") == -1){
                            e.ServerTransaction.SendResponse(m_pStack.CreateResponse(SIP_ResponseCodes.x606_Not_Acceptable + ": We don't accpet SDP offerless calls.",e.Request));

                            return;
                        }

                        SDP_Message sdpOffer = SDP_Message.Parse(Encoding.UTF8.GetString(e.Request.Data));

                        // Check if we can accept any media stream.
                        bool canAccept = false;
                        foreach(SDP_MediaDescription media in sdpOffer.MediaDescriptions){
                            if(CanSupportMedia(media)){
                                canAccept = true;

                                break;
                            }
                        }
                        if(!canAccept){
                            e.ServerTransaction.SendResponse(m_pStack.CreateResponse(SIP_ResponseCodes.x606_Not_Acceptable,e.Request));

                            return;
                        }
                        
                        #endregion
                                                                        
                        // Send ringing to remote-party.
                        SIP_Response responseRinging = m_pStack.CreateResponse(SIP_ResponseCodes.x180_Ringing,e.Request,e.Flow);
                        responseRinging.To.Tag = SIP_Utils.CreateTag();
                        e.ServerTransaction.SendResponse(responseRinging);

                        SIP_Dialog_Invite dialog = (SIP_Dialog_Invite)m_pStack.TransactionLayer.GetOrCreateDialog(e.ServerTransaction,responseRinging);
                                                
                        // We need invoke here, otherwise we block SIP stack RequestReceived event while incoming call UI showed.
                        this.BeginInvoke(new MethodInvoker(delegate(){
                            try{
                                m_pPlayer.Play(ResManager.GetStream("ringing.wav"),20);

                                // Show incoming call UI.
                                m_pIncomingCallUI = new wfrm_IncomingCall(e.ServerTransaction);
                                // Call accepted.
                                if(m_pIncomingCallUI.ShowDialog(this) == DialogResult.Yes){  
                                    RTP_MultimediaSession rtpMultimediaSession = new RTP_MultimediaSession(RTP_Utils.GenerateCNAME());

                                    // Build local SDP template
                                    SDP_Message sdpLocal = new SDP_Message();
                                    sdpLocal.Version = "0";
                                    sdpLocal.Origin = new SDP_Origin("-",sdpLocal.GetHashCode(),1,"IN","IP4",System.Net.Dns.GetHostAddresses("")[0].ToString());
                                    sdpLocal.SessionName = "SIP Call";            
                                    sdpLocal.Times.Add(new SDP_Time(0,0));
                           
                                    ProcessMediaOffer(dialog,e.ServerTransaction,rtpMultimediaSession,sdpOffer,sdpLocal);

                                    // Create call.
                                    m_pCall = new SIP_Call(m_pStack,dialog,rtpMultimediaSession,sdpLocal);
                                    m_pCall.StateChanged += new EventHandler(m_pCall_StateChanged);
                                    m_pCall_StateChanged(m_pCall,new EventArgs());

                                    if(m_IsDebug){
                                        wfrm_RTP_Debug rtpDebug = new wfrm_RTP_Debug(m_pCall.RtpMultimediaSession);
                                        rtpDebug.Show();
                                    }
                                }
                                // Call rejected.
                                else{
                                    // Transaction response is sent in call UI.

                                    dialog.Terminate(null,false);
                                }
                                m_pIncomingCallUI = null;
                                m_pPlayer.Stop();
                            }
                            catch(Exception x1){
                                MessageBox.Show("Error: " + x1.Message,"Error:",MessageBoxButtons.OK,MessageBoxIcon.Error);
                            }
                        }));
                    }

                    #endregion

                    #region Re-INVITE

                    else{
                        try{                                                        
                            // Remote-party provided SDP offer.
                            if(e.Request.ContentType != null && e.Request.ContentType.ToLower().IndexOf("application/sdp") > -1){
                                ProcessMediaOffer(m_pCall.Dialog,e.ServerTransaction,m_pCall.RtpMultimediaSession,SDP_Message.Parse(Encoding.UTF8.GetString(e.Request.Data)),m_pCall.LocalSDP);

                                // We are holding a call.
                                if(m_pToggleOnHold.Text == "Unhold"){
                                    // We don't need to do anything here.
                                }
                                // Remote-party is holding a call.
                                else if(IsRemotePartyHolding(SDP_Message.Parse(Encoding.UTF8.GetString(e.Request.Data)))){
                                    // We need invoke here, we are running on thread pool thread.
                                    this.BeginInvoke(new MethodInvoker(delegate(){
                                        m_pStatusBar.Items["text"].Text = "Remote party holding a call";                                    
                                    }));

                                    m_pPlayer.Play(ResManager.GetStream("onhold.wav"),20);
                                }
                                // Call is active.
                                else{
                                    // We need invoke here, we are running on thread pool thread.
                                    this.BeginInvoke(new MethodInvoker(delegate(){
                                        m_pStatusBar.Items["text"].Text = "Call established";                                    
                                    }));

                                    m_pPlayer.Stop();
                                }
                            }
                            // Error: Re-INVITE can't be SDP offerless.
                            else{
                                e.ServerTransaction.SendResponse(m_pStack.CreateResponse(SIP_ResponseCodes.x500_Server_Internal_Error + ": Re-INVITE must contain SDP offer.",e.Request));
                            }
                        }
                        catch(Exception x1){
                            e.ServerTransaction.SendResponse(m_pStack.CreateResponse(SIP_ResponseCodes.x500_Server_Internal_Error + ": " + x1.Message,e.Request));
                        }
                    }

                    #endregion
                }

                #endregion

                #region ACK

                else if(e.Request.RequestLine.Method == SIP_Methods.ACK){
                    // Abandoned ACK, just skip it.
                }

                #endregion

                #region Other

                else{
                    // ACK is response less method.
                    if(e.Request.RequestLine.Method != SIP_Methods.ACK){
                        e.ServerTransaction.SendResponse(m_pStack.CreateResponse(SIP_ResponseCodes.x501_Not_Implemented,e.Request));
                    }
                }

                #endregion
            }
            catch{
                e.ServerTransaction.SendResponse(m_pStack.CreateResponse(SIP_ResponseCodes.x500_Server_Internal_Error,e.Request));
            }
        }
Beispiel #13
0
        /// <summary>
        /// Default constructor.
        /// </summary>
        /// <param name="session">RTP multimedia session.</param>
        public wfrm_RTP_Debug(RTP_MultimediaSession session)
        {
            if(session == null){
                throw new ArgumentNullException("session");
            }

            m_pSession = session;

            InitUI();

            // Windows must be visible, otherwise we may get "window handle not created" if RTP session rises events before window gets visible.
            this.Visible = true;

            m_pSession.Error += new EventHandler<LumiSoft.Net.ExceptionEventArgs>(m_pSession_Error);
            m_pSession.SessionCreated += new EventHandler<LumiSoft.Net.EventArgs<RTP_Session>>(m_pSession_SessionCreated);
            m_pSession.NewParticipant += new EventHandler<RTP_ParticipantEventArgs>(m_pSession_NewParticipant);
            m_pSession.LocalParticipant.SourceAdded += new EventHandler<RTP_SourceEventArgs>(Participant_SourceAdded);
            m_pSession.LocalParticipant.SourceRemoved += new EventHandler<RTP_SourceEventArgs>(Participant_SourceRemoved);
            //m_pSession.Disposed

            m_pTimer = new Timer();
            m_pTimer.Interval = 1000;
            m_pTimer.Tick += new EventHandler(m_pTimer_Tick);
            m_pTimer.Enabled = true;

            foreach(RTP_Session s in m_pSession.Sessions){
                ComboBoxItem item = new ComboBoxItem("Session: " + s.GetHashCode(),new RTP_SessionStatistics(s));
                m_pSessions.Items.Add(item);
            }
            if(m_pSessions.Items.Count > 0){
                m_pSessions.SelectedIndex = 0;
            }
        }
        private void btnRestartConnection_Click_1(object sender, RoutedEventArgs e)
        {
            if (cbLocalIp.SelectedIndex < 0)
            {
                MessageBox.Show("Choose local IP");
                return;
            }

            IsConnected = true;
            InitializeClient();
            InitializeServer();
            /*InitializeSoundSender();
            InitializeSoundReceiver();*/
            if (m_IsRunning)
            {
                m_IsRunning = false;
                m_IsSendingTest = false;

                m_pRtpSession.Dispose();
                m_pRtpSession = null;

                m_pWaveOut.Dispose();
                m_pWaveOut = null;
            }
            else
            {
                m_IsRunning = true;

                switch (_selectedCodec)
                {
                    case "PCMU":
                        m_pActiveCodec = new PCMU();
                        break;
                    case "PCMA":
                    default:
                        m_pActiveCodec = new PCMA();
                        break;
                }

                var selectedOutDevice = cbAudioOutDevices.SelectedItem as AudioOutDevice;
                m_pWaveOut = new AudioOut(selectedOutDevice, _samplesPerSecond, _bitsPerSample, 1); // 1 - one channel (mono)
                m_pRtpSession = new RTP_MultimediaSession(RTP_Utils.GenerateCNAME());

                string localIp = cbLocalIp.SelectedItem.ToString();
                string partnerIp = tbxPartnerIp.Text;
                int k = string.Compare(localIp, partnerIp);

                m_pRtpSession.CreateSession(new RTP_Address(IPAddress.Parse(cbLocalIp.SelectedItem.ToString()), (int)10000 + k * 500/*m_pLocalPort.Value*/, (int)/*m_pLocalPort.Value*/10000 + k * 500 + 1), new RTP_Clock(0, _samplesPerSecond));
                m_pRtpSession.Sessions[0].AddTarget(new RTP_Address(IPAddress.Parse(tbxPartnerIp.Text), (int)/*m_pRemotePort.Value*/10000 - k * 500, (int)/*m_pRemotePort.Value*/10000 - k * 500 + 1));
                m_pRtpSession.Sessions[0].NewSendStream += new EventHandler<RTP_SendStreamEventArgs>(m_pRtpSession_NewSendStream);
                m_pRtpSession.Sessions[0].NewReceiveStream += new EventHandler<RTP_ReceiveStreamEventArgs>(m_pRtpSession_NewReceiveStream);
                m_pRtpSession.Sessions[0].Payload = 0;
                m_pRtpSession.Sessions[0].Start();

                m_pAudioCodecs = new Dictionary<int, AudioCodec>();
                m_pAudioCodecs.Add(0, new PCMU());
                m_pAudioCodecs.Add(8, new PCMA());
            }
        }