Ejemplo n.º 1
0
        /// <summary>
        /// Initializes a new instance of the <see cref="MediaSessionCallback"/> class.
        /// </summary>
        /// <param name="session">The session.</param>
        /// <param name="eventCallback">The event callback. The object <see cref="MediaEvent"/> must be disposed by the callback when finished with it.</param>
        /// <exception cref="System.ArgumentNullException">session or eventCallback</exception>
        public MediaSessionCallback(MediaSession session, Action<MediaEvent> eventCallback)
        {
            if (session == null)
                throw new ArgumentNullException("session");

            if (eventCallback == null)
                throw new ArgumentNullException("eventCallback");

            this.session = session;
            this.eventCallback = eventCallback;

            // Subscribe to next events automatically
            session.BeginGetEvent(this, null);
        }
Ejemplo n.º 2
0
        public void Play(string filename)
        {
            mediaSession = new MediaSession()
            {
                Flags = MFASync.FastIOProcessingCallback,
                Queue = MFAsyncCallbackQueue.Standard,
                OnSessionTopologyStatus = mediaSession_OnSessionTopologyStatus
            };

            mediaSession.Begin();

            using (var sourceResolver = SourceResolver.Create())
            using (var source = sourceResolver.CreateObjectFromURL(filename, MFResolution.MediaSource))
            using (var topology = Topology.Create())
            {
                BuildTopology(source, topology);

                mediaSession.SetTopology(topology);
            }
        }
Ejemplo n.º 3
0
        /// <summary>
        /// Event handler for a client call (one initiated by us) being answered.
        /// </summary>
        /// <param name="uac">The client user agent used to initiate the call.</param>
        /// <param name="sipResponse">The INVITE success response.</param>
        private async void ClientCallAnsweredHandler(ISIPClientUserAgent uac, SIPResponse sipResponse)
        {
            if (sipResponse.StatusCode >= 200 && sipResponse.StatusCode <= 299)
            {
                // Only set the remote RTP end point if there hasn't already been a packet received on it.
                MediaSession.SetRemoteDescription(SDP.ParseSDPDescription(sipResponse.Body));
                await MediaSession.Start().ConfigureAwait(false);

                Dialogue.DialogueState = SIPDialogueStateEnum.Confirmed;

                logger.LogInformation($"Call attempt to {m_uac.CallDescriptor.Uri} was answered.");

                ClientCallAnswered?.Invoke(uac, sipResponse);
            }
            else
            {
                logger.LogDebug($"Call attempt was answered with failure response {sipResponse.ShortDescription}.");
                ClientCallFailed?.Invoke(uac, sipResponse.ReasonPhrase);
                CallEnded();
            }
        }
 public override void Dispose()
 {
     FLLog.Info("Video", "Closing Windows Media Foundation backend");
     if (session != null)
     {
         session.Stop();
         session.ClearTopologies();
         //Sample grabber thread works asynchronously (as task), so we need give him a time, to understand, that session is closed
         //minimal time to wait: 33 ms (1000 ms / 30 fps), but I decide to use a little more
         System.Threading.Thread.Sleep(100);
         session.Close();
         session.Dispose();
         session = null;
     }
     if (topology != null)
     {
         topology.Dispose();
         topology = null;
     }
     if (videoSampler != null)
     {
         videoSampler.Dispose();
         videoSampler = null;
     }
     if (clock != null)
     {
         clock.Dispose();
         clock = null;
     }
     if (_texture != null)
     {
         _texture.Dispose();
         _texture = null;
     }
     if (cb != null)
     {
         cb.Dispose();
         cb = null;
     }
 }
Ejemplo n.º 5
0
        public void RegisterSession(string sessionId)
        {
            if (streamData != null)
            {
                scriptedGameContext.sendSystemInternal(sessionId, SessionMessageTypeEnum.VOD, streamData);
            }

            MediaSession session;

            lock (mediaSessionsLock)
            {
                if (!mediaSessions.ContainsKey(sessionId))
                {
                    mediaSessions[sessionId] = new MediaSession();
                }

                session = mediaSessions[sessionId];
            }

            defaultSession.SendInitialPackets(scriptedGameContext, sessionId);
            session.SendInitialPackets(scriptedGameContext, sessionId);
        }
Ejemplo n.º 6
0
        private void Initialize()
        {
            String baseDirectory = System.AppDomain.CurrentDomain.BaseDirectory;

            // set up the logfile
            _evsServiceLogger.Filename = baseDirectory + "DvtkDicomEvsLogFile.txt";

            // load the fixed configuration filename from the base directory
            _dvtkDicomEvsConfig.LoadConfig();

            // define the log level
            _evsServiceLogger.LogLevel = _dvtkDicomEvsConfig.EvsLogLevel;

            try
            {
                // check all the required directories / files are present
                CheckDirectoryPresence(baseDirectory);

                // create the DVTK media session - using the default session file
                _mediaSession = MediaSession.LoadFromFile(baseDirectory + _dvtkDicomEvsConfig.ConfigurationSubDirectory + @"\" + "DvtkDicomEvs.ses");

                // set the remaining session parameters
                _mediaSession.ResultsRootDirectory = _dvtkDicomEvsConfig.BaseCacheDirectory + @"\" + _dvtkDicomEvsConfig.MessageSubDirectory + @"\results";
                _mediaSession.DefinitionManagement.DefinitionFileRootDirectory = baseDirectory + @"\" + _dvtkDicomEvsConfig.DefinitionSubDirectory;

                // load the definition files
                LoadDefinitionFiles(baseDirectory);

                // set the validation service status
                _dvtkValidationServiceStatus.Status = "OK";
            }
            catch (System.Exception e)
            {
                _evsServiceLogger.LogError("Initialize Exception: {0}", e.Message);
                _evsServiceLogger.LogError("with Inner Exception: {0}", e.InnerException.Message);
                throw e;
            }
        }
Ejemplo n.º 7
0
        private void ContinueAfterDescribe(RTSPClient rtspClient, int resultCode, string resultString)
        {
            while (true)
            {
                var scs = ((OurRtspClient)rtspClient).scs;

                if (resultCode != 0)
                {
                    Console.Error.WriteLine("Failed to get a SDP description: " + resultString);
                    break;
                }

                var description = resultString;

                Console.Error.WriteLine("Got a SDP description:");
                Console.Error.Write(description);

                scs.session = MediaSession.CreateNew(env, description);

                if (scs.session == null)
                {
                    Console.Error.WriteLine("Failed to create a MediaSession object from the SDP description: " + env.GetResultMsg);
                    break;
                }

                if (scs.session.HasSubsessions == 0)
                {
                    Console.Error.WriteLine("This session has no media subsessions (i.e., no \"m=\" lines)");
                    break;
                }

                scs.iter = new MediaSubsessionIterator(scs.session);
                SetupNextSubsession(rtspClient);
                return;
            }

            ShutdownStream(rtspClient);
        }
Ejemplo n.º 8
0
        /// <summary>
        /// Puts the remote call party on hold.
        /// </summary>
        public async void PutOnHold()
        {
            bool hasAudio = MediaSession.HasAudio;
            bool hasVideo = MediaSession.HasVideo;

            m_userAgent.PutOnHold();

            AudioOptions audioOnHold = (!hasAudio) ? null :
                                       new AudioOptions
            {
                AudioSource       = AudioSourcesEnum.Music,
                OutputDeviceIndex = m_audioOutDeviceIndex,
                SourceFiles       = new Dictionary <SDPMediaFormatsEnum, string>
                {
                    { SDPMediaFormatsEnum.PCMU, MUSIC_FILE_PCMU },
                    { SDPMediaFormatsEnum.PCMA, MUSIC_FILE_PCMA }
                }
            };
            VideoOptions videoOnHold = null;

            if (hasVideo)
            {
                videoOnHold = new VideoOptions
                {
                    VideoSource           = VideoSourcesEnum.TestPattern,
                    SourceFile            = RtpAVSession.VIDEO_ONHOLD_TESTPATTERN,
                    SourceFramesPerSecond = VIDEO_ONHOLD_FRAMES_PER_SECOND
                };
            }

            await MediaSession.SetSources(audioOnHold, videoOnHold);

            // At this point we could stop listening to the remote party's RTP and play something
            // else and also stop sending our microphone output and play some music.
            StatusMessage(this, "Local party put on hold");
        }
Ejemplo n.º 9
0
        public void Play()
        {
            List <MediaSession.QueueItem> playingQueue;

            var          currentContext = Forms.Context;
            MediaSession session        = new MediaSession(currentContext, "mySession");
            var          mediaControler = session.Controller;
            var          meta           = mediaControler.Metadata;
            var          pbIn           = mediaControler.GetPlaybackInfo();



            playingQueue = new List <MediaSession.QueueItem> ();

            var tt = session.SessionToken;
            var qu = mediaControler.Queue;


            var mediaCallback = new MediaSessionCallback();

            mediaCallback.OnPlayImpl = () => {
                //LogHelper.Debug (Tag, "play");

                //if (playingQueue == null || playingQueue.Count != 0) {
                //	playingQueue = new List<MediaSession.QueueItem> (QueueHelper.GetRandomQueue (musicProvider));
                //	session.SetQueue (playingQueue);
                //	session.SetQueueTitle (GetString(Resource.String.random_queue_title));
                //	//currentIndexOnQueue = 0;
                //}

                //if (playingQueue != null && playingQueue.Count != 0) {
                //	HandlePlayRequest();
                //}
            };
            mediaControler.SetVolumeTo(10, AudioFlags.AudibilityEnforced);
        }
Ejemplo n.º 10
0
        /// <summary>
        /// Puts the remote call party on hold.
        /// </summary>
        public async void PutOnHold(IBitmapSource bmpSource)
        {
            await m_userAgent.PutOnHold();

            AudioOptions audioOnHold = (!MediaSession.HasAudio) ? null : new AudioOptions {
                AudioSource = AudioSourcesEnum.Music
            };
            VideoOptions videoOnHold = null;

            if (MediaSession.HasVideo)
            {
                if (bmpSource != null)
                {
                    videoOnHold = new VideoOptions
                    {
                        VideoSource  = VideoSourcesEnum.ExternalBitmap,
                        BitmapSource = bmpSource
                    };
                }
                else
                {
                    videoOnHold = new VideoOptions
                    {
                        VideoSource           = VideoSourcesEnum.TestPattern,
                        SourceFile            = RtpAVSession.VIDEO_ONHOLD_TESTPATTERN,
                        SourceFramesPerSecond = VIDEO_ONHOLD_FRAMES_PER_SECOND
                    };
                }
            }

            await MediaSession.SetSources(audioOnHold, videoOnHold);

            // At this point we could stop listening to the remote party's RTP and play something
            // else and also stop sending our microphone output and play some music.
            StatusMessage(this, "Local party put on hold");
        }
Ejemplo n.º 11
0
        /// <summary>
        /// Takes the remote call party off hold.
        /// </summary>
        public async void TakeOffHold()
        {
            bool hasAudio = MediaSession.HasAudio;
            bool hasVideo = MediaSession.HasVideo;

            m_userAgent.TakeOffHold();

            AudioOptions audioOnHold = (!hasAudio) ? null : new AudioOptions
            {
                AudioSource       = AudioSourcesEnum.CaptureDevice,
                OutputDeviceIndex = m_audioOutDeviceIndex
            };
            VideoOptions videoOnHold = (!hasVideo) ? null : new VideoOptions
            {
                VideoSource           = VideoSourcesEnum.TestPattern,
                SourceFile            = RtpAVSession.VIDEO_TESTPATTERN,
                SourceFramesPerSecond = VIDEO_LIVE_FRAMES_PER_SECOND
            };
            await MediaSession.SetSources(audioOnHold, videoOnHold);

            // At this point we should reverse whatever changes we made to the media stream when we
            // put the remote call part on hold.
            StatusMessage(this, "Local party taken off on hold");
        }
Ejemplo n.º 12
0
 /// <summary>
 /// Takes the remote call party off hold.
 /// </summary>
 public void TakeOffHold()
 {
     MediaSession.TakeOffHold();
     m_userAgent.TakeOffHold();
     StatusMessage(this, "Local party taken off on hold");
 }
Ejemplo n.º 13
0
        /// <summary>
        /// Save the session under a new file name.
        /// 
        /// A new session object will be created from this new saved file (and returned by this method) 
        /// and added to the project. The original session wil not be saved.
        /// </summary>
        /// <param name="theCurrentSession"></param>
        /// <returns>The new created session object, null if save as a new session has been cancelled or failed.</returns>
        public Session SaveSessionAs(Session theCurrentSession)
        {
            Session theNewSession = null;

            SaveFileDialog theSaveFileDialog = new SaveFileDialog();
            theSaveFileDialog.AddExtension = true;
            theSaveFileDialog.DefaultExt = ".ses";
            theSaveFileDialog.OverwritePrompt = false;
            theSaveFileDialog.Filter = "All session files (*.ses)|*.ses";

            DialogResult theDialogResult = theSaveFileDialog.ShowDialog();

            // User has specified a file name and has pressed the OK button.
            if (theDialogResult == DialogResult.OK)
            {
                if (File.Exists(theSaveFileDialog.FileName))
                {
                    MessageBox.Show(string.Format("File name \"{0}\" already exists.\nOperation cancelled", theSaveFileDialog.FileName));
                }
                else
                {
                    // Save the current session to a new file.
                    string theCurrentSessionFullFileName = theCurrentSession.SessionFileName;

                    theCurrentSession.SessionFileName = theSaveFileDialog.FileName;
                    theCurrentSession.Save();
                    Session.SessionType sessionType = theCurrentSession.sessionType ;
                    // Create a new session object from this new saved file and replace the current session.
                    switch(sessionType)
                    {
                        case Session.SessionType.ST_MEDIA:
                            theNewSession = new MediaSession(theSaveFileDialog.FileName);
                            LoadSession();
                            break;
                        case Session.SessionType.ST_SCRIPT:
                            theNewSession = new ScriptSession(theSaveFileDialog.FileName);
                            LoadSession();
                            break;
                        case Session.SessionType.ST_EMULATOR:
                            theNewSession = new EmulatorSession(theSaveFileDialog.FileName);
                            LoadSession();
                            break;
                        case Session.SessionType.ST_UNKNOWN:
                            break;
                    }

                    // Create a new session object from this new saved file and replace the current session.
                    if (theNewSession != null)
                    {
                        int theCurrentIndex = GetLoadedSessionsIndex(theCurrentSession);
                        parentProject.Sessions[theCurrentIndex]  = theNewSession;
                        parentProject.HasProjectChanged = true;
                    }
                }
            }

            return(theNewSession);
        }
        private void ProcessPlayerClosed()
        {
            // The session finished to close, we have to dispose all related object.
            currentMusic = null;

            mediaSessionCallback.Dispose();

            if (mediaSource != null) mediaSource.Shutdown();
            if (mediaSession != null) mediaSession.Shutdown();

            if (streamVolume != null) streamVolume.Dispose();
            if (mediaSource != null) mediaSource.Dispose();
            if (topology != null) topology.Dispose();
            if (mediaSession != null) mediaSession.Dispose();
            if (mediaInputByteStream != null) mediaInputByteStream.Dispose();

            topology = null;
            streamVolume = null;
            mediaSession = null;
            mediaSource = null;
            mediaInputByteStream = null;
            mediaSessionCallback = null;
            isMusicPlayerReady = false;
        }
Ejemplo n.º 15
0
        internal static IntPtr GetVolumeObj(MediaSession session)
        {
            // Get the volume interface - shared between MediaPlayer and VideoPlayer
            const int retries = 10;
            const int sleepTimeFactor = 50;

            var volumeObj = (IntPtr)0;

            //See https://github.com/mono/MonoGame/issues/2620
            //MediaFactory.GetService throws a SharpDX exception for unknown reasons. it appears retrying will solve the problem but there
            //is no specific number of times, nor pause that works. So we will retry N times with an increasing Sleep between each one
            //before finally throwing the error we saw in the first place.
            for (int i = 0; i < retries; i++)
            {
                try
                {
                    MediaFactory.GetService(session, MediaServiceKeys.StreamVolume, AudioStreamVolumeGuid, out volumeObj);
                    break;
                }
                catch (SharpDXException)
                {
                    if (i == retries - 1)
                    {
                        throw;
                    }
                    Debug.WriteLine("MediaFactory.GetService failed({0}) sleeping for {1} ms", i + 1, i * sleepTimeFactor);
                    Thread.Sleep(i * sleepTimeFactor); //Sleep for longer and longer times
                }
            }
            return volumeObj;
        }
Ejemplo n.º 16
0
 private static void RemoveSession(MediaSession mediaSession)
 {
     CurrentMediaSessions.Remove(mediaSession.ControlSession.SourceAppUserModelId);
     OnRemovedSource?.Invoke(mediaSession);
 }
Ejemplo n.º 17
0
        protected override void Dispose(bool disposing)
        {
            base.Dispose(disposing);

              if (mediaPlayer != null) {
            mediaPlayer.Release();
            mediaPlayer.Dispose();
            mediaPlayer = null;
              }

              if (mediaSession != null) {
            mediaSession.Release();
            mediaSession.Dispose();
            mediaSession = null;
              }
        }
Ejemplo n.º 18
0
        /// <summary>
        /// Handler for when an in dialog request is received on an established call.
        /// Typical types of request will be re-INVITES for things like putting a call on or
        /// off hold and REFER requests for transfers. Some in dialog request types, such
        /// as re-INVITES have specific events so they can be bubbled up to the
        /// application to deal with.
        /// </summary>
        /// <param name="sipRequest">The in dialog request received.</param>
        private async Task DialogRequestReceivedAsync(SIPRequest sipRequest)
        {
            if (sipRequest.Method == SIPMethodsEnum.BYE)
            {
                logger.LogInformation($"Remote call party hungup {sipRequest.StatusLine}.");
                Dialogue.DialogueState = SIPDialogueStateEnum.Terminated;

                SIPNonInviteTransaction byeTx = new SIPNonInviteTransaction(m_transport, sipRequest, null);
                byeTx.SendResponse(SIPResponse.GetResponse(sipRequest, SIPResponseStatusCodesEnum.Ok, null));

                CallEnded();
            }
            else if (sipRequest.Method == SIPMethodsEnum.INVITE)
            {
                logger.LogDebug($"Re-INVITE request received {sipRequest.StatusLine}.");

                UASInviteTransaction reInviteTransaction = new UASInviteTransaction(m_transport, sipRequest, m_outboundProxy);

                try
                {
                    MediaSession.setRemoteDescription(new RTCSessionDescription {
                        sdp = SDP.ParseSDPDescription(sipRequest.Body), type = RTCSdpType.offer
                    });

                    CheckRemotePartyHoldCondition(MediaSession.remoteDescription.sdp);

                    var answerSdp = await MediaSession.createAnswer(null).ConfigureAwait(false);

                    Dialogue.RemoteSDP  = sipRequest.Body;
                    Dialogue.SDP        = answerSdp.ToString();
                    Dialogue.RemoteCSeq = sipRequest.Header.CSeq;

                    var okResponse = reInviteTransaction.GetOkResponse(SDP.SDP_MIME_CONTENTTYPE, Dialogue.SDP);
                    reInviteTransaction.SendFinalResponse(okResponse);
                }
                catch (Exception ex)
                {
                    logger.LogError(ex, "MediaSession can't process the re-INVITE request.");

                    if (OnReinviteRequest == null)
                    {
                        // The application isn't prepared to accept re-INVITE requests and we can't work out what it was for.
                        // We'll reject as gently as we can to try and not lose the call.
                        SIPResponse notAcceptableResponse = SIPResponse.GetResponse(sipRequest, SIPResponseStatusCodesEnum.NotAcceptable, null);
                        reInviteTransaction.SendFinalResponse(notAcceptableResponse);
                    }
                    else
                    {
                        // The application is going to handle the re-INVITE request. We'll send a Trying response as a precursor.
                        SIPResponse tryingResponse = SIPResponse.GetResponse(sipRequest, SIPResponseStatusCodesEnum.Trying, null);
                        await reInviteTransaction.SendProvisionalResponse(tryingResponse).ConfigureAwait(false);

                        OnReinviteRequest.Invoke(reInviteTransaction);
                    }
                }
            }
            else if (sipRequest.Method == SIPMethodsEnum.OPTIONS)
            {
                //Log_External(new SIPMonitorConsoleEvent(SIPMonitorServerTypesEnum.AppServer, SIPMonitorEventTypesEnum.DialPlan, "OPTIONS request for established dialogue " + dialogue.DialogueName + ".", dialogue.Owner));
                SIPResponse okResponse = SIPResponse.GetResponse(sipRequest, SIPResponseStatusCodesEnum.Ok, null);
                okResponse.Body = Dialogue.RemoteSDP;
                okResponse.Header.ContentLength = okResponse.Body.Length;
                okResponse.Header.ContentType   = m_sdpContentType;
                await SendResponseAsync(okResponse).ConfigureAwait(false);
            }
            else if (sipRequest.Method == SIPMethodsEnum.MESSAGE)
            {
                //Log_External(new SIPMonitorConsoleEvent(SIPMonitorServerTypesEnum.AppServer, SIPMonitorEventTypesEnum.DialPlan, "MESSAGE for call " + sipRequest.URI.ToString() + ": " + sipRequest.Body + ".", dialogue.Owner));
                SIPResponse okResponse = SIPResponse.GetResponse(sipRequest, SIPResponseStatusCodesEnum.Ok, null);
                await m_transport.SendResponseAsync(okResponse).ConfigureAwait(false);
            }
            else if (sipRequest.Method == SIPMethodsEnum.REFER)
            {
                if (sipRequest.Header.ReferTo.IsNullOrBlank())
                {
                    // A REFER request must have a Refer-To header.
                    //Log_External(new SIPMonitorConsoleEvent(SIPMonitorServerTypesEnum.AppServer, SIPMonitorEventTypesEnum.DialPlan, "Bad REFER request, no Refer-To header.", dialogue.Owner));
                    SIPResponse invalidResponse = SIPResponse.GetResponse(sipRequest, SIPResponseStatusCodesEnum.BadRequest, "Missing mandatory Refer-To header");
                    await SendResponseAsync(invalidResponse).ConfigureAwait(false);
                }
                else
                {
                    //TODO: Add handling logic for in transfer requests from the remote call party.
                }
            }
            else if (sipRequest.Method == SIPMethodsEnum.NOTIFY)
            {
                SIPResponse okResponse = SIPResponse.GetResponse(sipRequest, SIPResponseStatusCodesEnum.Ok, null);
                await SendResponseAsync(okResponse).ConfigureAwait(false);

                if (sipRequest.Body?.Length > 0 && sipRequest.Header.ContentType?.Contains(m_sipReferContentType) == true)
                {
                    OnTransferNotify?.Invoke(sipRequest.Body);
                }
            }
        }
Ejemplo n.º 19
0
        public override void OnCreate()
        {
            base.OnCreate();
            LogHelper.Debug(Tag, "onCreate");

            playingQueue     = new List <MediaSession.QueueItem> ();
            musicProvider    = new MusicProvider();
            packageValidator = new PackageValidator(this);

            session      = new MediaSession(this, "MusicService");
            SessionToken = session.SessionToken;
            var mediaCallback = new MediaSessionCallback();

            mediaCallback.OnPlayImpl = () => {
                LogHelper.Debug(Tag, "play");

                if (playingQueue == null || playingQueue.Count != 0)
                {
                    playingQueue = new List <MediaSession.QueueItem> (QueueHelper.GetRandomQueue(musicProvider));
                    session.SetQueue(playingQueue);
                    session.SetQueueTitle(GetString(Resource.String.random_queue_title));
                    currentIndexOnQueue = 0;
                }

                if (playingQueue != null && playingQueue.Count != 0)
                {
                    HandlePlayRequest();
                }
            };
            mediaCallback.OnSkipToQueueItemImpl = (id) => {
                LogHelper.Debug(Tag, "OnSkipToQueueItem:" + id);

                if (playingQueue != null && playingQueue.Count != 0)
                {
                    currentIndexOnQueue = QueueHelper.GetMusicIndexOnQueue(playingQueue, id);
                    HandlePlayRequest();
                }
            };
            mediaCallback.OnSeekToImpl = (pos) => {
                LogHelper.Debug(Tag, "onSeekTo:", pos);
                playback.SeekTo((int)pos);
            };
            mediaCallback.OnPlayFromMediaIdImpl = (mediaId, extras) => {
                LogHelper.Debug(Tag, "playFromMediaId mediaId:", mediaId, "  extras=", extras);

                playingQueue = QueueHelper.GetPlayingQueue(mediaId, musicProvider);
                session.SetQueue(playingQueue);
                var queueTitle = GetString(Resource.String.browse_musics_by_genre_subtitle,
                                           MediaIDHelper.ExtractBrowseCategoryValueFromMediaID(mediaId));
                session.SetQueueTitle(queueTitle);

                if (playingQueue != null && playingQueue.Count != 0)
                {
                    currentIndexOnQueue = QueueHelper.GetMusicIndexOnQueue(playingQueue, mediaId);

                    if (currentIndexOnQueue < 0)
                    {
                        LogHelper.Error(Tag, "playFromMediaId: media ID ", mediaId,
                                        " could not be found on queue. Ignoring.");
                    }
                    else
                    {
                        HandlePlayRequest();
                    }
                }
            };
            mediaCallback.OnPauseImpl = () => {
                LogHelper.Debug(Tag, "pause. current state=" + playback.State);
                HandlePauseRequest();
            };
            mediaCallback.OnStopImpl = () => {
                LogHelper.Debug(Tag, "stop. current state=" + playback.State);
                HandleStopRequest(null);
            };
            mediaCallback.OnSkipToNextImpl = () => {
                LogHelper.Debug(Tag, "skipToNext");
                currentIndexOnQueue++;
                if (playingQueue != null && currentIndexOnQueue >= playingQueue.Count)
                {
                    currentIndexOnQueue = 0;
                }
                if (QueueHelper.isIndexPlayable(currentIndexOnQueue, playingQueue))
                {
                    HandlePlayRequest();
                }
                else
                {
                    LogHelper.Error(Tag, "skipToNext: cannot skip to next. next Index=" +
                                    currentIndexOnQueue + " queue length=" +
                                    (playingQueue == null ? "null" : playingQueue.Count.ToString()));
                    HandleStopRequest("Cannot skip");
                }
            };
            mediaCallback.OnSkipToPreviousImpl = () => {
                LogHelper.Debug(Tag, "skipToPrevious");
                currentIndexOnQueue--;
                if (playingQueue != null && currentIndexOnQueue < 0)
                {
                    currentIndexOnQueue = 0;
                }
                if (QueueHelper.isIndexPlayable(currentIndexOnQueue, playingQueue))
                {
                    HandlePlayRequest();
                }
                else
                {
                    LogHelper.Error(Tag, "skipToPrevious: cannot skip to previous. previous Index=" +
                                    currentIndexOnQueue + " queue length=" +
                                    (playingQueue == null ? "null" : playingQueue.Count.ToString()));
                    HandleStopRequest("Cannot skip");
                }
            };
            mediaCallback.OnCustomActionImpl = (action, extras) => {
                if (CustomActionThumbsUp == action)
                {
                    LogHelper.Info(Tag, "onCustomAction: favorite for current track");
                    var track = GetCurrentPlayingMusic();
                    if (track != null)
                    {
                        var musicId = track.GetString(MediaMetadata.MetadataKeyMediaId);
                        musicProvider.SetFavorite(musicId, !musicProvider.IsFavorite(musicId));
                    }
                    UpdatePlaybackState(null);
                }
                else
                {
                    LogHelper.Error(Tag, "Unsupported action: ", action);
                }
            };
            mediaCallback.OnPlayFromSearchImpl = (query, extras) => {
                LogHelper.Debug(Tag, "playFromSearch  query=", query);

                if (string.IsNullOrEmpty(query))
                {
                    playingQueue = new List <MediaSession.QueueItem> (QueueHelper.GetRandomQueue(musicProvider));
                }
                else
                {
                    playingQueue = new List <MediaSession.QueueItem> (QueueHelper.GetPlayingQueueFromSearch(query, musicProvider));
                }

                LogHelper.Debug(Tag, "playFromSearch  playqueue.length=" + playingQueue.Count);
                session.SetQueue(playingQueue);

                if (playingQueue != null && playingQueue.Count != 0)
                {
                    currentIndexOnQueue = 0;

                    HandlePlayRequest();
                }
                else
                {
                    HandleStopRequest(GetString(Resource.String.no_search_results));
                }
            };
            session.SetCallback(mediaCallback);
            session.SetFlags(MediaSessionFlags.HandlesMediaButtons |
                             MediaSessionFlags.HandlesTransportControls);

            playback          = new Playback(this, musicProvider);
            playback.State    = PlaybackStateCode.None;
            playback.Callback = this;
            playback.Start();

            var context = ApplicationContext;
            var intent  = new Intent(context, typeof(MusicPlayerActivity));
            var pi      = PendingIntent.GetActivity(context, 99 /*request code*/,
                                                    intent, PendingIntentFlags.UpdateCurrent);

            session.SetSessionActivity(pi);

            var extraBundle = new Bundle();

            CarHelper.SetSlotReservationFlags(extraBundle, true, true, true);
            session.SetExtras(extraBundle);

            UpdatePlaybackState(null);

            mediaNotificationManager = new MediaNotificationManager(this);
        }
Ejemplo n.º 20
0
 /// <summary>
 /// Puts the remote call party on hold.
 /// </summary>
 public void PutOnHold()
 {
     MediaSession.PutOnHold();
     m_userAgent.PutOnHold();
     StatusMessage(this, "Local party put on hold");
 }
Ejemplo n.º 21
0
        /// <summary>
        /// Handler for when an in dialog request is received on an established call.
        /// Typical types of request will be re-INVITES for things like putting a call on or
        /// off hold and REFER requests for transfers. Some in dialog request types, such
        /// as re-INVITES have specific events so they can be bubbled up to the
        /// application to deal with.
        /// </summary>
        /// <param name="sipRequest">The in dialog request received.</param>
        private async Task DialogRequestReceivedAsync(SIPRequest sipRequest)
        {
            // Make sure the request matches our dialog and is not a stray.
            // A dialog request should match on to tag, from tag and call ID. We'll be more
            // accepting just in case the sender got the tags wrong.
            if (Dialogue == null || sipRequest.Header.CallId != Dialogue.CallId)
            {
                var noCallLegResponse = SIPResponse.GetResponse(sipRequest, SIPResponseStatusCodesEnum.CallLegTransactionDoesNotExist, null);
                var sendResult        = await SendResponseAsync(noCallLegResponse);

                if (sendResult != SocketError.Success)
                {
                    logger.LogWarning($"SIPUserAgent send response failed in DialogRequestReceivedAsync with {sendResult}.");
                }
            }
            else
            {
                if (sipRequest.Method == SIPMethodsEnum.BYE)
                {
                    logger.LogInformation($"Remote call party hungup {sipRequest.StatusLine}.");
                    Dialogue.DialogueState = SIPDialogueStateEnum.Terminated;

                    SIPResponse okResponse = SIPResponse.GetResponse(sipRequest, SIPResponseStatusCodesEnum.Ok, null);
                    await SendResponseAsync(okResponse).ConfigureAwait(false);

                    CallEnded();
                }
                else if (sipRequest.Method == SIPMethodsEnum.INVITE)
                {
                    logger.LogDebug($"Re-INVITE request received {sipRequest.StatusLine}.");

                    UASInviteTransaction reInviteTransaction = new UASInviteTransaction(m_transport, sipRequest, m_outboundProxy);

                    try
                    {
                        var answerSdp = await MediaSession.RemoteReInvite(sipRequest.Body).ConfigureAwait(false);

                        Dialogue.RemoteSDP  = sipRequest.Body;
                        Dialogue.SDP        = answerSdp;
                        Dialogue.RemoteCSeq = sipRequest.Header.CSeq;

                        var okResponse = reInviteTransaction.GetOkResponse(SDP.SDP_MIME_CONTENTTYPE, Dialogue.SDP);
                        reInviteTransaction.SendFinalResponse(okResponse);
                    }
                    catch (Exception ex)
                    {
                        logger.LogError(ex, "MediaSession can't process the re-INVITE request.");

                        if (OnReinviteRequest == null)
                        {
                            // The application isn't prepared to accept re-INVITE requests and we can't work out what it was for.
                            // We'll reject as gently as we can to try and not lose the call.
                            SIPResponse notAcceptableResponse = SIPResponse.GetResponse(sipRequest, SIPResponseStatusCodesEnum.NotAcceptable, null);
                            reInviteTransaction.SendFinalResponse(notAcceptableResponse);
                        }
                        else
                        {
                            // The application is going to handle the re-INVITE request. We'll send a Trying response as a precursor.
                            SIPResponse tryingResponse = SIPResponse.GetResponse(sipRequest, SIPResponseStatusCodesEnum.Trying, null);
                            await reInviteTransaction.SendProvisionalResponse(tryingResponse);

                            OnReinviteRequest.Invoke(reInviteTransaction);
                        }
                    }
                }
                else if (sipRequest.Method == SIPMethodsEnum.OPTIONS)
                {
                    //Log_External(new SIPMonitorConsoleEvent(SIPMonitorServerTypesEnum.AppServer, SIPMonitorEventTypesEnum.DialPlan, "OPTIONS request for established dialogue " + dialogue.DialogueName + ".", dialogue.Owner));
                    SIPResponse okResponse = SIPResponse.GetResponse(sipRequest, SIPResponseStatusCodesEnum.Ok, null);
                    okResponse.Body = Dialogue.RemoteSDP;
                    okResponse.Header.ContentLength = okResponse.Body.Length;
                    okResponse.Header.ContentType   = m_sdpContentType;
                    await SendResponseAsync(okResponse);
                }
                else if (sipRequest.Method == SIPMethodsEnum.MESSAGE)
                {
                    //Log_External(new SIPMonitorConsoleEvent(SIPMonitorServerTypesEnum.AppServer, SIPMonitorEventTypesEnum.DialPlan, "MESSAGE for call " + sipRequest.URI.ToString() + ": " + sipRequest.Body + ".", dialogue.Owner));
                    SIPResponse okResponse = SIPResponse.GetResponse(sipRequest, SIPResponseStatusCodesEnum.Ok, null);
                    await m_transport.SendResponseAsync(okResponse);
                }
                else if (sipRequest.Method == SIPMethodsEnum.REFER)
                {
                    if (sipRequest.Header.ReferTo.IsNullOrBlank())
                    {
                        // A REFER request must have a Refer-To header.
                        //Log_External(new SIPMonitorConsoleEvent(SIPMonitorServerTypesEnum.AppServer, SIPMonitorEventTypesEnum.DialPlan, "Bad REFER request, no Refer-To header.", dialogue.Owner));
                        SIPResponse invalidResponse = SIPResponse.GetResponse(sipRequest, SIPResponseStatusCodesEnum.BadRequest, "Missing mandatory Refer-To header");
                        await SendResponseAsync(invalidResponse);
                    }
                    else
                    {
                        //TODO: Add handling logic for in transfer requests from the remote call party.
                    }
                }
                else if (sipRequest.Method == SIPMethodsEnum.NOTIFY)
                {
                    SIPResponse okResponse = SIPResponse.GetResponse(sipRequest, SIPResponseStatusCodesEnum.Ok, null);
                    await SendResponseAsync(okResponse);

                    if (sipRequest.Body?.Length > 0 && sipRequest.Header.ContentType?.Contains(m_sipReferContentType) == true)
                    {
                        OnTransferNotify?.Invoke(sipRequest.Body);
                    }
                }
            }
        }
Ejemplo n.º 22
0
 public MFCallback(VideoPlayerWMF player, MediaSession _session)
 {
     this._session = _session;
     _player       = player;
 }
 public MFCallback(VideoPlayerWMF player, MediaSession _session)
 {
     this._session = _session;
     _player       = player;
     Disposed     += (sender, args) => disposed = true;
 }
        /// <summary>
        /// OnCreate() detects some of our managers
        /// </summary>
        public override void OnCreate()
        {
            Log.Debug(TAG, "StreamingService.OnCreate()");
            base.OnCreate();

            audioManager = (AudioManager)GetSystemService(AudioService);
            wifiManager = (WifiManager)GetSystemService(WifiService);
            headphonesUnpluggedReceiver = new MusicBroadcastReceiver();
            if (Android.OS.Build.VERSION.SdkInt >= BuildVersionCodes.Lollipop)
            {
                mediaSession = new MediaSession(this, "KVMRMediaSession");

                mediaCallback = new MediaSessionCallback();
                mediaCallback.OnPlayImpl = () =>
                {
                    if (IsPlaying)
                    {
                        Log.Debug(TAG, "MediaCallback stop playing");
                        Stop();
                        MessagingCenter.Send<PlayerStoppedMessage>(new PlayerStoppedMessage(), "PlayerStopped");
                    }
                    else
                    {
                        Log.Debug(TAG, "MediaCallback start playing. source: " + source ?? "null");
                        Play(source);
                        MessagingCenter.Send(new RemoteControlPlayMessage(), "RemoteControlPlay");
                    }
                };

                mediaSession.SetCallback(mediaCallback);
                mediaSession.SetFlags(MediaSessionFlags.HandlesMediaButtons |
                    MediaSessionFlags.HandlesTransportControls);

                PlaybackState state = new PlaybackState.Builder()
                    .SetActions(PlaybackState.ActionPlay | PlaybackState.ActionPlayPause
                                          | PlaybackState.ActionPause | PlaybackState.ActionStop)
                    .Build();
                mediaSession.SetPlaybackState(state);
                mediaSession.Active = true;
            }
        }
Ejemplo n.º 25
0
        public override void OnCreate()
        {
            base.OnCreate();
              mediaPlayer = new MediaPlayer();
              mediaPlayer.SetAudioStreamType(Stream.Music);
              mediaPlayer.SetDataSource(StreamAddress);

              mediaPlayer.Prepared += MediaPlayerPrepared;

              mediaSession = new MediaSession(this, PackageName);

              notificationManager = (NotificationManager)GetSystemService(NotificationService);
        }
Ejemplo n.º 26
0
		public void Play (MediaSession.QueueItem item) 
		{
			playOnFocusGain = true;
			TryToGetAudioFocus ();
			RegisterAudioNoisyReceiver ();
			string mediaId = item.Description.MediaId;
			bool mediaHasChanged = mediaId != currentMediaId;
			if (mediaHasChanged) {
				currentPosition = 0;
				currentMediaId = mediaId;
			}

			if (State == PlaybackStateCode.Paused && !mediaHasChanged && mediaPlayer != null) {
				ConfigMediaPlayerState ();
			} else {
				State = PlaybackStateCode.Stopped;
				RelaxResources (false);
				MediaMetadata track = musicProvider.GetMusic (
					MediaIDHelper.ExtractMusicIDFromMediaID (item.Description.MediaId));

				string source = track.GetString (MusicProvider.CustomMetadataTrackSource);

				try {
					CreateMediaPlayerIfNeeded ();

					State = PlaybackStateCode.Buffering;

					mediaPlayer.SetAudioStreamType (Android.Media.Stream.Music);
					mediaPlayer.SetDataSource (source);

					mediaPlayer.PrepareAsync ();

					wifiLock.Acquire ();

					if (Callback != null) {
						Callback.OnPlaybackStatusChanged (State);
					}

				} catch (IOException ex) {
					LogHelper.Error (Tag, ex, "Exception playing song");
					if (Callback != null) {
						Callback.OnError (ex.Message);
					}
				}
			}
		}
Ejemplo n.º 27
0
 /// <summary>
 /// Requests the RTP session to transmit a DTMF tone using an RTP event.
 /// </summary>
 /// <param name="tone">The DTMF tone to transmit.</param>
 public Task SendDtmf(byte tone)
 {
     return(MediaSession.SendDtmf(tone, m_cts.Token));
 }
Ejemplo n.º 28
0
        private static void ValidateMediaDirectory()
        {
            MediaSession mediaSession = new MediaSession();

            mediaSession.OptionVerbose   = _OptionVerbose;
            mediaSession.SessionFileName = (string)_NonOptions[0];
            FileInfo  sessionFileName = null;
            ArrayList allDCMFilesTemp = new ArrayList();
            FileInfo  mediaFileInfo   = null;

            if (mediaSession.SessionFileName == "")
            {
                Console.WriteLine("Warning : Provide proper arguments.\n");
                return;
            }
            else
            {
                sessionFileName = new FileInfo(mediaSession.SessionFileName);
            }

            if (!sessionFileName.Exists)
            {
                Console.WriteLine(" Error : Session File  does not exists.\n");
            }
            else
            {
                MediaInput mediaInput = new MediaInput();
                string     mediaFile  = (string)_NonOptions[1];
                mediaFileInfo = new FileInfo(mediaFile);


                if (mediaFile == "")
                {
                    Console.WriteLine("Warning : Provide proper arguments.\n");
                    return;
                }
                else if (mediaFileInfo.Exists)
                {
                    allDCMFilesTemp.Add(mediaFileInfo.FullName);
                    mediaInput.FileNames = allDCMFilesTemp;
                    Console.WriteLine();
                    Console.WriteLine("> Validating media file {0}...", mediaInput.FileNames[0]);
                    mediaSession.Execute(mediaInput);
                    DisplayResultCounters(mediaSession);
                    DetermineExitCode(mediaSession);
                }
                else
                {
                    DirectoryInfo theDirectoryInfo = new DirectoryInfo(mediaFile);
                    if (!theDirectoryInfo.Exists)
                    {
                        Console.WriteLine("Error : Directory or File mentioned does not exists.\n");
                    }
                    else
                    {
                        mediaInput.FileNames = GetFilesRecursively(theDirectoryInfo);
                        Console.WriteLine();
                        Console.WriteLine("> Validating media files ...");
                        _exitCode = mediaSession.ExecuteDir(mediaInput);
                        //DisplayResultCounters(mediaSession);
                        //DetermineExitCode(mediaSession);
                    }
                }
            }
        }
Ejemplo n.º 29
0
 /// <summary>
 /// Hangup established call
 /// </summary>
 public void Hangup()
 {
     MediaSession?.Close();
     Dialogue?.Hangup(m_transport, m_outboundProxy);
     CallEnded();
 }
Ejemplo n.º 30
0
		public override void OnCreate ()
		{
			base.OnCreate ();
			LogHelper.Debug (Tag, "onCreate");

			playingQueue = new List<MediaSession.QueueItem> ();
			musicProvider = new MusicProvider ();
			packageValidator = new PackageValidator (this);

			session = new MediaSession (this, "MusicService");
			SessionToken = session.SessionToken;
			var mediaCallback = new MediaSessionCallback ();

			mediaCallback.OnPlayImpl = () => {
				LogHelper.Debug (Tag, "play");

				if (playingQueue == null || playingQueue.Count != 0) {
					playingQueue = new List<MediaSession.QueueItem> (QueueHelper.GetRandomQueue (musicProvider));
					session.SetQueue (playingQueue);
					session.SetQueueTitle (GetString (Resource.String.random_queue_title));
					currentIndexOnQueue = 0;
				}

				if (playingQueue != null && playingQueue.Count != 0) {
					HandlePlayRequest ();
				}
			};

			mediaCallback.OnSkipToQueueItemImpl = (id) => {
				LogHelper.Debug (Tag, "OnSkipToQueueItem:" + id);

				if (playingQueue != null && playingQueue.Count != 0) {
					currentIndexOnQueue = QueueHelper.GetMusicIndexOnQueue (playingQueue, id);
					HandlePlayRequest ();
				}
			};

			mediaCallback.OnSeekToImpl = (pos) => {
				LogHelper.Debug (Tag, "onSeekTo:", pos);
				playback.SeekTo ((int)pos);
			};

			mediaCallback.OnPlayFromMediaIdImpl = (mediaId, extras) => {
				LogHelper.Debug (Tag, "playFromMediaId mediaId:", mediaId, "  extras=", extras);

				playingQueue = QueueHelper.GetPlayingQueue (mediaId, musicProvider);
				session.SetQueue (playingQueue);
				var queueTitle = GetString (Resource.String.browse_musics_by_genre_subtitle,
					                 MediaIDHelper.ExtractBrowseCategoryValueFromMediaID (mediaId));
				session.SetQueueTitle (queueTitle);

				if (playingQueue != null && playingQueue.Count != 0) {
					currentIndexOnQueue = QueueHelper.GetMusicIndexOnQueue (playingQueue, mediaId);

					if (currentIndexOnQueue < 0) {
						LogHelper.Error (Tag, "playFromMediaId: media ID ", mediaId,
							" could not be found on queue. Ignoring.");
					} else {
						HandlePlayRequest ();
					}
				}
			};

			mediaCallback.OnPauseImpl = () => {
				LogHelper.Debug (Tag, "pause. current state=" + playback.State);
				HandlePauseRequest ();
			};

			mediaCallback.OnStopImpl = () => {
				LogHelper.Debug (Tag, "stop. current state=" + playback.State);
				HandleStopRequest (null);
			};

			mediaCallback.OnSkipToNextImpl = () => {
				LogHelper.Debug (Tag, "skipToNext");
				currentIndexOnQueue++;
				if (playingQueue != null && currentIndexOnQueue >= playingQueue.Count) {
					currentIndexOnQueue = 0;
				}
				if (QueueHelper.isIndexPlayable (currentIndexOnQueue, playingQueue)) {
					HandlePlayRequest ();
				} else {
					LogHelper.Error (Tag, "skipToNext: cannot skip to next. next Index=" +
					currentIndexOnQueue + " queue length=" +
					(playingQueue == null ? "null" : playingQueue.Count.ToString ()));
					HandleStopRequest ("Cannot skip");
				}
			};

			mediaCallback.OnSkipToPreviousImpl = () => {
				LogHelper.Debug (Tag, "skipToPrevious");
				currentIndexOnQueue--;
				if (playingQueue != null && currentIndexOnQueue < 0) {
					currentIndexOnQueue = 0;
				}
				if (QueueHelper.isIndexPlayable (currentIndexOnQueue, playingQueue)) {
					HandlePlayRequest ();
				} else {
					LogHelper.Error (Tag, "skipToPrevious: cannot skip to previous. previous Index=" +
					currentIndexOnQueue + " queue length=" +
					(playingQueue == null ? "null" : playingQueue.Count.ToString ()));
					HandleStopRequest ("Cannot skip");
				}
			};

			mediaCallback.OnCustomActionImpl = (action, extras) => {
				if (CustomActionThumbsUp == action) {
					LogHelper.Info (Tag, "onCustomAction: favorite for current track");
					var track = GetCurrentPlayingMusic ();
					if (track != null) {
						var musicId = track.GetString (MediaMetadata.MetadataKeyMediaId);
						musicProvider.SetFavorite (musicId, !musicProvider.IsFavorite (musicId));
					}
					UpdatePlaybackState (null);
				} else {
					LogHelper.Error (Tag, "Unsupported action: ", action);
				}
			};

			mediaCallback.OnPlayFromSearchImpl = (query, extras) => {
				LogHelper.Debug (Tag, "playFromSearch  query=", query);

				if (string.IsNullOrEmpty (query)) {
					playingQueue = new List<MediaSession.QueueItem> (QueueHelper.GetRandomQueue (musicProvider));
				} else {
					playingQueue = new List<MediaSession.QueueItem> (QueueHelper.GetPlayingQueueFromSearch (query, musicProvider));
				}

				LogHelper.Debug (Tag, "playFromSearch  playqueue.length=" + playingQueue.Count);
				session.SetQueue (playingQueue);

				if (playingQueue != null && playingQueue.Count != 0) {
					currentIndexOnQueue = 0;

					HandlePlayRequest ();
				} else {
					HandleStopRequest (GetString (Resource.String.no_search_results));
				}
			};

			session.SetCallback (mediaCallback);
			session.SetFlags (MediaSessionFlags.HandlesMediaButtons |
			MediaSessionFlags.HandlesTransportControls);

			playback = new Playback (this, musicProvider);
			playback.State = PlaybackStateCode.None;
			playback.Callback = this;
			playback.Start ();

			Context context = ApplicationContext;
			var intent = new Intent (context, typeof(MusicPlayerActivity));
			var pi = PendingIntent.GetActivity (context, 99 /*request code*/,
				         intent, PendingIntentFlags.UpdateCurrent);
			session.SetSessionActivity (pi);

			var extraBundle = new Bundle ();
			CarHelper.SetSlotReservationFlags (extraBundle, true, true, true);
			session.SetExtras (extraBundle);

			UpdatePlaybackState (null);

			mediaNotificationManager = new MediaNotificationManager (this);
		}