<commit_before>﻿using CoreAudioApi;
using MediaBrowser.Common.Events;
using MediaBrowser.Model.ApiClient;
using MediaBrowser.Model.Dto;
using MediaBrowser.Model.Entities;
using MediaBrowser.Model.Library;
using MediaBrowser.Model.Logging;
using MediaBrowser.Theater.Interfaces.Configuration;
using MediaBrowser.Theater.Interfaces.Navigation;
using MediaBrowser.Theater.Interfaces.Playback;
using MediaBrowser.Theater.Interfaces.Presentation;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Threading.Tasks;
using System.Windows;

namespace MediaBrowser.Theater.Implementations.Playback
{
    public class PlaybackManager : IPlaybackManager
    {
        private readonly ITheaterConfigurationManager _configurationManager;
        private readonly ILogger _logger;
        private readonly IApiClient _apiClient;
        private readonly INavigationService _nav;
        private readonly IPresentationManager _presentationManager;

        public event EventHandler<PlaybackStartEventArgs> PlaybackStarted;

        public event EventHandler<PlaybackStopEventArgs> PlaybackCompleted;

        public void AddParts(IEnumerable<IMediaPlayer> mediaPlayers)
        {
            _mediaPlayers.AddRange(mediaPlayers);
        }

        private readonly List<IMediaPlayer> _mediaPlayers = new List<IMediaPlayer>();

        public PlaybackManager(ITheaterConfigurationManager configurationManager, ILogger logger, IApiClient apiClient, INavigationService nav, IPresentationManager presentationManager)
        {
            _configurationManager = configurationManager;
            _logger = logger;
            _apiClient = apiClient;
            _nav = nav;
            _presentationManager = presentationManager;
        }

        public IEnumerable<IMediaPlayer> MediaPlayers
        {
            get { return _mediaPlayers; }
        }

        /// <summary>
        /// Plays the specified options.
        /// </summary>
        /// <param name="options">The options.</param>
        /// <returns>Task.</returns>
        /// <exception cref="System.ArgumentNullException">
        /// options
        /// or
        /// options
        /// </exception>
        /// <exception cref="System.InvalidOperationException">There are no available players.</exception>
        public async Task Play(PlayOptions options)
        {
            if (options == null)
            {
                throw new ArgumentNullException("options");
            }

            if (options.Items == null || options.Items.Count(i => i.LocationType != LocationType.Offline) == 0)
            {
                throw new ArgumentException("At least one item must be supplied.");
            }

            PlayerConfiguration config;
            var player = GetPlayer(options.Items, options.EnableCustomPlayers, out config);

            if (player == null)
            {
                throw new InvalidOperationException("There are no available players.");
            }

            StopAllPlayback();

            await Task.Run(() => Play(player, options, config));
        }

        /// <summary>
        /// Plays the specified player.
        /// </summary>
        /// <param name="player">The player.</param>
        /// <param name="options">The options.</param>
        /// <param name="configuration">The configuration.</param>
        /// <returns>Task.</returns>
        private async Task Play(IMediaPlayer player, PlayOptions options, PlayerConfiguration configuration)
        {
            if (options.Shuffle)
            {
                options.Items = options.Items.OrderBy(i => Guid.NewGuid()).ToList();
            }

            var firstItem = options.Items[0];

            if (options.StartPositionTicks == 0 && player.SupportsMultiFilePlayback && firstItem.IsVideo && firstItem.LocationType == LocationType.FileSystem && options.GoFullScreen)
            {
                try
                {
                    var intros = await _apiClient.GetIntrosAsync(firstItem.Id, _apiClient.CurrentUserId);

                    options.Items.InsertRange(0, intros.Items);
                }
                catch (Exception ex)
                {
                    _logger.ErrorException("Error retrieving intros", ex);
                }
            }

            options.Configuration = configuration;

            await player.Play(options);

            if (player is IInternalMediaPlayer && player is IVideoPlayer && firstItem.IsVideo)
            {
                await _presentationManager.Window.Dispatcher.InvokeAsync(() => _presentationManager.WindowOverlay.SetResourceReference(FrameworkElement.StyleProperty, "WindowBackgroundContentDuringPlayback"));

                if (options.GoFullScreen)
                {
                    await _nav.NavigateToInternalPlayerPage();
                }
            }

            OnPlaybackStarted(player, options);
        }

        /// <summary>
        /// Called when [playback started].
        /// </summary>
        /// <param name="player">The player.</param>
        /// <param name="options">The options.</param>
        private async void OnPlaybackStarted(IMediaPlayer player, PlayOptions options)
        {
            EventHelper.QueueEventIfNotNull(PlaybackStarted, this, new PlaybackStartEventArgs
            {
                Options = options,
                Player = player<commit_msg>Fix issue #83 (threadsafe version)  - Pushing play on a trailer while it is loading causes MBT crash<commit_after>﻿using System.Threading;
using CoreAudioApi;
using MediaBrowser.Common.Events;
using MediaBrowser.Model.ApiClient;
using MediaBrowser.Model.Dto;
using MediaBrowser.Model.Entities;
using MediaBrowser.Model.Library;
using MediaBrowser.Model.Logging;
using MediaBrowser.Theater.Interfaces.Configuration;
using MediaBrowser.Theater.Interfaces.Navigation;
using MediaBrowser.Theater.Interfaces.Playback;
using MediaBrowser.Theater.Interfaces.Presentation;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Threading.Tasks;
using System.Windows;

namespace MediaBrowser.Theater.Implementations.Playback
{
    public class PlaybackManager : IPlaybackManager
    {
        private readonly ITheaterConfigurationManager _configurationManager;
        private readonly ILogger _logger;
        private readonly IApiClient _apiClient;
        private readonly INavigationService _nav;
        private readonly IPresentationManager _presentationManager;
        private int _isStarting;

        public event EventHandler<PlaybackStartEventArgs> PlaybackStarted;

        public event EventHandler<PlaybackStopEventArgs> PlaybackCompleted;

        public void AddParts(IEnumerable<IMediaPlayer> mediaPlayers)
        {
            _mediaPlayers.AddRange(mediaPlayers);
        }

        private readonly List<IMediaPlayer> _mediaPlayers = new List<IMediaPlayer>();

        public PlaybackManager(ITheaterConfigurationManager configurationManager, ILogger logger, IApiClient apiClient, INavigationService nav, IPresentationManager presentationManager)
        {
            _configurationManager = configurationManager;
            _logger = logger;
            _apiClient = apiClient;
            _nav = nav;
            _presentationManager = presentationManager;
        }

        public IEnumerable<IMediaPlayer> MediaPlayers
        {
            get { return _mediaPlayers; }
        }

        /// <summary>
        /// Plays the specified options.
        /// </summary>
        /// <param name="options">The options.</param>
        /// <returns>Task.</returns>
        /// <exception cref="System.ArgumentNullException">
        /// options
        /// or
        /// options
        /// </exception>
        /// <exception cref="System.InvalidOperationException">There are no available players.</exception>
        public async Task Play(PlayOptions options)
        {
            if (options == null)
            {
                throw new ArgumentNullException("options");
            }

            if (options.Items == null || options.Items.Count(i => i.LocationType != LocationType.Offline) == 0)
            {
                throw new ArgumentException("At least one item must be supplied.");
            }

            PlayerConfiguration config;
            var player = GetPlayer(options.Items, options.EnableCustomPlayers, out config);

            if (player == null)
            {
                throw new InvalidOperationException("There are no available players.");
            }

            StopAllPlayback();

            await Task.Run(() => Play(player, options, config));
        }

        /// <summary>
        /// Plays the specified player.
        /// </summary>
        /// <param name="player">The player.</param>
        /// <param name="options">The options.</param>
        /// <param name="configuration">The configuration.</param>
        /// <returns>Task.</returns>
        private async Task Play(IMediaPlayer player, PlayOptions options, PlayerConfiguration configuration)
        {
            if (Interlocked.CompareExchange(ref _isStarting, 1, 0) == 0) // prevent race conditions, thread safe check we are not already starting to play an item
            {
                try
                {
                    if (options.Shuffle)
                    {
                        options.Items = options.Items.OrderBy(i => Guid.NewGuid()).ToList();
                    }

                    var firstItem = options.Items[0];

                    if (options.StartPositionTicks == 0 && player.SupportsMultiFilePlayback && firstItem.IsVideo && firstItem.LocationType == LocationType.FileSystem && options.GoFullScreen)
                    {
                        try
                        {
                            var intros = await _apiClient.GetIntrosAsync(firstItem.Id, _apiClient.CurrentUserId);

                            options.Items.InsertRange(0, intros.Items);
                        }
                        catch (Exception ex)
                        {
                            _logger.ErrorException("Error retrieving intros", ex);
                        }
                    }

                    options.Configuration = configuration;

                    await player.Play(options);

                    if (player is IInternalMediaPlayer && player is IVideoPlayer && firstItem.IsVideo)
                    {
                        await _presentationManager.Window.Dispatcher.InvokeAsync(() => _presentationManager.WindowOverlay.SetResourceReference(FrameworkElement.StyleProperty, "WindowBackgroundContentDuringPlayback"));

                        if (options.GoFullScreen)
                        {
                            await _nav.NavigateToInternalPlayerPage();
                        }
                    }

                    OnPlaybackStarted(player, options);
                }
                finally
                {
                    Interlocked.Exchange(ref _isStarting, 0);
                }
            }
        }

        /// <summary>
        /// Called when [playback started].
        /// </summary>
        /// <param name="player">The player.</param>
        /// <param name="options">The options.</param>
        private async void OnPlaybackStarted(IMediaPlayer player, PlayOptions options)
        {
            EventHelper.QueueEventIfNotNull(PlaybackStarted, this, new PlaybackStartEventArgs
            {
                Options = options,
                Player = player
{'fraction_non_alphanumeric': 0.08969152337336905, 'fraction_numerical': 0.0012097122612978485, 'mean_word_length': 1.9829896907216495, 'pattern_counts': {'":': 0, '<': 67, '<?xml version=': 0, '>': 75, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '3871642', 'n_tokens_mistral': 2738, 'n_tokens_neox': 2623, 'n_words': 614}