void player_MediaChanged(object sender, MediaChangeEventArgs e)
 {
     NowPlayingItem = e.NewMedia;
 }
        /// <summary>
        /// Handles the MediaChanged event of the _mediaPlayer control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="MediaChangeEventArgs"/> instance containing the event data.</param>
        async void _mediaPlayer_MediaChanged(object sender, MediaChangeEventArgs e)
        {
            if (e.PreviousMedia != null)
            {
                var info = new PlaybackStopInfo
                {
                    ItemId = e.PreviousMedia.Id,
                    UserId = _apiClient.CurrentUserId,
                    PositionTicks = e.EndingPositionTicks
                };

                try
                {
                    await _apiClient.ReportPlaybackStoppedAsync(info);
                }
                catch (Exception ex)
                {
                    _logger.ErrorException("Error sending playback stopped checking for {0}", ex, e.PreviousMedia.Name);
                }
            }

            if (e.NewMedia != null)
            {
                try
                {
                    var queueTypes = _mediaPlayer.CanQueue
                                ? new List<string> { e.NewMedia.MediaType }
                                : new List<string> { };

                    var info = new PlaybackStartInfo
                    {
                        ItemId = e.NewMedia.Id,
                        UserId = _apiClient.CurrentUserId,
                        IsSeekable = _mediaPlayer.CanSeek,
                        QueueableMediaTypes = queueTypes.ToArray()
                    };

                    await _apiClient.ReportPlaybackStartAsync(info);
                }
                catch (Exception ex)
                {
                    _logger.ErrorException("Error sending playback start checking for {0}", ex, e.NewMedia.Name);
                }
            }
        }
        private async Task PlayTrack(int index, long? startPositionTicks)
        {
            var previousMedia = CurrentMedia;
            var previousIndex = CurrentPlaylistIndex;
            var endingTicks = CurrentPositionTicks;

            var options = CurrentPlayOptions;

            var playableItem = await GetPlayableItem(options.Items[index], startPositionTicks, CancellationToken.None);

            try
            {
                var enableMadVr = EnableMadvr(options);
                //var enableReclock = EnableReclock(options);

                InvokeOnPlayerThread(() =>
                {
                    //create a fresh DS Player everytime we want one
                    DisposePlayer();
                    _mediaPlayer = new DirectShowPlayer(_logger, _hiddenWindow, this, _presentation.WindowHandle, _sessionManager, _config, _inputManager, _apiClient, _zipClient, _httpClient);
                    _mediaPlayer.Play(playableItem, enableMadVr, false);
                });
            }
            catch
            {
                DisposeMount(playableItem);

                throw;
            }

            CurrentPlaylistIndex = index;

            if (startPositionTicks.HasValue && startPositionTicks.Value > 0)
            {
                InvokeOnPlayerThread(() => _mediaPlayer.Seek(startPositionTicks.Value));
            }

            if (previousMedia != null && MediaChanged != null)
            {
                var args = new MediaChangeEventArgs
                {
                    Player = this,
                    NewPlaylistIndex = index,
                    NewMedia = CurrentMedia,
                    PreviousMedia = previousMedia,
                    PreviousPlaylistIndex = previousIndex,
                    EndingPositionTicks = endingTicks
                };
                
               
                _presentation.Window.Dispatcher.Invoke
                (
                    () => MediaChanged(this, args)
                );
               
            }
        }
        /// <summary>
        /// Handles the MediaChanged event of the _mediaPlayer control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="eventArgs">The <see cref="MediaChangeEventArgs"/> instance containing the event data.</param>
        async void _mediaPlayer_MediaChanged(object sender, MediaChangeEventArgs eventArgs)
        {
            if (eventArgs.PreviousMedia != null)
            {
                var apiClient = _connectionManager.GetApiClient(eventArgs.PreviousMedia);

                var stopInfo = new PlaybackStopInfo
                {
                    ItemId = eventArgs.PreviousMedia.Id,
                    PositionTicks = eventArgs.EndingPositionTicks
                };

                // Have to test this for null because external players are currently not supplying this
                // Also some players will play in contexts not currently supported by common playback managers, e.g. direct play of folder rips, and iso-mounted media
                // Remove when implemented
                if (eventArgs.PreviousStreamInfo != null)
                {
                    await _apiPlaybackManager.ReportPlaybackStopped(stopInfo, eventArgs.PreviousStreamInfo, eventArgs.PreviousMedia.ServerId, apiClient.CurrentUserId, false, apiClient);
                }
                else
                {
                    await apiClient.ReportPlaybackStoppedAsync(stopInfo);
                }
            }

            if (eventArgs.NewMedia != null)
            {
                try
                {
                    var queueTypes = _mediaPlayer.CanQueue
                                ? new List<string> { eventArgs.NewMedia.MediaType }
                                : new List<string> { };

                    var info = new PlaybackStartInfo
                    {
                        ItemId = eventArgs.NewMedia.Id,

                        CanSeek = _mediaPlayer.CanSeek,
                        QueueableMediaTypes = queueTypes.ToList(),

                        // TODO: Remove this hardcoding
                        PlayMethod = PlayMethod.DirectPlay
                    };

                    var apiClient = _connectionManager.GetApiClient(eventArgs.NewMedia);

                    await apiClient.ReportPlaybackStartAsync(info);
                }
                catch (Exception ex)
                {
                    _logger.ErrorException("Error sending internalPlaybackManager start checking for {0}", ex, eventArgs.NewMedia.Name);
                }
            }
        }
        /// <summary>
        /// Handles the MediaChanged event of the _mediaPlayer control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="MediaChangeEventArgs"/> instance containing the event data.</param>
        async void _mediaPlayer_MediaChanged(object sender, MediaChangeEventArgs e)
        {
            if (e.PreviousMedia != null)
            {
                var info = new PlaybackStopInfo
                {
                    ItemId = e.PreviousMedia.Id,
                    PositionTicks = e.EndingPositionTicks
                };

                var apiClient = _connectionManager.GetApiClient(e.PreviousMedia);

                try
                {
                    await apiClient.ReportPlaybackStoppedAsync(info);
                }
                catch (Exception ex)
                {
                    _logger.ErrorException("Error sending playback stopped checking for {0}", ex, e.PreviousMedia.Name);
                }
            }

            if (e.NewMedia != null)
            {
                try
                {
                    var queueTypes = _mediaPlayer.CanQueue
                                ? new List<string> { e.NewMedia.MediaType }
                                : new List<string> { };

                    var info = new PlaybackStartInfo
                    {
                        ItemId = e.NewMedia.Id,

                        CanSeek = _mediaPlayer.CanSeek,
                        QueueableMediaTypes = queueTypes.ToList(),

                        // TODO: Remove this hardcoding
                        PlayMethod = PlayMethod.DirectPlay
                    };

                    var apiClient = _connectionManager.GetApiClient(e.NewMedia);

                    await apiClient.ReportPlaybackStartAsync(info);
                }
                catch (Exception ex)
                {
                    _logger.ErrorException("Error sending playback start checking for {0}", ex, e.NewMedia.Name);
                }
            }
        }
        /// <summary>
        /// Handles the MediaChanged event of the _mediaPlayer control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="MediaChangeEventArgs"/> instance containing the event data.</param>
        async void _mediaPlayer_MediaChanged(object sender, MediaChangeEventArgs e)
        {
            if (e.PreviousMedia != null)
            {
                try
                {
                    await _apiClient.ReportPlaybackStoppedAsync(e.PreviousMedia.Id, _apiClient.CurrentUserId, e.EndingPositionTicks);
                }
                catch (Exception ex)
                {
                    _logger.ErrorException("Error sending playback stopped checking for {0}", ex, e.PreviousMedia.Name);
                }
            }

            if (e.NewMedia != null)
            {
                try
                {
                    var queueTypes = _mediaPlayer.CanQueue
                                ? new List<string> { e.NewMedia.MediaType }
                                : new List<string> { };

                    await _apiClient.ReportPlaybackStartAsync(e.NewMedia.Id, _apiClient.CurrentUserId, _mediaPlayer.CanSeek, queueTypes);
                }
                catch (Exception ex)
                {
                    _logger.ErrorException("Error sending playback start checking for {0}", ex, e.NewMedia.Name);
                }
            }
        }
        private async Task PlayTrack(int index, long? startPositionTicks)
        {
            var previousMedia = CurrentMedia;
            var previousIndex = CurrentPlaylistIndex;
            var endingTicks = CurrentPositionTicks;

            var options = CurrentPlayOptions;

            var playableItem = await GetPlayableItem(options.Items[index], CancellationToken.None);

            try
            {
                _currentPlaybackDispatcher.Invoke(() => _mediaPlayer.Play(playableItem, EnableReclock(options), EnableMadvr(options), _config.Configuration.InternalPlayerConfiguration.EnableXySubFilter));
            }
            catch
            {
                DisposeMount(playableItem);

                throw;
            }

            CurrentPlaylistIndex = index;

            if (startPositionTicks.HasValue && startPositionTicks.Value > 0)
            {
                _currentPlaybackDispatcher.Invoke(() => _mediaPlayer.Seek(startPositionTicks.Value));
            }

            if (previousMedia != null)
            {
                var args = new MediaChangeEventArgs
                {
                    Player = this,
                    NewPlaylistIndex = index,
                    NewMedia = CurrentMedia,
                    PreviousMedia = previousMedia,
                    PreviousPlaylistIndex = previousIndex,
                    EndingPositionTicks = endingTicks
                };

                EventHelper.FireEventIfNotNull(MediaChanged, this, args, _logger);
            }
        }
        private async Task PlayTrack(int index, long? startPositionTicks, StreamInfo previousStreamInfo)
        {
            var previousMedia = CurrentMedia;
            var previousIndex = CurrentPlaylistIndex;
            var endingTicks = CurrentPositionTicks;

            var options = CurrentPlayOptions;

            PlayableItem playableItem;

            try
            {
                playableItem = await GetPlayableItem(options.Items[index], startPositionTicks, CancellationToken.None);
            }
            catch (PlaybackException ex)
            {
                string text;

                switch (ex.ErrorCode)
                {
                    case PlaybackErrorCode.NoCompatibleStream:
                        text = "No compatible streams are currently available. Please try again later or contact your system administrator for details.";
                        break;
                    case PlaybackErrorCode.NotAllowed:
                        text = "You do not have access to play this content at this time. Please contact your system administrator for details.";
                        break;
                    case PlaybackErrorCode.RateLimitExceeded:
                        text = "Your playback limit has been exceeded. Please try again later or contact your system administrator for details.";
                        break;
                    default:
                        text = "There was an error processing the request.";
                        break;
                }
                _presentation.ShowMessage(new MessageBoxInfo
                {
                    Button = MessageBoxButton.OK,
                    Icon = MessageBoxIcon.Error,
                    Caption = "Error",
                    Text = text
                });

                return;
            }

            try
            {
                var enableMadVr = EnableMadvr(options);
                //var enableReclock = EnableReclock(options);

                InvokeOnPlayerThread(() =>
                {
                    //create a fresh DS Player everytime we want one
                    DisposePlayer();

                    var apiClient = _connectionManager.GetApiClient(playableItem.OriginalItem);

                    _mediaPlayer = new DirectShowPlayer(_logger, _hiddenWindow, this, _presentation.WindowHandle,
                        _sessionManager, _config, _inputManager, apiClient, _zipClient, _httpClient);
                    _mediaPlayer.Play(playableItem, enableMadVr, false);

                }, true);
            }
            catch (PlaybackException ex)
            {
                string text;

                switch (ex.ErrorCode)
                {
                    case PlaybackErrorCode.NoCompatibleStream:
                        text = "No compatible streams are currently available. Please try again later or contact your system administrator for details.";
                        break;
                    case PlaybackErrorCode.NotAllowed:
                        text = "You do not have access to play this content at this time. Please contact your system administrator for details.";
                        break;
                    case PlaybackErrorCode.RateLimitExceeded:
                        text = "Your playback limit has been exceeded. Please try again later or contact your system administrator for details.";
                        break;
                    default:
                        text = "There was an error processing the request.";
                        break;
                }
                _presentation.ShowMessage(new MessageBoxInfo
                {
                    Button = MessageBoxButton.OK,
                    Icon = MessageBoxIcon.Error,
                    Caption = "Error",
                    Text = text
                });

                OnPlaybackStopped(playableItem, null, TrackCompletionReason.Failure, null);

                throw;
            }
            catch
            {
                OnPlaybackStopped(playableItem, null, TrackCompletionReason.Failure, null);

                throw;
            }

            CurrentStreamInfo = playableItem.StreamInfo;
            CurrentPlaylistIndex = index;

            if (startPositionTicks.HasValue && startPositionTicks.Value > 0)
            {
                InvokeOnPlayerThread(() => _mediaPlayer.Seek(startPositionTicks.Value));
            }

            if (playableItem.OriginalItem.IsVideo)
            {
                var audioIndex = playableItem.MediaSource.DefaultAudioStreamIndex;
                var subtitleIndex = playableItem.MediaSource.DefaultSubtitleStreamIndex;

                if (audioIndex.HasValue && audioIndex.Value != -1)
                {
                    SetAudioStreamIndex(audioIndex.Value);
                }
                SetSubtitleStreamIndex(subtitleIndex ?? -1);
            }

            if (previousMedia != null && MediaChanged != null)
            {
                var args = new MediaChangeEventArgs
                {
                    Player = this,
                    NewPlaylistIndex = index,
                    NewMedia = CurrentMedia,
                    PreviousMedia = previousMedia,
                    PreviousPlaylistIndex = previousIndex,
                    EndingPositionTicks = endingTicks,
                    PreviousStreamInfo = previousStreamInfo
                };

                _presentation.Window.Dispatcher.Invoke
                (
                    () => MediaChanged(this, args)
                );
            }
        }
        private async Task PlayTrack(int index, long? startPositionTicks)
        {
            var previousMedia = CurrentMedia;
            var previousIndex = CurrentPlaylistIndex;
            var endingTicks = CurrentPositionTicks;

            var options = CurrentPlayOptions;

            var playableItem = await GetPlayableItem(options.Items[index], startPositionTicks, CancellationToken.None);

            try
            {
                var enableMadVr = EnableMadvr(options);
                var enableReclock = EnableReclock(options);

                InvokeOnPlayerThread(() => _mediaPlayer.Play(playableItem, enableReclock, enableMadVr, false));
            }
            catch
            {
                DisposeMount(playableItem);

                throw;
            }

            CurrentPlaylistIndex = index;

            if (startPositionTicks.HasValue && startPositionTicks.Value > 0)
            {
                InvokeOnPlayerThread(() => _mediaPlayer.Seek(startPositionTicks.Value));
            }

            if (previousMedia != null)
            {
                var args = new MediaChangeEventArgs
                {
                    Player = this,
                    NewPlaylistIndex = index,
                    NewMedia = CurrentMedia,
                    PreviousMedia = previousMedia,
                    PreviousPlaylistIndex = previousIndex,
                    EndingPositionTicks = endingTicks
                };
                // can't InvokeOnPlayerThread because InvokeRequired returns false
                 _presentation.Window.Dispatcher.Invoke
                (
                    () => EventHelper.FireEventIfNotNull(MediaChanged, this, args, _logger)
                );
            }
        }
        private async Task PlayTrack(int index, long? startPositionTicks)
        {
            var previousMedia = CurrentMedia;
            var previousIndex = CurrentPlaylistIndex;
            var endingTicks = CurrentPositionTicks;

            var options = CurrentPlayOptions;

            var playableItem = await GetPlayableItem(options.Items[index], startPositionTicks, CancellationToken.None);

            try
            {
                var enableMadVr = EnableMadvr(options);
                //var enableReclock = EnableReclock(options);

                InvokeOnPlayerThread(() =>
                {
                    //create a fresh DS Player everytime we want one
                    DisposePlayer();

                    var apiClient = _connectionManager.GetApiClient(playableItem.OriginalItem);

                    _mediaPlayer = new DirectShowPlayer(_logger, _hiddenWindow, this, _presentation.WindowHandle, _sessionManager, _config, _inputManager, apiClient, _zipClient, _httpClient);
                    _mediaPlayer.Play(playableItem, enableMadVr, false);

                }, true);
            }
            catch
            {
                OnPlaybackStopped(playableItem, null, TrackCompletionReason.Failure, null);

                throw;
            }

            CurrentPlaylistIndex = index;

            if (startPositionTicks.HasValue && startPositionTicks.Value > 0)
            {
                InvokeOnPlayerThread(() => _mediaPlayer.Seek(startPositionTicks.Value));
            }

            if (playableItem.OriginalItem.IsVideo)
            {
                var audioIndex = playableItem.MediaSource.DefaultAudioStreamIndex;
                var subtitleIndex = playableItem.MediaSource.DefaultSubtitleStreamIndex;

                if (audioIndex.HasValue && audioIndex.Value != -1)
                {
                    SetAudioStreamIndex(audioIndex.Value);
                }
                SetSubtitleStreamIndex(subtitleIndex ?? -1);
            }

            if (previousMedia != null && MediaChanged != null)
            {
                var args = new MediaChangeEventArgs
                {
                    Player = this,
                    NewPlaylistIndex = index,
                    NewMedia = CurrentMedia,
                    PreviousMedia = previousMedia,
                    PreviousPlaylistIndex = previousIndex,
                    EndingPositionTicks = endingTicks
                };

                _presentation.Window.Dispatcher.Invoke
                (
                    () => MediaChanged(this, args)
                );
            }
        }