void PlaybackController_OnProgress(object sender, PlaybackStateEventArgs e)
 {
     if (!UpdatePosition(e.Title, e.Position))
     {
         PlaybackController.OnProgress -= new EventHandler <PlaybackStateEventArgs>(PlaybackController_OnProgress);
     }
 }
        private VideoStartInfo GetStartInfo(PlaylistItem item, PlaybackStateEventArgs eventArgs)
        {
            var videoStartInfo = new VideoStartInfo();

            if (eventArgs == null)
            {
                videoStartInfo.StartTime = TimeSpan.Zero;
                videoStartInfo.EndTime   = TimeSpan.FromSeconds(item.Duration);
            }
            else
            {
                if (eventArgs.TimeRemaining != TimeSpan.Zero)
                {
                    videoStartInfo.StartTime = eventArgs.EndTime - eventArgs.TimeRemaining - eventArgs.StartTime;
                    videoStartInfo.EndTime   = eventArgs.TimeRemaining;
                }
                else
                {
                    videoStartInfo.StartTime = eventArgs.StartTime;
                    videoStartInfo.EndTime   = eventArgs.EndTime;
                }
            }

            videoStartInfo.EndTime = videoStartInfo.EndTime == TimeSpan.Zero
                                         ? TimeSpan.FromSeconds(item.Duration)
                                         : videoStartInfo.EndTime;
            videoStartInfo.Source = SubsonicService.GetUriForVideoStartingAt(
                item.Uri, videoStartInfo.StartTime.TotalSeconds);

            return(videoStartInfo);
        }
        /// <summary>
        /// Goes through each Media object within PlayableMediaItems and updates Playstate for each individually
        /// </summary>
        private void UpdatePlayStates(BasePlaybackController controller, PlaybackStateEventArgs args)
        {
            string currentFile = CurrentFile;

            for (int i = 0; i < MediaItems.Count(); i++)
            {
                Media media = MediaItems.ElementAt(i);

                bool isCurrentMedia = i == CurrentMediaIndex;

                long currentPositionTicks    = 0;
                int  currentPlaylistPosition = 0;

                if (isCurrentMedia)
                {
                    // If this is where playback is, update position and playlist
                    currentPlaylistPosition            = controller.GetPlayableFiles(media).ToList().IndexOf(currentFile);
                    media.PlaybackStatus.PositionTicks = currentPositionTicks = args.Position;
                }

                Application.CurrentInstance.UpdatePlayState(media, media.PlaybackStatus, controller.IsPaused, EnablePlayStateSaving);

                if (isCurrentMedia)
                {
                    break;
                }
            }

            HasUpdatedPlayState = true;
        }
        /// <summary>
        /// This is designed to help subclasses during the Progress and Finished event.
        /// Most subclasses can identify the currently playing file, so this uses that to determine the corresponding Media object that's playing
        /// If a subclass can figure this out on their own, it's best that they do so to avoid traversing the entire playlist
        /// </summary>
        private void NormalizeEventProperties(PlaybackStateEventArgs args)
        {
            PlayableItem playable = args.Item;

            if (playable != null)
            {
                // Auto-fill current file index if there's only one file
                if (args.CurrentFileIndex == -1 && playable.FilesFormattedForPlayer.Count() == 1)
                {
                    args.CurrentFileIndex = 0;
                }

                // Fill this in if the subclass wasn't able to supply it
                if (playable.HasMediaItems && args.CurrentMediaIndex == -1)
                {
                    // If there's only one Media item, set CurrentMediaId in the args object
                    // This is just a convenience for subclasses that only support one Media at a time
                    if (playable.MediaItems.Count() == 1)
                    {
                        args.CurrentMediaIndex = 0;
                    }
                    else
                    {
                        SetMediaEventPropertiesBasedOnCurrentFileIndex(playable, args);
                    }
                }
            }
        }
        //alesbal: end
        #endregion

        protected override void ResetPlaybackProperties()
        {
            base.ResetPlaybackProperties();

            CurrentProcess             = null;
            CurrentProcessName         = string.Empty;
            _LastProgressPlaybackState = null;
        }
        //alesbal: end
        #endregion

        protected override void ResetPlaybackProperties()
        {
            base.ResetPlaybackProperties();

            CurrentProcess = null;
            CurrentProcessName = string.Empty;
            _LastProgressPlaybackState = null;
        }
Example #7
0
 private void SwitchVideoPlayback(PlaybackStateEventArgs eventArgs, IVideoPlayer videoPlayer)
 {
     EventAggregator.Publish(new StopMessage());
     PlayerManagementService.DefaultVideoPlayer = videoPlayer;
     EventAggregator.Publish(new PlayMessage {
         Options = eventArgs
     });
 }
 private void UpdateCurrentMediaPlayState(BasePlaybackController controller, PlaybackStateEventArgs args)
 {
     if (CurrentMedia != null)
     {
         CurrentMedia.PlaybackStatus.PositionTicks = args.Position;
         Application.CurrentInstance.UpdatePlayState(CurrentMedia, CurrentMedia.PlaybackStatus, controller.IsPaused, EnablePlayStateSaving);
     }
 }
Example #9
0
        /// <summary>
        /// Constructs a PlaybackStateEventArgs based on current playback properties
        /// </summary>
        protected PlaybackStateEventArgs GetPlaybackState(long positionTicks, long durationTicks)
        {
            PlaybackStateEventArgs state = new PlaybackStateEventArgs()
            {
                Item = GetCurrentPlayableItem()
            };

            state.DurationFromPlayer = durationTicks;
            state.Position           = positionTicks;

            state.CurrentFileIndex = 0;

            return(state);
        }
Example #10
0
        /// <summary>
        /// This updates Playstates, runs post-play actions and fires the PlaybackFinished event
        /// </summary>
        protected virtual void OnPlaybackFinished(PlaybackStateEventArgs args)
        {
            Logger.ReportVerbose("{0} playback finished", ControllerName);

            KeyboardListener.Instance.KeyDown -= KeyboardListener_KeyDown;

            if (Config.Instance.WakeServer && !string.IsNullOrEmpty(Kernel.Instance.CommonConfigData.LastServerMacAddress))
            {
                Helper.WakeMachine(Kernel.Instance.CommonConfigData.LastServerMacAddress);
            }

            _IsStopping = true;

            NormalizeEventProperties(args);

            // Fire the finished event for each PlayableItem
            foreach (PlayableItem playable in CurrentPlayableItems)
            {
                playable.OnPlaybackFinished(this, args);
            }

            // Fire the playback controller's finished event
            if (_PlaybackFinished != null)
            {
                try
                {
                    _PlaybackFinished(this, args);
                }
                catch (Exception ex)
                {
                    Logger.ReportException("PlaybackController.PlaybackFinished event listener had an error: ", ex);
                }
            }

            // Show or hide the resume button depending on playstate
            UpdateResumeStatusInUI();

            SetPlaybackStage(PlayableItemPlayState.PostPlayActionsComplete);

            // Clear state
            CurrentPlayableItemId = Guid.Empty;
            CurrentPlayableItems.Clear();

            ResetPlaybackProperties();

            PlayStateChanged();

            Logger.ReportVerbose("All post-playback actions have completed.");
        }
Example #11
0
        internal void OnPlaybackFinished(BasePlaybackController controller, PlaybackStateEventArgs args)
        {
            if (args.Item == this && HasMediaItems)
            {
                // If there's still a valid position, fire progress one last time
                if (args.Position > 0)
                {
                    OnProgress(controller, args);
                }
                //update any previously played items to fully watched
                for (var i = 0; i < args.Item.CurrentMediaIndex; i++)
                {
                    OnItemFinished(args.Item.MediaItems.ElementAt(i), long.MaxValue);
                }

                //and then the current one with current state
                OnItemFinished(CurrentMedia, args.Position);
            }

            PlaybackStoppedByUser = args.StoppedByUser;


            PlayState = PlayableItemPlayState.Stopped;

            //DisplayUtil.RevertRefreshRate();

            // Fire finished event
            if (_PlaybackFinished != null)
            {
                Async.Queue(Async.ThreadPoolName.PlayableItemPlaybackFinished, () =>
                {
                    _PlaybackFinished(this, new GenericEventArgs <PlayableItem>()
                    {
                        Item = this
                    });
                });
            }

            if (RaiseGlobalPlaybackEvents)
            {
                Application.CurrentInstance.RunPostPlayProcesses(this);
            }

            if (UnmountISOAfterPlayback)
            {
                Application.CurrentInstance.UnmountIso();
            }
        }
        internal void OnProgress(BasePlaybackController controller, PlaybackStateEventArgs args)
        {
            CurrentFileIndex = args.CurrentFileIndex;
            CurrentMediaIndex = args.CurrentMediaIndex;

            PlayState = PlayableItemPlayState.Playing;

            UpdateCurrentMediaPlayState(controller, args);

            if (_Progress != null)
            {
                try
                {
                    _Progress(this, new GenericEventArgs<PlayableItem>() { Item = this });
                }
                catch (Exception ex)
                {
                    Logger.ReportException("PlayableItem Progress event listener had an error: ", ex);
                }
            } 
        }
Example #13
0
        internal void OnPlaybackFinished(BasePlaybackController controller, PlaybackStateEventArgs args)
        {
            if (args.Item == this)
            {
                // If there's still a valid position, fire progress one last time
                if (args.Position > 0)
                {
                    OnProgress(controller, args);
                }

                PlaybackStoppedByUser = args.StoppedByUser;

                MarkWatchedIfNeeded();
            }

            PlayState = PlayableItemPlayState.Stopped;

            // Fire finished event
            if (_PlaybackFinished != null)
            {
                Async.Queue("PlayableItem PlaybackFinished", () =>
                {
                    _PlaybackFinished(this, new GenericEventArgs <PlayableItem>()
                    {
                        Item = this
                    });
                });
            }

            if (RaiseGlobalPlaybackEvents)
            {
                Application.CurrentInstance.RunPostPlayProcesses(this);
            }

            if (UnmountISOAfterPlayback)
            {
                Application.CurrentInstance.UnmountIso();
            }
        }
Example #14
0
        private void HelperOnPlaybackStateChanged(object sender, PlaybackStateEventArgs playbackStateEventArgs)
        {
            IsLoading = false;
            switch (playbackStateEventArgs.State)
            {
            default:
                PlayPauseIcon = Symbol.Play;
                if (_timer.IsEnabled)
                {
                    _timer.Stop();
                }
                break;

            case MediaPlayerState.Playing:
                PlayPauseIcon  = Symbol.Pause;
                _root.IsPause  = false;
                _root.IsEnable = false;
                _timer.Start();
                break;

            case MediaPlayerState.Paused:
                PlayPauseIcon = Symbol.Play;
                _root.IsPause = true;
                break;

            case MediaPlayerState.Buffering:
            case MediaPlayerState.Opening:
                _root.IsEnable = true;
                _root.IsPause  = true;
                IsLoading      = true;
                if (_timer.IsEnabled)
                {
                    _timer.Stop();
                }

                break;
            }
        }
        /// <summary>
        /// Constructs a PlaybackStateEventArgs based on current playback properties
        /// </summary>
        private PlaybackStateEventArgs GetPlaybackState(long positionTicks, long durationTicks, string currentFilename)
        {
            PlaybackStateEventArgs args = new PlaybackStateEventArgs() { Item = GetCurrentPlayableItem() };

            args.DurationFromPlayer = durationTicks;
            args.Position = positionTicks;

            if (args.Item != null)
            {
                if (args.Item.HasMediaItems)
                {
                    int currentFileIndex;
                    args.CurrentMediaIndex = GetCurrentPlayingMediaIndex(args.Item, currentFilename, out currentFileIndex);
                    args.CurrentFileIndex = currentFileIndex;
                }
                else
                {
                    args.CurrentFileIndex = GetCurrentPlayingFileIndex(args.Item, currentFilename);
                }
            }

            return args;
        }
        /// <summary>
        /// This updates Playstates and fires the Progress event
        /// </summary>
        protected virtual void OnProgress(PlaybackStateEventArgs args)
        {
            CurrentFileDurationTicks = args.DurationFromPlayer;
            CurrentFilePositionTicks = args.Position;

            // Set the current PlayableItem based on the incoming args
            CurrentPlayableItemId = args.Item == null ? Guid.Empty : args.Item.Id;

            Async.Queue("BasePlaybackController OnProgress", () =>
            {
                NormalizeEventProperties(args);

                PlayableItem playable = args.Item;

                // Update PlayableItem progress event
                // Only report progress to the PlayableItem if the position is > 0, because the player may start with an initial position of 0, or reset to 0 when stopping
                // This could end up blowing away resume data
                if (playable != null && args.Position > 0)
                {
                    // Fire it's progress event handler
                    playable.OnProgress(this, args);
                }

                // Fire PlaybackController progress event
                if (_Progress != null)
                {
                    try
                    {
                        _Progress(this, args);
                    }
                    catch (Exception ex)
                    {
                        Logger.ReportException("PlaybackController.Progress event listener had an error: ", ex);
                    }
                }
            });
        }
        /// <summary>
        /// This updates Playstates and fires the Progress event
        /// </summary>
        protected virtual void OnProgress(PlaybackStateEventArgs args)
        {
            CurrentFileDurationTicks = args.DurationFromPlayer;
            CurrentFilePositionTicks = args.Position;

            // Set the current PlayableItem based on the incoming args
            CurrentPlayableItemId = args.Item == null ? Guid.Empty : args.Item.Id;

            Async.Queue("BasePlaybackController OnProgress", () =>
            {
                NormalizeEventProperties(args);

                PlayableItem playable = args.Item;

                // Update PlayableItem progress event
                // Only report progress to the PlayableItem if the position is > 0, because the player may start with an initial position of 0, or reset to 0 when stopping
                // This could end up blowing away resume data
                if (playable != null && args.Position > 0)
                {
                    // Fire it's progress event handler
                    playable.OnProgress(this, args);
                }

                // Fire PlaybackController progress event
                if (_Progress != null)
                {
                    try
                    {
                        _Progress(this, args);
                    }
                    catch (Exception ex)
                    {
                        Logger.ReportException("PlaybackController.Progress event listener had an error: ", ex);
                    }
                }
            }); 
        }
        internal void OnProgress(BasePlaybackController controller, PlaybackStateEventArgs args)
        {
            CurrentFileIndex  = args.CurrentFileIndex;
            CurrentMediaIndex = args.CurrentMediaIndex;

            PlayState = PlayableItemPlayState.Playing;

            UpdateCurrentMediaPlayState(controller, args);

            if (_Progress != null)
            {
                try
                {
                    _Progress(this, new GenericEventArgs <PlayableItem>()
                    {
                        Item = this
                    });
                }
                catch (Exception ex)
                {
                    Logger.ReportException("PlayableItem Progress event listener had an error: ", ex);
                }
            }
        }
                IEnumerable<string> mediaFiles = GetPlayableFiles(playable.MediaItems.ElementAt(i));

                int fileIndex = GetIndexOfFile(mediaFiles, currentFilename);

                if (fileIndex != -1)
                {
                    currentPlayingFileIndex = totalFileCount + fileIndex;
                    return i;
                }

                totalFileCount += mediaFiles.Count();
            }

            return -1;
        }

        private int GetIndexOfFile(IEnumerable<string> files, string file)
        {
            int numFiles = files.Count();

            for (int i = 0; i < numFiles; i++)
            {
                if (file.StartsWith(files.ElementAt(i).ToLower()))
                {
                    return i;
                }
 private void SwitchVideoPlayback(PlaybackStateEventArgs eventArgs, IVideoPlayer videoPlayer)
 {
     EventAggregator.Publish(new StopMessage());
     PlayerManagementService.DefaultVideoPlayer = videoPlayer;
     EventAggregator.Publish(new PlayMessage { Options = eventArgs });
 }
        /// <summary>
        /// Takes the current playing file in PlaybackStateEventArgs and uses that to determine the corresponding Media object
        /// </summary>
        private void SetMediaEventPropertiesBasedOnCurrentFileIndex(PlayableItem playable, PlaybackStateEventArgs state)
        {
            int mediaIndex = -1;

            if (state.CurrentFileIndex != -1)
            {
                int totalFileCount = 0;
                int numMediaItems  = playable.MediaItems.Count();

                for (int i = 0; i < numMediaItems; i++)
                {
                    int numFiles = playable.MediaItems.ElementAt(i).Files.Count();

                    if (totalFileCount + numFiles > state.CurrentFileIndex)
                    {
                        mediaIndex = i;
                        break;
                    }

                    totalFileCount += numFiles;
                }
            }

            state.CurrentMediaIndex = mediaIndex;
        }
 protected override void HandleStoppedState(PlaybackStateEventArgs args)
 {
     OnPlaybackFinished(args);
 }
Example #23
0
        void _StatusFileWatcher_Changed(object sender, FileSystemEventArgs e)
        {
            NameValueCollection values;

            try
            {
                values = Helper.ParseIniFile(e.FullPath);
            }
            catch (IOException)
            {
                // This can happen if the file is being written to at the exact moment we're trying to access it
                // Unfortunately we kind of have to just eat it
                return;
            }

            string tmtPlayState = values["State"].ToLower();

            _CurrentPlayState = tmtPlayState;

            if (tmtPlayState == "play")
            {
                // Playback just started
                _HasStartedPlaying = true;

                // Protect against really agressive calls
                var diff = (DateTime.Now - _LastFileSystemUpdate).TotalMilliseconds;

                if (diff < 1000 && diff >= 0)
                {
                    return;
                }

                _LastFileSystemUpdate = DateTime.Now;
            }

            // If playback has previously started...
            // First notify the Progress event handler
            // Then check if playback has stopped
            if (_HasStartedPlaying)
            {
                TimeSpan currentDuration = TimeSpan.FromTicks(0);
                TimeSpan currentPosition = TimeSpan.FromTicks(0);

                TimeSpan.TryParse(values["TotalTime"], out currentDuration);
                TimeSpan.TryParse(values["CurTime"], out currentPosition);

                PlaybackStateEventArgs state = GetPlaybackState(currentPosition.Ticks, currentDuration.Ticks);

                OnProgress(state);

                // Playback has stopped
                if (tmtPlayState == "stop")
                {
                    Logger.ReportVerbose(ControllerName + " playstate changed to stopped");

                    if (!_HasStopped)
                    {
                        _HasStopped = true;

                        DisposeFileSystemWatcher();

                        HandleStoppedState(state);
                    }
                }
            }
        }
Example #24
0
        /// <summary>
        /// Goes through each Media object within PlayableMediaItems and updates Playstate for each individually
        /// </summary>
        private void UpdatePlayStates(BasePlaybackController controller, PlaybackStateEventArgs args)
        {
            string currentFile = CurrentFile;

            for (int i = 0; i < MediaItems.Count(); i++)
            {
                Media media = MediaItems.ElementAt(i);

                bool isCurrentMedia = i == CurrentMediaIndex;

                long currentPositionTicks = 0;
                int currentPlaylistPosition = 0;

                if (isCurrentMedia)
                {
                    // If this is where playback is, update position and playlist
                    currentPlaylistPosition = controller.GetPlayableFiles(media).ToList().IndexOf(currentFile);
                    currentPositionTicks = args.Position;
                }

                Application.CurrentInstance.UpdatePlayState(media, media.PlaybackStatus, currentPlaylistPosition, currentPositionTicks, args.DurationFromPlayer, PlaybackStartTime, EnablePlayStateSaving);

                if (isCurrentMedia)
                {
                    break;
                }
            }

            HasUpdatedPlayState = true;
        }
        /// <summary>
        /// This is designed to help subclasses during the Progress and Finished event.
        /// Most subclasses can identify the currently playing file, so this uses that to determine the corresponding Media object that's playing
        /// If a subclass can figure this out on their own, it's best that they do so to avoid traversing the entire playlist
        /// </summary>
        private void NormalizeEventProperties(PlaybackStateEventArgs args)
        {
            PlayableItem playable = args.Item;

            if (playable != null)
            {
                // Auto-fill current file index if there's only one file
                if (args.CurrentFileIndex == -1 && playable.FilesFormattedForPlayer.Count() == 1)
                {
                    args.CurrentFileIndex = 0;
                }

                // Fill this in if the subclass wasn't able to supply it
                if (playable.HasMediaItems && args.CurrentMediaIndex == -1)
                {
                    // If there's only one Media item, set CurrentMediaId in the args object
                    // This is just a convenience for subclasses that only support one Media at a time
                    if (playable.MediaItems.Count() == 1)
                    {
                        args.CurrentMediaIndex = 0;
                    }
                    else
                    {
                        SetMediaEventPropertiesBasedOnCurrentFileIndex(playable, args);
                    }
                }
            }
        }
        internal void OnPlaybackFinished(BasePlaybackController controller, PlaybackStateEventArgs args)
        {
            if (args.Item == this && HasMediaItems)
            {
                // If there's still a valid position, fire progress one last time
                if (args.Position > 0)
                {
                    OnProgress(controller, args);
                }
                //update any previously played items to fully watched
                for (var i = 0; i < args.Item.CurrentMediaIndex; i++)
                    OnItemFinished(args.Item.MediaItems.ElementAt(i), long.MaxValue);

                //and then the current one with current state
                OnItemFinished(CurrentMedia, args.Position);
            }

            PlaybackStoppedByUser = args.StoppedByUser;


            PlayState = PlayableItemPlayState.Stopped;

            //DisplayUtil.RevertRefreshRate();

            // Fire finished event
            if (_PlaybackFinished != null)
            {
                Async.Queue(Async.ThreadPoolName.PlayableItemPlaybackFinished, () =>
                {
                    _PlaybackFinished(this, new GenericEventArgs<PlayableItem>() { Item = this });
                }); 
            }

            if (RaiseGlobalPlaybackEvents)
            {
                Application.CurrentInstance.RunPostPlayProcesses(this);
            }

            if (UnmountISOAfterPlayback)
            {
                Application.CurrentInstance.UnmountIso();
            }
        }
Example #27
0
 protected override void HandleStoppedState(PlaybackStateEventArgs args)
 {
     OnPlaybackFinished(args);
 }
        private VideoStartInfo GetStartInfo(PlaylistItem item, PlaybackStateEventArgs eventArgs)
        {
            var videoStartInfo = new VideoStartInfo();
            if (eventArgs == null)
            {
                videoStartInfo.StartTime = TimeSpan.Zero;
                videoStartInfo.EndTime = TimeSpan.FromSeconds(item.Duration);
            }
            else
            {
                if (eventArgs.TimeRemaining != TimeSpan.Zero)
                {
                    videoStartInfo.StartTime = eventArgs.EndTime - eventArgs.TimeRemaining - eventArgs.StartTime;
                    videoStartInfo.EndTime = eventArgs.TimeRemaining;
                }
                else
                {
                    videoStartInfo.StartTime = eventArgs.StartTime;
                    videoStartInfo.EndTime = eventArgs.EndTime;
                }
            }

            videoStartInfo.EndTime = videoStartInfo.EndTime == TimeSpan.Zero
                                         ? TimeSpan.FromSeconds(item.Duration)
                                         : videoStartInfo.EndTime;
            videoStartInfo.Source = SubsonicService.GetUriForVideoStartingAt(
                item.Uri, videoStartInfo.StartTime.TotalSeconds);

            return videoStartInfo;
        }
Example #29
0
        /// <summary>
        /// Handles a change of Playstate by firing various events and post play processes
        /// </summary>
        private void HandleStoppedState(MediaCenterEnvironment env, MediaExperience exp, MediaTransport transport, PlaybackStateEventArgs e)
        {
            Logger.ReportVerbose("In HandleStoppedState");
            // Stop listening to the events
            env.PropertyChanged       -= MediaCenterEnvironment_PropertyChanged;
            transport.PropertyChanged -= MediaTransport_PropertyChanged;

            Logger.ReportVerbose("Events unhooked");

            // This will prevent us from getting in here twice after playback stops and calling post-play processes more than once.
            _HasStartedPlaying = false;

            CurrentMediaCollection = null;

            var mediaType = exp.MediaType;


            // Check if internal wmc player is still playing, which could happen if the user launches live tv while playing something
            if (mediaType != Microsoft.MediaCenter.Extensibility.MediaType.TV)
            {
                Logger.ReportVerbose("Turning off NPV");
                Application.CurrentInstance.ShowNowPlaying = false;

                if (mediaType == Microsoft.MediaCenter.Extensibility.MediaType.Audio || mediaType == Microsoft.MediaCenter.Extensibility.MediaType.DVD)
                {
                    PlaybackControllerHelper.ReturnToApplication(true);
                }
            }
            else
            {
                Logger.ReportVerbose("Not turning off NPV because Live TV is playing.");
            }

            Helper.AllowSleep();

            // Fire the OnFinished event for each item
            Async.Queue(Async.ThreadPoolName.PlaybackFinished, () => OnPlaybackFinished(e));
        }
        protected override void OnProgress(PlaybackStateEventArgs args)
        {
            base.OnProgress(args);

            _LastProgressPlaybackState = args;
        }
 protected virtual void HandleStoppedState(PlaybackStateEventArgs args)
 {
     ClosePlayer();
 }
Example #32
0
        protected override void OnPlaybackFinished(PlaybackStateEventArgs args)
        {
            _MonitorPlayback = false;

            base.OnPlaybackFinished(args);
        }
        /// <summary>
        /// Handles a change of Playstate by firing various events and post play processes
        /// </summary>
        private void HandleStoppedState(MediaCenterEnvironment env, MediaExperience exp, MediaTransport transport, PlaybackStateEventArgs e)
        {
            // Stop listening to the events
            env.PropertyChanged       -= MediaCenterEnvironment_PropertyChanged;
            transport.PropertyChanged -= MediaTransport_PropertyChanged;

            // This will prevent us from getting in here twice after playback stops and calling post-play processes more than once.
            _HasStartedPlaying = false;

            _CurrentMediaCollection = null;

            var mediaType = exp.MediaType;

            // Check if internal wmc player is still playing, which could happen if the user launches live tv while playing something
            if (mediaType != Microsoft.MediaCenter.Extensibility.MediaType.TV)
            {
                Application.CurrentInstance.ShowNowPlaying = false;

                if (mediaType == Microsoft.MediaCenter.Extensibility.MediaType.Audio || mediaType == Microsoft.MediaCenter.Extensibility.MediaType.DVD)
                {
                    PlaybackControllerHelper.ReturnToApplication(true);
                }
            }

            // Fire the OnFinished event for each item
            OnPlaybackFinished(e);
        }
 private void UpdateCurrentMediaPlayState(BasePlaybackController controller, PlaybackStateEventArgs args)
 {
     if (CurrentMedia != null)
     {
         CurrentMedia.PlaybackStatus.PositionTicks = args.Position;
         Application.CurrentInstance.UpdatePlayState(CurrentMedia, CurrentMedia.PlaybackStatus, controller.IsPaused, EnablePlayStateSaving);
     }
 }
Example #35
0
        internal void OnPlaybackFinished(BasePlaybackController controller, PlaybackStateEventArgs args)
        {
            if (args.Item == this)
            {
                // If there's still a valid position, fire progress one last time
                if (args.Position > 0)
                {
                    OnProgress(controller, args);
                }

                PlaybackStoppedByUser = args.StoppedByUser;

                MarkWatchedIfNeeded();
            }

            PlayState = PlayableItemPlayState.Stopped;

            // Fire finished event
            if (_PlaybackFinished != null)
            {
                Async.Queue("PlayableItem PlaybackFinished", () =>
                {
                    _PlaybackFinished(this, new GenericEventArgs<PlayableItem>() { Item = this });
                });
            }

            if (RaiseGlobalPlaybackEvents)
            {
                Application.CurrentInstance.RunPostPlayProcesses(this);
            }

            if (UnmountISOAfterPlayback)
            {
                Application.CurrentInstance.UnmountIso();
            }
        }
 private void MediaHelper_PlaybackStateChanged(object sender, PlaybackStateEventArgs e)
 {
     IsPlaying = e.PlaybackState == PlaybackState.Playing;
 }
        /// <summary>
        /// This updates Playstates, runs post-play actions and fires the PlaybackFinished event
        /// </summary>
        protected virtual void OnPlaybackFinished(PlaybackStateEventArgs args)
        {
            Logger.ReportVerbose("{0} playback finished", ControllerName);

            KeyboardListener.Instance.KeyDown -= KeyboardListener_KeyDown;

            _IsStopping = true;

            NormalizeEventProperties(args);

            // Fire the finished event for each PlayableItem
            foreach (PlayableItem playable in CurrentPlayableItems)
            {
                playable.OnPlaybackFinished(this, args);
            }

            // Fire the playback controller's finished event
            if (_PlaybackFinished != null)
            {
                try
                {
                    _PlaybackFinished(this, args);
                }
                catch (Exception ex)
                {
                    Logger.ReportException("PlaybackController.PlaybackFinished event listener had an error: ", ex);
                }
            }

            // Show or hide the resume button depending on playstate
            UpdateResumeStatusInUI();

            SetPlaybackStage(PlayableItemPlayState.PostPlayActionsComplete);

            // Clear state
            CurrentPlayableItemId = Guid.Empty;
            CurrentPlayableItems.Clear();

            ResetPlaybackProperties();

            PlayStateChanged();

            Logger.ReportVerbose("All post-playback actions have completed.");
        }
Example #38
0
 protected virtual void HandleStoppedState(PlaybackStateEventArgs args)
 {
     ClosePlayer();
 }
        /// <summary>
        /// Takes the current playing file in PlaybackStateEventArgs and uses that to determine the corresponding Media object
        /// </summary>
        private void SetMediaEventPropertiesBasedOnCurrentFileIndex(PlayableItem playable, PlaybackStateEventArgs state)
        {
            int mediaIndex = -1;

            if (state.CurrentFileIndex != -1)
            {
                int totalFileCount = 0;
                int numMediaItems = playable.MediaItems.Count();

                for (int i = 0; i < numMediaItems; i++)
                {
                    int numFiles = playable.MediaItems.ElementAt(i).Files.Count();

                    if (totalFileCount + numFiles > state.CurrentFileIndex)
                    {
                        mediaIndex = i;
                        break;
                    }

                    totalFileCount += numFiles;
                }
            }

            state.CurrentMediaIndex = mediaIndex;
        }
        private PlaybackStateEventArgs GetPlaybackState(long positionTicks, long durationTicks, int currentFileIndex)
        {
            PlaybackStateEventArgs state = new PlaybackStateEventArgs() { Item = GetCurrentPlayableItem() };

            state.DurationFromPlayer = durationTicks;
            state.Position = positionTicks;

            state.CurrentFileIndex = currentFileIndex;

            return state;
        }
        private void IntroPlaybackFinished(object sender, PlaybackStateEventArgs e)
        {
            // unhook us
            currentPlaybackController.PlaybackFinished -= IntroPlaybackFinished;
            SuppressInitialOverlay = false;

            // and kick off main item
            if (MainPlayable != null) Play(MainPlayable);
        }
        protected override void OnProgress(PlaybackStateEventArgs args)
        {
            base.OnProgress(args);

            _LastProgressPlaybackState = args;
        }
        protected override void OnPlaybackFinished(PlaybackStateEventArgs args)
        {
            _MonitorPlayback = false;

            base.OnPlaybackFinished(args);
        }
 void ExternalItem_OnProgress(object sender, PlaybackStateEventArgs e)
 {
     //do nothing - we are used when something is already playing when we are created
 }
        /// <summary>
        /// Handles a change of Playstate by firing various events and post play processes
        /// </summary>
        private void HandleStoppedState(MediaCenterEnvironment env, MediaExperience exp, MediaTransport transport, PlaybackStateEventArgs e)
        {
            Logger.ReportVerbose("In HandleStoppedState");
            // Stop listening to the events
            env.PropertyChanged -= MediaCenterEnvironment_PropertyChanged;
            transport.PropertyChanged -= MediaTransport_PropertyChanged;

            Logger.ReportVerbose("Events unhooked");

            // This will prevent us from getting in here twice after playback stops and calling post-play processes more than once.
            _HasStartedPlaying = false;

            _CurrentMediaCollection = null;

            var mediaType = exp.MediaType;


            // Check if internal wmc player is still playing, which could happen if the user launches live tv while playing something
            if (mediaType != Microsoft.MediaCenter.Extensibility.MediaType.TV)
            {
                Logger.ReportVerbose("Turning off NPV");
                Application.CurrentInstance.ShowNowPlaying = false;

                if (mediaType == Microsoft.MediaCenter.Extensibility.MediaType.Audio || mediaType == Microsoft.MediaCenter.Extensibility.MediaType.DVD)
                {
                    PlaybackControllerHelper.ReturnToApplication(true);
                }
            }
            else
            {
                Logger.ReportVerbose("Not turning off NPV because Live TV is playing.");
            }

            // Fire the OnFinished event for each item
            Async.Queue("Playback Finished", () => OnPlaybackFinished(e));
        }
Example #46
0
        private void HandlePropertyChange(MediaCenterEnvironment env, MediaExperience exp, MediaTransport transport, string property)
        {
            PlayState state;
            long      positionTicks = 0;

            // If another application is playing the content, such as the WMC autoplay handler, we will
            // not have permission to access Transport properties
            // But we can look at MediaExperience.MediaType to determine if something is playing
            try
            {
                state         = transport.PlayState;
                positionTicks = transport.Position.Ticks;
            }
            catch (InvalidOperationException)
            {
                Logger.ReportVerbose("HandlePropertyChange was not able to access MediaTransport. Defaulting values.");
                state = exp.MediaType == Microsoft.MediaCenter.Extensibility.MediaType.Unknown ? Microsoft.MediaCenter.PlayState.Undefined : Microsoft.MediaCenter.PlayState.Playing;
            }

            bool playstateChanged = state != _CurrentPlayState;

            _CurrentPlayState = state;

            // Determine if playback has stopped. Per MSDN documentation, Finished is no longer used with Windows 7
            bool isStopped = state == Microsoft.MediaCenter.PlayState.Finished || state == Microsoft.MediaCenter.PlayState.Stopped || state == Microsoft.MediaCenter.PlayState.Undefined;

            // Don't get tripped up at the initial state of Stopped with position 0
            if (!_HasStartedPlaying)
            {
                if (!isStopped)
                {
                    Logger.ReportVerbose("HandlePropertyChange has recognized that playback has started");
                    _HasStartedPlaying = true;
                    IsStreaming        = Playable.CurrentFile.StartsWith("http://", StringComparison.OrdinalIgnoreCase) ||
                                         Playable.CurrentFile.StartsWith("https://", StringComparison.OrdinalIgnoreCase);
                    if (Playable.HasMediaItems)
                    {
                        Application.CurrentInstance.CurrentlyPlayingItemId = lastItemId = Playable.CurrentMedia.Id;
                        Application.CurrentInstance.ReportPlaybackStart(Playable.CurrentMedia.ApiId, IsStreaming);
                    }
                }
                else
                {
                    return;
                }
            }

            // protect against really agressive calls
            if (property == "Position")
            {
                Application.CurrentInstance.CurrentlyPlayingItem.CurrentPlaybackPosition = positionTicks;
                var diff = (DateTime.Now - _LastTransportUpdateTime).TotalMilliseconds;

                // Only cancel out Position reports
                if (diff < 5000 && diff >= 0)
                {
                    return;
                }
            }

            _LastTransportUpdateTime = DateTime.Now;

            // Get metadata from player
            MediaMetadata metadata = exp.MediaMetadata;

            string metadataTitle    = PlaybackControllerHelper.GetTitleOfCurrentlyPlayingMedia(metadata);
            long   metadataDuration = PlaybackControllerHelper.GetDurationOfCurrentlyPlayingMedia(metadata);

            PlaybackStateEventArgs eventArgs = GetCurrentPlaybackState(metadataTitle, metadataDuration, positionTicks);

            // Only fire the progress handler while playback is still active, because once playback stops position will be reset to 0
            OnProgress(eventArgs);

            if (eventArgs.Item != null && eventArgs.Item.HasMediaItems && eventArgs.Item.CurrentMedia.Id != lastItemId)
            {
                // started playing a new item - update
                Application.CurrentInstance.CurrentlyPlayingItemId = lastItemId = eventArgs.Item.MediaItems.ElementAt(eventArgs.CurrentMediaIndex).Id;
            }


            Application.CurrentInstance.ShowNowPlaying = eventArgs.Item == null || eventArgs.Item.ShowNowPlayingView;

            if (playstateChanged)
            {
                FirePropertyChanged("IsPaused");

                if (state == Microsoft.MediaCenter.PlayState.Paused)
                {
                    // allow screensavers/sleep
                    Helper.AllowSleep();
                }
                else if (state == Microsoft.MediaCenter.PlayState.Playing || state == Microsoft.MediaCenter.PlayState.Buffering)
                {
                    // disallow again
                    Helper.PreventSleep();
                }

                // Get the title from the PlayableItem, if it's available. Otherwise use MediaMetadata
                string title = eventArgs.Item == null ? metadataTitle : (eventArgs.Item.HasMediaItems ? eventArgs.Item.MediaItems.ElementAt(eventArgs.CurrentMediaIndex).Name : eventArgs.Item.Files.ElementAt(eventArgs.CurrentFileIndex));

                Logger.ReportVerbose("Playstate changed to {0} for {1}, PositionTicks:{2}, Playlist Index:{3}", state, title, positionTicks, eventArgs.CurrentFileIndex);
                //Logger.ReportVerbose("Refresh rate is {0}", DisplayUtil.GetCurrentRefreshRate());

                PlayStateChanged();
                Logger.ReportVerbose("Back from PlayStateChanged");
            }

            if (isStopped)
            {
                Logger.ReportVerbose("Calling HandleStopedState");
                HandleStoppedState(env, exp, transport, eventArgs);
            }
        }