{"repo_name": "LLPlayer", "file_name": "/LLPlayer/FlyleafLib/Engine/Engine.Plugins.cs", "inference_info": {"prefix_code": "using System;\nusing System.Collections.Generic;\nusing System.IO;\nusing System.Reflection;\n\nusing FlyleafLib.Plugins;\n\nnamespace FlyleafLib;\n\npublic class PluginsEngine\n{\n public Dictionary\n Types { get; private set; } = new Dictionary();\n\n public string Folder { get; private set; }\n\n private Type pluginBaseType = typeof(PluginBase);\n\n internal PluginsEngine()\n {\n Folder = string.IsNullOrEmpty(Engine.Config.PluginsPath) ? null : Utils.GetFolderPath(Engine.Config.PluginsPath);\n\n LoadAssemblies();\n }\n\n ", "suffix_code": "\n\n /// \n /// Manually load plugins\n /// \n /// The assembly to search for plugins\n public void LoadPlugin(Assembly assembly)\n {\n try\n {\n var types = assembly.GetTypes();\n\n foreach (var type in types)\n {\n if (pluginBaseType.IsAssignableFrom(type) && type.IsClass && !type.IsAbstract)\n {\n // Force static constructors to execute (For early load, will be useful with c# 8.0 and static properties for interfaces eg. DefaultOptions)\n // System.Runtime.CompilerServices.RuntimeHelpers.RunClassConstructor(type.TypeHandle);\n\n if (!Types.ContainsKey(type.Name))\n {\n Types.Add(type.Name, new PluginType() { Name = type.Name, Type = type, Version = assembly.GetName().Version});\n Engine.Log.Info($\"Plugin loaded ({type.Name} - {assembly.GetName().Version})\");\n }\n else\n Engine.Log.Info($\"Plugin already exists ({type.Name} - {assembly.GetName().Version})\");\n }\n }\n }\n catch (Exception e) { Engine.Log.Error($\"[PluginHandler] [Error] Failed to load assembly ({e.Message} {Utils.GetRecInnerException(e)})\"); }\n }\n}\n", "middle_code": "internal void LoadAssemblies()\n {\n LoadPlugin(Assembly.GetExecutingAssembly());\n if (Folder != null && Directory.Exists(Folder))\n {\n string[] dirs = Directory.GetDirectories(Folder);\n foreach(string dir in dirs)\n foreach(string file in Directory.GetFiles(dir, \"*.dll\"))\n LoadPlugin(Assembly.LoadFrom(Path.GetFullPath(file)));\n }\n else\n {\n Engine.Log.Info($\"[PluginHandler] No external plugins found\");\n }\n }", "code_description": null, "fill_type": "FUNCTION_TYPE", "language_type": "c_sharp", "sub_task_type": null}, "context_code": [["/LLPlayer/FlyleafLib/Plugins/PluginHandler.cs", "using System.Collections.Generic;\nusing System.Collections.ObjectModel;\nusing System.Linq;\n\nusing FlyleafLib.MediaFramework.MediaPlaylist;\nusing FlyleafLib.MediaFramework.MediaStream;\n\nnamespace FlyleafLib.Plugins;\n\npublic class PluginHandler\n{\n #region Properties\n public Config Config { get; private set; }\n public bool Interrupt { get; set; }\n public IOpen OpenedPlugin { get; private set; }\n public IOpenSubtitles OpenedSubtitlesPlugin { get; private set; }\n public long OpenCounter { get; internal set; }\n public long OpenItemCounter { get; internal set; }\n public Playlist Playlist { get; set; }\n public int UniqueId { get; set; }\n\n public Dictionary\n Plugins { get; private set; }\n public Dictionary\n PluginsOpen { get; private set; }\n public Dictionary\n PluginsOpenSubtitles { get; private set; }\n\n public Dictionary\n PluginsScrapeItem { get; private set; }\n\n public Dictionary\n PluginsSuggestItem { get; private set; }\n\n public Dictionary\n PluginsSuggestAudioStream { get; private set; }\n public Dictionary\n PluginsSuggestVideoStream { get; private set; }\n public Dictionary\n PluginsSuggestExternalAudio { get; private set; }\n public Dictionary\n PluginsSuggestExternalVideo { get; private set; }\n\n public Dictionary\n PluginsSuggestSubtitlesStream { get; private set; }\n public Dictionary\n PluginsSuggestSubtitles { get; private set; }\n public Dictionary\n PluginsSuggestBestExternalSubtitles\n { get; private set; }\n\n public Dictionary\n PluginsDownloadSubtitles { get; private set; }\n\n public Dictionary\n PluginsSearchLocalSubtitles { get; private set; }\n public Dictionary\n PluginsSearchOnlineSubtitles { get; private set; }\n #endregion\n\n #region Initialize\n LogHandler Log;\n public PluginHandler(Config config, int uniqueId = -1)\n {\n Config = config;\n UniqueId= uniqueId == -1 ? Utils.GetUniqueId() : uniqueId;\n Playlist = new Playlist(UniqueId);\n Log = new LogHandler((\"[#\" + UniqueId + \"]\").PadRight(8, ' ') + \" [PluginHandler ] \");\n LoadPlugins();\n }\n\n public static PluginBase CreatePluginInstance(PluginType type, PluginHandler handler = null)\n {\n PluginBase plugin = (PluginBase) Activator.CreateInstance(type.Type, true);\n plugin.Handler = handler;\n plugin.Name = type.Name;\n plugin.Type = type.Type;\n plugin.Version = type.Version;\n\n if (handler != null)\n plugin.OnLoaded();\n\n return plugin;\n }\n private void LoadPlugins()\n {\n Plugins = new Dictionary();\n\n foreach (var type in Engine.Plugins.Types.Values)\n {\n try\n {\n var plugin = CreatePluginInstance(type, this);\n plugin.Log = new LogHandler((\"[#\" + UniqueId + \"]\").PadRight(8, ' ') + $\" [{plugin.Name,-14}] \");\n Plugins.Add(plugin.Name, plugin);\n } catch (Exception e) { Log.Error($\"[Plugins] [Error] Failed to load plugin ... ({e.Message} {Utils.GetRecInnerException(e)}\"); }\n }\n\n PluginsOpen = new Dictionary();\n PluginsOpenSubtitles = new Dictionary();\n PluginsScrapeItem = new Dictionary();\n\n PluginsSuggestItem = new Dictionary();\n\n PluginsSuggestAudioStream = new Dictionary();\n PluginsSuggestVideoStream = new Dictionary();\n PluginsSuggestSubtitlesStream = new Dictionary();\n PluginsSuggestSubtitles = new Dictionary();\n\n PluginsSuggestExternalAudio = new Dictionary();\n PluginsSuggestExternalVideo = new Dictionary();\n PluginsSuggestBestExternalSubtitles\n = new Dictionary();\n\n PluginsSearchLocalSubtitles = new Dictionary();\n PluginsSearchOnlineSubtitles = new Dictionary();\n PluginsDownloadSubtitles = new Dictionary();\n\n foreach (var plugin in Plugins.Values)\n LoadPluginInterfaces(plugin);\n }\n private void LoadPluginInterfaces(PluginBase plugin)\n {\n if (plugin is IOpen) PluginsOpen.Add(plugin.Name, (IOpen)plugin);\n else if (plugin is IOpenSubtitles) PluginsOpenSubtitles.Add(plugin.Name, (IOpenSubtitles)plugin);\n\n if (plugin is IScrapeItem) PluginsScrapeItem.Add(plugin.Name, (IScrapeItem)plugin);\n\n if (plugin is ISuggestPlaylistItem) PluginsSuggestItem.Add(plugin.Name, (ISuggestPlaylistItem)plugin);\n\n if (plugin is ISuggestAudioStream) PluginsSuggestAudioStream.Add(plugin.Name, (ISuggestAudioStream)plugin);\n if (plugin is ISuggestVideoStream) PluginsSuggestVideoStream.Add(plugin.Name, (ISuggestVideoStream)plugin);\n if (plugin is ISuggestSubtitlesStream) PluginsSuggestSubtitlesStream.Add(plugin.Name, (ISuggestSubtitlesStream)plugin);\n if (plugin is ISuggestSubtitles) PluginsSuggestSubtitles.Add(plugin.Name, (ISuggestSubtitles)plugin);\n\n if (plugin is ISuggestExternalAudio) PluginsSuggestExternalAudio.Add(plugin.Name, (ISuggestExternalAudio)plugin);\n if (plugin is ISuggestExternalVideo) PluginsSuggestExternalVideo.Add(plugin.Name, (ISuggestExternalVideo)plugin);\n if (plugin is ISuggestBestExternalSubtitles) PluginsSuggestBestExternalSubtitles.Add(plugin.Name, (ISuggestBestExternalSubtitles)plugin);\n\n if (plugin is ISearchLocalSubtitles) PluginsSearchLocalSubtitles.Add(plugin.Name, (ISearchLocalSubtitles)plugin);\n if (plugin is ISearchOnlineSubtitles) PluginsSearchOnlineSubtitles.Add(plugin.Name, (ISearchOnlineSubtitles)plugin);\n if (plugin is IDownloadSubtitles) PluginsDownloadSubtitles.Add(plugin.Name, (IDownloadSubtitles)plugin);\n }\n #endregion\n\n #region Misc / Events\n public void OnInitializing()\n {\n OpenCounter++;\n OpenItemCounter++;\n foreach(var plugin in Plugins.Values)\n plugin.OnInitializing();\n }\n public void OnInitialized()\n {\n OpenedPlugin = null;\n OpenedSubtitlesPlugin = null;\n\n Playlist.Reset();\n\n foreach(var plugin in Plugins.Values)\n plugin.OnInitialized();\n }\n\n public void OnInitializingSwitch()\n {\n OpenItemCounter++;\n foreach(var plugin in Plugins.Values)\n plugin.OnInitializingSwitch();\n }\n public void OnInitializedSwitch()\n {\n foreach(var plugin in Plugins.Values)\n plugin.OnInitializedSwitch();\n }\n\n public void Dispose()\n {\n foreach(var plugin in Plugins.Values)\n plugin.Dispose();\n }\n #endregion\n\n #region Audio / Video\n public OpenResults Open()\n {\n long sessionId = OpenCounter;\n var plugins = PluginsOpen.Values.OrderBy(x => x.Priority);\n foreach(var plugin in plugins)\n {\n if (Interrupt || sessionId != OpenCounter)\n return new OpenResults(\"Cancelled\");\n\n if (!plugin.CanOpen())\n continue;\n\n var res = plugin.Open();\n if (res == null)\n continue;\n\n // Currently fallback is not allowed if an error has been returned\n if (res.Error != null)\n return res;\n\n OpenedPlugin = plugin;\n Log.Info($\"[{plugin.Name}] Open Success\");\n\n return res;\n }\n\n return new OpenResults(\"No plugin found for the provided input\");\n }\n public OpenResults OpenItem()\n {\n long sessionId = OpenItemCounter;\n var res = OpenedPlugin.OpenItem();\n\n res ??= new OpenResults { Error = \"Cancelled\" };\n\n if (sessionId != OpenItemCounter)\n res.Error = \"Cancelled\";\n\n if (res.Error == null)\n Log.Info($\"[{OpenedPlugin.Name}] Open Item ({Playlist.Selected.Index}) Success\");\n\n return res;\n }\n\n // Should only be called from opened plugin\n public void OnPlaylistCompleted()\n {\n Playlist.Completed = true;\n if (Playlist.ExpectingItems == 0)\n Playlist.ExpectingItems = Playlist.Items.Count;\n\n if (Playlist.Items.Count > 1)\n {\n Log.Debug(\"Playlist Completed\");\n Playlist.UpdatePrevNextItem();\n }\n }\n\n public void ScrapeItem(PlaylistItem item)\n {\n var plugins = PluginsScrapeItem.Values.OrderBy(x => x.Priority);\n foreach (var plugin in plugins)\n {\n if (Interrupt)\n return;\n\n plugin.ScrapeItem(item);\n }\n }\n\n public PlaylistItem SuggestItem()\n {\n var plugins = PluginsSuggestItem.Values.OrderBy(x => x.Priority);\n foreach (var plugin in plugins)\n {\n if (Interrupt)\n return null;\n\n var item = plugin.SuggestItem();\n if (item != null)\n {\n Log.Info($\"SuggestItem #{item.Index} - {item.Title}\");\n return item;\n }\n }\n\n return null;\n }\n\n public ExternalVideoStream SuggestExternalVideo()\n {\n var plugins = PluginsSuggestExternalVideo.Values.OrderBy(x => x.Priority);\n foreach (var plugin in plugins)\n {\n if (Interrupt)\n return null;\n\n var extStream = plugin.SuggestExternalVideo();\n if (extStream != null)\n {\n Log.Info($\"SuggestVideo (External) {extStream.Width} x {extStream.Height} @ {extStream.FPS}\");\n Log.Debug($\"SuggestVideo (External) Url: {extStream.Url}, UrlFallback: {extStream.UrlFallback}\");\n return extStream;\n }\n }\n\n return null;\n }\n public ExternalAudioStream SuggestExternalAudio()\n {\n var plugins = PluginsSuggestExternalAudio.Values.OrderBy(x => x.Priority);\n foreach(var plugin in plugins)\n {\n if (Interrupt)\n return null;\n\n var extStream = plugin.SuggestExternalAudio();\n if (extStream != null)\n {\n Log.Info($\"SuggestAudio (External) {extStream.SampleRate} Hz, {extStream.Codec}\");\n Log.Debug($\"SuggestAudio (External) Url: {extStream.Url}, UrlFallback: {extStream.UrlFallback}\");\n return extStream;\n }\n }\n\n return null;\n }\n\n public VideoStream SuggestVideo(ObservableCollection streams)\n {\n if (streams == null || streams.Count == 0) return null;\n\n var plugins = PluginsSuggestVideoStream.Values.OrderBy(x => x.Priority);\n foreach(var plugin in plugins)\n {\n if (Interrupt)\n return null;\n\n var stream = plugin.SuggestVideo(streams);\n if (stream != null) return stream;\n }\n\n return null;\n }\n public void SuggestVideo(out VideoStream stream, out ExternalVideoStream extStream, ObservableCollection streams)\n {\n stream = null;\n extStream = null;\n\n if (Interrupt)\n return;\n\n stream = SuggestVideo(streams);\n if (stream != null)\n return;\n\n if (Interrupt)\n return;\n\n extStream = SuggestExternalVideo();\n }\n\n public AudioStream SuggestAudio(ObservableCollection streams)\n {\n if (streams == null || streams.Count == 0) return null;\n\n var plugins = PluginsSuggestAudioStream.Values.OrderBy(x => x.Priority);\n foreach(var plugin in plugins)\n {\n if (Interrupt)\n return null;\n\n var stream = plugin.SuggestAudio(streams);\n if (stream != null) return stream;\n }\n\n return null;\n }\n public void SuggestAudio(out AudioStream stream, out ExternalAudioStream extStream, ObservableCollection streams)\n {\n stream = null;\n extStream = null;\n\n if (Interrupt)\n return;\n\n stream = SuggestAudio(streams);\n if (stream != null)\n return;\n\n if (Interrupt)\n return;\n\n extStream = SuggestExternalAudio();\n }\n #endregion\n\n #region Subtitles\n public OpenSubtitlesResults OpenSubtitles(string url)\n {\n var plugins = PluginsOpenSubtitles.Values.OrderBy(x => x.Priority);\n foreach(var plugin in plugins)\n {\n var res = plugin.Open(url);\n if (res == null)\n continue;\n\n if (res.Error != null)\n return res;\n\n OpenedSubtitlesPlugin = plugin;\n Log.Info($\"[{plugin.Name}] Open Subtitles Success\");\n\n return res;\n }\n\n return null;\n }\n\n public bool SearchLocalSubtitles()\n {\n if (!Playlist.Selected.SearchedLocal && Config.Subtitles.SearchLocal && (Config.Subtitles.SearchLocalOnInputType == null || Config.Subtitles.SearchLocalOnInputType.Count == 0 || Config.Subtitles.SearchLocalOnInputType.Contains(Playlist.InputType)))\n {\n Log.Debug(\"[Subtitles] Searching Local\");\n var plugins = PluginsSearchLocalSubtitles.Values.OrderBy(x => x.Priority);\n foreach(var plugin in plugins)\n {\n if (Interrupt)\n return false;\n\n plugin.SearchLocalSubtitles();\n }\n\n Playlist.Selected.SearchedLocal = true;\n\n return true;\n }\n\n return false;\n }\n public void SearchOnlineSubtitles()\n {\n if (!Playlist.Selected.SearchedOnline && Config.Subtitles.SearchOnline && (Config.Subtitles.SearchOnlineOnInputType == null || Config.Subtitles.SearchOnlineOnInputType.Count == 0 || Config.Subtitles.SearchOnlineOnInputType.Contains(Playlist.InputType)))\n {\n Log.Debug(\"[Subtitles] Searching Online\");\n var plugins = PluginsSearchOnlineSubtitles.Values.OrderBy(x => x.Priority);\n foreach(var plugin in plugins)\n {\n if (Interrupt)\n return;\n\n plugin.SearchOnlineSubtitles();\n }\n\n Playlist.Selected.SearchedOnline = true;\n }\n }\n public bool DownloadSubtitles(ExternalSubtitlesStream extStream)\n {\n bool res = false;\n\n var plugins = PluginsDownloadSubtitles.Values.OrderBy(x => x.Priority);\n foreach(var plugin in plugins)\n if (res = plugin.DownloadSubtitles(extStream))\n {\n extStream.Downloaded = true;\n return res;\n }\n\n return res;\n }\n\n public ExternalSubtitlesStream SuggestBestExternalSubtitles()\n {\n var plugins = PluginsSuggestBestExternalSubtitles.Values.OrderBy(x => x.Priority);\n foreach(var plugin in plugins)\n {\n if (Interrupt)\n return null;\n\n var extStream = plugin.SuggestBestExternalSubtitles();\n if (extStream != null)\n return extStream;\n }\n\n return null;\n }\n public void SuggestSubtitles(out SubtitlesStream stream, out ExternalSubtitlesStream extStream)\n {\n stream = null;\n extStream = null;\n\n var plugins = PluginsSuggestSubtitles.Values.OrderBy(x => x.Priority);\n foreach(var plugin in plugins)\n {\n if (Interrupt)\n return;\n\n plugin.SuggestSubtitles(out stream, out extStream);\n if (stream != null || extStream != null)\n return;\n }\n }\n public SubtitlesStream SuggestSubtitles(ObservableCollection streams, List langs)\n {\n if (streams == null || streams.Count == 0) return null;\n\n var plugins = PluginsSuggestSubtitlesStream.Values.OrderBy(x => x.Priority);\n foreach(var plugin in plugins)\n {\n if (Interrupt)\n return null;\n\n var stream = plugin.SuggestSubtitles(streams, langs);\n if (stream != null)\n return stream;\n }\n\n return null;\n }\n #endregion\n\n #region Data\n public void SuggestData(out DataStream stream, ObservableCollection streams)\n {\n stream = null;\n\n if (Interrupt)\n return;\n\n stream = streams.FirstOrDefault();\n }\n #endregion\n}\n"], ["/LLPlayer/FlyleafLib/Engine/Config.cs", "using System.Collections.Generic;\nusing System.IO;\nusing System.Linq;\nusing System.Text.Json;\nusing System.Text.Json.Serialization;\nusing System.Threading;\nusing System.Threading.Tasks;\n\nusing FlyleafLib.Controls.WPF;\nusing FlyleafLib.MediaFramework.MediaDecoder;\nusing FlyleafLib.MediaFramework.MediaFrame;\nusing FlyleafLib.MediaFramework.MediaRenderer;\nusing FlyleafLib.MediaPlayer;\nusing FlyleafLib.MediaPlayer.Translation;\nusing FlyleafLib.MediaPlayer.Translation.Services;\nusing FlyleafLib.Plugins;\nusing static FlyleafLib.Utils;\n\nnamespace FlyleafLib;\n\n/// \n/// Player's configuration\n/// \npublic class Config : NotifyPropertyChanged\n{\n static JsonSerializerOptions jsonOpts = new() { WriteIndented = true };\n\n public Config()\n {\n // Parse default plugin options to Config.Plugins (Creates instances until fix with statics in interfaces)\n foreach (var plugin in Engine.Plugins.Types.Values)\n {\n var tmpPlugin = PluginHandler.CreatePluginInstance(plugin);\n var defaultOptions = tmpPlugin.GetDefaultOptions();\n tmpPlugin.Dispose();\n\n if (defaultOptions == null || defaultOptions.Count == 0) continue;\n\n Plugins.Add(plugin.Name, new ObservableDictionary());\n foreach (var opt in defaultOptions)\n Plugins[plugin.Name].Add(opt.Key, opt.Value);\n }\n // save default plugin options for later\n _PluginsDefault = Plugins;\n\n Player.config = this;\n Demuxer.config = this;\n }\n\n public Config(bool test) { }\n\n public Config Clone()\n {\n Config config = new()\n {\n Audio = Audio.Clone(),\n Video = Video.Clone(),\n Subtitles = Subtitles.Clone(),\n Demuxer = Demuxer.Clone(),\n Decoder = Decoder.Clone(),\n Player = Player.Clone()\n };\n\n config.Player.config = config;\n config.Demuxer.config = config;\n\n return config;\n }\n public static Config Load(string path, JsonSerializerOptions jsonOptions = null)\n {\n Config config = JsonSerializer.Deserialize(File.ReadAllText(path), jsonOptions);\n config.Loaded = true;\n config.LoadedPath = path;\n\n if (config.Audio.FiltersEnabled && Engine.Config.FFmpegLoadProfile == LoadProfile.Main)\n config.Audio.FiltersEnabled = false;\n\n // TODO: L: refactor\n config.Player.config = config;\n config.Demuxer.config = config;\n\n config.Subtitles.SetChildren();\n\n // Restore the plugin options initialized by the constructor, as they are overwritten during deserialization.\n\n // Remove removed plugin options\n foreach (var plugin in config.Plugins)\n {\n // plugin deleted\n if (!config._PluginsDefault.ContainsKey(plugin.Key))\n {\n config.Plugins.Remove(plugin.Key);\n continue;\n }\n\n // plugin option deleted\n foreach (var opt in plugin.Value)\n {\n if (!config._PluginsDefault[plugin.Key].ContainsKey(opt.Key))\n {\n config.Plugins[plugin.Key].Remove(opt.Key);\n }\n }\n }\n\n // Restore added plugin options\n foreach (var plugin in config._PluginsDefault)\n {\n // plugin added\n if (!config.Plugins.ContainsKey(plugin.Key))\n {\n config.Plugins[plugin.Key] = plugin.Value;\n continue;\n }\n\n // plugin option added\n foreach (var opt in plugin.Value)\n {\n if (!config.Plugins[plugin.Key].ContainsKey(opt.Key))\n {\n config.Plugins[plugin.Key][opt.Key] = opt.Value;\n }\n }\n }\n\n config.UpdateDefault();\n\n return config;\n }\n public void Save(string path = null, JsonSerializerOptions jsonOptions = null)\n {\n if (path == null)\n {\n if (string.IsNullOrEmpty(LoadedPath))\n return;\n\n path = LoadedPath;\n }\n\n jsonOptions ??= jsonOpts;\n\n File.WriteAllText(path, JsonSerializer.Serialize(this, jsonOptions));\n }\n\n private void UpdateDefault()\n {\n bool parsed = System.Version.TryParse(Version, out var loadedVer);\n\n if (!parsed || loadedVer <= System.Version.Parse(\"0.2.1\"))\n {\n // for FlyleafLib v3.8.3, Ensure extension_picky is set\n Demuxer.FormatOpt = DemuxerConfig.DefaultVideoFormatOpt();\n Demuxer.AudioFormatOpt = DemuxerConfig.DefaultVideoFormatOpt();\n Demuxer.SubtitlesFormatOpt = DemuxerConfig.DefaultVideoFormatOpt();\n\n\n // for subtitles search #91\n int ctrlFBindingIdx = Player.KeyBindings.Keys\n .FindIndex(k => k.Key == System.Windows.Input.Key.F &&\n k.Ctrl && !k.Alt && !k.Shift);\n if (ctrlFBindingIdx != -1)\n {\n // remove existing binding\n Player.KeyBindings.Keys.RemoveAt(ctrlFBindingIdx);\n }\n // set CTRL+F to subtitles search\n Player.KeyBindings.Keys.Add(new KeyBinding { Ctrl = true, Key = System.Windows.Input.Key.F, IsKeyUp = true, Action = KeyBindingAction.Custom, ActionName = \"ActivateSubsSearch\" });\n\n // Toggle always on top\n int ctrlTBindingIdx = Player.KeyBindings.Keys\n .FindIndex(k => k.Key == System.Windows.Input.Key.T &&\n k.Ctrl && !k.Alt && !k.Shift);\n if (ctrlTBindingIdx == -1)\n {\n Player.KeyBindings.Keys.Add(new KeyBinding { Ctrl = true, Key = System.Windows.Input.Key.T, IsKeyUp = true, Action = KeyBindingAction.Custom, ActionName = \"ToggleAlwaysOnTop\" });\n }\n\n // Set Ctrl+A for ToggleSubsAutoTextCopy (previous Alt+A)\n int ctrlABindingIdx = Player.KeyBindings.Keys\n .FindIndex(k => k.Key == System.Windows.Input.Key.A &&\n k.Ctrl && !k.Alt && !k.Shift);\n if (ctrlABindingIdx == -1)\n {\n Player.KeyBindings.Keys.Add(new KeyBinding { Ctrl = true, Key = System.Windows.Input.Key.A, IsKeyUp = true, Action = KeyBindingAction.Custom, ActionName = \"ToggleSubsAutoTextCopy\" });\n }\n }\n }\n\n internal void SetPlayer(Player player)\n {\n Player.player = player;\n Player.KeyBindings.SetPlayer(player);\n Demuxer.player = player;\n Decoder.player = player;\n Audio.player = player;\n Video.player = player;\n Subtitles.SetPlayer(player);\n }\n\n public string Version { get; set; }\n\n /// \n /// Whether configuration has been loaded from file\n /// \n [JsonIgnore]\n public bool Loaded { get; private set; }\n\n /// \n /// The path that this configuration has been loaded from\n /// \n [JsonIgnore]\n public string LoadedPath { get; private set; }\n\n public PlayerConfig Player { get; set; } = new PlayerConfig();\n public DemuxerConfig Demuxer { get; set; } = new DemuxerConfig();\n public DecoderConfig Decoder { get; set; } = new DecoderConfig();\n public VideoConfig Video { get; set; } = new VideoConfig();\n public AudioConfig Audio { get; set; } = new AudioConfig();\n public SubtitlesConfig Subtitles { get; set; } = new SubtitlesConfig();\n public DataConfig Data { get; set; } = new DataConfig();\n\n public Dictionary>\n Plugins { get; set; } = new();\n private\n Dictionary>\n _PluginsDefault;\n public class PlayerConfig : NotifyPropertyChanged\n {\n public PlayerConfig Clone()\n {\n PlayerConfig player = (PlayerConfig) MemberwiseClone();\n player.player = null;\n player.config = null;\n player.KeyBindings = KeyBindings.Clone();\n return player;\n }\n\n internal Player player;\n internal Config config;\n\n /// \n /// It will automatically start playing after open or seek after ended\n /// \n public bool AutoPlay { get; set; } = true;\n\n /// \n /// Required buffered duration ticks before playing\n /// \n public long MinBufferDuration {\n get => _MinBufferDuration;\n set\n {\n if (!Set(ref _MinBufferDuration, value)) return;\n if (config != null && value > config.Demuxer.BufferDuration)\n config.Demuxer.BufferDuration = value;\n }\n }\n long _MinBufferDuration = 500 * 10000;\n\n /// \n /// Key bindings configuration\n /// \n public KeysConfig\n KeyBindings { get; set; } = new KeysConfig();\n\n /// \n /// Fps while the player is not playing\n /// \n public double IdleFps { get; set; } = 60.0;\n\n /// \n /// Max Latency (ticks) forces playback (with speed x1+) to stay at the end of the live network stream (default: 0 - disabled)\n /// \n public long MaxLatency {\n get => _MaxLatency;\n set\n {\n if (value < 0)\n value = 0;\n\n if (!Set(ref _MaxLatency, value)) return;\n\n if (value == 0)\n {\n if (player != null)\n player.Speed = 1;\n\n if (config != null)\n config.Decoder.LowDelay = false;\n\n return;\n }\n\n // Large max buffer so we ensure the actual latency distance\n if (config != null)\n {\n if (config.Demuxer.BufferDuration < value * 2)\n config.Demuxer.BufferDuration = value * 2;\n\n config.Decoder.LowDelay = true;\n }\n\n // Small min buffer to avoid enabling latency speed directly\n if (_MinBufferDuration > value / 10)\n MinBufferDuration = value / 10;\n }\n }\n long _MaxLatency = 0;\n\n /// \n /// Min Latency (ticks) prevents MaxLatency to go (with speed x1) less than this limit (default: 0 - as low as possible)\n /// \n public long MinLatency { get => _MinLatency; set => Set(ref _MinLatency, value); }\n long _MinLatency = 0;\n\n /// \n /// Prevents frequent speed changes when MaxLatency is enabled (to avoid audio/video gaps and desyncs)\n /// \n public long LatencySpeedChangeInterval { get; set; } = TimeSpan.FromMilliseconds(700).Ticks;\n\n /// \n /// Folder to save recordings (when filename is not specified)\n /// \n public string FolderRecordings { get; set; } = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, \"Recordings\");\n\n /// \n /// Folder to save snapshots (when filename is not specified)\n /// \n\n public string FolderSnapshots { get; set; } = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, \"Snapshots\");\n\n /// \n /// Forces CurTime/SeekBackward/SeekForward to seek accurate on video\n /// \n public bool SeekAccurate { get => _SeekAccurate; set => Set(ref _SeekAccurate, value); }\n bool _SeekAccurate;\n\n /// \n /// Margin time to move back forward when doing an exact seek (ticks)\n /// \n public long SeekAccurateFixMargin { get; set => Set(ref field, value); } = TimeSpan.FromMilliseconds(0).Ticks;\n\n /// \n /// Margin time to move back forward when getting frame (ticks)\n /// \n public long SeekGetFrameFixMargin { get; set => Set(ref field, value); } = TimeSpan.FromMilliseconds(3000).Ticks;\n\n /// \n /// Snapshot encoding will be used (valid formats bmp, png, jpg/jpeg)\n /// \n public string SnapshotFormat { get ;set; } = \"bmp\";\n\n /// \n /// Whether to refresh statistics about bitrates/fps/drops etc.\n /// \n public bool Stats { get => _Stats; set => Set(ref _Stats, value); }\n bool _Stats = false;\n\n /// \n /// Sets playback's thread priority\n /// \n public ThreadPriority\n ThreadPriority { get; set; } = ThreadPriority.AboveNormal;\n\n /// \n /// Refreshes CurTime in UI on every frame (can cause performance issues)\n /// \n public bool UICurTimePerFrame { get; set; } = false;\n\n /// \n /// The upper limit of the volume amplifier\n /// \n public int VolumeMax { get => _VolumeMax; set { Set(ref _VolumeMax, value); if (player != null && player.Audio.masteringVoice != null) player.Audio.masteringVoice.Volume = value / 100f; } }\n int _VolumeMax = 150;\n\n /// \n /// The default volume\n /// \n public int VolumeDefault { get; set => Set(ref field, value); } = 75;\n\n /// \n /// The purpose of the player\n /// \n public Usage Usage { get; set; } = Usage.AVS;\n\n // Offsets\n public long AudioDelayOffset { get; set; } = 100 * 10000;\n public long AudioDelayOffset2 { get; set; } = 1000 * 10000;\n public long SubtitlesDelayOffset { get; set; } = 100 * 10000;\n public long SubtitlesDelayOffset2 { get; set; } = 1000 * 10000;\n public long SeekOffset { get; set; } = 1 * (long)1000 * 10000;\n public long SeekOffset2 { get; set; } = 5 * (long)1000 * 10000;\n public long SeekOffset3 { get; set; } = 15 * (long)1000 * 10000;\n public long SeekOffset4 { get; set; } = 30 * (long)1000 * 10000;\n public bool SeekOffsetAccurate { get; set; } = true;\n public bool SeekOffsetAccurate2 { get; set; } = false;\n public bool SeekOffsetAccurate3 { get; set; } = false;\n public bool SeekOffsetAccurate4 { get; set; } = false;\n public double SpeedOffset { get; set; } = 0.10;\n public double SpeedOffset2 { get; set; } = 0.25;\n public int ZoomOffset { get => _ZoomOffset; set { if (Set(ref _ZoomOffset, value)) player?.ResetAll(); } }\n int _ZoomOffset = 10;\n\n public int VolumeOffset { get; set; } = 5;\n }\n public class DemuxerConfig : NotifyPropertyChanged\n {\n public DemuxerConfig Clone()\n {\n DemuxerConfig demuxer = (DemuxerConfig) MemberwiseClone();\n\n demuxer.FormatOpt = new Dictionary();\n demuxer.AudioFormatOpt = new Dictionary();\n demuxer.SubtitlesFormatOpt = new Dictionary();\n\n foreach (var kv in FormatOpt) demuxer.FormatOpt.Add(kv.Key, kv.Value);\n foreach (var kv in AudioFormatOpt) demuxer.AudioFormatOpt.Add(kv.Key, kv.Value);\n foreach (var kv in SubtitlesFormatOpt) demuxer.SubtitlesFormatOpt.Add(kv.Key, kv.Value);\n\n demuxer.player = null;\n demuxer.config = null;\n\n return demuxer;\n }\n\n internal Player player;\n internal Config config;\n\n /// \n /// Whethere to allow avformat_find_stream_info during open (avoiding this can open the input faster but it could cause other issues)\n /// \n public bool AllowFindStreamInfo { get; set; } = true;\n\n /// \n /// Whether to enable demuxer's custom interrupt callback (for timeouts and interrupts)\n /// \n public bool AllowInterrupts { get; set; } = true;\n\n /// \n /// Whether to allow interrupts during av_read_frame\n /// \n public bool AllowReadInterrupts { get; set; } = true;\n\n /// \n /// Whether to allow timeouts checks within the interrupts callback\n /// \n public bool AllowTimeouts { get; set; } = true;\n\n /// \n /// List of FFmpeg formats to be excluded from interrupts\n /// \n public List ExcludeInterruptFmts{ get; set; } = new List() { \"rtsp\" };\n\n /// \n /// Maximum allowed duration ticks for buffering\n /// \n public long BufferDuration {\n get => _BufferDuration;\n set\n {\n if (!Set(ref _BufferDuration, value)) return;\n if (config != null && value < config.Player.MinBufferDuration)\n config.Player.MinBufferDuration = value;\n }\n }\n long _BufferDuration = 30 * (long)1000 * 10000;\n\n /// \n /// Maximuim allowed packets for buffering (as an extra check along with BufferDuration)\n /// \n public long BufferPackets { get; set; }\n\n /// \n /// Maximuim allowed audio packets (when reached it will drop the extra packets and will fire the AudioLimit event)\n /// \n public long MaxAudioPackets { get; set; }\n\n /// \n /// Maximum allowed errors before stopping\n /// \n public int MaxErrors { get; set; } = 30;\n\n /// \n /// Custom IO Stream buffer size (in bytes) for the AVIO Context\n /// \n public int IOStreamBufferSize\n { get; set; } = 0x200000;\n\n /// \n /// avformat_close_input timeout (ticks) for protocols that support interrupts\n /// \n public long CloseTimeout { get => closeTimeout; set { closeTimeout = value; closeTimeoutMs = value / 10000; } }\n private long closeTimeout = 1 * 1000 * 10000;\n internal long closeTimeoutMs = 1 * 1000;\n\n /// \n /// avformat_open_input + avformat_find_stream_info timeout (ticks) for protocols that support interrupts (should be related to probesize/analyzeduration)\n /// \n public long OpenTimeout { get => openTimeout; set { openTimeout = value; openTimeoutMs = value / 10000; } }\n private long openTimeout = 5 * 60 * (long)1000 * 10000;\n internal long openTimeoutMs = 5 * 60 * 1000;\n\n /// \n /// av_read_frame timeout (ticks) for protocols that support interrupts\n /// \n public long ReadTimeout { get => readTimeout; set { readTimeout = value; readTimeoutMs = value / 10000; } }\n private long readTimeout = 10 * 1000 * 10000;\n internal long readTimeoutMs = 10 * 1000;\n\n /// \n /// av_read_frame timeout (ticks) for protocols that support interrupts (for Live streams)\n /// \n public long ReadLiveTimeout { get => readLiveTimeout; set { readLiveTimeout = value; readLiveTimeoutMs = value / 10000; } }\n private long readLiveTimeout = 20 * 1000 * 10000;\n internal long readLiveTimeoutMs = 20 * 1000;\n\n /// \n /// av_seek_frame timeout (ticks) for protocols that support interrupts\n /// \n public long SeekTimeout { get => seekTimeout; set { seekTimeout = value; seekTimeoutMs = value / 10000; } }\n private long seekTimeout = 8 * 1000 * 10000;\n internal long seekTimeoutMs = 8 * 1000;\n\n /// \n /// Forces Input Format\n /// \n public string ForceFormat { get; set; }\n\n /// \n /// Forces FPS for NoTimestamp formats (such as h264/hevc)\n /// \n public double ForceFPS { get; set; }\n\n /// \n /// FFmpeg's format flags for demuxer (see https://ffmpeg.org/doxygen/trunk/avformat_8h.html)\n /// eg. FormatFlags |= 0x40; // For AVFMT_FLAG_NOBUFFER\n /// \n public DemuxerFlags FormatFlags { get; set; } = DemuxerFlags.DiscardCorrupt;// FFmpeg.AutoGen.ffmpeg.AVFMT_FLAG_DISCARD_CORRUPT;\n\n /// \n /// Certain muxers and demuxers do nesting (they open one or more additional internal format contexts). This will pass the FormatOpt and HTTPQuery params to the underlying contexts)\n /// \n public bool FormatOptToUnderlying\n { get; set; }\n\n /// \n /// Passes original's Url HTTP Query String parameters to underlying\n /// \n public bool DefaultHTTPQueryToUnderlying\n { get; set; } = true;\n\n /// \n /// HTTP Query String parameters to pass to underlying\n /// \n public Dictionary\n ExtraHTTPQueryParamsToUnderlying\n { get; set; } = new();\n\n /// \n /// FFmpeg's format options for demuxer\n /// \n public Dictionary\n FormatOpt { get; set; } = DefaultVideoFormatOpt();\n public Dictionary\n AudioFormatOpt { get; set; } = DefaultVideoFormatOpt();\n\n public Dictionary\n SubtitlesFormatOpt { get; set; } = DefaultVideoFormatOpt();\n\n public static Dictionary DefaultVideoFormatOpt()\n {\n // TODO: Those should be set based on the demuxer format/protocol (to avoid false warnings about invalid options and best fit for the input, eg. live stream)\n\n Dictionary defaults = new()\n {\n // General\n { \"probesize\", (50 * (long)1024 * 1024).ToString() }, // (Bytes) Default 5MB | Higher for weird formats (such as .ts?) and 4K/Hevc\n { \"analyzeduration\", (10 * (long)1000 * 1000).ToString() }, // (Microseconds) Default 5 seconds | Higher for network streams\n\n // HTTP\n { \"reconnect\", \"1\" }, // auto reconnect after disconnect before EOF\n { \"reconnect_streamed\", \"1\" }, // auto reconnect streamed / non seekable streams (this can cause issues with HLS ts segments - disable this or http_persistent)\n { \"reconnect_delay_max\",\"7\" }, // max reconnect delay in seconds after which to give up\n { \"user_agent\", \"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/92.0.4515.159 Safari/537.36\" },\n\n { \"extension_picky\", \"0\" }, // Added in ffmpeg v7.1.1 and causes issues when enabled with allowed extentions #577\n\n // HLS\n { \"http_persistent\", \"0\" }, // Disables keep alive for HLS - mainly when use reconnect_streamed and non-live HLS streams\n\n // RTSP\n { \"rtsp_transport\", \"tcp\" }, // Seems UDP causing issues\n };\n\n //defaults.Add(\"live_start_index\", \"-1\");\n //defaults.Add(\"timeout\", (2 * (long)1000 * 1000).ToString()); // (Bytes) Default 5MB | Higher for weird formats (such as .ts?)\n //defaults.Add(\"rw_timeout\", (2 * (long)1000 * 1000).ToString()); // (Microseconds) Default 5 seconds | Higher for network streams\n\n return defaults;\n }\n\n public Dictionary GetFormatOptPtr(MediaType type)\n => type == MediaType.Video ? FormatOpt : type == MediaType.Audio ? AudioFormatOpt : SubtitlesFormatOpt;\n }\n public class DecoderConfig : NotifyPropertyChanged\n {\n internal Player player;\n\n public DecoderConfig Clone()\n {\n DecoderConfig decoder = (DecoderConfig) MemberwiseClone();\n decoder.player = null;\n\n return decoder;\n }\n\n /// \n /// Threads that will be used from the decoder\n /// \n public int VideoThreads { get; set; } = Environment.ProcessorCount;\n\n /// \n /// Maximum video frames to be decoded and processed for rendering\n /// \n public int MaxVideoFrames { get => _MaxVideoFrames; set { if (Set(ref _MaxVideoFrames, value)) { player?.RefreshMaxVideoFrames(); } } }\n int _MaxVideoFrames = 4;\n\n /// \n /// Maximum audio frames to be decoded and processed for playback\n /// \n public int MaxAudioFrames { get; set; } = 10;\n\n /// \n /// Maximum subtitle frames to be decoded\n /// \n public int MaxSubsFrames { get; set; } = 1;\n\n /// \n /// Maximum data frames to be decoded\n /// \n public int MaxDataFrames { get; set; } = 100;\n\n /// \n /// Maximum allowed errors before stopping\n /// \n public int MaxErrors { get; set; } = 200;\n\n /// \n /// Whether or not to use decoder's textures directly as shader resources\n /// (TBR: Better performance but might need to be disabled while video input has padding or not supported by older Direct3D versions)\n /// \n public ZeroCopy ZeroCopy { get => _ZeroCopy; set { if (SetUI(ref _ZeroCopy, value) && player != null && player.Video.isOpened) player.VideoDecoder?.RecalculateZeroCopy(); } }\n ZeroCopy _ZeroCopy = ZeroCopy.Auto;\n\n /// \n /// Allows video accceleration even in codec's profile mismatch\n /// \n public bool AllowProfileMismatch\n { get => _AllowProfileMismatch; set => SetUI(ref _AllowProfileMismatch, value); }\n bool _AllowProfileMismatch;\n\n /// \n /// Allows corrupted frames (Parses AV_CODEC_FLAG_OUTPUT_CORRUPT to AVCodecContext)\n /// \n public bool ShowCorrupted { get => _ShowCorrupted; set => SetUI(ref _ShowCorrupted, value); }\n bool _ShowCorrupted;\n\n /// \n /// Forces low delay (Parses AV_CODEC_FLAG_LOW_DELAY to AVCodecContext) (auto-enabled with MaxLatency)\n /// \n public bool LowDelay { get => _LowDelay; set => SetUI(ref _LowDelay, value); }\n bool _LowDelay;\n\n public Dictionary\n AudioCodecOpt { get; set; } = new();\n public Dictionary\n VideoCodecOpt { get; set; } = new();\n public Dictionary\n SubtitlesCodecOpt { get; set; } = new();\n\n public Dictionary GetCodecOptPtr(MediaType type)\n => type == MediaType.Video ? VideoCodecOpt : type == MediaType.Audio ? AudioCodecOpt : SubtitlesCodecOpt;\n }\n public class VideoConfig : NotifyPropertyChanged\n {\n public VideoConfig Clone()\n {\n VideoConfig video = (VideoConfig) MemberwiseClone();\n video.player = null;\n\n return video;\n }\n\n internal Player player;\n\n /// \n /// Forces a specific GPU Adapter to be used by the renderer\n /// GPUAdapter must match with the description of the adapter eg. rx 580 (available adapters can be found in Engine.Video.GPUAdapters)\n /// \n public string GPUAdapter { get; set; }\n\n /// \n /// Video aspect ratio\n /// \n public AspectRatio AspectRatio { get => _AspectRatio; set { if (Set(ref _AspectRatio, value) && player != null && player.renderer != null && !player.renderer.SCDisposed) lock(player.renderer.lockDevice) { player.renderer.SetViewport(); if (player.renderer.child != null) player.renderer.child.SetViewport(); } } }\n AspectRatio _AspectRatio = AspectRatio.Keep;\n\n /// \n /// Custom aspect ratio (AspectRatio must be set to Custom to have an effect)\n /// \n public AspectRatio CustomAspectRatio { get => _CustomAspectRatio; set { if (Set(ref _CustomAspectRatio, value) && AspectRatio == AspectRatio.Custom) { _AspectRatio = AspectRatio.Fill; AspectRatio = AspectRatio.Custom; } } }\n AspectRatio _CustomAspectRatio = new(16, 9);\n\n /// \n /// Background color of the player's control\n /// \n public System.Windows.Media.Color\n BackgroundColor { get => VorticeToWPFColor(_BackgroundColor); set { Set(ref _BackgroundColor, WPFToVorticeColor(value)); player?.renderer?.UpdateBackgroundColor(); } }\n internal Vortice.Mathematics.Color _BackgroundColor = (Vortice.Mathematics.Color)Vortice.Mathematics.Colors.Black;\n\n /// \n /// Clears the screen on stop/close/open\n /// \n public bool ClearScreen { get; set; } = true;\n\n /// \n /// Whether video should be allowed\n /// \n public bool Enabled { get => _Enabled; set { if (Set(ref _Enabled, value)) if (value) player?.Video.Enable(); else player?.Video.Disable(); } }\n bool _Enabled = true;\n internal void SetEnabled(bool enabled) => Set(ref _Enabled, enabled, true, nameof(Enabled));\n\n /// \n /// Used to limit the number of frames rendered, particularly at increased speed\n /// \n public double MaxOutputFps { get; set; } = 60;\n\n /// \n /// DXGI Maximum Frame Latency (1 - 16)\n /// \n public uint MaxFrameLatency { get; set; } = 1;\n\n /// \n /// The max resolution that the current system can achieve and will be used from the input/stream suggester plugins\n /// \n [JsonIgnore]\n public int MaxVerticalResolutionAuto { get; internal set; }\n\n /// \n /// Custom max vertical resolution that will be used from the input/stream suggester plugins\n /// \n public int MaxVerticalResolutionCustom { get => _MaxVerticalResolutionCustom; set => Set(ref _MaxVerticalResolutionCustom, value); }\n int _MaxVerticalResolutionCustom;\n\n /// \n /// The max resolution that is currently used (based on Auto/Custom)\n /// \n [JsonIgnore]\n public int MaxVerticalResolution => MaxVerticalResolutionCustom == 0 ? (MaxVerticalResolutionAuto != 0 ? MaxVerticalResolutionAuto : 1080) : MaxVerticalResolutionCustom;\n\n /// \n /// In case of no hardware accelerated or post process accelerated pixel formats will use FFmpeg's SwsScale\n /// \n public bool SwsHighQuality { get; set; } = false;\n\n /// \n /// Forces SwsScale instead of FlyleafVP for non HW decoded frames\n /// \n public bool SwsForce { get; set; } = false;\n\n /// \n /// Activates Direct3D video acceleration (decoding)\n /// \n public bool VideoAcceleration { get; set => Set(ref field, value); } = true;\n\n /// \n /// Whether to use embedded video processor with custom pixel shaders or D3D11
\n /// (Currently D3D11 works only on video accelerated / hardware surfaces)
\n /// * FLVP supports HDR to SDR, D3D11 does not
\n /// * FLVP supports Pan Move/Zoom, D3D11 does not
\n /// * D3D11 possible performs better with color conversion and filters, FLVP supports only brightness/contrast filters
\n /// * D3D11 supports deinterlace (bob)\n ///
\n public VideoProcessors VideoProcessor { get => _VideoProcessor; set { if (Set(ref _VideoProcessor, value)) player?.renderer?.UpdateVideoProcessor(); } }\n VideoProcessors _VideoProcessor = VideoProcessors.Auto;\n\n /// \n /// Whether Vsync should be enabled (0: Disabled, 1: Enabled)\n /// \n public uint VSync { get; set; }\n\n /// \n /// Swap chain's present flags (mainly for waitable -None- or non-waitable -DoNotWait) (default: non-waitable)
\n /// Non-waitable swap chain will reduce re-buffering and audio/video desyncs\n ///
\n public Vortice.DXGI.PresentFlags\n PresentFlags { get; set; } = Vortice.DXGI.PresentFlags.DoNotWait;\n\n /// \n /// Enables the video processor to perform post process deinterlacing\n /// (D3D11 video processor should be enabled and support bob deinterlace method)\n /// \n public bool Deinterlace { get=> _Deinterlace; set { if (Set(ref _Deinterlace, value)) player?.renderer?.UpdateDeinterlace(); } }\n bool _Deinterlace;\n\n public bool DeinterlaceBottomFirst { get=> _DeinterlaceBottomFirst; set { if (Set(ref _DeinterlaceBottomFirst, value)) player?.renderer?.UpdateDeinterlace(); } }\n bool _DeinterlaceBottomFirst;\n\n /// \n /// The HDR to SDR method that will be used by the pixel shader\n /// \n public unsafe HDRtoSDRMethod\n HDRtoSDRMethod { get => _HDRtoSDRMethod; set { if (Set(ref _HDRtoSDRMethod, value) && player != null && player.VideoDecoder.VideoStream != null && player.VideoDecoder.VideoStream.ColorSpace == ColorSpace.BT2020) player.renderer.UpdateHDRtoSDR(); }}\n HDRtoSDRMethod _HDRtoSDRMethod = HDRtoSDRMethod.Hable;\n\n /// \n /// The HDR to SDR Tone float correnction (not used by Reinhard)\n /// \n public unsafe float HDRtoSDRTone { get => _HDRtoSDRTone; set { if (Set(ref _HDRtoSDRTone, value) && player != null && player.VideoDecoder.VideoStream != null && player.VideoDecoder.VideoStream.ColorSpace == ColorSpace.BT2020) player.renderer.UpdateHDRtoSDR(); } }\n float _HDRtoSDRTone = 1.4f;\n\n /// \n /// Whether the renderer will use 10-bit swap chaing or 8-bit output\n /// \n public bool Swap10Bit { get; set; }\n\n /// \n /// The number of buffers to use for the renderer's swap chain\n /// \n public uint SwapBuffers { get; set; } = 2;\n\n /// \n /// \n /// Whether the renderer will use R8G8B8A8_UNorm instead of B8G8R8A8_UNorm format for the swap chain (experimental)
\n /// (TBR: causes slightly different colors with D3D11VP)\n ///
\n ///
\n public bool SwapForceR8G8B8A8 { get; set; }\n\n public Dictionary Filters {get ; set; } = DefaultFilters();\n\n public static Dictionary DefaultFilters()\n {\n Dictionary filters = new();\n\n var available = Enum.GetValues(typeof(VideoFilters));\n\n foreach(object filter in available)\n filters.Add((VideoFilters)filter, new VideoFilter((VideoFilters)filter));\n\n return filters;\n }\n }\n public class AudioConfig : NotifyPropertyChanged\n {\n public AudioConfig Clone()\n {\n AudioConfig audio = (AudioConfig) MemberwiseClone();\n audio.player = null;\n\n return audio;\n }\n\n internal Player player;\n\n /// \n /// Audio delay ticks (will be reseted to 0 for every new audio stream)\n /// \n public long Delay { get => _Delay; set { if (player != null && !player.Audio.IsOpened) return; if (Set(ref _Delay, value)) player?.ReSync(player.decoder.AudioStream); } }\n long _Delay;\n internal void SetDelay(long delay) => Set(ref _Delay, delay, true, nameof(Delay));\n\n /// \n /// Whether audio should allowed\n /// \n public bool Enabled { get => _Enabled; set { if (Set(ref _Enabled, value)) if (value) player?.Audio.Enable(); else player?.Audio.Disable(); } }\n bool _Enabled = true;\n internal void SetEnabled(bool enabled) => Set(ref _Enabled, enabled, true, nameof(Enabled));\n\n /// \n /// Whether to process samples with Filters or SWR (experimental)
\n /// 1. Requires FFmpeg avfilter lib
\n /// 2. Currently SWR performs better if you dont need filters
\n ///
\n public bool FiltersEnabled { get => _FiltersEnabled; set { if (Set(ref _FiltersEnabled, value && Engine.Config.FFmpegLoadProfile != LoadProfile.Main)) player?.AudioDecoder.SetupFiltersOrSwr(); } }\n bool _FiltersEnabled = false;\n\n /// \n /// List of filters for post processing the audio samples (experimental)
\n /// (Requires FiltersEnabled)\n ///
\n public List Filters { get; set; }\n\n /// \n /// Audio languages preference by priority\n /// \n public List Languages\n {\n get\n {\n field ??= GetSystemLanguages();\n return field;\n }\n set => Set(ref field, value);\n }\n\n }\n\n public class SubConfig : NotifyPropertyChanged\n {\n internal Player player;\n\n public SubConfig()\n {\n }\n\n public SubConfig(int subIndex)\n {\n SubIndex = subIndex;\n }\n\n [JsonIgnore]\n public int SubIndex { get; set => Set(ref field, value); }\n\n [JsonIgnore]\n public bool EnabledTranslated\n {\n get;\n set\n {\n if (Set(ref field, value))\n {\n if (player == null)\n {\n return;\n }\n\n // Clear once to update the subtitle being displayed.\n player.sFramesPrev[SubIndex] = null;\n player.SubtitleClear(SubIndex);\n\n // Switching the display while leaving the translated text itself\n foreach (SubtitleData sub in player.SubtitlesManager[SubIndex].Subs)\n {\n sub.EnabledTranslated = field;\n }\n\n // Update text in sidebar\n player.SubtitlesManager[SubIndex].Refresh();\n }\n }\n } = false;\n\n /// \n /// Subtitle delay ticks (will be reset to 0 for every new subtitle stream)\n /// \n public long Delay\n {\n get => _delay;\n set\n {\n if (player == null || !player.Subtitles[SubIndex].Enabled)\n {\n return;\n }\n if (Set(ref _delay, value))\n {\n player.SubtitlesManager[SubIndex].SetCurrentTime(new TimeSpan(player.CurTime));\n player.ReSync(player.decoder.SubtitlesStreams[SubIndex]);\n }\n }\n }\n private long _delay;\n\n internal void SetDelay(long delay) => Set(ref _delay, delay, true, nameof(Delay));\n\n /// \n /// Whether subtitle should be visible\n /// TODO: L: should move to AppConfig?\n /// \n [JsonIgnore]\n public bool Visible { get; set => Set(ref field, value); } = true;\n\n /// \n /// OCR Engine Type\n /// \n public SubOCREngineType OCREngine { get; set => Set(ref field, value); } = SubOCREngineType.Tesseract;\n }\n\n public class SubtitlesConfig : NotifyPropertyChanged\n {\n public SubConfig[] SubConfigs { get; set; }\n\n public SubConfig this[int subIndex] => SubConfigs[subIndex];\n\n public SubtitlesConfig()\n {\n int subNum = 2;\n SubConfigs = new SubConfig[subNum];\n for (int i = 0; i < subNum; i++)\n {\n SubConfigs[i] = new SubConfig(i);\n }\n }\n\n internal void SetChildren()\n {\n for (int i = 0; i < SubConfigs.Length; i++)\n {\n SubConfigs[i].SubIndex = i;\n }\n }\n\n public SubtitlesConfig Clone()\n {\n SubtitlesConfig subs = new();\n subs = (SubtitlesConfig) MemberwiseClone();\n\n subs.Languages = new List();\n if (Languages != null) foreach(var lang in Languages) subs.Languages.Add(lang);\n\n subs.player = null;\n\n return subs;\n }\n\n internal Player player;\n internal void SetPlayer(Player player)\n {\n this.player = player;\n\n foreach (SubConfig conf in SubConfigs)\n {\n conf.player = player;\n }\n }\n\n /// \n /// Whether subtitles should be allowed\n /// \n public bool Enabled { get => _Enabled; set { if(Set(ref _Enabled, value)) if (value) player?.Subtitles.Enable(); else player?.Subtitles.Disable(); } }\n bool _Enabled = true;\n internal void SetEnabled(bool enabled) => Set(ref _Enabled, enabled, true, nameof(Enabled));\n\n /// \n /// Max number of subtitles (currently not configurable)\n /// \n public int Max { get; set => Set(ref field, value); } = 2;\n\n /// \n /// Whether to cache internal bitmap subtitles on memory\n /// Memory usage is larger since all bitmap are read on memory, but has the following advantages\n /// 1. Internal bitmap subtitles can be displayed in the sidebar\n /// 2. Can display bitmap subtitles during playback when seeking (mpv: can, VLC: cannot)\n /// \n public bool EnabledCached { get; set => Set(ref field, value); } = true;\n\n public bool OpenAutomaticSubs { get; set => Set(ref field, value); }\n\n /// \n /// Subtitle languages preference by priority\n /// \n public List Languages\n {\n get\n {\n field ??= GetSystemLanguages();\n return field;\n }\n set => Set(ref field, value);\n }\n\n /// \n /// Whether to use automatic language detection\n /// \n public bool LanguageAutoDetect { get; set => Set(ref field, value); } = true;\n\n /// \n /// Language to be used when source language was unknown (primary)\n /// \n public Language LanguageFallbackPrimary\n {\n get\n {\n field ??= Languages.FirstOrDefault();\n return field;\n }\n set => Set(ref field, value);\n }\n\n /// \n /// Language to be used when source language was unknown (secondary)\n /// \n public Language LanguageFallbackSecondary\n {\n get\n {\n if (LanguageFallbackSecondarySame)\n {\n return LanguageFallbackPrimary;\n }\n\n field ??= LanguageFallbackPrimary;\n\n return field;\n }\n set => Set(ref field, value);\n }\n\n /// \n /// Whether to use LanguageFallbackPrimary for secondary subtitles\n /// \n public bool LanguageFallbackSecondarySame\n {\n get;\n set\n {\n if (Set(ref field, value))\n {\n Raise(nameof(LanguageFallbackSecondary));\n }\n }\n } = true;\n\n /// \n /// Whether to use local search plugins (see also )\n /// \n public bool SearchLocal { get => _SearchLocal; set => Set(ref _SearchLocal, value); }\n bool _SearchLocal = false;\n\n public const string DefaultSearchLocalPaths = \"subs; subtitles\";\n\n public string SearchLocalPaths\n {\n get;\n set\n {\n if (Set(ref field, value))\n {\n CmdResetSearchLocalPaths.OnCanExecuteChanged();\n }\n }\n } = DefaultSearchLocalPaths;\n\n [JsonIgnore]\n public RelayCommand CmdResetSearchLocalPaths => field ??= new((_) =>\n {\n SearchLocalPaths = DefaultSearchLocalPaths;\n }, (_) => SearchLocalPaths != DefaultSearchLocalPaths);\n\n /// \n /// Allowed input types to be searched locally for subtitles (empty list allows all types)\n /// \n public List SearchLocalOnInputType\n { get; set; } = new List() { InputType.File, InputType.UNC, InputType.Torrent };\n\n /// \n /// Whether to use online search plugins (see also )\n /// \n public bool SearchOnline { get => _SearchOnline; set { Set(ref _SearchOnline, value); if (player != null && player.Video.isOpened) Task.Run(() => { if (player != null && player.Video.isOpened) player.decoder.SearchOnlineSubtitles(); }); } }\n bool _SearchOnline = false;\n\n /// \n /// Allowed input types to be searched online for subtitles (empty list allows all types)\n /// \n public List SearchOnlineOnInputType\n { get; set; } = new List() { InputType.File, InputType.Torrent };\n\n /// \n /// Subtitles parser (can be used for custom parsing)\n /// \n [JsonIgnore]\n public Action\n Parser { get; set; } = ParseSubtitles.Parse;\n\n #region ASR\n /// \n /// ASR Engine Type (Currently only supports OpenAI Whisper)\n /// \n public SubASREngineType ASREngine { get; set => Set(ref field, value); } = SubASREngineType.WhisperCpp;\n\n /// \n /// ASR OpenAI Whisper common config\n /// \n public WhisperConfig WhisperConfig { get; set => Set(ref field, value); } = new();\n\n /// \n /// ASR whisper.cpp config\n /// \n public WhisperCppConfig WhisperCppConfig { get; set => Set(ref field, value); } = new();\n\n /// \n /// ASR Faster-Whisper config\n /// \n public FasterWhisperConfig FasterWhisperConfig { get; set => Set(ref field, value); } = new();\n\n /// \n /// Chunk size (MB) when processing ASR with audio stream\n /// Increasing size will increase memory usage but may result in more natural subtitle breaks\n /// \n public int ASRChunkSizeMB\n {\n get;\n set\n {\n if (Set(ref field, value))\n {\n Raise(nameof(ASRChunkSize));\n }\n }\n } = 20;\n\n [JsonIgnore]\n public long ASRChunkSize => ASRChunkSizeMB * 1024 * 1024;\n\n /// \n /// Chunk seconds when processing ASR with audio stream\n /// In the case of network streams, etc., the size is small and can be divided by specifying the number of seconds.\n /// \n public int ASRChunkSeconds { get; set => Set(ref field, value); } = 20;\n #endregion\n\n #region OCR\n /// \n /// OCR Tesseract Region Settings (key: iso6391, value: LangCode)\n /// \n public Dictionary TesseractOcrRegions { get; set => Set(ref field, value); } = new();\n\n /// \n /// OCR Microsoft Region Settings (key: iso6391, value: LanguageTag (BCP-47)\n /// \n public Dictionary MsOcrRegions { get; set => Set(ref field, value); } = new();\n #endregion\n\n #region Translation\n /// \n /// Language to be translated to\n /// \n public TargetLanguage TranslateTargetLanguage\n {\n get;\n set\n {\n if (Set(ref field, value))\n {\n TranslateLanguage = Language.Get(value.ToISO6391());\n }\n }\n } = TargetLanguage.EnglishAmerican;\n\n [JsonIgnore]\n public Language TranslateLanguage { get; private set; }\n\n /// \n /// Translation Service Type\n /// \n public TranslateServiceType TranslateServiceType { get; set => Set(ref field, value); } = TranslateServiceType.GoogleV1;\n\n /// \n /// Translation Word Service Type\n /// \n public TranslateServiceType TranslateWordServiceType { get; set => Set(ref field, value); } = TranslateServiceType.GoogleV1;\n\n /// \n /// Translation Service Type Settings\n /// \n public Dictionary TranslateServiceSettings { get; set => Set(ref field, value); } = new();\n\n /// \n /// Maximum count backward\n /// \n public int TranslateCountBackward { get; set => Set(ref field, value); } = 1;\n\n /// \n /// Maximum count forward\n /// \n public int TranslateCountForward { get; set => Set(ref field, value); } = 12;\n\n /// \n /// Number of concurrent requests to translation services\n /// \n public int TranslateMaxConcurrency {\n get;\n set\n {\n if (value <= 0)\n return;\n\n Set(ref field, value);\n }\n } = 2;\n\n /// \n /// Chat-style LLM API config\n /// \n public TranslateChatConfig TranslateChatConfig { get; set => Set(ref field, value); } = new();\n #endregion\n }\n public class DataConfig : NotifyPropertyChanged\n {\n public DataConfig Clone()\n {\n DataConfig data = new();\n data = (DataConfig)MemberwiseClone();\n\n data.player = null;\n\n return data;\n }\n\n internal Player player;\n\n /// \n /// Whether data should be processed\n /// \n public bool Enabled { get => _Enabled; set { if (Set(ref _Enabled, value)) if (value) player?.Data.Enable(); else player?.Data.Disable(); } }\n bool _Enabled = false;\n internal void SetEnabled(bool enabled) => Set(ref _Enabled, enabled, true, nameof(Enabled));\n }\n}\n\n/// \n/// Engine's configuration\n/// \npublic class EngineConfig\n{\n public string Version { get; set; }\n\n /// \n /// It will not initiallize audio and will be disabled globally\n /// \n public bool DisableAudio { get; set; }\n\n /// \n /// Required to register ffmpeg libraries. Make sure you provide x86 or x64 based on your project.\n /// :<path> for relative path from current folder or any below\n /// <path> for absolute or relative path\n /// \n public string FFmpegPath { get; set; } = \"FFmpeg\";\n\n /// \n /// Can be used to choose which FFmpeg libs to load\n /// All (Devices & Filters)
\n /// Filters
\n /// Main
\n ///
\n public LoadProfile\n FFmpegLoadProfile { get; set; } = LoadProfile.Filters; // change default to disable devices\n\n /// \n /// Whether to allow HLS live seeking (this can cause segmentation faults in case of incompatible ffmpeg version with library's custom structures)\n /// \n public bool FFmpegHLSLiveSeek { get; set; }\n\n /// \n /// Sets FFmpeg logger's level\n /// \n public Flyleaf.FFmpeg.LogLevel\n FFmpegLogLevel { get => _FFmpegLogLevel; set { _FFmpegLogLevel = value; if (Engine.IsLoaded) FFmpegEngine.SetLogLevel(); } }\n Flyleaf.FFmpeg.LogLevel _FFmpegLogLevel = Flyleaf.FFmpeg.LogLevel.Quiet;\n\n /// \n /// Whether configuration has been loaded from file\n /// \n [JsonIgnore]\n public bool Loaded { get; private set; }\n\n /// \n /// The path that this configuration has been loaded from\n /// \n [JsonIgnore]\n public string LoadedPath { get; private set; }\n\n /// \n /// Sets loggers output\n /// :debug -> System.Diagnostics.Debug\n /// :console -> System.Console\n /// <path> -> Absolute or relative file path\n /// \n public string LogOutput { get => _LogOutput; set { _LogOutput = value; if (Engine.IsLoaded) Logger.SetOutput(); } }\n string _LogOutput = \"\";\n\n /// \n /// Sets logger's level\n /// \n public LogLevel LogLevel { get; set; } = LogLevel.Quiet;\n\n /// \n /// When the output is file it will append instead of overwriting\n /// \n public bool LogAppend { get; set; }\n\n /// \n /// Lines to cache before writing them to file\n /// \n public int LogCachedLines { get; set; } = 20;\n\n /// \n /// Sets the logger's datetime string format\n /// \n public string LogDateTimeFormat { get; set; } = \"HH.mm.ss.fff\";\n\n /// \n /// Required to register plugins. Make sure you provide x86 or x64 based on your project and same .NET framework.\n /// :<path> for relative path from current folder or any below\n /// <path> for absolute or relative path\n /// \n public string PluginsPath { get; set; } = \"Plugins\";\n\n /// \n /// Updates Player.CurTime when the second changes otherwise on every UIRefreshInterval\n /// \n public bool UICurTimePerSecond { get; set; } = true;\n\n /// \n /// Activates Master Thread to monitor all the players and perform the required updates\n /// Required for Activity Mode, Stats & Buffered Duration on Pause\n /// \n public bool UIRefresh { get => _UIRefresh; set { _UIRefresh = value; if (value && Engine.IsLoaded) Engine.StartThread(); } }\n static bool _UIRefresh;\n\n /// \n /// How often should update the UI in ms (low values can cause performance issues)\n /// Should UIRefreshInterval < 1000ms and 1000 % UIRefreshInterval == 0 for accurate per second stats\n /// \n public int UIRefreshInterval { get; set; } = 250;\n\n /// \n /// Loads engine's configuration\n /// \n /// Absolute or relative path to load the configuraiton\n /// JSON serializer options\n // \n public static EngineConfig Load(string path, JsonSerializerOptions jsonOptions = null)\n {\n EngineConfig config = JsonSerializer.Deserialize(File.ReadAllText(path), jsonOptions);\n config.Loaded = true;\n config.LoadedPath = path;\n\n return config;\n }\n\n /// \n /// Saves engine's current configuration\n /// \n /// Absolute or relative path to save the configuration\n /// JSON serializer options\n public void Save(string path = null, JsonSerializerOptions jsonOptions = null)\n {\n if (path == null)\n {\n if (string.IsNullOrEmpty(LoadedPath))\n return;\n\n path = LoadedPath;\n }\n\n jsonOptions ??= new JsonSerializerOptions { WriteIndented = true };\n\n File.WriteAllText(path, JsonSerializer.Serialize(this, jsonOptions));\n }\n}\n"], ["/LLPlayer/Plugins/YoutubeDL/YoutubeDL.cs", "using System;\nusing System.Collections.Generic;\nusing System.Diagnostics;\nusing System.IO;\nusing System.Linq;\nusing System.Text.Json;\nusing System.Text.Json.Serialization;\nusing System.Text.RegularExpressions;\nusing System.Threading;\nusing System.Threading.Tasks;\nusing FlyleafLib.MediaFramework.MediaDemuxer;\nusing FlyleafLib.MediaFramework.MediaPlaylist;\nusing FlyleafLib.MediaFramework.MediaStream;\n\nusing static FlyleafLib.Utils;\n\nnamespace FlyleafLib.Plugins\n{\n public class YoutubeDL : PluginBase, IOpen, ISuggestExternalAudio, ISuggestExternalVideo\n {\n /* TODO\n * 1) Check Audio streams if we need to add also video streams with audio\n * 2) Check Best Audio bitrates/quality (mainly for audio only player)\n * 3) Dispose ytdl and not tag it to every item (use only format if required)\n * 4) Use playlist_index to set the default playlist item\n */\n\n public new int Priority { get; set; } = 1999;\n static string plugin_path = \"yt-dlp.exe\";\n static JsonSerializerOptions\n jsonSettings = new() { DefaultIgnoreCondition = JsonIgnoreCondition.WhenWritingNull };\n\n FileSystemWatcher watcher;\n string workingDir;\n\n Process proc;\n int procId = -1;\n object procLocker = new();\n\n bool addingItem;\n string dynamicOptions = \"\";\n bool errGenericImpersonate;\n long sessionId = -1; // same for playlists\n int retries;\n\n static HashSet\n subsExt = new(StringComparer.OrdinalIgnoreCase) { \"vtt\", \"srt\", \"ass\", \"ssa\" };\n\n public override Dictionary GetDefaultOptions()\n => new()\n {\n { \"ExtraArguments\", \"\" }, // TBR: Restore default functionality with --cookies-from-browser {defaultBrowser} || https://github.com/yt-dlp/yt-dlp/issues/7271\n { \"MaxVideoHeight\", \"720\" },\n { \"PreferVideoWithAudio\", \"False\" },\n };\n\n public override void OnInitializing()\n => DisposeInternal();\n\n public override void Dispose()\n => DisposeInternal();\n\n private Format GetAudioOnly(YoutubeDLJson ytdl)\n {\n // Prefer best with no video and protocol\n // Prioritize m3u8 protocol because https is very slow on YouTube\n var m3u8Formats = ytdl.formats.Where(f => f.protocol == \"m3u8_native\").ToList();\n for (int i = m3u8Formats.Count - 1; i >= 0; i--)\n if (HasAudio(m3u8Formats[i]) && !HasVideo(m3u8Formats[i]))\n return m3u8Formats[i];\n\n // Prefer best with no video (dont waste bandwidth)\n for (int i = ytdl.formats.Count - 1; i >= 0; i--)\n if (HasAudio(ytdl.formats[i]) && !HasVideo(ytdl.formats[i]))\n return ytdl.formats[i];\n\n // Prefer audio from worst video?\n for (int i = 0; i < ytdl.formats.Count; i++)\n if (HasAudio(ytdl.formats[i]))\n return ytdl.formats[i];\n\n return null;\n }\n private Format GetBestMatch(YoutubeDLJson ytdl)\n {\n // TODO: Expose in settings (vCodecs Blacklist) || Create a HW decoding failed list dynamic (check also for whitelist)\n List vCodecsBlacklist = [];\n\n int maxHeight;\n\n if (int.TryParse(Options[\"MaxVideoHeight\"], out var height) && height > 0)\n maxHeight = Math.Min(Config.Video.MaxVerticalResolution, height);\n else\n maxHeight = Config.Video.MaxVerticalResolution;\n\n // Video Streams Order based on Screen Resolution\n var iresults =\n from format in ytdl.formats\n where HasVideo(format) && format.height <= maxHeight && (!Regex.IsMatch(format.protocol, \"dash\", RegexOptions.IgnoreCase) || format.vcodec.ToLower() == \"vp9\")\n orderby format.width descending,\n format.height descending,\n format.protocol descending, // prefer m3u8 over https (for performance)\n format.vcodec descending, // prefer vp09 over avc (for performance)\n format.tbr descending,\n format.fps descending\n select format;\n\n if (iresults == null || iresults.Count() == 0)\n {\n // Fall-back to any\n iresults =\n from format in ytdl.formats\n where HasVideo(format)\n orderby format.width descending,\n format.height descending,\n format.protocol descending,\n format.vcodec descending,\n format.tbr descending,\n format.fps descending\n select format;\n\n if (iresults == null || iresults.Count() == 0) return null;\n }\n\n List results = iresults.ToList();\n\n // Best Resolution\n double bestWidth = results[0].width;\n double bestHeight = results[0].height;\n\n // Choose from the best resolution (0. with acodec and not blacklisted 1. not blacklisted 2. any)\n int priority = 1;\n if (bool.TryParse(Options[\"PreferVideoWithAudio\"], out var v) && v)\n {\n priority = 0;\n }\n while (priority < 3)\n {\n for (int i = 0; i < results.Count; i++)\n {\n if (results[i].width != bestWidth || results[i].height != bestHeight)\n break;\n\n if (priority == 0 && !IsBlackListed(vCodecsBlacklist, results[i].vcodec) && results[i].acodec != \"none\")\n return results[i];\n else if (priority == 1 && !IsBlackListed(vCodecsBlacklist, results[i].vcodec))\n return results[i];\n else if (priority == 2)\n return results[i];\n }\n\n priority++;\n }\n\n return results[results.Count - 1]; // Fall-back to any\n }\n private static bool IsBlackListed(List blacklist, string codec)\n {\n foreach (string codec2 in blacklist)\n if (Regex.IsMatch(codec, codec2, RegexOptions.IgnoreCase))\n return true;\n\n return false;\n }\n private static bool HasVideo(Format fmt)\n {\n if (fmt.height > 0 || fmt.vbr > 0 || fmt.vcodec != \"none\")\n return true;\n\n return false;\n }\n private static bool HasAudio(Format fmt)\n {\n if (fmt.abr > 0 || fmt.acodec != \"none\")\n return true;\n\n return false;\n }\n\n private static bool IsAutomaticSubtitle(string url)\n {\n if (url.Contains(\"youtube\") && url.Contains(\"/api/timedtext\"))\n return true;\n\n return false;\n }\n\n private void DisposeInternal()\n {\n lock (procLocker)\n {\n if (Disposed)\n return;\n\n Log.Debug($\"Disposing ({procId})\");\n\n if (procId != -1)\n {\n Process.Start(new ProcessStartInfo\n {\n FileName = \"taskkill\",\n Arguments = $\"/pid {procId} /f /t\",\n CreateNoWindow = true,\n UseShellExecute = false,\n WindowStyle = ProcessWindowStyle.Hidden,\n }).WaitForExit();\n }\n\n retries = 0;\n sessionId = -1;\n dynamicOptions = \"\";\n errGenericImpersonate = false;\n\n if (watcher != null)\n {\n watcher.Dispose();\n watcher = null;\n }\n\n if (workingDir != null)\n {\n Log.Debug($\"Folder deleted ({workingDir})\");\n Directory.Delete(workingDir, true);\n workingDir = null;\n }\n\n Disposed = true;\n Log.Debug($\"Disposed ({procId})\");\n }\n }\n\n private void NewPlaylistItem(string path)\n {\n string json = null;\n\n // File Watcher informs us on rename but the process still accessing the file\n for (int i=0; i<3; i++)\n {\n Thread.Sleep(20);\n try { json = File.ReadAllText(path); } catch { if (sessionId != Handler.OpenCounter) return; continue; }\n break;\n }\n\n YoutubeDLJson ytdl = null;\n\n try\n {\n ytdl = JsonSerializer.Deserialize(json, jsonSettings);\n } catch (Exception e)\n {\n Log.Error($\"[JsonSerializer] {e.Message}\");\n }\n\n if (sessionId != Handler.OpenCounter) return;\n\n if (ytdl == null)\n return;\n\n if (ytdl._type == \"playlist\")\n return;\n\n PlaylistItem item = new();\n\n if (Playlist.ExpectingItems == 0)\n Playlist.ExpectingItems = (int)ytdl.playlist_count;\n\n if (Playlist.Title == null)\n {\n if (!string.IsNullOrEmpty(ytdl.playlist_title))\n {\n Playlist.Title = ytdl.playlist_title;\n Log.Debug($\"Playlist Title -> {Playlist.Title}\");\n }\n else if (!string.IsNullOrEmpty(ytdl.playlist))\n {\n Playlist.Title = ytdl.playlist;\n Log.Debug($\"Playlist Title -> {Playlist.Title}\");\n }\n }\n\n item.Title = ytdl.title;\n Log.Debug($\"Adding {item.Title}\");\n\n item.DirectUrl = ytdl.webpage_url;\n\n if (ytdl.chapters != null && ytdl.chapters.Count > 0)\n {\n item.Chapters.AddRange(ytdl.chapters.Select(c => new Demuxer.Chapter()\n {\n StartTime = TimeSpan.FromSeconds(c.start_time).Ticks,\n EndTime = TimeSpan.FromSeconds(c.end_time).Ticks,\n Title = c.title\n }));\n }\n\n // If no formats still could have a single format attched to the main root class\n if (ytdl.formats == null)\n ytdl.formats = [ytdl];\n\n // Audio / Video Streams\n for (int i=0; i addedUrl = new(); // for de-duplication\n\n if (ytdl.automatic_captions != null)\n {\n foreach (var subtitle1 in ytdl.automatic_captions)\n {\n if (sessionId != Handler.OpenCounter)\n return;\n\n // original (source) language has this suffix\n const string suffix = \"-orig\";\n\n string langCode = subtitle1.Key;\n bool isOriginal = langCode.EndsWith(suffix, StringComparison.OrdinalIgnoreCase);\n\n if (isOriginal)\n {\n // remove -orig suffix\n langCode = langCode[..^suffix.Length];\n }\n\n Language lang = Language.Get(langCode);\n\n foreach (var subtitle in subtitle1.Value)\n {\n if (!subsExt.Contains(subtitle.ext))\n continue;\n\n bool automatic = IsAutomaticSubtitle(subtitle.url);\n\n if (!isOriginal && automatic) // always load original subtitle\n {\n // Automatic subtitles are loaded under the following ORed conditions\n // 1. If the language matches the set language\n // 2. Subtitles in the same language as the video\n if (!(Config.Subtitles.Languages.Contains(lang) || videoLang != Language.Unknown && videoLang == lang))\n {\n continue;\n }\n }\n\n // because -orig may be duplicated\n if (!addedUrl.Add(subtitle.url))\n continue;\n\n AddExternalStream(new ExternalSubtitlesStream()\n {\n Downloaded = true,\n Protocol = subtitle.ext,\n Language = lang,\n Url = subtitle.url,\n Automatic = automatic\n }, null, item);\n }\n }\n }\n } catch (Exception e) { Log.Warn($\"Failed to add subtitles ({e.Message})\"); }\n\n AddPlaylistItem(item, ytdl);\n }\n public void AddHeaders(ExternalStream extStream, Format fmt)\n {\n if (fmt.http_headers != null)\n {\n if (fmt.http_headers.TryGetValue(\"User-Agent\", out string value))\n {\n extStream.UserAgent = value;\n fmt.http_headers.Remove(\"User-Agent\");\n }\n\n if (fmt.http_headers.TryGetValue(\"Referer\", out value))\n {\n extStream.Referrer = value;\n fmt.http_headers.Remove(\"Referer\");\n }\n\n extStream.HTTPHeaders = fmt.http_headers;\n\n if (!string.IsNullOrEmpty(fmt.cookies))\n extStream.HTTPHeaders.Add(\"Cookies\", fmt.cookies);\n\n }\n }\n\n public bool CanOpen()\n {\n try\n {\n if (Playlist.IOStream != null)\n return false;\n\n Uri uri = new(Playlist.Url);\n string scheme = uri.Scheme.ToLower();\n\n if (scheme != \"http\" && scheme != \"https\")\n return false;\n\n string ext = GetUrlExtention(uri.AbsolutePath);\n\n if (ext == \"m3u8\" || ext == \"mp3\" || ext == \"m3u\" || ext == \"pls\")\n return false;\n\n // TBR: try to avoid processing radio stations\n if (string.IsNullOrEmpty(uri.PathAndQuery) || uri.PathAndQuery.Length < 5)\n return false;\n\n } catch (Exception) { return false; }\n\n return true;\n }\n public OpenResults Open()\n {\n try\n {\n lock (procLocker)\n {\n Disposed = false;\n sessionId = Handler.OpenCounter;\n Playlist.InputType = InputType.Web;\n\n workingDir = Path.GetTempPath() + Guid.NewGuid().ToString();\n\n Log.Debug($\"Folder created ({workingDir})\");\n Directory.CreateDirectory(workingDir);\n proc = new Process\n {\n EnableRaisingEvents = true,\n\n StartInfo = new ProcessStartInfo\n {\n FileName = Path.Combine(Engine.Plugins.Folder, Name, plugin_path),\n Arguments = $\"{dynamicOptions}{Options[\"ExtraArguments\"]} --no-check-certificate --skip-download --youtube-skip-dash-manifest --write-info-json -P \\\"{workingDir}\\\" \\\"{Playlist.Url}\\\" -o \\\"%(title).220B\\\"\", // 418 max filename length\n CreateNoWindow = true,\n UseShellExecute = false,\n WindowStyle = ProcessWindowStyle.Hidden,\n RedirectStandardError = true,\n RedirectStandardOutput = Logger.CanDebug,\n }\n };\n\n proc.Exited += (o, e) =>\n {\n lock (procLocker)\n {\n if (Logger.CanDebug)\n Log.Debug($\"Process completed ({(procId == -1 ? \"Killed\" : $\"{procId}\")})\");\n\n proc.Close();\n proc = null;\n procId = -1;\n }\n };\n\n proc.ErrorDataReceived += (o, e) =>\n {\n if (sessionId != Handler.OpenCounter || e.Data == null)\n return;\n\n Log.Debug($\"[stderr] {e.Data}\");\n\n if (!errGenericImpersonate && e.Data.Contains(\"generic:impersonate\"))\n errGenericImpersonate = true;\n };\n\n if (Logger.CanDebug)\n proc.OutputDataReceived += (o, e) =>\n {\n if (sessionId == Handler.OpenCounter)\n Log.Debug($\"[stdout] {e.Data}\");\n };\n\n watcher = new()\n {\n Path = workingDir,\n EnableRaisingEvents = true,\n };\n watcher.Renamed += (o, e) =>\n {\n try\n {\n if (sessionId != Handler.OpenCounter)\n return;\n\n addingItem = true;\n\n NewPlaylistItem(e.FullPath);\n\n if (Playlist.Items.Count == 1)\n Handler.OnPlaylistCompleted();\n\n } catch (Exception e2) { Log.Warn($\"Renamed Event Error {e2.Message} | {sessionId != Handler.OpenCounter}\");\n } finally { addingItem = false; }\n };\n\n proc.Start();\n procId = proc.Id;\n Log.Debug($\"Process started ({procId})\");\n\n // Don't try to read them at once at the end as the buffers (hardcoded to 4096) can be full and proc will freeze\n proc.BeginErrorReadLine();\n if (Logger.CanDebug)\n proc.BeginOutputReadLine();\n }\n\n while (Playlist.Items.Count < 1 && (proc != null || addingItem) && sessionId == Handler.OpenCounter)\n Thread.Sleep(35);\n\n if (sessionId != Handler.OpenCounter)\n {\n Log.Info(\"Session cancelled\");\n DisposeInternal();\n return null;\n }\n\n if (Playlist.Items.Count == 0) // Allow fallback to default plugin in case of YT-DLP bug with windows filename (this affects proper direct URLs as well)\n {\n if (!errGenericImpersonate || retries > 0)\n return null;\n\n Log.Warn(\"Re-trying with --extractor-args \\\"generic:impersonate\\\"\");\n DisposeInternal();\n retries = 1;\n dynamicOptions = \"--extractor-args \\\"generic:impersonate\\\" \";\n return Open();\n }\n }\n catch (Exception e) { Log.Error($\"Open ({e.Message})\"); return new(e.Message); }\n\n return new();\n }\n\n public OpenResults OpenItem()\n => new();\n\n public ExternalAudioStream SuggestExternalAudio()\n {\n if (Handler.OpenedPlugin == null || Handler.OpenedPlugin.Name != Name)\n return null;\n\n var fmt = GetAudioOnly((YoutubeDLJson)GetTag(Selected));\n if (fmt == null)\n return null;\n\n foreach (var extStream in Selected.ExternalAudioStreams)\n if (fmt.url == extStream.Url)\n return extStream;\n\n return null;\n }\n public ExternalVideoStream SuggestExternalVideo()\n {\n if (Handler.OpenedPlugin == null || Handler.OpenedPlugin.Name != Name)\n return null;\n\n Format fmt = GetBestMatch((YoutubeDLJson)GetTag(Selected));\n if (fmt == null)\n return null;\n\n foreach (var extStream in Selected.ExternalVideoStreams)\n if (fmt.url == extStream.Url)\n return extStream;\n\n return null;\n }\n }\n}\n"], ["/LLPlayer/FlyleafLib/MediaPlayer/SubtitlesASR.cs", "using System.Collections.Concurrent;\nusing System.Collections.Generic;\nusing System.Diagnostics;\nusing System.IO;\nusing System.Linq;\nusing System.Runtime.CompilerServices;\nusing System.Text;\nusing System.Text.RegularExpressions;\nusing System.Threading;\nusing System.Threading.Channels;\nusing System.Threading.Tasks;\nusing CliWrap;\nusing CliWrap.Builders;\nusing CliWrap.EventStream;\nusing FlyleafLib.MediaFramework.MediaDecoder;\nusing FlyleafLib.MediaFramework.MediaDemuxer;\nusing FlyleafLib.MediaFramework.MediaStream;\nusing Whisper.net;\nusing Whisper.net.LibraryLoader;\nusing Whisper.net.Logger;\nusing static FlyleafLib.Logger;\n\nnamespace FlyleafLib.MediaPlayer;\n\n#nullable enable\n\n// TODO: L: Pause and resume ASR\n\n/// \n/// Running ASR from a media file\n/// \n/// \n/// Read in a separate thread from the video playback.\n/// Note that multiple threads cannot seek to multiple locations for a single AVFormatContext,\n/// so it is necessary to open it with another avformat_open_input for the same video.\n/// \npublic class SubtitlesASR\n{\n private readonly SubtitlesManager _subtitlesManager;\n private readonly Config _config;\n private readonly Lock _locker = new();\n private readonly Lock _lockerSubs = new();\n private CancellationTokenSource? _cts = null;\n public HashSet SubIndexSet { get; } = new();\n\n private readonly LogHandler Log;\n\n public SubtitlesASR(SubtitlesManager subtitlesManager, Config config)\n {\n _subtitlesManager = subtitlesManager;\n _config = config;\n\n Log = new LogHandler((\"[#1]\").PadRight(8, ' ') + \" [SubtitlesASR ] \");\n }\n\n /// \n /// Check that ASR is executable\n /// \n /// error information\n /// \n public bool CanExecute(out string err)\n {\n if (_config.Subtitles.ASREngine == SubASREngineType.WhisperCpp)\n {\n if (_config.Subtitles.WhisperCppConfig.Model == null)\n {\n err = \"whisper.cpp model is not set. Please download it from the settings.\";\n return false;\n }\n\n if (!File.Exists(_config.Subtitles.WhisperCppConfig.Model.ModelFilePath))\n {\n err = $\"whisper.cpp model file '{_config.Subtitles.WhisperCppConfig.Model.ModelFileName}' does not exist in the folder. Please download it from the settings.\";\n return false;\n }\n }\n else if (_config.Subtitles.ASREngine == SubASREngineType.FasterWhisper)\n {\n if (_config.Subtitles.FasterWhisperConfig.UseManualEngine)\n {\n if (!File.Exists(_config.Subtitles.FasterWhisperConfig.ManualEnginePath))\n {\n err = \"faster-whisper engine does not exist in the manual path.\";\n return false;\n }\n }\n else\n {\n if (!File.Exists(FasterWhisperConfig.DefaultEnginePath))\n {\n err = \"faster-whisper engine is not downloaded. Please download it from the settings.\";\n return false;\n }\n }\n\n if (_config.Subtitles.FasterWhisperConfig.UseManualModel)\n {\n if (!Directory.Exists(_config.Subtitles.FasterWhisperConfig.ManualModelDir))\n {\n err = \"faster-whisper manual model directory does not exist.\";\n return false;\n }\n }\n }\n\n err = \"\";\n\n return true;\n }\n\n /// \n /// Open media file and read all subtitle data from audio\n /// \n /// 0: Primary, 1: Secondary\n /// media file path\n /// Audio streamIndex\n /// Demuxer type\n /// Current playback timestamp, from which whisper is run\n /// true: process completed, false: run in progress\n public bool Execute(int subIndex, string url, int streamIndex, MediaType type, TimeSpan curTime)\n {\n // When Dual ASR: Copy the other ASR result and return early\n if (SubIndexSet.Count > 0 && !SubIndexSet.Contains(subIndex))\n {\n lock (_lockerSubs)\n {\n SubIndexSet.Add(subIndex);\n int otherIndex = (subIndex + 1) % 2;\n\n if (_subtitlesManager[otherIndex].Subs.Count > 0)\n {\n bool enableTranslated = _config.Subtitles[subIndex].EnabledTranslated;\n\n // Copy other ASR result\n _subtitlesManager[subIndex]\n .Load(_subtitlesManager[otherIndex].Subs.Select(s =>\n {\n SubtitleData clone = s.Clone();\n\n if (!enableTranslated)\n {\n clone.TranslatedText = null;\n clone.EnabledTranslated = true;\n }\n\n return clone;\n }));\n\n if (!_subtitlesManager[otherIndex].IsLoading)\n {\n // Copy the language source if one of them is already done.\n _subtitlesManager[subIndex].LanguageSource = _subtitlesManager[otherIndex].LanguageSource;\n }\n }\n }\n\n // return early\n return false;\n }\n\n // If it has already been executed, cancel it to start over from the current playback position.\n if (SubIndexSet.Contains(subIndex))\n {\n Dictionary> prevSubs = new();\n HashSet prevSubIndexSet = [.. SubIndexSet];\n lock (_lockerSubs)\n {\n // backup current result\n foreach (int i in SubIndexSet)\n {\n prevSubs[i] = _subtitlesManager[i].Subs.ToList();\n }\n }\n // Cancel preceding execution and wait\n TryCancel(true);\n\n // restore previous result\n lock (_lockerSubs)\n {\n foreach (int i in prevSubIndexSet)\n {\n _subtitlesManager[i].Load(prevSubs[i]);\n // Re-enable spinner\n _subtitlesManager[i].StartLoading();\n\n SubIndexSet.Add(i);\n }\n }\n }\n\n lock (_locker)\n {\n SubIndexSet.Add(subIndex);\n\n _cts = new CancellationTokenSource();\n using AudioReader reader = new(_config, subIndex);\n reader.Open(url, streamIndex, type, _cts.Token);\n\n if (_cts.Token.IsCancellationRequested)\n {\n return true;\n }\n\n reader.ReadAll(curTime, data =>\n {\n if (_cts.Token.IsCancellationRequested)\n {\n return;\n }\n\n lock (_lockerSubs)\n {\n foreach (int i in SubIndexSet)\n {\n bool isInit = false;\n if (_subtitlesManager[i].LanguageSource == null)\n {\n isInit = true;\n\n // Delete subtitles after the first subtitle to be added (leave the previous one)\n _subtitlesManager[i].DeleteAfter(data.StartTime);\n\n // Set language\n // Can currently only be set for the whole, not per subtitle\n _subtitlesManager[i].LanguageSource = Language.Get(data.Language);\n }\n\n SubtitleData sub = new()\n {\n Text = data.Text,\n StartTime = data.StartTime,\n EndTime = data.EndTime,\n#if DEBUG\n ChunkNo = data.ChunkNo,\n StartTimeChunk = data.StartTimeChunk,\n EndTimeChunk = data.EndTimeChunk,\n#endif\n };\n\n _subtitlesManager[i].Add(sub);\n if (isInit)\n {\n _subtitlesManager[i].SetCurrentTime(new TimeSpan(_config.Subtitles.player.CurTime));\n }\n }\n }\n }, _cts.Token);\n\n if (!_cts.Token.IsCancellationRequested)\n {\n // TODO: L: Notify, express completion in some way\n Utils.PlayCompletionSound();\n }\n\n foreach (int i in SubIndexSet)\n {\n lock (_lockerSubs)\n {\n // Stop spinner (required when dual ASR)\n _subtitlesManager[i].StartLoading().Dispose();\n }\n }\n }\n\n return true;\n }\n\n public void TryCancel(bool isWait)\n {\n var cts = _cts;\n if (cts != null)\n {\n if (!cts.IsCancellationRequested)\n {\n lock (_lockerSubs)\n {\n foreach (var i in SubIndexSet)\n {\n _subtitlesManager[i].Clear();\n }\n }\n\n cts.Cancel();\n lock (_lockerSubs)\n {\n SubIndexSet.Clear();\n }\n }\n else\n {\n Log.Info(\"Already cancel requested\");\n }\n\n if (!isWait)\n {\n return;\n }\n\n lock (_locker)\n {\n // dispose after it is no longer used.\n cts.Dispose();\n _cts = null;\n }\n }\n }\n\n public void Reset(int subIndex)\n {\n if (!SubIndexSet.Contains(subIndex))\n return;\n\n if (SubIndexSet.Count == 2)\n {\n lock (_lockerSubs)\n {\n // When Dual ASR: only the state is cleared without stopping ASR execution.\n SubIndexSet.Remove(subIndex);\n _subtitlesManager[subIndex].Clear();\n }\n\n return;\n }\n\n // cancel asynchronously as it takes time to cancel.\n TryCancel(false);\n }\n}\n\npublic class AudioReader : IDisposable\n{\n private readonly Config _config;\n private readonly int _subIndex;\n\n private Demuxer? _demuxer;\n private AudioDecoder? _decoder;\n private AudioStream? _stream;\n\n private unsafe AVPacket* _packet = null;\n private unsafe AVFrame* _frame = null;\n private unsafe SwrContext* _swrContext = null;\n\n private bool _isFile;\n\n private readonly LogHandler Log;\n\n public AudioReader(Config config, int subIndex)\n {\n _config = config;\n _subIndex = subIndex;\n Log = new LogHandler((\"[#1]\").PadRight(8, ' ') + \" [AudioReader ] \");\n }\n\n public void Open(string url, int streamIndex, MediaType type, CancellationToken token)\n {\n _demuxer = new Demuxer(_config.Demuxer, type, _subIndex + 1, false);\n\n token.Register(() =>\n {\n if (_demuxer != null)\n _demuxer.Interrupter.ForceInterrupt = 1;\n });\n\n _demuxer.Log.Prefix = _demuxer.Log.Prefix.Replace(\"Demuxer: \", \"DemuxerA:\");\n string? error = _demuxer.Open(url);\n\n if (error != null)\n {\n if (token.IsCancellationRequested)\n return;\n\n throw new InvalidOperationException($\"demuxer open error: {error}\");\n }\n\n _stream = (AudioStream)_demuxer.AVStreamToStream[streamIndex];\n\n _decoder = new AudioDecoder(_config, _subIndex + 1);\n _decoder.Log.Prefix = _decoder.Log.Prefix.Replace(\"Decoder: \", \"DecoderA:\");\n\n error = _decoder.Open(_stream);\n\n if (error != null)\n {\n if (token.IsCancellationRequested)\n return;\n\n throw new InvalidOperationException($\"decoder open error: {error}\");\n }\n\n _isFile = File.Exists(url);\n }\n\n private record struct AudioChunk(MemoryStream Stream, int ChunkNumber, TimeSpan Start, TimeSpan End);\n\n /// \n /// Extract audio files in WAV format and run Whisper\n /// \n /// Current playback timestamp, from which whisper is run\n /// Action to process one result\n /// \n /// \n /// \n public void ReadAll(TimeSpan curTime, Action addSub, CancellationToken cancellationToken)\n {\n if (_demuxer == null || _decoder == null || _stream == null)\n throw new InvalidOperationException(\"Open() is not called\");\n\n // Assume a network stream and parallelize the reading of packets and the execution of whisper.\n // For network video, increase capacity as downloads may take longer.\n // (concern that memory usage will increase by three times the chunk size)\n int capacity = _isFile ? 1 : 2;\n BoundedChannelOptions channelOptions = new(capacity)\n {\n SingleReader = true,\n SingleWriter = true,\n };\n Channel channel = Channel.CreateBounded(channelOptions);\n\n // own cancellation for producer/consumer\n var cts = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken);\n CancellationToken token = cts.Token;\n\n ConcurrentStack memoryStreamPool = new();\n\n // Consumer: Run whisper\n Task consumerTask = Task.Run(DoConsumer, token);\n\n // Producer: Extract WAV and pass to consumer\n Task producerTask = Task.Run(DoProducer, token);\n\n // complete channel\n producerTask.ContinueWith(t =>\n channel.Writer.Complete(), token);\n\n // When an exception occurs in both consumer and producer, the other is canceled.\n consumerTask.ContinueWith(t =>\n cts.Cancel(), TaskContinuationOptions.OnlyOnFaulted);\n producerTask.ContinueWith(t =>\n cts.Cancel(), TaskContinuationOptions.OnlyOnFaulted);\n\n try\n {\n Task.WhenAll(consumerTask, producerTask).Wait();\n }\n catch (AggregateException)\n {\n if (cancellationToken.IsCancellationRequested)\n {\n // canceled by caller\n if (CanDebug) Log.Debug(\"Whisper canceled\");\n return;\n }\n\n // canceled because of exceptions\n throw;\n }\n\n return;\n\n async Task DoConsumer()\n {\n await using IASRService asrService = _config.Subtitles.ASREngine switch\n {\n SubASREngineType.WhisperCpp => new WhisperCppASRService(_config),\n SubASREngineType.FasterWhisper => new FasterWhisperASRService(_config),\n _ => throw new InvalidOperationException()\n };\n\n while (await channel.Reader.WaitToReadAsync(token))\n {\n // Use TryPeek() to reduce the channel capacity by one.\n if (!channel.Reader.TryPeek(out AudioChunk chunk))\n throw new InvalidOperationException(\"can not peek AudioChunk from channel\");\n\n try\n {\n if (CanDebug) Log.Debug(\n $\"Reading chunk from channel (chunkNo: {chunk.ChunkNumber}, start: {chunk.Start}, end: {chunk.End})\");\n\n //// Output wav file for debugging\n //await using (FileStream fs = new($\"subtitlewhisper-{chunk.ChunkNumber}.wav\", FileMode.Create, FileAccess.Write))\n //{\n // chunk.Stream.WriteTo(fs);\n // chunk.Stream.Position = 0;\n //}\n\n await foreach (var data in asrService.Do(chunk.Stream, token))\n {\n TimeSpan start = chunk.Start.Add(data.start);\n TimeSpan end = chunk.Start.Add(data.end);\n if (end > chunk.End)\n {\n // Shorten by 20 ms to prevent the next subtitle from being covered\n end = chunk.End.Subtract(TimeSpan.FromMilliseconds(20));\n }\n\n SubtitleASRData subData = new()\n {\n Text = data.text,\n Language = data.language,\n StartTime = start,\n EndTime = end,\n#if DEBUG\n ChunkNo = chunk.ChunkNumber,\n StartTimeChunk = chunk.Start,\n EndTimeChunk = chunk.End\n#endif\n };\n\n if (CanDebug) Log.Debug(string.Format(\"{0}->{1} ({2}->{3}): {4}\",\n start, end,\n chunk.Start, chunk.End,\n data.text));\n\n addSub(subData);\n }\n }\n finally\n {\n chunk.Stream.SetLength(0);\n memoryStreamPool.Push(chunk.Stream);\n\n if (!channel.Reader.TryRead(out _))\n throw new InvalidOperationException(\"can not discard AudioChunk from channel\");\n }\n }\n }\n\n unsafe void DoProducer()\n {\n _packet = av_packet_alloc();\n _frame = av_frame_alloc();\n\n // Whisper from the current playback position\n // TODO: L: Fold back and allow the first half to run as well.\n if (curTime > TimeSpan.FromSeconds(30))\n {\n // copy from DecoderContext.CalcSeekTimestamp()\n long startTime = _demuxer.hlsCtx == null ? _demuxer.StartTime : _demuxer.hlsCtx->first_timestamp * 10;\n long ticks = curTime.Ticks + startTime;\n\n bool forward = false;\n\n if (_demuxer.Type == MediaType.Audio) ticks -= _config.Audio.Delay;\n\n if (ticks < startTime)\n {\n ticks = startTime;\n forward = true;\n }\n else if (ticks > startTime + _demuxer.Duration - (50 * 10000))\n {\n ticks = Math.Max(startTime, startTime + _demuxer.Duration - (50 * 10000));\n forward = false;\n }\n\n _ = _demuxer.Seek(ticks, forward);\n }\n\n // When passing the audio file to Whisper, it must be converted to a 16000 sample rate WAV file.\n // For this purpose, the ffmpeg API is used to perform the conversion.\n // Audio files are divided by a certain size, stored in memory, and passed by memory stream.\n int targetSampleRate = 16000;\n int targetChannel = 1;\n MemoryStream waveStream = new(); // MemoryStream does not need to be disposed for releasing memory\n TimeSpan waveDuration = TimeSpan.Zero; // for logging\n\n const int waveHeaderSize = 44;\n\n // Stream processing is performed by dividing the audio by a certain size and passing it to whisper.\n long chunkSize = _config.Subtitles.ASRChunkSize;\n // Also split by elapsed seconds for live\n TimeSpan chunkElapsed = TimeSpan.FromSeconds(_config.Subtitles.ASRChunkSeconds);\n Stopwatch chunkSw = new();\n chunkSw.Start();\n\n WriteWavHeader(waveStream, targetSampleRate, targetChannel);\n\n int chunkCnt = 0;\n TimeSpan? chunkStart = null;\n long framePts = AV_NOPTS_VALUE;\n\n int demuxErrors = 0;\n int decodeErrors = 0;\n\n while (!token.IsCancellationRequested)\n {\n _demuxer.Interrupter.ReadRequest();\n int ret = av_read_frame(_demuxer.fmtCtx, _packet);\n\n if (ret != 0)\n {\n av_packet_unref(_packet);\n\n if (_demuxer.Interrupter.Timedout)\n {\n if (token.IsCancellationRequested)\n break;\n\n ret.ThrowExceptionIfError(\"av_read_frame (timed out)\");\n }\n\n if (ret == AVERROR_EOF || token.IsCancellationRequested)\n {\n break;\n }\n\n // demux error\n if (CanWarn) Log.Warn($\"av_read_frame: {FFmpegEngine.ErrorCodeToMsg(ret)} ({ret})\");\n\n if (++demuxErrors == _config.Demuxer.MaxErrors)\n {\n ret.ThrowExceptionIfError(\"av_read_frame\");\n }\n continue;\n }\n\n // Discard all but the selected audio stream.\n if (_packet->stream_index != _stream.StreamIndex)\n {\n av_packet_unref(_packet);\n continue;\n }\n\n ret = avcodec_send_packet(_decoder.CodecCtx, _packet);\n av_packet_unref(_packet);\n\n if (ret != 0)\n {\n if (ret == AVERROR(EAGAIN))\n {\n // Receive_frame and send_packet both returned EAGAIN, which is an API violation.\n ret.ThrowExceptionIfError(\"avcodec_send_packet (EAGAIN)\");\n }\n\n // decoder error\n if (CanWarn) Log.Warn($\"avcodec_send_packet: {FFmpegEngine.ErrorCodeToMsg(ret)} ({ret})\");\n\n if (++decodeErrors == _config.Decoder.MaxErrors)\n {\n ret.ThrowExceptionIfError(\"avcodec_send_packet\");\n }\n\n continue;\n }\n\n while (ret >= 0)\n {\n ret = avcodec_receive_frame(_decoder.CodecCtx, _frame);\n if (ret == AVERROR(EAGAIN) || ret == AVERROR_EOF)\n {\n break;\n }\n ret.ThrowExceptionIfError(\"avcodec_receive_frame\");\n\n if (_frame->best_effort_timestamp != AV_NOPTS_VALUE)\n {\n framePts = _frame->best_effort_timestamp;\n }\n else if (_frame->pts != AV_NOPTS_VALUE)\n {\n framePts = _frame->pts;\n }\n else\n {\n // Certain encoders sometimes cannot get pts (APE, Musepack)\n framePts += _frame->duration;\n }\n\n waveDuration = waveDuration.Add(new TimeSpan((long)(_frame->duration * _stream.Timebase)));\n\n if (chunkStart == null)\n {\n chunkStart = new TimeSpan((long)(framePts * _stream.Timebase) - _demuxer.StartTime);\n if (chunkStart.Value.Ticks < 0)\n {\n // Correct to 0 if negative\n chunkStart = new TimeSpan(0);\n }\n }\n\n ResampleTo(waveStream, _frame, targetSampleRate, targetChannel);\n\n // TODO: L: want it to split at the silent part\n if (waveStream.Length >= chunkSize || chunkSw.Elapsed >= chunkElapsed)\n {\n TimeSpan chunkEnd = new TimeSpan((long)(framePts * _stream.Timebase) - _demuxer.StartTime);\n chunkCnt++;\n\n if (CanInfo) Log.Info(\n $\"Process chunk (chunkNo: {chunkCnt}, sizeMB: {waveStream.Length / 1024 / 1024}, duration: {waveDuration}, elapsed: {chunkSw.Elapsed})\");\n\n UpdateWavHeader(waveStream);\n\n AudioChunk chunk = new(waveStream, chunkCnt, chunkStart.Value, chunkEnd);\n\n if (CanDebug) Log.Debug($\"Writing chunk to channel ({chunkCnt})\");\n // if channel capacity reached, it will be waited\n channel.Writer.WriteAsync(chunk, token).AsTask().Wait(token);\n if (CanDebug) Log.Debug($\"Done writing chunk to channel ({chunkCnt})\");\n\n if (memoryStreamPool.TryPop(out var stream))\n waveStream = stream;\n else\n waveStream = new MemoryStream();\n\n WriteWavHeader(waveStream, targetSampleRate, targetChannel);\n waveDuration = TimeSpan.Zero;\n\n chunkStart = null;\n chunkSw.Restart();\n framePts = AV_NOPTS_VALUE;\n }\n }\n }\n\n token.ThrowIfCancellationRequested();\n\n // Process remaining\n if (waveStream.Length > waveHeaderSize && framePts != AV_NOPTS_VALUE)\n {\n TimeSpan chunkEnd = new TimeSpan((long)(framePts * _stream.Timebase) - _demuxer.StartTime);\n\n chunkCnt++;\n\n if (CanInfo) Log.Info(\n $\"Process last chunk (chunkNo: {chunkCnt}, sizeMB: {waveStream.Length / 1024 / 1024}, duration: {waveDuration}, elapsed: {chunkSw.Elapsed})\");\n\n UpdateWavHeader(waveStream);\n\n AudioChunk chunk = new(waveStream, chunkCnt, chunkStart!.Value, chunkEnd);\n\n if (CanDebug) Log.Debug($\"Writing last chunk to channel ({chunkCnt})\");\n channel.Writer.WriteAsync(chunk, token).AsTask().Wait(token);\n if (CanDebug) Log.Debug($\"Done writing last chunk to channel ({chunkCnt})\");\n }\n }\n }\n\n private static void WriteWavHeader(Stream stream, int sampleRate, int channels)\n {\n using BinaryWriter writer = new(stream, Encoding.UTF8, true);\n writer.Write(['R', 'I', 'F', 'F']);\n writer.Write(0); // placeholder for file size\n writer.Write(['W', 'A', 'V', 'E']);\n writer.Write(['f', 'm', 't', ' ']);\n writer.Write(16); // PCM header size\n writer.Write((short)1); // PCM format\n writer.Write((short)channels);\n writer.Write(sampleRate);\n writer.Write(sampleRate * channels * 2); // Byte rate\n writer.Write((short)(channels * 2)); // Block align\n writer.Write((short)16); // Bits per sample\n writer.Write(['d', 'a', 't', 'a']);\n writer.Write(0); // placeholder for data size\n }\n\n private static void UpdateWavHeader(Stream stream)\n {\n long fileSize = stream.Length;\n stream.Seek(4, SeekOrigin.Begin);\n stream.Write(BitConverter.GetBytes((int)(fileSize - 8)), 0, 4);\n stream.Seek(40, SeekOrigin.Begin);\n stream.Write(BitConverter.GetBytes((int)(fileSize - 44)), 0, 4);\n stream.Position = 0;\n }\n\n private byte[] _sampledBuf = [];\n private int _sampledBufSize;\n\n // for codec change detection\n private int _lastFormat;\n private int _lastSampleRate;\n private ulong _lastChannelLayout;\n\n private unsafe void ResampleTo(Stream toStream, AVFrame* frame, int targetSampleRate, int targetChannel)\n {\n bool codecChanged = false;\n\n if (_lastFormat != frame->format)\n {\n _lastFormat = frame->format;\n codecChanged = true;\n }\n if (_lastSampleRate != frame->sample_rate)\n {\n _lastSampleRate = frame->sample_rate;\n codecChanged = true;\n }\n if (_lastChannelLayout != frame->ch_layout.u.mask)\n {\n _lastChannelLayout = frame->ch_layout.u.mask;\n codecChanged = true;\n }\n\n // Reinitialize SwrContext because codec changed\n // Note that native error will occur if not reinitialized.\n // Reference: AudioDecoder::RunInternal\n if (_swrContext != null && codecChanged)\n {\n fixed (SwrContext** ptr = &_swrContext)\n {\n swr_free(ptr);\n }\n _swrContext = null;\n }\n\n if (_swrContext == null)\n {\n AVChannelLayout outLayout;\n av_channel_layout_default(&outLayout, targetChannel);\n\n // NOTE: important to reuse this context\n fixed (SwrContext** ptr = &_swrContext)\n {\n swr_alloc_set_opts2(\n ptr,\n &outLayout,\n AVSampleFormat.S16,\n targetSampleRate,\n &frame->ch_layout,\n (AVSampleFormat)frame->format,\n frame->sample_rate,\n 0, null)\n .ThrowExceptionIfError(\"swr_alloc_set_opts2\");\n\n swr_init(_swrContext)\n .ThrowExceptionIfError(\"swr_init\");\n }\n }\n\n // ffmpeg ref: https://github.com/FFmpeg/FFmpeg/blob/504df09c34607967e4109b7b114ee084cf15a3ae/libavfilter/af_aresample.c#L171-L227\n double ratio = targetSampleRate * 1.0 / frame->sample_rate; // 16000:44100=0.36281179138321995\n int nOut = (int)(frame->nb_samples * ratio) + 32;\n\n long delay = swr_get_delay(_swrContext, targetSampleRate);\n if (delay > 0)\n {\n nOut += (int)Math.Min(delay, Math.Max(4096, nOut));\n }\n int needed = nOut * targetChannel * sizeof(ushort);\n\n if (_sampledBufSize < needed)\n {\n _sampledBuf = new byte[needed];\n _sampledBufSize = needed;\n }\n\n int samplesPerChannel;\n\n fixed (byte* dst = _sampledBuf)\n {\n samplesPerChannel = swr_convert(\n _swrContext,\n &dst,\n nOut,\n frame->extended_data,\n frame->nb_samples);\n }\n samplesPerChannel.ThrowExceptionIfError(\"swr_convert\");\n\n int resampledDataSize = samplesPerChannel * targetChannel * sizeof(ushort);\n\n toStream.Write(_sampledBuf, 0, resampledDataSize);\n }\n\n private bool _isDisposed;\n\n public unsafe void Dispose()\n {\n if (_isDisposed)\n return;\n\n // av_frame_alloc\n if (_frame != null)\n {\n fixed (AVFrame** ptr = &_frame)\n {\n av_frame_free(ptr);\n }\n }\n\n // av_packet_alloc\n if (_packet != null)\n {\n fixed (AVPacket** ptr = &_packet)\n {\n av_packet_free(ptr);\n }\n }\n\n // swr_init\n if (_swrContext != null)\n {\n fixed (SwrContext** ptr = &_swrContext)\n {\n swr_free(ptr);\n }\n }\n\n _decoder?.Dispose();\n if (_demuxer != null)\n {\n _demuxer.Interrupter.ForceInterrupt = 0;\n _demuxer.Dispose();\n }\n\n _isDisposed = true;\n }\n}\n\npublic interface IASRService : IAsyncDisposable\n{\n public IAsyncEnumerable<(string text, TimeSpan start, TimeSpan end, string language)> Do(MemoryStream waveStream, CancellationToken token);\n}\n\n// https://github.com/sandrohanea/whisper.net\n// https://github.com/ggerganov/whisper.cpp\npublic class WhisperCppASRService : IASRService\n{\n private readonly Config _config;\n\n private readonly LogHandler Log;\n private readonly IDisposable _logger;\n private readonly WhisperFactory _factory;\n private readonly WhisperProcessor _processor;\n\n private readonly bool _isLanguageDetect;\n private string? _detectedLanguage;\n\n public WhisperCppASRService(Config config)\n {\n _config = config;\n Log = new LogHandler((\"[#1]\").PadRight(8, ' ') + \" [WhisperCpp ] \");\n\n if (_config.Subtitles.WhisperCppConfig.RuntimeLibraries.Count >= 1)\n {\n RuntimeOptions.RuntimeLibraryOrder = [.. _config.Subtitles.WhisperCppConfig.RuntimeLibraries];\n }\n else\n {\n RuntimeOptions.RuntimeLibraryOrder = [RuntimeLibrary.Cpu, RuntimeLibrary.CpuNoAvx]; // fallback to default\n }\n\n _logger = CanDebug\n ? LogProvider.AddLogger((level, s) => Log.Debug($\"[Whisper.net] [{level.ToString()}] {s}\"))\n : Disposable.Empty;\n\n if (CanDebug) Log.Debug($\"Selecting whisper runtime libraries from ({string.Join(\",\", RuntimeOptions.RuntimeLibraryOrder)})\");\n\n _factory = WhisperFactory.FromPath(_config.Subtitles.WhisperCppConfig.Model!.ModelFilePath, _config.Subtitles.WhisperCppConfig.GetFactoryOptions());\n\n if (CanDebug) Log.Debug($\"Selected whisper runtime library '{RuntimeOptions.LoadedLibrary}'\");\n\n WhisperProcessorBuilder whisperBuilder = _factory.CreateBuilder();\n _processor = _config.Subtitles.WhisperCppConfig.ConfigureBuilder(_config.Subtitles.WhisperConfig, whisperBuilder).Build();\n\n if (_config.Subtitles.WhisperCppConfig.IsEnglishModel)\n {\n _isLanguageDetect = false;\n _detectedLanguage = \"en\";\n }\n else\n {\n _isLanguageDetect = _config.Subtitles.WhisperConfig.LanguageDetection;\n }\n }\n\n public async ValueTask DisposeAsync()\n {\n await _processor.DisposeAsync();\n _factory.Dispose();\n _logger.Dispose();\n }\n\n public async IAsyncEnumerable<(string text, TimeSpan start, TimeSpan end, string language)> Do(MemoryStream waveStream, [EnumeratorCancellation] CancellationToken token)\n {\n // If language detection is on, set detected language manually\n // TODO: L: Currently this is set because language information is managed for the entire subtitle,\n // but if language information is maintained for each subtitle, it should not be set.\n if (_isLanguageDetect && _detectedLanguage is not null)\n {\n _processor.ChangeLanguage(_detectedLanguage);\n }\n\n await foreach (var result in _processor.ProcessAsync(waveStream, token).ConfigureAwait(false))\n {\n token.ThrowIfCancellationRequested();\n\n if (_detectedLanguage is null && !string.IsNullOrEmpty(result.Language))\n {\n _detectedLanguage = result.Language;\n }\n\n string text = result.Text.Trim(); // remove leading whitespace\n\n yield return (text, result.Start, result.End, result.Language);\n }\n }\n}\n\n// https://github.com/Purfview/whisper-standalone-win\n// Purfview's Stand-alone Faster-Whisper-XXL & Faster-Whisper\n// Do not support official OpenAI Whisper version\npublic partial class FasterWhisperASRService : IASRService\n{\n private readonly Config _config;\n\n public FasterWhisperASRService(Config config)\n {\n _config = config;\n\n _cmdBase = BuildCommand(_config.Subtitles.FasterWhisperConfig, _config.Subtitles.WhisperConfig);\n\n if (_config.Subtitles.FasterWhisperConfig.IsEnglishModel)\n {\n // force English and disable auto-detection\n _isLanguageDetect = false;\n _manualLanguage = \"en\";\n }\n else\n {\n _isLanguageDetect = _config.Subtitles.WhisperConfig.LanguageDetection;\n _manualLanguage = _config.Subtitles.WhisperConfig.Language;\n }\n\n if (!_config.Subtitles.FasterWhisperConfig.UseManualModel)\n {\n WhisperConfig.EnsureModelsDirectory();\n }\n }\n\n private readonly Command _cmdBase;\n private readonly bool _isLanguageDetect;\n private readonly string _manualLanguage;\n private string? _detectedLanguage;\n\n [GeneratedRegex(\"^Detected language '(.+)' with probability\")]\n private static partial Regex LanguageReg { get; }\n\n [GeneratedRegex(@\"^\\[\\d{2}:\\d{2}\\.\\d{3} --> \\d{2}:\\d{2}\\.\\d{3}\\] \")]\n private static partial Regex SubShortReg { get; } // [08:15.050 --> 08:16.450] Text\n\n [GeneratedRegex(@\"^\\[\\d{2}:\\d{2}:\\d{2}\\.\\d{3} --> \\d{2}:\\d{2}:\\d{2}\\.\\d{3}\\] \")]\n private static partial Regex SubLongReg { get; } // [02:08:15.050 --> 02:08:16.450] Text\n\n [GeneratedRegex(\"^Operation finished in:\")]\n private static partial Regex EndReg { get; }\n\n\n public ValueTask DisposeAsync()\n {\n return ValueTask.CompletedTask;\n }\n\n public static Command BuildCommand(FasterWhisperConfig config, WhisperConfig commonConfig)\n {\n string tempFolder = Path.GetTempPath();\n string enginePath = config.UseManualEngine ? config.ManualEnginePath! : FasterWhisperConfig.DefaultEnginePath;\n\n ArgumentsBuilder args = new();\n args.Add(\"--output_dir\").Add(tempFolder);\n args.Add(\"--output_format\").Add(\"srt\");\n args.Add(\"--verbose\").Add(\"True\");\n args.Add(\"--beep_off\");\n args.Add(\"--model\").Add(config.Model);\n args.Add(\"--model_dir\")\n .Add(config.UseManualModel ? config.ManualModelDir! : WhisperConfig.ModelsDirectory);\n\n if (config.IsEnglishModel)\n {\n args.Add(\"--language\").Add(\"en\");\n }\n else\n {\n if (commonConfig.Translate)\n args.Add(\"--task\").Add(\"translate\");\n\n if (!commonConfig.LanguageDetection)\n args.Add(\"--language\").Add(commonConfig.Language);\n }\n\n string arguments = args.Build();\n\n if (!string.IsNullOrWhiteSpace(config.ExtraArguments))\n {\n arguments += $\" {config.ExtraArguments}\";\n }\n\n Command cmd = Cli.Wrap(enginePath)\n .WithArguments(arguments)\n .WithValidation(CommandResultValidation.None);\n\n if (config.ProcessPriority != ProcessPriorityClass.Normal)\n {\n cmd = cmd.WithResourcePolicy(builder =>\n builder.SetPriority(config.ProcessPriority));\n }\n\n return cmd;\n }\n\n private static TimeSpan ParseTime(ReadOnlySpan time, bool isLong)\n {\n if (isLong)\n {\n // 01:28:02.130\n // hh:mm:ss.fff\n int hours = int.Parse(time[..2]);\n int minutes = int.Parse(time[3..5]);\n int seconds = int.Parse(time[6..8]);\n int milliseconds = int.Parse(time[9..12]);\n return new TimeSpan(0, hours, minutes, seconds, milliseconds);\n }\n else\n {\n // 28:02.130\n // mm:ss.fff\n int minutes = int.Parse(time[..2]);\n int seconds = int.Parse(time[3..5]);\n int milliseconds = int.Parse(time[6..9]);\n return new TimeSpan(0, 0, minutes, seconds, milliseconds);\n }\n }\n\n public async IAsyncEnumerable<(string text, TimeSpan start, TimeSpan end, string language)> Do(MemoryStream waveStream, [EnumeratorCancellation] CancellationToken token)\n {\n string tempFilePath = Path.GetTempFileName();\n // because no output option\n string outputFilePath = Path.ChangeExtension(tempFilePath, \"srt\");\n\n // write WAV to tmp folder\n await using (FileStream fileStream = new(tempFilePath, FileMode.Create, FileAccess.Write))\n {\n waveStream.WriteTo(fileStream);\n }\n\n CancellationTokenSource forceCts = new();\n token.Register(() =>\n {\n // force kill if not exited when sending interrupt\n forceCts.CancelAfter(5000);\n });\n\n try\n {\n string? lastLine = null;\n StringBuilder output = new(); // for error output\n Lock outputLock = new();\n bool oneSuccess = false;\n\n ArgumentsBuilder args = new();\n if (_isLanguageDetect && !string.IsNullOrEmpty(_detectedLanguage))\n {\n args.Add(\"--language\").Add(_detectedLanguage);\n }\n args.Add(tempFilePath);\n string addedArgs = args.Build();\n\n Command cmd = _cmdBase.WithArguments($\"{_cmdBase.Arguments} {addedArgs}\");\n\n await foreach (var cmdEvent in cmd.ListenAsync(Encoding.Default, Encoding.Default, forceCts.Token, token))\n {\n token.ThrowIfCancellationRequested();\n\n if (cmdEvent is StandardErrorCommandEvent stdErr)\n {\n lock (outputLock)\n {\n output.AppendLine(stdErr.Text);\n }\n\n continue;\n }\n\n if (cmdEvent is not StandardOutputCommandEvent stdOut)\n {\n continue;\n }\n\n string line = stdOut.Text;\n\n // process stdout\n if (!oneSuccess)\n {\n lock (outputLock)\n {\n output.AppendLine(line);\n }\n\n }\n if (string.IsNullOrEmpty(line))\n {\n continue;\n }\n\n lastLine = line;\n\n if (_isLanguageDetect && _detectedLanguage == null)\n {\n var match = LanguageReg.Match(line);\n if (match.Success)\n {\n string languageName = match.Groups[1].Value;\n _detectedLanguage = WhisperLanguage.LanguageToCode[languageName];\n }\n\n continue;\n }\n\n bool isLong = false;\n\n Match subtitleMatch = SubShortReg.Match(line);\n if (!subtitleMatch.Success)\n {\n subtitleMatch = SubLongReg.Match(line);\n if (!subtitleMatch.Success)\n {\n continue;\n }\n\n isLong = true;\n }\n\n ReadOnlySpan lineSpan = line.AsSpan();\n\n Range startRange = 1..10;\n Range endRange = 15..24;\n Range textRange = 26..;\n\n if (isLong)\n {\n startRange = 1..13;\n endRange = 18..30;\n textRange = 32..;\n }\n\n TimeSpan start = ParseTime(lineSpan[startRange], isLong);\n TimeSpan end = ParseTime(lineSpan[endRange], isLong);\n // because some languages have leading spaces\n string text = lineSpan[textRange].Trim().ToString();\n\n yield return (text, start, end, _isLanguageDetect ? _detectedLanguage! : _manualLanguage);\n\n if (!oneSuccess)\n {\n oneSuccess = true;\n }\n }\n\n // validate if success\n if (lastLine == null || !EndReg.Match(lastLine).Success)\n {\n throw new InvalidOperationException(\"Failed to execute faster-whisper\")\n {\n Data =\n {\n [\"whisper_command\"] = cmd.CommandToText(),\n [\"whisper_output\"] = output.ToString()\n }\n };\n }\n }\n finally\n {\n // delete tmp wave\n if (File.Exists(tempFilePath))\n {\n File.Delete(tempFilePath);\n }\n // delete output srt\n if (File.Exists(outputFilePath))\n {\n File.Delete(outputFilePath);\n }\n }\n }\n}\n\npublic class SubtitleASRData\n{\n public required string Text { get; init; }\n public required TimeSpan StartTime { get; init; }\n public required TimeSpan EndTime { get; init; }\n\n#if DEBUG\n public required int ChunkNo { get; init; }\n public required TimeSpan StartTimeChunk { get; init; }\n public required TimeSpan EndTimeChunk { get; init; }\n#endif\n\n public TimeSpan Duration => EndTime - StartTime;\n\n // ISO6391\n // ref: https://github.com/openai/whisper/blob/main/whisper/tokenizer.py#L10\n public required string Language { get; init; }\n}\n"], ["/LLPlayer/FlyleafLib/Engine/Engine.cs", "using System.Collections.Generic;\nusing System.Threading.Tasks;\nusing System.Threading;\nusing System.Windows;\n\nusing FlyleafLib.MediaFramework.MediaDevice;\nusing FlyleafLib.MediaPlayer;\n\nnamespace FlyleafLib;\n\n/// \n/// Flyleaf Engine\n/// \npublic static class Engine\n{\n /// \n /// Engine has been loaded and is ready for use\n /// \n public static bool IsLoaded { get; private set; }\n\n /// \n /// Engine's configuration\n /// \n public static EngineConfig Config { get; private set; }\n\n /// \n /// Audio Engine\n /// \n public static AudioEngine Audio { get; private set; }\n\n /// \n /// Video Engine\n /// \n public static VideoEngine Video { get; private set; }\n\n /// \n /// Plugins Engine\n /// \n public static PluginsEngine Plugins { get; private set; }\n\n /// \n /// FFmpeg Engine\n /// \n public static FFmpegEngine FFmpeg { get; private set; }\n\n /// \n /// List of active Players\n /// \n public static List Players { get; private set; }\n\n public static event EventHandler\n Loaded;\n\n internal static LogHandler\n Log;\n\n static Thread tMaster;\n static object lockEngine = new();\n static bool isLoading;\n static int timePeriod;\n\n /// \n /// Initializes Flyleaf's Engine (Must be called from UI thread)\n /// \n /// Engine's configuration\n public static void Start(EngineConfig config = null) => StartInternal(config);\n\n /// \n /// Initializes Flyleaf's Engine Async (Must be called from UI thread)\n /// \n /// Engine's configuration\n public static void StartAsync(EngineConfig config = null) => StartInternal(config, true);\n\n /// \n /// Requests timeBeginPeriod(1) - You should call TimeEndPeriod1 when not required anymore\n /// \n public static void TimeBeginPeriod1()\n {\n lock (lockEngine)\n {\n timePeriod++;\n\n if (timePeriod == 1)\n {\n Log.Trace(\"timeBeginPeriod(1)\");\n Utils.NativeMethods.TimeBeginPeriod(1);\n }\n }\n }\n\n /// \n /// Stops previously requested timeBeginPeriod(1)\n /// \n public static void TimeEndPeriod1()\n {\n lock (lockEngine)\n {\n timePeriod--;\n\n if (timePeriod == 0)\n {\n Log.Trace(\"timeEndPeriod(1)\");\n Utils.NativeMethods.TimeEndPeriod(1);\n }\n }\n }\n\n private static void StartInternal(EngineConfig config = null, bool async = false)\n {\n lock (lockEngine)\n {\n if (isLoading)\n return;\n\n isLoading = true;\n\n Config = config ?? new EngineConfig();\n\n if (Application.Current == null)\n new Application();\n\n StartInternalUI();\n\n if (async)\n Task.Run(() => StartInternalNonUI());\n else\n StartInternalNonUI();\n }\n }\n\n private static void StartInternalUI()\n {\n Application.Current.Exit += (o, e) =>\n {\n Config.UIRefresh = false;\n Config.UIRefreshInterval = 1;\n\n while (Players.Count != 0)\n Players[0].Dispose();\n };\n\n Logger.SetOutput();\n\n Log = new LogHandler(\"[FlyleafEngine] \");\n\n Audio = new AudioEngine();\n if (Config.FFmpegLoadProfile == LoadProfile.All)\n AudioDevice.RefreshDevices();\n }\n\n private static void StartInternalNonUI()\n {\n var version = System.Reflection.Assembly.GetExecutingAssembly().GetName().Version;\n Log.Info($\"FlyleafLib {version.Major }.{version.Minor}.{version.Build}\");\n\n FFmpeg = new FFmpegEngine();\n Video = new VideoEngine();\n if (Config.FFmpegLoadProfile == LoadProfile.All)\n VideoDevice.RefreshDevices();\n Plugins = new PluginsEngine();\n Players = new List();\n\n IsLoaded = true;\n Loaded?.Invoke(null, null);\n\n if (Config.UIRefresh)\n StartThread();\n }\n internal static void AddPlayer(Player player)\n {\n lock (Players)\n Players.Add(player);\n }\n internal static int GetPlayerPos(int playerId)\n {\n for (int i=0; i { MasterThread(); })\n {\n Name = \"FlyleafEngine\",\n IsBackground = true\n };\n tMaster.Start();\n }\n internal static void MasterThread()\n {\n Log.Info(\"Thread started\");\n\n int curLoop = 0;\n int secondLoops = 1000 / Config.UIRefreshInterval;\n long prevTicks = DateTime.UtcNow.Ticks;\n double curSecond= 0;\n\n do\n {\n try\n {\n if (Players.Count == 0)\n {\n Thread.Sleep(Config.UIRefreshInterval);\n continue;\n }\n\n curLoop++;\n if (curLoop == secondLoops)\n {\n long curTicks = DateTime.UtcNow.Ticks;\n curSecond = (curTicks - prevTicks) / 10000000.0;\n prevTicks = curTicks;\n }\n\n lock (Players)\n foreach (var player in Players)\n {\n /* Every UIRefreshInterval */\n player.Activity.RefreshMode();\n\n /* Every Second */\n if (curLoop == secondLoops)\n {\n if (player.Config.Player.Stats)\n {\n var curStats = player.stats;\n // TODO: L: including Subtitles bytes?\n long curTotalBytes = player.VideoDemuxer.TotalBytes + player.AudioDemuxer.TotalBytes;\n long curVideoBytes = player.VideoDemuxer.VideoPackets.Bytes + player.AudioDemuxer.VideoPackets.Bytes;\n long curAudioBytes = player.VideoDemuxer.AudioPackets.Bytes + player.AudioDemuxer.AudioPackets.Bytes;\n\n player.bitRate = (curTotalBytes - curStats.TotalBytes) * 8 / 1000.0;\n player.Video.bitRate= (curVideoBytes - curStats.VideoBytes) * 8 / 1000.0;\n player.Audio.bitRate= (curAudioBytes - curStats.AudioBytes) * 8 / 1000.0;\n\n curStats.TotalBytes = curTotalBytes;\n curStats.VideoBytes = curVideoBytes;\n curStats.AudioBytes = curAudioBytes;\n\n if (player.IsPlaying)\n {\n player.Video.fpsCurrent = (player.Video.FramesDisplayed - curStats.FramesDisplayed) / curSecond;\n curStats.FramesDisplayed = player.Video.FramesDisplayed;\n }\n }\n }\n }\n\n if (curLoop == secondLoops)\n curLoop = 0;\n\n Action action = () =>\n {\n try\n {\n foreach (var player in Players)\n {\n /* Every UIRefreshInterval */\n\n // Activity Mode Refresh & Hide Mouse Cursor (FullScreen only)\n if (player.Activity.mode != player.Activity._Mode)\n player.Activity.SetMode();\n\n // CurTime / Buffered Duration (+Duration for HLS)\n if (!Config.UICurTimePerSecond)\n player.UpdateCurTime();\n else if (player.Status == Status.Paused)\n {\n if (player.MainDemuxer.IsRunning)\n player.UpdateCurTime();\n else\n player.UpdateBufferedDuration();\n }\n\n /* Every Second */\n if (curLoop == 0)\n {\n // Stats Refresh (BitRates / FrameDisplayed / FramesDropped / FPS)\n if (player.Config.Player.Stats)\n {\n player.BitRate = player.BitRate;\n player.Video.BitRate = player.Video.BitRate;\n player.Audio.BitRate = player.Audio.BitRate;\n\n if (player.IsPlaying)\n {\n player.Audio.FramesDisplayed= player.Audio.FramesDisplayed;\n player.Audio.FramesDropped = player.Audio.FramesDropped;\n\n player.Video.FramesDisplayed= player.Video.FramesDisplayed;\n player.Video.FramesDropped = player.Video.FramesDropped;\n player.Video.FPSCurrent = player.Video.FPSCurrent;\n }\n }\n }\n }\n } catch { }\n };\n\n Utils.UI(action);\n Thread.Sleep(Config.UIRefreshInterval);\n\n } catch { curLoop = 0; }\n\n } while (Config.UIRefresh);\n\n Log.Info(\"Thread stopped\");\n }\n}\n"], ["/LLPlayer/FlyleafLib/Utils/Utils.cs", "using System;\nusing System.Collections.Generic;\nusing System.Diagnostics;\nusing System.Globalization;\nusing System.IO;\nusing System.IO.Compression;\nusing System.Linq;\nusing System.Net.Http;\nusing System.Runtime.InteropServices;\nusing System.Text;\nusing System.Text.RegularExpressions;\nusing System.Threading;\nusing System.Threading.Tasks;\nusing System.Windows;\nusing CliWrap;\nusing Microsoft.Win32;\n\nnamespace FlyleafLib;\n\npublic static partial class Utils\n{\n // VLC : https://github.com/videolan/vlc/blob/master/modules/gui/qt/dialogs/preferences/simple_preferences.cpp\n // Kodi: https://github.com/xbmc/xbmc/blob/master/xbmc/settings/AdvancedSettings.cpp\n\n public static List ExtensionsAudio = new()\n {\n // VLC\n \"3ga\" , \"669\" , \"a52\" , \"aac\" , \"ac3\"\n , \"adt\" , \"adts\", \"aif\" , \"aifc\", \"aiff\"\n , \"au\" , \"amr\" , \"aob\" , \"ape\" , \"caf\"\n , \"cda\" , \"dts\" , \"flac\", \"it\" , \"m4a\"\n , \"m4p\" , \"mid\" , \"mka\" , \"mlp\" , \"mod\"\n , \"mp1\" , \"mp2\" , \"mp3\" , \"mpc\" , \"mpga\"\n , \"oga\" , \"oma\" , \"opus\", \"qcp\" , \"ra\"\n , \"rmi\" , \"snd\" , \"s3m\" , \"spx\" , \"tta\"\n , \"voc\" , \"vqf\" , \"w64\" , \"wav\" , \"wma\"\n , \"wv\" , \"xa\" , \"xm\"\n };\n\n public static List ExtensionsPictures = new()\n {\n \"apng\", \"bmp\", \"gif\", \"jpg\", \"jpeg\", \"png\", \"ico\", \"tif\", \"tiff\", \"tga\",\"jfif\"\n };\n\n public static List ExtensionsSubtitlesText = new()\n {\n \"ass\", \"ssa\", \"srt\", \"txt\", \"text\", \"vtt\"\n };\n\n public static List ExtensionsSubtitlesBitmap = new()\n {\n \"sub\", \"sup\"\n };\n\n public static List ExtensionsSubtitles = [..ExtensionsSubtitlesText, ..ExtensionsSubtitlesBitmap];\n\n public static List ExtensionsVideo = new()\n {\n // VLC\n \"3g2\" , \"3gp\" , \"3gp2\", \"3gpp\", \"amrec\"\n , \"amv\" , \"asf\" , \"avi\" , \"bik\" , \"divx\"\n , \"drc\" , \"dv\" , \"f4v\" , \"flv\" , \"gvi\"\n , \"gxf\" , \"m1v\" , \"m2t\" , \"m2v\" , \"m2ts\"\n , \"m4v\" , \"mkv\" , \"mov\" , \"mp2v\", \"mp4\"\n , \"mp4v\", \"mpa\" , \"mpe\" , \"mpeg\", \"mpeg1\"\n , \"mpeg2\",\"mpeg4\",\"mpg\" , \"mpv2\", \"mts\"\n , \"mtv\" , \"mxf\" , \"nsv\" , \"nuv\" , \"ogg\"\n , \"ogm\" , \"ogx\" , \"ogv\" , \"rec\" , \"rm\"\n , \"rmvb\", \"rpl\" , \"thp\" , \"tod\" , \"ts\"\n , \"tts\" , \"vob\" , \"vro\" , \"webm\", \"wmv\"\n , \"xesc\"\n\n // Additional\n , \"dav\"\n };\n\n private static int uniqueId;\n public static int GetUniqueId() { Interlocked.Increment(ref uniqueId); return uniqueId; }\n\n /// \n /// Begin Invokes the UI thread to execute the specified action\n /// \n /// \n public static void UI(Action action)\n {\n#if DEBUG\n if (Application.Current == null)\n return;\n#endif\n\n Application.Current.Dispatcher.BeginInvoke(action, System.Windows.Threading.DispatcherPriority.DataBind);\n }\n\n /// \n /// Begin Invokes the UI thread if required to execute the specified action\n /// \n /// \n public static void UIIfRequired(Action action)\n {\n if (Thread.CurrentThread.ManagedThreadId == Application.Current.Dispatcher.Thread.ManagedThreadId)\n action();\n else\n Application.Current.Dispatcher.BeginInvoke(action);\n }\n\n /// \n /// Invokes the UI thread to execute the specified action\n /// \n /// \n public static void UIInvoke(Action action) => Application.Current.Dispatcher.Invoke(action);\n\n /// \n /// Invokes the UI thread if required to execute the specified action\n /// \n /// \n public static void UIInvokeIfRequired(Action action)\n {\n if (Thread.CurrentThread.ManagedThreadId == Application.Current.Dispatcher.Thread.ManagedThreadId)\n action();\n else\n Application.Current.Dispatcher.Invoke(action);\n }\n\n public static Thread STA(Action action)\n {\n Thread thread = new(() => action());\n thread.SetApartmentState(ApartmentState.STA);\n thread.Start();\n\n return thread;\n }\n\n public static void STAInvoke(Action action)\n {\n Thread thread = STA(action);\n thread.Join();\n }\n\n public static int Align(int num, int align)\n {\n int mod = num % align;\n return mod == 0 ? num : num + (align - mod);\n }\n public static float Scale(float value, float inMin, float inMax, float outMin, float outMax)\n => ((value - inMin) * (outMax - outMin) / (inMax - inMin)) + outMin;\n\n /// \n /// Adds a windows firewall rule if not already exists for the specified program path\n /// \n /// Default value is Flyleaf\n /// Default value is current executable path\n public static void AddFirewallRule(string ruleName = null, string path = null)\n {\n Task.Run(() =>\n {\n try\n {\n if (string.IsNullOrEmpty(ruleName))\n ruleName = \"Flyleaf\";\n\n if (string.IsNullOrEmpty(path))\n path = Process.GetCurrentProcess().MainModule.FileName;\n\n path = $\"\\\"{path}\\\"\";\n\n // Check if rule already exists\n Process proc = new()\n {\n StartInfo = new ProcessStartInfo\n {\n FileName = \"cmd\",\n Arguments = $\"/C netsh advfirewall firewall show rule name={ruleName} verbose | findstr /L {path}\",\n CreateNoWindow = true,\n UseShellExecute = false,\n RedirectStandardOutput\n = true,\n WindowStyle = ProcessWindowStyle.Hidden\n }\n };\n\n proc.Start();\n proc.WaitForExit();\n\n if (proc.StandardOutput.Read() > 0)\n return;\n\n // Add rule with admin rights\n proc = new Process\n {\n StartInfo = new ProcessStartInfo\n {\n FileName = \"cmd\",\n Arguments = $\"/C netsh advfirewall firewall add rule name={ruleName} dir=in action=allow enable=yes program={path} profile=any &\" +\n $\"netsh advfirewall firewall add rule name={ruleName} dir=out action=allow enable=yes program={path} profile=any\",\n Verb = \"runas\",\n CreateNoWindow = true,\n UseShellExecute = true,\n WindowStyle = ProcessWindowStyle.Hidden\n }\n };\n\n proc.Start();\n proc.WaitForExit();\n\n Log($\"Firewall rule \\\"{ruleName}\\\" added for {path}\");\n }\n catch { }\n });\n }\n\n // We can't trust those\n //public static private bool IsDesignMode=> (bool) DesignerProperties.IsInDesignModeProperty.GetMetadata(typeof(DependencyObject)).DefaultValue;\n //public static bool IsDesignMode = LicenseManager.UsageMode == LicenseUsageMode.Designtime; // Will not work properly (need to be called from non-static class constructor)\n\n //public static bool IsWin11 = Regex.IsMatch(Registry.GetValue(@\"HKEY_LOCAL_MACHINE\\SOFTWARE\\Microsoft\\Windows NT\\CurrentVersion\", \"ProductName\", \"\").ToString(), \"Windows 11\");\n //public static bool IsWin10 = Regex.IsMatch(Registry.GetValue(@\"HKEY_LOCAL_MACHINE\\SOFTWARE\\Microsoft\\Windows NT\\CurrentVersion\", \"ProductName\", \"\").ToString(), \"Windows 10\");\n //public static bool IsWin8 = Regex.IsMatch(Registry.GetValue(@\"HKEY_LOCAL_MACHINE\\SOFTWARE\\Microsoft\\Windows NT\\CurrentVersion\", \"ProductName\", \"\").ToString(), \"Windows 8\");\n //public static bool IsWin7 = Regex.IsMatch(Registry.GetValue(@\"HKEY_LOCAL_MACHINE\\SOFTWARE\\Microsoft\\Windows NT\\CurrentVersion\", \"ProductName\", \"\").ToString(), \"Windows 7\");\n\n public static List GetMoviesSorted(List movies)\n {\n List moviesSorted = new();\n\n for (int i = 0; i < movies.Count; i++)\n {\n string ext = Path.GetExtension(movies[i]);\n\n if (ext == null || ext.Trim() == \"\")\n continue;\n\n if (ExtensionsVideo.Contains(ext[1..].ToLower()))\n moviesSorted.Add(movies[i]);\n }\n\n moviesSorted.Sort(new NaturalStringComparer());\n\n return moviesSorted;\n }\n public sealed class NaturalStringComparer : IComparer\n { public int Compare(string a, string b) => NativeMethods.StrCmpLogicalW(a, b); }\n\n public static string GetRecInnerException(Exception e)\n {\n string dump = \"\";\n var cur = e.InnerException;\n\n for (int i = 0; i < 4; i++)\n {\n if (cur == null) break;\n dump += \"\\r\\n - \" + cur.Message;\n cur = cur.InnerException;\n }\n\n return dump;\n }\n public static string GetUrlExtention(string url)\n {\n int index;\n if ((index = url.LastIndexOf('.')) > 0)\n return url[(index + 1)..].ToLower();\n\n return \"\";\n }\n\n public static List GetSystemLanguages()\n {\n List Languages = [ Language.English ];\n\n if (OriginalCulture.ThreeLetterISOLanguageName != \"eng\")\n Languages.Add(Language.Get(OriginalCulture));\n\n foreach (System.Windows.Forms.InputLanguage lang in System.Windows.Forms.InputLanguage.InstalledInputLanguages)\n if (lang.Culture.ThreeLetterISOLanguageName != OriginalCulture.ThreeLetterISOLanguageName && lang.Culture.ThreeLetterISOLanguageName != \"eng\")\n Languages.Add(Language.Get(lang.Culture));\n\n return Languages;\n }\n\n public static CultureInfo OriginalCulture { get; private set; }\n public static CultureInfo OriginalUICulture { get; private set; }\n\n public static void SaveOriginalCulture()\n {\n OriginalCulture = CultureInfo.CurrentCulture;\n OriginalUICulture = CultureInfo.CurrentUICulture;\n }\n\n public class MediaParts\n {\n public string Title { get; set; } = \"\";\n public string Extension { get; set; } = \"\";\n public int Season { get; set; }\n public int Episode { get; set; }\n public int Year { get; set; }\n }\n public static MediaParts GetMediaParts(string title, bool checkSeasonEpisodeOnly = false)\n {\n Match res;\n MediaParts mp = new();\n int index = int.MaxValue; // title end pos\n\n res = RxSeasonEpisode1().Match(title);\n if (!res.Success)\n {\n res = RxSeasonEpisode2().Match(title);\n\n if (!res.Success)\n res = RxEpisodePart().Match(title);\n }\n\n if (res.Groups.Count > 1)\n {\n if (res.Groups[\"season\"].Value != \"\")\n mp.Season = int.Parse(res.Groups[\"season\"].Value);\n\n if (res.Groups[\"episode\"].Value != \"\")\n mp.Episode = int.Parse(res.Groups[\"episode\"].Value);\n\n if (checkSeasonEpisodeOnly || res.Index == 0) // 0: No title just season/episode\n return mp;\n\n index = res.Index;\n }\n\n mp.Extension = GetUrlExtention(title);\n if (mp.Extension.Length > 0 && mp.Extension.Length < 5)\n title = title[..(title.Length - mp.Extension.Length - 1)];\n\n // non-movie words, 1080p, 2015\n if ((res = RxExtended().Match(title)).Index > 0 && res.Index < index)\n index = res.Index;\n\n if ((res = RxDirectorsCut().Match(title)).Index > 0 && res.Index < index)\n index = res.Index;\n\n if ((res = RxBrrip().Match(title)).Index > 0 && res.Index < index)\n index = res.Index;\n\n if ((res = RxResolution().Match(title)).Index > 0 && res.Index < index)\n index = res.Index;\n\n res = RxYear().Match(title);\n Group gc;\n if (res.Success && (gc = res.Groups[\"year\"]).Index > 2)\n {\n mp.Year = int.Parse(gc.Value);\n if (res.Index < index)\n index = res.Index;\n }\n\n if (index != int.MaxValue)\n title = title[..index];\n\n title = title.Replace(\".\", \" \").Replace(\"_\", \" \");\n title = RxSpaces().Replace(title, \" \");\n title = RxNonAlphaNumeric().Replace(title, \"\");\n\n mp.Title = title.Trim();\n\n return mp;\n }\n\n public static string FindNextAvailableFile(string fileName)\n {\n if (!File.Exists(fileName)) return fileName;\n\n string tmp = Path.Combine(Path.GetDirectoryName(fileName), Regex.Replace(Path.GetFileNameWithoutExtension(fileName), @\"(.*) (\\([0-9]+)\\)$\", \"$1\"));\n string newName;\n\n for (int i = 1; i < 101; i++)\n {\n newName = tmp + \" (\" + i + \")\" + Path.GetExtension(fileName);\n if (!File.Exists(newName)) return newName;\n }\n\n return null;\n }\n public static string GetValidFileName(string name) => string.Join(\"_\", name.Split(Path.GetInvalidFileNameChars()));\n\n public static string FindFileBelow(string filename)\n {\n string current = AppDomain.CurrentDomain.BaseDirectory;\n\n while (current != null)\n {\n if (File.Exists(Path.Combine(current, filename)))\n return Path.Combine(current, filename);\n\n current = Directory.GetParent(current)?.FullName;\n }\n\n return null;\n }\n public static string GetFolderPath(string folder)\n {\n if (folder.StartsWith(\":\"))\n {\n folder = folder[1..];\n return FindFolderBelow(folder);\n }\n\n return Path.IsPathRooted(folder) ? folder : Path.GetFullPath(folder);\n }\n\n public static string FindFolderBelow(string folder)\n {\n string current = AppDomain.CurrentDomain.BaseDirectory;\n\n while (current != null)\n {\n if (Directory.Exists(Path.Combine(current, folder)))\n return Path.Combine(current, folder);\n\n current = Directory.GetParent(current)?.FullName;\n }\n\n return null;\n }\n public static string GetUserDownloadPath() { try { return Registry.CurrentUser.OpenSubKey(@\"Software\\Microsoft\\Windows\\CurrentVersion\\Explorer\\User Shell Folders\\\").GetValue(\"{374DE290-123F-4565-9164-39C4925E467B}\").ToString(); } catch (Exception) { return null; } }\n public static string DownloadToString(string url, int timeoutMs = 30000)\n {\n try\n {\n using HttpClient client = new() { Timeout = TimeSpan.FromMilliseconds(timeoutMs) };\n return client.GetAsync(url).Result.Content.ReadAsStringAsync().Result;\n }\n catch (Exception e)\n {\n Log($\"Download failed {e.Message} [Url: {url ?? \"Null\"}]\");\n }\n\n return null;\n }\n\n public static MemoryStream DownloadFile(string url, int timeoutMs = 30000)\n {\n MemoryStream ms = new();\n\n try\n {\n using HttpClient client = new() { Timeout = TimeSpan.FromMilliseconds(timeoutMs) };\n client.GetAsync(url).Result.Content.CopyToAsync(ms).Wait();\n }\n catch (Exception e)\n {\n Log($\"Download failed {e.Message} [Url: {url ?? \"Null\"}]\");\n }\n\n return ms;\n }\n\n public static bool DownloadFile(string url, string filename, int timeoutMs = 30000, bool overwrite = true)\n {\n try\n {\n using HttpClient client = new() { Timeout = TimeSpan.FromMilliseconds(timeoutMs) };\n using FileStream fs = new(filename, overwrite ? FileMode.Create : FileMode.CreateNew);\n client.GetAsync(url).Result.Content.CopyToAsync(fs).Wait();\n\n return true;\n }\n catch (Exception e)\n {\n Log($\"Download failed {e.Message} [Url: {url ?? \"Null\"}, Path: {filename ?? \"Null\"}]\");\n }\n\n return false;\n }\n public static string FixFileUrl(string url)\n {\n try\n {\n if (url == null || url.Length < 5)\n return url;\n\n if (url[..5].ToLower() == \"file:\")\n return new Uri(url).LocalPath;\n }\n catch { }\n\n return url;\n }\n\n /// \n /// Convert Windows lnk file path to target path\n /// \n /// lnk file path\n /// targetPath or null\n public static string GetLnkTargetPath(string filepath)\n {\n try\n {\n // Using dynamic COM\n // ref: https://stackoverflow.com/a/49198242/9070784\n dynamic windowsShell = Activator.CreateInstance(Type.GetTypeFromProgID(\"WScript.Shell\", true)!);\n dynamic shortcut = windowsShell!.CreateShortcut(filepath);\n string targetPath = shortcut.TargetPath;\n\n if (string.IsNullOrEmpty(targetPath))\n {\n throw new InvalidOperationException(\"TargetPath is empty.\");\n }\n\n return targetPath;\n }\n catch (Exception e)\n {\n Log($\"Resolving Windows Link failed {e.Message} [FilePath: {filepath}]\");\n\n return null;\n }\n }\n\n public static string GetBytesReadable(nuint i)\n {\n // Determine the suffix and readable value\n string suffix;\n double readable;\n if (i >= 0x1000000000000000) // Exabyte\n {\n suffix = \"EB\";\n readable = i >> 50;\n }\n else if (i >= 0x4000000000000) // Petabyte\n {\n suffix = \"PB\";\n readable = i >> 40;\n }\n else if (i >= 0x10000000000) // Terabyte\n {\n suffix = \"TB\";\n readable = i >> 30;\n }\n else if (i >= 0x40000000) // Gigabyte\n {\n suffix = \"GB\";\n readable = i >> 20;\n }\n else if (i >= 0x100000) // Megabyte\n {\n suffix = \"MB\";\n readable = i >> 10;\n }\n else if (i >= 0x400) // Kilobyte\n {\n suffix = \"KB\";\n readable = i;\n }\n else\n {\n return i.ToString(\"0 B\"); // Byte\n }\n // Divide by 1024 to get fractional value\n readable /= 1024;\n // Return formatted number with suffix\n return readable.ToString(\"0.## \") + suffix;\n }\n static List gpuCounters;\n public static void GetGPUCounters()\n {\n PerformanceCounterCategory category = new(\"GPU Engine\");\n string[] counterNames = category.GetInstanceNames();\n gpuCounters = new List();\n\n foreach (string counterName in counterNames)\n if (counterName.EndsWith(\"engtype_3D\"))\n foreach (var counter in category.GetCounters(counterName))\n if (counter.CounterName == \"Utilization Percentage\")\n gpuCounters.Add(counter);\n }\n public static float GetGPUUsage()\n {\n float result = 0f;\n\n try\n {\n if (gpuCounters == null) GetGPUCounters();\n\n gpuCounters.ForEach(x => { _ = x.NextValue(); });\n Thread.Sleep(1000);\n gpuCounters.ForEach(x => { result += x.NextValue(); });\n\n }\n catch (Exception e) { Log($\"[GPUUsage] Error {e.Message}\"); result = -1f; GetGPUCounters(); }\n\n return result;\n }\n public static string GZipDecompress(string filename)\n {\n string newFileName = \"\";\n\n FileInfo fileToDecompress = new(filename);\n using (var originalFileStream = fileToDecompress.OpenRead())\n {\n string currentFileName = fileToDecompress.FullName;\n newFileName = currentFileName.Remove(currentFileName.Length - fileToDecompress.Extension.Length);\n\n using var decompressedFileStream = File.Create(newFileName);\n using GZipStream decompressionStream = new(originalFileStream, CompressionMode.Decompress);\n decompressionStream.CopyTo(decompressedFileStream);\n }\n\n return newFileName;\n }\n\n public static Dictionary ParseQueryString(ReadOnlySpan query)\n {\n Dictionary dict = [];\n\n int nameStart = 0;\n int equalPos = -1;\n for (int i = 0; i < query.Length; i++)\n {\n if (query[i] == '=')\n equalPos = i;\n else if (query[i] == '&')\n {\n if (equalPos == -1)\n dict[query[nameStart..i].ToString()] = null;\n else\n dict[query[nameStart..equalPos].ToString()] = query.Slice(equalPos + 1, i - equalPos - 1).ToString();\n\n equalPos = -1;\n nameStart = i + 1;\n }\n }\n\n if (nameStart < query.Length - 1)\n {\n if (equalPos == -1)\n dict[query[nameStart..].ToString()] = null;\n else\n dict[query[nameStart..equalPos].ToString()] = query.Slice(equalPos + 1, query.Length - equalPos - 1).ToString();\n }\n\n return dict;\n }\n\n public unsafe static string BytePtrToStringUTF8(byte* bytePtr)\n => Marshal.PtrToStringUTF8((nint)bytePtr);\n\n public static System.Windows.Media.Color WinFormsToWPFColor(System.Drawing.Color sColor)\n => System.Windows.Media.Color.FromArgb(sColor.A, sColor.R, sColor.G, sColor.B);\n public static System.Drawing.Color WPFToWinFormsColor(System.Windows.Media.Color wColor)\n => System.Drawing.Color.FromArgb(wColor.A, wColor.R, wColor.G, wColor.B);\n\n public static System.Windows.Media.Color VorticeToWPFColor(Vortice.Mathematics.Color sColor)\n => System.Windows.Media.Color.FromArgb(sColor.A, sColor.R, sColor.G, sColor.B);\n public static Vortice.Mathematics.Color WPFToVorticeColor(System.Windows.Media.Color wColor)\n => new Vortice.Mathematics.Color(wColor.R, wColor.G, wColor.B, wColor.A);\n\n public static double SWFREQ_TO_TICKS = 10000000.0 / Stopwatch.Frequency;\n public static string ToHexadecimal(byte[] bytes)\n {\n StringBuilder hexBuilder = new();\n for (int i = 0; i < bytes.Length; i++)\n {\n hexBuilder.Append(bytes[i].ToString(\"x2\"));\n }\n return hexBuilder.ToString();\n }\n public static int GCD(int a, int b) => b == 0 ? a : GCD(b, a % b);\n public static string TicksToTime(long ticks) => new TimeSpan(ticks).ToString();\n public static void Log(string msg) { try { Debug.WriteLine($\"[{DateTime.Now:hh.mm.ss.fff}] {msg}\"); } catch (Exception) { Debug.WriteLine($\"[............] [MediaFramework] {msg}\"); } }\n\n [GeneratedRegex(\"[^a-z0-9]extended\", RegexOptions.IgnoreCase)]\n private static partial Regex RxExtended();\n [GeneratedRegex(\"[^a-z0-9]directors.cut\", RegexOptions.IgnoreCase)]\n private static partial Regex RxDirectorsCut();\n [GeneratedRegex(@\"(^|[^a-z0-9])(s|season)[^a-z0-9]*(?[0-9]{1,2})[^a-z0-9]*(e|episode|part)[^a-z0-9]*(?[0-9]{1,2})($|[^a-z0-9])\", RegexOptions.IgnoreCase)]\n\n // s|season 01 ... e|episode|part 01\n private static partial Regex RxSeasonEpisode1();\n [GeneratedRegex(@\"(^|[^a-z0-9])(?[0-9]{1,2})x(?[0-9]{1,2})($|[^a-z0-9])\", RegexOptions.IgnoreCase)]\n // 01x01\n private static partial Regex RxSeasonEpisode2();\n // TODO: in case of single season should check only for e|episode|part 01\n [GeneratedRegex(@\"(^|[^a-z0-9])(episode|part)[^a-z0-9]*(?[0-9]{1,2})($|[^a-z0-9])\", RegexOptions.IgnoreCase)]\n private static partial Regex RxEpisodePart();\n [GeneratedRegex(\"[^a-z0-9]brrip\", RegexOptions.IgnoreCase)]\n private static partial Regex RxBrrip();\n\n [GeneratedRegex(\"[^a-z0-9][0-9]{3,4}p\", RegexOptions.IgnoreCase)]\n private static partial Regex RxResolution();\n [GeneratedRegex(@\"[^a-z0-9](?(19|20)[0-9][0-9])($|[^a-z0-9])\", RegexOptions.IgnoreCase)]\n private static partial Regex RxYear();\n [GeneratedRegex(@\"\\s{2,}\")]\n private static partial Regex RxSpaces();\n [GeneratedRegex(@\"[^a-z0-9]$\", RegexOptions.IgnoreCase)]\n private static partial Regex RxNonAlphaNumeric();\n\n public static string TruncateString(string str, int maxLength, string suffix = \"...\")\n {\n if (string.IsNullOrEmpty(str))\n return str;\n\n if (str.Length <= maxLength)\n return str;\n\n int availableLength = maxLength - suffix.Length;\n\n if (availableLength <= 0)\n {\n return suffix.Substring(0, Math.Min(maxLength, suffix.Length));\n }\n\n return str.Substring(0, availableLength) + suffix;\n }\n\n // TODO: L: move to app, using event\n public static void PlayCompletionSound()\n {\n string soundPath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, \"Assets/completion.mp3\");\n\n if (!File.Exists(soundPath))\n {\n return;\n }\n\n UI(() =>\n {\n try\n {\n // play completion sound\n System.Windows.Media.MediaPlayer mp = new();\n mp.Open(new Uri(soundPath));\n mp.Play();\n }\n catch\n {\n // ignored\n }\n });\n }\n\n public static string CommandToText(this Command cmd)\n {\n if (cmd.TargetFilePath.Any(char.IsWhiteSpace))\n {\n return $\"& \\\"{cmd.TargetFilePath}\\\" {cmd.Arguments}\";\n }\n\n return cmd.ToString();\n }\n}\n"], ["/LLPlayer/FlyleafLib/MediaPlayer/SubtitlesManager.cs", "using System.Collections.Generic;\nusing System.Collections.ObjectModel;\nusing System.Collections.Specialized;\nusing System.ComponentModel;\nusing System.Diagnostics;\nusing System.Linq;\nusing System.Runtime.CompilerServices;\nusing System.Runtime.InteropServices;\nusing System.Threading;\nusing System.Windows;\nusing System.Windows.Data;\nusing System.Windows.Media;\nusing System.Windows.Media.Imaging;\nusing FlyleafLib.MediaFramework.MediaDecoder;\nusing FlyleafLib.MediaFramework.MediaDemuxer;\nusing FlyleafLib.MediaFramework.MediaFrame;\nusing FlyleafLib.MediaFramework.MediaRenderer;\nusing FlyleafLib.MediaFramework.MediaStream;\nusing FlyleafLib.MediaPlayer.Translation;\nusing static FlyleafLib.Logger;\n\nnamespace FlyleafLib.MediaPlayer;\n\n#nullable enable\n\npublic class SubtitlesManager\n{\n private readonly SubManager[] _subManagers;\n public SubManager this[int subIndex] => _subManagers[subIndex];\n private readonly int _subNum;\n\n public SubtitlesManager(Config config, int subNum)\n {\n _subNum = subNum;\n _subManagers = new SubManager[subNum];\n for (int i = 0; i < subNum; i++)\n {\n _subManagers[i] = new SubManager(config, i);\n }\n }\n\n /// \n /// Open a file and read all subtitle data by streaming\n /// \n /// 0: Primary, 1: Secondary\n /// subtitle file path or video file path\n /// streamIndex of subtitle\n /// demuxer media type\n /// Use bitmap subtitles or immediately release bitmap if not used\n /// subtitle language\n public void Open(int subIndex, string url, int streamIndex, MediaType type, bool useBitmap, Language lang)\n {\n // TODO: L: Add caching subtitle data for the same stream and URL?\n this[subIndex].Open(url, streamIndex, type, useBitmap, lang);\n }\n\n public void SetCurrentTime(TimeSpan currentTime)\n {\n for (int i = 0; i < _subNum; i++)\n {\n this[i].SetCurrentTime(currentTime);\n }\n }\n}\n\npublic class SubManager : INotifyPropertyChanged\n{\n private readonly Lock _locker = new();\n private CancellationTokenSource? _cts;\n public SubtitleData? SelectedSub { get; set => Set(ref field, value); }\n public int CurrentIndex { get; private set => Set(ref field, value); } = -1;\n\n public PositionState State\n {\n get;\n private set\n {\n bool prevIsDisplaying = IsDisplaying;\n if (Set(ref field, value) && prevIsDisplaying != IsDisplaying)\n {\n OnPropertyChanged(nameof(IsDisplaying));\n }\n }\n } = PositionState.First;\n\n public bool IsDisplaying => State == PositionState.Showing;\n\n /// \n /// List of subtitles that can be bound to ItemsControl\n /// Must be sorted with timestamp to perform binary search.\n /// \n public BulkObservableCollection Subs { get; } = new();\n\n /// \n /// True when addition to Subs is running... (Reading all subtitles, OCR, ASR)\n /// \n public bool IsLoading { get; private set => Set(ref field, value); }\n\n // LanguageSource with fallback\n public Language? Language\n {\n get\n {\n if (LanguageSource == Language.Unknown)\n {\n // fallback to user set language\n return _subIndex == 0 ? _config.Subtitles.LanguageFallbackPrimary : _config.Subtitles.LanguageFallbackSecondary;\n }\n\n return LanguageSource;\n }\n }\n\n public Language? LanguageSource\n {\n get;\n set\n {\n if (Set(ref field, value))\n {\n OnPropertyChanged(nameof(Language));\n }\n }\n }\n\n // For displaying bitmap subtitles, manage video width and height\n public int Width { get; internal set; }\n public int Height { get; internal set; }\n\n private readonly object _subsLocker = new();\n private readonly Config _config;\n private readonly int _subIndex;\n private readonly SubTranslator _subTranslator;\n private readonly LogHandler Log;\n\n public SubManager(Config config, int subIndex, bool enableSync = true)\n {\n _config = config;\n _subIndex = subIndex;\n // TODO: L: Review whether to initialize it here.\n _subTranslator = new SubTranslator(this, config.Subtitles, subIndex);\n Log = new LogHandler((\"[#1]\").PadRight(8, ' ') + $\" [SubManager{subIndex + 1} ] \");\n\n if (enableSync)\n {\n // Enable binding to ItemsControl\n Utils.UIInvokeIfRequired(() =>\n {\n BindingOperations.EnableCollectionSynchronization(Subs, _subsLocker);\n });\n }\n }\n\n public enum PositionState\n {\n First, // still haven't reached the first subtitle\n Showing, // currently displaying\n Around, // not displayed and can seek before and after\n Last // After the last subtitle\n }\n\n /// \n /// Force UI refresh\n /// \n internal void Refresh()\n {\n // NOTE: If it is not executed in the main thread, the following error occurs.\n // System.NotSupportedException: 'This type of CollectionView does not support'\n Utils.UI(() =>\n {\n CollectionViewSource.GetDefaultView(Subs).Refresh();\n OnPropertyChanged(nameof(CurrentIndex)); // required for translating current sub\n });\n }\n\n /// \n /// This must be called when doing heavy operation\n /// \n /// \n internal IDisposable StartLoading()\n {\n IsLoading = true;\n\n return Disposable.Create(() =>\n {\n IsLoading = false;\n });\n }\n\n public void Load(IEnumerable items)\n {\n lock (_subsLocker)\n {\n CurrentIndex = -1;\n SelectedSub = null;\n Subs.Clear();\n Subs.AddRange(items);\n }\n }\n\n public void Add(SubtitleData sub)\n {\n lock (_subsLocker)\n {\n sub.Index = Subs.Count;\n Subs.Add(sub);\n }\n }\n\n public void AddRange(IEnumerable items)\n {\n lock (_subsLocker)\n {\n Subs.AddRange(items);\n }\n }\n\n public SubtitleData? GetCurrent()\n {\n lock (_subsLocker)\n {\n if (Subs.Count == 0 || CurrentIndex == -1)\n {\n return null;\n }\n\n Debug.Assert(CurrentIndex < Subs.Count);\n\n if (State == PositionState.Showing)\n {\n return Subs[CurrentIndex];\n }\n\n return null;\n }\n }\n\n public SubtitleData? GetNext()\n {\n lock (_subsLocker)\n {\n if (Subs.Count == 0)\n {\n return null;\n }\n\n switch (State)\n {\n case PositionState.First:\n return Subs[0];\n\n case PositionState.Showing:\n if (CurrentIndex < Subs.Count - 1)\n return Subs[CurrentIndex + 1];\n break;\n\n case PositionState.Around:\n if (CurrentIndex < Subs.Count - 1)\n return Subs[CurrentIndex + 1];\n break;\n }\n\n return null;\n }\n }\n\n public SubtitleData? GetPrev()\n {\n lock (_subsLocker)\n {\n if (Subs.Count == 0 || CurrentIndex == -1)\n return null;\n\n switch (State)\n {\n case PositionState.Showing:\n if (CurrentIndex > 0)\n return Subs[CurrentIndex - 1];\n break;\n\n case PositionState.Around:\n if (CurrentIndex >= 0)\n return Subs[CurrentIndex];\n break;\n\n case PositionState.Last:\n return Subs[^1];\n }\n }\n\n return null;\n }\n\n private readonly SubtitleData _searchSub = new();\n\n public SubManager SetCurrentTime(TimeSpan currentTime)\n {\n // Adjust the display timing of subtitles by adjusting the timestamp of the video\n currentTime = currentTime.Subtract(new TimeSpan(_config.Subtitles[_subIndex].Delay));\n\n lock (_subsLocker)\n {\n // If no subtitle data is loaded, nothing is done.\n if (Subs.Count == 0)\n return this;\n\n // If it is a subtitle that is displaying, it does nothing.\n var curSub = GetCurrent();\n if (curSub != null && curSub.StartTime < currentTime && curSub.EndTime > currentTime)\n {\n return this;\n }\n\n _searchSub.StartTime = currentTime;\n\n int ret = Subs.BinarySearch(_searchSub, SubtitleTimeStartComparer.Instance);\n int cur = -1;\n\n if (~ret == 0)\n {\n CurrentIndex = -1;\n SelectedSub = null;\n State = PositionState.First;\n return this;\n }\n\n if (ret < 0)\n {\n // The reason subtracting 1 is that the result of the binary search is the next big index.\n cur = (~ret) - 1;\n }\n else\n {\n // If the starting position is matched, it is unlikely\n cur = ret;\n }\n\n Debug.Assert(cur >= 0, \"negative index detected\");\n Debug.Assert(cur < Subs.Count, \"out of bounds detected\");\n\n if (cur == Subs.Count - 1)\n {\n if (Subs[cur].EndTime < currentTime)\n {\n CurrentIndex = cur;\n SelectedSub = Subs[cur];\n State = PositionState.Last;\n }\n else\n {\n CurrentIndex = cur;\n SelectedSub = Subs[cur];\n State = PositionState.Showing;\n }\n }\n else\n {\n if (Subs[cur].StartTime <= currentTime && Subs[cur].EndTime >= currentTime)\n {\n // Show subtitles\n CurrentIndex = cur;\n SelectedSub = Subs[cur];\n State = PositionState.Showing;\n }\n else if (Subs[cur].StartTime <= currentTime)\n {\n // Almost there to display in currentIndex.\n CurrentIndex = cur;\n SelectedSub = Subs[cur];\n State = PositionState.Around;\n }\n }\n }\n\n return this;\n }\n\n public void Sort()\n {\n lock (_subsLocker)\n {\n if (Subs.Count == 0)\n return;\n\n Subs.Sort(SubtitleTimeStartComparer.Instance);\n }\n }\n\n public void DeleteAfter(TimeSpan time)\n {\n lock (_subsLocker)\n {\n if (Subs.Count == 0)\n return;\n\n int index = Subs.BinarySearch(new SubtitleData { EndTime = time }, new SubtitleTimeEndComparer());\n\n if (index < 0)\n {\n index = ~index;\n }\n\n if (index < Subs.Count)\n {\n var newSubs = Subs.GetRange(0, index).ToList();\n var deleteSubs = Subs.GetRange(index, Subs.Count - index).ToList();\n Load(newSubs);\n\n foreach (var sub in deleteSubs)\n {\n sub.Dispose();\n }\n }\n }\n }\n\n public void Open(string url, int streamIndex, MediaType type, bool useBitmap, Language lang)\n {\n // Asynchronously read subtitle timestamps and text\n\n // Cancel if already executed\n TryCancelWait();\n\n lock (_locker)\n {\n using var loading = StartLoading();\n\n List subChunk = new();\n\n try\n {\n _cts = new CancellationTokenSource();\n using SubtitleReader reader = new(this, _config, _subIndex);\n reader.Open(url, streamIndex, type, _cts.Token);\n\n _cts.Token.ThrowIfCancellationRequested();\n\n bool isFirst = true;\n int subCnt = 0;\n\n Stopwatch refreshSw = new();\n refreshSw.Start();\n\n reader.ReadAll(useBitmap, data =>\n {\n if (isFirst)\n {\n isFirst = false;\n // Set the language at the timing of the first subtitle data set.\n LanguageSource = lang;\n\n Log.Info($\"Start loading subs... (lang:{lang.TopEnglishName})\");\n }\n\n data.Index = subCnt++;\n subChunk.Add(data);\n\n // Large files and network files take time to load to the end.\n // To prevent frequent UI updates, use AddRange to group files to some extent before adding them.\n if (subChunk.Count >= 2 && refreshSw.Elapsed > TimeSpan.FromMilliseconds(500))\n {\n AddRange(subChunk);\n subChunk.Clear();\n refreshSw.Restart();\n }\n }, _cts.Token);\n\n // Process remaining\n if (subChunk.Count > 0)\n {\n AddRange(subChunk);\n }\n refreshSw.Stop();\n Log.Info(\"End loading subs\");\n }\n catch (OperationCanceledException)\n {\n foreach (var sub in subChunk)\n {\n sub.Dispose();\n }\n\n Clear();\n }\n }\n }\n\n public void TryCancelWait()\n {\n if (_cts != null)\n {\n // If it has already been executed, cancel it and wait until the preceding process is finished.\n // (It waits because it has a lock)\n _cts.Cancel();\n lock (_locker)\n {\n // dispose after it is no longer used.\n _cts.Dispose();\n _cts = null;\n }\n }\n }\n\n public void Clear()\n {\n lock (_subsLocker)\n {\n CurrentIndex = -1;\n SelectedSub = null;\n foreach (var sub in Subs)\n {\n sub.Dispose();\n }\n Subs.Clear();\n State = PositionState.First;\n LanguageSource = null;\n IsLoading = false;\n Width = 0;\n Height = 0;\n }\n }\n\n public void Reset()\n {\n TryCancelWait();\n Clear();\n }\n\n #region INotifyPropertyChanged\n public event PropertyChangedEventHandler? PropertyChanged;\n\n protected virtual void OnPropertyChanged([CallerMemberName] string? propertyName = null)\n {\n PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));\n }\n\n protected bool Set(ref T field, T value, [CallerMemberName] string? propertyName = null)\n {\n if (EqualityComparer.Default.Equals(field, value))\n return false;\n field = value;\n OnPropertyChanged(propertyName);\n return true;\n }\n #endregion\n}\n\npublic unsafe class SubtitleReader : IDisposable\n{\n private readonly SubManager _manager;\n private readonly Config _config;\n private readonly LogHandler Log;\n private readonly int _subIndex;\n\n private Demuxer? _demuxer;\n private SubtitlesDecoder? _decoder;\n private SubtitlesStream? _stream;\n\n private AVPacket* _packet = null;\n\n public SubtitleReader(SubManager manager, Config config, int subIndex)\n {\n _manager = manager;\n _config = config;\n Log = new LogHandler((\"[#1]\").PadRight(8, ' ') + $\" [SubReader{subIndex + 1} ] \");\n\n _subIndex = subIndex;\n }\n\n public void Open(string url, int streamIndex, MediaType type, CancellationToken token)\n {\n _demuxer = new Demuxer(_config.Demuxer, type, _subIndex + 1, false);\n\n token.Register(() =>\n {\n if (_demuxer != null)\n _demuxer.Interrupter.ForceInterrupt = 1;\n });\n\n _demuxer.Log.Prefix = _demuxer.Log.Prefix.Replace(\"Demuxer: \", \"DemuxerS:\");\n string? error = _demuxer.Open(url);\n\n if (error != null)\n {\n token.ThrowIfCancellationRequested(); // if canceled\n\n throw new InvalidOperationException($\"demuxer open error: {error}\");\n }\n\n _stream = (SubtitlesStream)_demuxer.AVStreamToStream[streamIndex];\n\n if (type == MediaType.Subs)\n {\n\n _stream.ExternalStream = new ExternalSubtitlesStream()\n {\n Url = url,\n IsBitmap = _stream.IsBitmap\n };\n\n _stream.ExternalStreamAdded();\n }\n\n _decoder = new SubtitlesDecoder(_config, _subIndex + 1);\n _decoder.Log.Prefix = _decoder.Log.Prefix.Replace(\"Decoder: \", \"DecoderS:\");\n error = _decoder.Open(_stream);\n\n if (error != null)\n {\n token.ThrowIfCancellationRequested(); // if canceled\n\n throw new InvalidOperationException($\"decoder open error: {error}\");\n }\n }\n\n /// \n /// Read subtitle stream to the end and get all subtitle data\n /// \n /// \n /// \n /// \n /// The token has had cancellation requested.\n public void ReadAll(bool useBitmap, Action addSub, CancellationToken token)\n {\n if (_demuxer == null || _decoder == null || _stream == null)\n throw new InvalidOperationException(\"Open() is not called\");\n\n SubtitleData? prevSub = null;\n\n _packet = av_packet_alloc();\n\n int demuxErrors = 0;\n int decodeErrors = 0;\n\n while (!token.IsCancellationRequested)\n {\n _demuxer.Interrupter.ReadRequest();\n int ret = av_read_frame(_demuxer.fmtCtx, _packet);\n\n if (ret != 0)\n {\n av_packet_unref(_packet);\n\n if (_demuxer.Interrupter.Timedout)\n {\n if (token.IsCancellationRequested)\n break;\n\n ret.ThrowExceptionIfError(\"av_read_frame (timed out)\");\n }\n\n if (ret == AVERROR_EOF || token.IsCancellationRequested)\n {\n break;\n }\n\n // demux error\n if (CanWarn) Log.Warn($\"av_read_frame: {FFmpegEngine.ErrorCodeToMsg(ret)} ({ret})\");\n\n if (++demuxErrors == _config.Demuxer.MaxErrors)\n {\n ret.ThrowExceptionIfError(\"av_read_frame\");\n }\n\n continue;\n }\n\n // Discard all but the subtitle stream.\n if (_packet->stream_index != _stream.StreamIndex)\n {\n av_packet_unref(_packet);\n continue;\n }\n\n SubtitleData subData = new();\n int gotSub = 0;\n AVSubtitle sub = default;\n\n ret = avcodec_decode_subtitle2(_decoder.CodecCtx, &sub, &gotSub, _packet);\n if (ret < 0)\n {\n // decode error\n av_packet_unref(_packet);\n if (CanWarn) Log.Warn($\"avcodec_decode_subtitle2: {FFmpegEngine.ErrorCodeToMsg(ret)} ({ret})\");\n if (++decodeErrors == _config.Decoder.MaxErrors)\n {\n ret.ThrowExceptionIfError(\"avcodec_decode_subtitle2\");\n }\n\n continue;\n }\n\n if (gotSub == 0)\n {\n av_packet_unref(_packet);\n continue;\n }\n\n long pts = AV_NOPTS_VALUE; // 0.1us\n if (sub.pts != AV_NOPTS_VALUE)\n {\n pts = sub.pts /*us*/ * 10;\n }\n else if (_packet->pts != AV_NOPTS_VALUE)\n {\n pts = (long)(_packet->pts * _stream.Timebase);\n }\n\n av_packet_unref(_packet);\n\n if (pts == AV_NOPTS_VALUE)\n {\n continue;\n }\n\n if (_stream.IsBitmap)\n {\n // Cache the width and height of the video for use in displaying bitmap subtitles\n // width and height may be 0 unless after decoding the subtitles\n // In this case, bitmap subtitles cannot be displayed correctly, so the size should be cached here\n if (_manager.Width != _decoder.CodecCtx->width)\n _manager.Width = _decoder.CodecCtx->width;\n if (_manager.Height != _decoder.CodecCtx->height)\n _manager.Height = _decoder.CodecCtx->height;\n }\n\n // Bitmap PGS has a special format.\n if (_stream.IsBitmap && prevSub != null\n /*&& _stream->codecpar->codec_id == AVCodecID.AV_CODEC_ID_HDMV_PGS_SUBTITLE*/)\n {\n if (sub.num_rects < 1)\n {\n // Support for special format bitmap subtitles.\n // In the case of bitmap subtitles, num_rects = 0 and 1 may alternate.\n // In this case sub->start_display_time and sub->end_display_time are always fixed at 0 and\n // AVPacket->duration is also always 0.\n // This indicates the end of the previous subtitle, and the time in pts is the end time of the previous subtitle.\n\n // Note that not all bitmap subtitles have this behavior.\n\n // Assign pts as the end time of the previous subtitle\n prevSub.EndTime = new TimeSpan(pts - _demuxer.StartTime);\n addSub(prevSub);\n prevSub = null;\n\n avsubtitle_free(&sub);\n continue;\n }\n\n // There are cases where num_rects = 1 is consecutive.\n // In this case, the previous subtitle end time is corrected by pts, and a new subtitle is started with the same pts.\n if (prevSub.Bitmap?.Sub.end_display_time == uint.MaxValue) // 4294967295\n {\n prevSub.EndTime = new TimeSpan(pts - _demuxer.StartTime);\n addSub(prevSub);\n prevSub = null;\n }\n }\n\n subData.StartTime = new TimeSpan(pts - _demuxer.StartTime);\n subData.EndTime = subData.StartTime.Add(TimeSpan.FromMilliseconds(sub.end_display_time));\n\n switch (sub.rects[0]->type)\n {\n case AVSubtitleType.Text:\n subData.Text = Utils.BytePtrToStringUTF8(sub.rects[0]->text).Trim();\n avsubtitle_free(&sub);\n\n if (string.IsNullOrEmpty(subData.Text))\n {\n continue;\n }\n\n break;\n case AVSubtitleType.Ass:\n string text = Utils.BytePtrToStringUTF8(sub.rects[0]->ass).Trim();\n avsubtitle_free(&sub);\n\n subData.Text = ParseSubtitles.SSAtoSubStyles(text, out var subStyles).Trim();\n subData.SubStyles = subStyles;\n\n if (string.IsNullOrEmpty(subData.Text))\n {\n continue;\n }\n\n break;\n\n case AVSubtitleType.Bitmap:\n subData.IsBitmap = true;\n\n if (useBitmap)\n {\n // Save subtitle data for (OCR or subtitle cache)\n subData.Bitmap = new SubtitleBitmapData(sub);\n }\n else\n {\n // Only subtitle timestamp information is used, so bitmap is released\n avsubtitle_free(&sub);\n }\n\n break;\n }\n\n if (prevSub != null)\n {\n addSub(prevSub);\n }\n\n prevSub = subData;\n }\n\n if (token.IsCancellationRequested)\n {\n prevSub?.Dispose();\n token.ThrowIfCancellationRequested();\n }\n\n // Process last\n if (prevSub != null)\n {\n addSub(prevSub);\n }\n }\n\n private bool _isDisposed;\n public void Dispose()\n {\n if (_isDisposed)\n return;\n\n // av_packet_alloc\n if (_packet != null)\n {\n fixed (AVPacket** ptr = &_packet)\n {\n av_packet_free(ptr);\n }\n }\n\n _decoder?.Dispose();\n if (_demuxer != null)\n {\n _demuxer.Interrupter.ForceInterrupt = 0;\n _demuxer.Dispose();\n }\n\n _isDisposed = true;\n }\n}\n\npublic class SubtitleBitmapData : IDisposable\n{\n public SubtitleBitmapData(AVSubtitle sub)\n {\n Sub = sub;\n }\n\n private readonly ReaderWriterLockSlim _rwLock = new();\n private bool _isDisposed;\n\n public AVSubtitle Sub;\n\n public WriteableBitmap SubToWritableBitmap(bool isGrey)\n {\n (byte[] data, AVSubtitleRect rect) = SubToBitmap(isGrey);\n\n WriteableBitmap wb = new(\n rect.w, rect.h,\n Utils.NativeMethods.DpiXSource, Utils.NativeMethods.DpiYSource,\n PixelFormats.Bgra32, null\n );\n Int32Rect dirtyRect = new(0, 0, rect.w, rect.h);\n wb.Lock();\n\n Marshal.Copy(data, 0, wb.BackBuffer, data.Length);\n\n wb.AddDirtyRect(dirtyRect);\n wb.Unlock();\n wb.Freeze();\n\n return wb;\n }\n\n public unsafe (byte[] data, AVSubtitleRect rect) SubToBitmap(bool isGrey)\n {\n if (_isDisposed)\n throw new InvalidOperationException(\"already disposed\");\n\n try\n {\n // Prevent from disposing\n _rwLock.EnterReadLock();\n\n AVSubtitleRect rect = *Sub.rects[0];\n byte[] data = Renderer.ConvertBitmapSub(Sub, isGrey);\n\n return (data, rect);\n }\n finally\n {\n _rwLock.ExitReadLock();\n }\n }\n\n public void Dispose()\n {\n if (_isDisposed)\n return;\n\n _rwLock.EnterWriteLock();\n\n if (Sub.num_rects > 0)\n {\n unsafe\n {\n fixed (AVSubtitle* subPtr = &Sub)\n {\n avsubtitle_free(subPtr);\n }\n }\n }\n\n _isDisposed = true;\n _rwLock.ExitWriteLock();\n\n#if DEBUG\n GC.SuppressFinalize(this);\n#endif\n }\n\n#if DEBUG\n ~SubtitleBitmapData()\n {\n System.Diagnostics.Debug.Fail(\"Dispose is not called\");\n }\n#endif\n}\n\npublic class SubtitleData : IDisposable, INotifyPropertyChanged\n{\n public int Index { get; set; }\n\n public string? Text\n {\n get;\n set\n {\n var prevIsText = IsText;\n if (Set(ref field, value))\n {\n if (prevIsText != IsText)\n OnPropertyChanged(nameof(IsText));\n OnPropertyChanged(nameof(DisplayText));\n }\n }\n }\n\n public string? TranslatedText\n {\n get;\n set\n {\n var prevUseTranslated = UseTranslated;\n if (Set(ref field, value))\n {\n if (prevUseTranslated != UseTranslated)\n {\n OnPropertyChanged(nameof(UseTranslated));\n }\n OnPropertyChanged(nameof(DisplayText));\n }\n }\n }\n\n public bool IsText => !string.IsNullOrEmpty(Text);\n\n public bool IsTranslated => TranslatedText != null;\n public bool UseTranslated => EnabledTranslated && IsTranslated;\n\n public bool EnabledTranslated = true;\n\n public string? DisplayText => UseTranslated ? TranslatedText : Text;\n\n public List? SubStyles;\n public TimeSpan StartTime { get; set; }\n public TimeSpan EndTime { get; set; }\n#if DEBUG\n public int ChunkNo { get; set => Set(ref field, value); }\n public TimeSpan StartTimeChunk { get; set => Set(ref field, value); }\n public TimeSpan EndTimeChunk { get; set => Set(ref field, value); }\n#endif\n public TimeSpan Duration => EndTime - StartTime;\n\n public SubtitleBitmapData? Bitmap { get; set; }\n\n public bool IsBitmap { get; set; }\n\n private bool _isDisposed;\n\n public void Dispose()\n {\n if (_isDisposed)\n return;\n\n if (IsBitmap && Bitmap != null)\n {\n Bitmap.Dispose();\n Bitmap = null;\n }\n\n _isDisposed = true;\n }\n\n public SubtitleData Clone()\n {\n return new SubtitleData()\n {\n Index = Index,\n Text = Text,\n TranslatedText = TranslatedText,\n EnabledTranslated = EnabledTranslated,\n StartTime = StartTime,\n EndTime = EndTime,\n#if DEBUG\n ChunkNo = ChunkNo,\n StartTimeChunk = StartTimeChunk,\n EndTimeChunk = EndTimeChunk,\n#endif\n IsBitmap = IsBitmap,\n Bitmap = null,\n };\n }\n\n #region INotifyPropertyChanged\n public event PropertyChangedEventHandler? PropertyChanged;\n protected virtual void OnPropertyChanged([CallerMemberName] string? propertyName = null)\n {\n PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));\n }\n\n protected bool Set(ref T field, T value, [CallerMemberName] string? propertyName = null)\n {\n if (EqualityComparer.Default.Equals(field, value))\n return false;\n field = value;\n OnPropertyChanged(propertyName);\n return true;\n }\n #endregion\n}\n\npublic class SubtitleTimeStartComparer : Comparer\n{\n public static SubtitleTimeStartComparer Instance { get; } = new();\n private SubtitleTimeStartComparer() { }\n static SubtitleTimeStartComparer() { }\n\n public override int Compare(SubtitleData? x, SubtitleData? y)\n {\n if (object.Equals(x, y)) return 0;\n if (x == null) return -1;\n if (y == null) return 1;\n\n return x.StartTime.CompareTo(y.StartTime);\n }\n}\n\npublic class SubtitleTimeEndComparer : Comparer\n{\n public override int Compare(SubtitleData? x, SubtitleData? y)\n {\n if (object.Equals(x, y)) return 0;\n if (x == null) return -1;\n if (y == null) return 1;\n\n return x.EndTime.CompareTo(y.EndTime);\n }\n}\n\ninternal static class WrapperHelper\n{\n public static int ThrowExceptionIfError(this int error, string message)\n {\n if (error < 0)\n {\n string errStr = AvErrorStr(error);\n throw new InvalidOperationException($\"{message}: {errStr} ({error})\");\n }\n\n return error;\n }\n\n public static unsafe string AvErrorStr(this int error)\n {\n int bufSize = 1024;\n byte* buf = stackalloc byte[bufSize];\n\n if (av_strerror(error, buf, (nuint)bufSize) == 0)\n {\n string errStr = Marshal.PtrToStringAnsi((IntPtr)buf)!;\n return errStr;\n }\n\n return \"unknown error\";\n }\n}\n\npublic static class ObservableCollectionExtensions\n{\n public static int FindIndex(this ObservableCollection collection, Predicate match)\n {\n ArgumentNullException.ThrowIfNull(collection);\n ArgumentNullException.ThrowIfNull(match);\n\n for (int i = 0; i < collection.Count; i++)\n {\n if (match(collection[i]))\n return i;\n }\n return -1;\n }\n\n public static int BinarySearch(this ObservableCollection collection, T item, IComparer comparer)\n {\n ArgumentNullException.ThrowIfNull(collection);\n\n //comparer ??= Comparer.Default;\n int low = 0;\n int high = collection.Count - 1;\n\n while (low <= high)\n {\n int mid = low + ((high - low) / 2);\n int comparison = comparer.Compare(collection[mid], item);\n\n if (comparison == 0)\n return mid;\n if (comparison < 0)\n low = mid + 1;\n else\n high = mid - 1;\n }\n\n return ~low;\n }\n\n public static IEnumerable GetRange(this ObservableCollection collection, int index, int count)\n {\n ArgumentNullException.ThrowIfNull(collection);\n if (index < 0 || count < 0 || (index + count) > collection.Count)\n throw new ArgumentOutOfRangeException();\n\n return collection.Skip(index).Take(count);\n }\n\n public static void Sort(this ObservableCollection collection, IComparer comparer)\n {\n ArgumentNullException.ThrowIfNull(collection);\n ArgumentNullException.ThrowIfNull(comparer);\n\n List sortedList = collection.ToList();\n sortedList.Sort(comparer);\n\n collection.Clear();\n foreach (var item in sortedList)\n {\n collection.Add(item);\n }\n }\n}\n\npublic class BulkObservableCollection : ObservableCollection\n{\n private bool _suppressNotification;\n\n protected override void OnCollectionChanged(NotifyCollectionChangedEventArgs e)\n {\n if (!_suppressNotification)\n base.OnCollectionChanged(e);\n }\n\n public void AddRange(IEnumerable list)\n {\n ArgumentNullException.ThrowIfNull(list);\n\n _suppressNotification = true;\n\n foreach (T item in list)\n {\n Add(item);\n }\n _suppressNotification = false;\n\n OnCollectionChanged(new NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction.Reset));\n }\n}\n"], ["/LLPlayer/FlyleafLib/Engine/Engine.Audio.cs", "using System;\nusing System.Collections.Generic;\nusing System.Collections.ObjectModel;\nusing System.ComponentModel;\nusing System.Threading.Tasks;\nusing System.Windows.Data;\n\nusing SharpGen.Runtime;\nusing SharpGen.Runtime.Win32;\n\nusing Vortice.MediaFoundation;\nusing static Vortice.XAudio2.XAudio2;\n\nusing FlyleafLib.MediaFramework.MediaDevice;\n\nnamespace FlyleafLib;\n\npublic class AudioEngine : CallbackBase, IMMNotificationClient, INotifyPropertyChanged\n{\n #region Properties (Public)\n\n public AudioEndpoint DefaultDevice { get; private set; } = new() { Id = \"0\", Name = \"Default\" };\n public AudioEndpoint CurrentDevice { get; private set; } = new();\n\n /// \n /// Whether no audio devices were found or audio failed to initialize\n /// \n public bool Failed { get; private set; }\n\n /// \n /// List of Audio Capture Devices\n /// \n public ObservableCollection\n CapDevices { get; set; } = new();\n\n public void RefreshCapDevices() => AudioDevice.RefreshDevices();\n\n /// \n /// List of Audio Devices\n /// \n public ObservableCollection\n Devices { get; private set; } = new();\n\n private readonly object lockDevices = new();\n #endregion\n\n IMMDeviceEnumerator deviceEnum;\n private object locker = new();\n\n public event PropertyChangedEventHandler PropertyChanged;\n\n public AudioEngine()\n {\n if (Engine.Config.DisableAudio)\n {\n Failed = true;\n return;\n }\n\n BindingOperations.EnableCollectionSynchronization(Devices, lockDevices);\n EnumerateDevices();\n }\n\n private void EnumerateDevices()\n {\n try\n {\n deviceEnum = new IMMDeviceEnumerator();\n\n var defaultDevice = deviceEnum.GetDefaultAudioEndpoint(DataFlow.Render, Role.Multimedia);\n if (defaultDevice == null)\n {\n Failed = true;\n return;\n }\n\n lock (lockDevices)\n {\n Devices.Clear();\n Devices.Add(DefaultDevice);\n foreach (var device in deviceEnum.EnumAudioEndpoints(DataFlow.Render, DeviceStates.Active))\n Devices.Add(new() { Id = device.Id, Name = device.FriendlyName });\n }\n\n CurrentDevice.Id = defaultDevice.Id;\n CurrentDevice.Name = defaultDevice.FriendlyName;\n\n if (Logger.CanInfo)\n {\n string dump = \"\";\n foreach (var device in deviceEnum.EnumAudioEndpoints(DataFlow.Render, DeviceStates.Active))\n dump += $\"{device.Id} | {device.FriendlyName} {(defaultDevice.Id == device.Id ? \"*\" : \"\")}\\r\\n\";\n Engine.Log.Info($\"Audio Devices\\r\\n{dump}\");\n }\n\n var xaudio2 = XAudio2Create();\n\n if (xaudio2 == null)\n Failed = true;\n else\n xaudio2.Dispose();\n\n deviceEnum.RegisterEndpointNotificationCallback(this);\n\n } catch { Failed = true; }\n }\n private void RefreshDevices()\n {\n lock (locker)\n {\n Utils.UIInvokeIfRequired(() => // UI Required?\n {\n List curs = new();\n List removed = new();\n\n lock (lockDevices)\n {\n foreach(var device in deviceEnum.EnumAudioEndpoints(DataFlow.Render, DeviceStates.Active))\n curs.Add(new () { Id = device.Id, Name = device.FriendlyName });\n\n foreach(var cur in curs)\n {\n bool exists = false;\n foreach (var device in Devices)\n if (cur.Id == device.Id)\n { exists = true; break; }\n\n if (!exists)\n {\n Engine.Log.Info($\"Audio device {cur} added\");\n Devices.Add(cur);\n }\n }\n\n foreach (var device in Devices)\n {\n if (device.Id == \"0\") // Default\n continue;\n\n bool exists = false;\n foreach(var cur in curs)\n if (cur.Id == device.Id)\n { exists = true; break; }\n\n if (!exists)\n {\n Engine.Log.Info($\"Audio device {device} removed\");\n removed.Add(device);\n }\n }\n\n foreach(var device in removed)\n Devices.Remove(device);\n }\n\n var defaultDevice = deviceEnum.GetDefaultAudioEndpoint(DataFlow.Render, Role.Multimedia);\n if (defaultDevice != null && CurrentDevice.Id != defaultDevice.Id)\n {\n CurrentDevice.Id = defaultDevice.Id;\n CurrentDevice.Name = defaultDevice.FriendlyName;\n PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(nameof(CurrentDevice)));\n }\n\n // Fall back to DefaultDevice *Non-UI thread otherwise will freeze (not sure where and why) during xaudio.Dispose()\n if (removed.Count > 0)\n Task.Run(() =>\n {\n foreach(var device in removed)\n {\n foreach(var player in Engine.Players)\n if (player.Audio.Device == device)\n player.Audio.Device = DefaultDevice;\n }\n });\n });\n }\n }\n\n public void OnDeviceStateChanged(string pwstrDeviceId, int newState) => RefreshDevices();\n public void OnDeviceAdded(string pwstrDeviceId) => RefreshDevices();\n public void OnDeviceRemoved(string pwstrDeviceId) => RefreshDevices();\n public void OnDefaultDeviceChanged(DataFlow flow, Role role, string pwstrDefaultDeviceId) => RefreshDevices();\n public void OnPropertyValueChanged(string pwstrDeviceId, PropertyKey key) { }\n\n public class AudioEndpoint\n {\n public string Id { get; set; }\n public string Name { get; set; }\n\n public override string ToString()\n => Name;\n }\n}\n"], ["/LLPlayer/FlyleafLib/Plugins/OpenSubtitles.cs", "using System.Collections.Generic;\nusing System.IO;\nusing System.Linq;\nusing System.Text;\nusing FlyleafLib.MediaFramework.MediaStream;\nusing Lingua;\n\nnamespace FlyleafLib.Plugins;\n\npublic class OpenSubtitles : PluginBase, IOpenSubtitles, ISearchLocalSubtitles\n{\n public new int Priority { get; set; } = 3000;\n\n private static readonly Lazy LanguageDetector = new(() =>\n {\n LanguageDetector detector = LanguageDetectorBuilder\n .FromAllLanguages()\n .Build();\n\n return detector;\n }, true);\n\n private static readonly HashSet ExtSet = new(Utils.ExtensionsSubtitles, StringComparer.OrdinalIgnoreCase);\n\n public OpenSubtitlesResults Open(string url)\n {\n foreach (var extStream in Selected.ExternalSubtitlesStreamsAll)\n if (extStream.Url == url)\n return new(extStream);\n\n string title;\n\n if (File.Exists(url))\n {\n Selected.FillMediaParts();\n\n FileInfo fi = new(url);\n title = fi.Name;\n }\n else\n {\n try\n {\n Uri uri = new(url);\n title = Path.GetFileName(uri.LocalPath);\n\n if (title == null || title.Trim().Length == 0)\n title = url;\n\n } catch\n {\n title = url;\n }\n }\n\n ExternalSubtitlesStream newExtStream = new()\n {\n Url = url,\n Title = title,\n Downloaded = true,\n IsBitmap = IsSubtitleBitmap(url),\n };\n\n if (Config.Subtitles.LanguageAutoDetect && !newExtStream.IsBitmap)\n {\n newExtStream.Language = DetectLanguage(url);\n newExtStream.LanguageDetected = true;\n }\n\n AddExternalStream(newExtStream);\n\n return new(newExtStream);\n }\n\n public OpenSubtitlesResults Open(Stream iostream) => null;\n\n public void SearchLocalSubtitles()\n {\n try\n {\n string mediaDir = Path.GetDirectoryName(Playlist.Url);\n string mediaName = Path.GetFileNameWithoutExtension(Playlist.Url);\n\n OrderedDictionary result = new(StringComparer.OrdinalIgnoreCase);\n\n CollectFromDirectory(mediaDir, mediaName, result);\n\n // also search in subdirectories\n string paths = Config.Subtitles.SearchLocalPaths;\n if (!string.IsNullOrWhiteSpace(paths))\n {\n foreach (Range seg in paths.AsSpan().Split(';'))\n {\n var path = paths.AsSpan(seg).Trim();\n if (path.IsEmpty) continue;\n\n string searchDir = !Path.IsPathRooted(path)\n ? Path.Join(mediaDir, path)\n : path.ToString();\n\n if (Directory.Exists(searchDir))\n {\n CollectFromDirectory(searchDir, mediaName, result);\n }\n }\n }\n\n if (result.Count == 0)\n {\n return;\n }\n\n Selected.FillMediaParts();\n\n foreach (var (path, lang) in result)\n {\n if (Selected.ExternalSubtitlesStreamsAll.Any(s => s.Url == path))\n {\n continue;\n }\n\n FileInfo fi = new(path);\n string title = fi.Name;\n\n ExternalSubtitlesStream sub = new()\n {\n Url = path,\n Title = title,\n Downloaded = true,\n IsBitmap = IsSubtitleBitmap(path),\n Language = lang\n };\n\n if (Config.Subtitles.LanguageAutoDetect && !sub.IsBitmap && lang == Language.Unknown)\n {\n sub.Language = DetectLanguage(path);\n sub.LanguageDetected = true;\n }\n\n Log.Debug($\"Adding [{sub.Language.TopEnglishName}] {path}\");\n\n AddExternalStream(sub);\n }\n }\n catch (Exception e)\n {\n Log.Error($\"SearchLocalSubtitles failed ({e.Message})\");\n }\n }\n\n private static void CollectFromDirectory(string searchDir, string filename, IDictionary result)\n {\n HashSet added = null;\n\n // Get files starting with the same filename\n List fileList;\n try\n {\n fileList = Directory.GetFiles(searchDir, $\"{filename}.*\", new EnumerationOptions { MatchCasing = MatchCasing.CaseInsensitive })\n .ToList();\n }\n catch\n {\n return;\n }\n\n if (fileList.Count == 0)\n {\n return;\n }\n\n var files = fileList.Select(f => new\n {\n FullPath = f,\n FileName = Path.GetFileName(f)\n }).ToList();\n\n // full match with top priority (video.srt, video.ass)\n foreach (string ext in ExtSet)\n {\n string expect = $\"{filename}.{ext}\";\n int match = files.FindIndex(x => string.Equals(x.FileName, expect, StringComparison.OrdinalIgnoreCase));\n if (match != -1)\n {\n result.TryAdd(files[match].FullPath, Language.Unknown);\n added ??= new HashSet();\n added.Add(match);\n }\n }\n\n // head match (video.*.srt, video.*.ass)\n var extSetLookup = ExtSet.GetAlternateLookup>();\n foreach (var (i, x) in files.Index())\n {\n // skip full match\n if (added != null && added.Contains(i))\n {\n continue;\n }\n\n var span = x.FileName.AsSpan();\n var fileExt = Path.GetExtension(span).TrimStart('.');\n\n // Check if the file is a subtitle file by its extension\n if (extSetLookup.Contains(fileExt))\n {\n var name = Path.GetFileNameWithoutExtension(span);\n\n if (!name.StartsWith(filename + '.', StringComparison.OrdinalIgnoreCase))\n {\n continue;\n }\n\n Language lang = Language.Unknown;\n\n var extraPart = name.Slice(filename.Length + 1); // Skip file name and dot\n if (extraPart.Length > 0)\n {\n foreach (var codeSeg in extraPart.Split('.'))\n {\n var code = extraPart[codeSeg];\n if (code.Length > 0)\n {\n Language parsed = Language.Get(code.ToString());\n if (!string.IsNullOrEmpty(parsed.IdSubLanguage) && parsed.IdSubLanguage != \"und\")\n {\n lang = parsed;\n break;\n }\n }\n }\n }\n\n result.TryAdd(x.FullPath, lang);\n }\n }\n }\n\n // TODO: L: To check the contents of a file by determining the bitmap.\n private static bool IsSubtitleBitmap(string path)\n {\n try\n {\n FileInfo fi = new(path);\n\n return Utils.ExtensionsSubtitlesBitmap.Contains(fi.Extension.TrimStart('.').ToLower());\n }\n catch\n {\n return false;\n }\n }\n\n // TODO: L: Would it be better to check with SubtitlesManager for network subtitles?\n private static Language DetectLanguage(string path)\n {\n if (!File.Exists(path))\n {\n return Language.Unknown;\n }\n\n Encoding encoding = Encoding.Default;\n Encoding detected = TextEncodings.DetectEncoding(path);\n\n if (detected != null)\n {\n encoding = detected;\n }\n\n // TODO: L: refactor: use the code for reading subtitles in Demuxer\n byte[] data = new byte[100 * 1024];\n\n try\n {\n using FileStream fs = new(path, FileMode.Open, FileAccess.Read);\n int bytesRead = fs.Read(data, 0, data.Length);\n Array.Resize(ref data, bytesRead);\n }\n catch\n {\n return Language.Unknown;\n }\n\n string content = encoding.GetString(data);\n\n var detectedLanguage = LanguageDetector.Value.DetectLanguageOf(content);\n\n if (detectedLanguage == Lingua.Language.Unknown)\n {\n return Language.Unknown;\n }\n\n return Language.Get(detectedLanguage.IsoCode6391().ToString().ToLower());\n }\n}\n"], ["/LLPlayer/FlyleafLib/MediaFramework/MediaDemuxer/Demuxer.cs", "using System.Collections.Concurrent;\nusing System.Collections.Generic;\nusing System.Collections.ObjectModel;\nusing System.IO;\nusing System.Runtime.InteropServices;\nusing System.Text;\nusing System.Threading;\nusing System.Threading.Tasks;\nusing System.Windows.Data;\n\nusing FlyleafLib.MediaFramework.MediaProgram;\nusing FlyleafLib.MediaFramework.MediaStream;\nusing FlyleafLib.MediaPlayer;\nusing static FlyleafLib.Config;\nusing static FlyleafLib.Logger;\n\nnamespace FlyleafLib.MediaFramework.MediaDemuxer;\n\npublic unsafe class Demuxer : RunThreadBase\n{\n /* TODO\n * 1) Review lockFmtCtx on Enable/Disable Streams causes delay and is not fully required\n * 2) Include AV_DISPOSITION_ATTACHED_PIC images in streams as VideoStream with flag\n * Possible introduce ImageStream and include also video streams with < 1 sec duration (eg. mjpeg etc)\n */\n\n #region Properties\n public MediaType Type { get; private set; }\n public DemuxerConfig Config { get; set; }\n\n // Format Info\n public string Url { get; private set; }\n public string Name { get; private set; }\n public string LongName { get; private set; }\n public string Extensions { get; private set; }\n public string Extension { get; private set; }\n public long StartTime { get; private set; }\n public long StartRealTime { get; private set; }\n public long Duration { get; internal set; }\n public void ForceDuration(long duration) { Duration = duration; IsLive = duration != 0; }\n\n public Dictionary\n Metadata { get; internal set; } = new Dictionary();\n\n /// \n /// The time of first packet in the queue (zero based, substracts start time)\n /// \n public long CurTime => CurPackets.CurTime != 0 ? CurPackets.CurTime : lastSeekTime;\n\n /// \n /// The buffered time in the queue (last packet time - first packet time)\n /// \n public long BufferedDuration=> CurPackets.BufferedDuration;\n\n public bool IsLive { get; private set; }\n public bool IsHLSLive { get; private set; }\n\n public AVFormatContext* FormatContext => fmtCtx;\n public CustomIOContext CustomIOContext { get; private set; }\n\n // Media Programs\n public ObservableCollection\n Programs { get; private set; } = new ObservableCollection();\n\n // Media Streams\n public ObservableCollection\n AudioStreams { get; private set; } = new ObservableCollection();\n public ObservableCollection\n VideoStreams { get; private set; } = new ObservableCollection();\n public ObservableCollection\n SubtitlesStreamsAll\n { get; private set; } = new ObservableCollection();\n public ObservableCollection\n DataStreams { get; private set; } = new ObservableCollection();\n readonly object lockStreams = new();\n\n public List EnabledStreams { get; private set; } = new List();\n public Dictionary\n AVStreamToStream{ get; private set; }\n\n public AudioStream AudioStream { get; private set; }\n public VideoStream VideoStream { get; private set; }\n // In the case of the secondary external subtitle, there is only one stream, but it goes into index=1 and index = 0 is null.\n public SubtitlesStream[] SubtitlesStreams\n { get; private set; }\n public DataStream DataStream { get; private set; }\n\n // Audio/Video Stream's HLSPlaylist\n internal playlist* HLSPlaylist { get; private set; }\n\n // Media Packets\n public PacketQueue Packets { get; private set; }\n public PacketQueue AudioPackets { get; private set; }\n public PacketQueue VideoPackets { get; private set; }\n public PacketQueue[] SubtitlesPackets\n { get; private set; }\n public PacketQueue DataPackets { get; private set; }\n public PacketQueue CurPackets { get; private set; }\n\n public bool UseAVSPackets { get; private set; }\n\n public PacketQueue GetPacketsPtr(StreamBase stream)\n {\n if (!UseAVSPackets)\n {\n return Packets;\n }\n\n switch (stream.Type)\n {\n case MediaType.Audio:\n return AudioPackets;\n case MediaType.Video:\n return VideoPackets;\n case MediaType.Subs:\n return SubtitlesPackets[SubtitlesSelectedHelper.CurIndex];\n default:\n return DataPackets;\n }\n }\n\n public ConcurrentQueue>>\n VideoPacketsReverse\n { get; private set; } = new ConcurrentQueue>>();\n\n public bool IsReversePlayback\n { get; private set; }\n\n public long TotalBytes { get; private set; } = 0;\n\n // Interrupt\n public Interrupter Interrupter { get; private set; }\n\n public ObservableCollection\n Chapters { get; private set; } = new ObservableCollection();\n public class Chapter\n {\n public long StartTime { get; set; }\n public long EndTime { get; set; }\n public string Title { get; set; }\n }\n\n public event EventHandler AudioLimit;\n bool audioBufferLimitFired;\n void OnAudioLimit()\n => Task.Run(() => AudioLimit?.Invoke(this, new EventArgs()));\n\n public event EventHandler TimedOut;\n internal void OnTimedOut()\n => Task.Run(() => TimedOut?.Invoke(this, new EventArgs()));\n #endregion\n\n #region Constructor / Declaration\n public AVPacket* packet;\n public AVFormatContext* fmtCtx;\n internal HLSContext* hlsCtx;\n\n long hlsPrevSeqNo = AV_NOPTS_VALUE; // Identifies the change of the m3u8 playlist (wraped)\n internal long hlsStartTime = AV_NOPTS_VALUE; // Calculation of first timestamp (lastPacketTs - hlsCurDuration)\n long hlsCurDuration; // Duration until the start of the current segment\n long lastSeekTime; // To set CurTime while no packets are available\n\n public object lockFmtCtx = new();\n internal bool allowReadInterrupts;\n\n /* Reverse Playback\n *\n * Video Packets Queue (FIFO) ConcurrentQueue>>\n * Video Packets Seek Stacks (FILO) ConcurrentStack>\n * Video Packets List Keyframe (List) List\n */\n\n long curReverseStopPts = AV_NOPTS_VALUE;\n long curReverseStopRequestedPts\n = AV_NOPTS_VALUE;\n long curReverseStartPts = AV_NOPTS_VALUE;\n List curReverseVideoPackets = new();\n ConcurrentStack>\n curReverseVideoStack = new();\n long curReverseSeekOffset;\n\n // Required for passing AV Options and HTTP Query params to the underlying contexts\n AVFormatContext_io_open ioopen;\n AVFormatContext_io_open ioopenDefault;\n AVDictionary* avoptCopy;\n Dictionary\n queryParams;\n byte[] queryCachedBytes;\n\n // for TEXT subtitles buffer\n byte* inputData;\n int inputDataSize;\n internal AVIOContext* avioCtx;\n\n int subNum => Config.config.Subtitles.Max;\n\n public Demuxer(DemuxerConfig config, MediaType type = MediaType.Video, int uniqueId = -1, bool useAVSPackets = true) : base(uniqueId)\n {\n Config = config;\n Type = type;\n UseAVSPackets = useAVSPackets;\n Interrupter = new Interrupter(this);\n CustomIOContext = new CustomIOContext(this);\n\n Packets = new PacketQueue(this);\n AudioPackets = new PacketQueue(this);\n VideoPackets = new PacketQueue(this);\n SubtitlesPackets = new PacketQueue[subNum];\n for (int i = 0; i < subNum; i++)\n {\n SubtitlesPackets[i] = new PacketQueue(this);\n }\n SubtitlesStreams = new SubtitlesStream[subNum];\n\n DataPackets = new PacketQueue(this);\n CurPackets = Packets; // Will be updated on stream switch in case of AVS\n\n string typeStr = Type == MediaType.Video ? \"Main\" : Type.ToString();\n threadName = $\"Demuxer: {typeStr,5}\";\n\n Utils.UIInvokeIfRequired(() =>\n {\n BindingOperations.EnableCollectionSynchronization(Programs, lockStreams);\n BindingOperations.EnableCollectionSynchronization(AudioStreams, lockStreams);\n BindingOperations.EnableCollectionSynchronization(VideoStreams, lockStreams);\n BindingOperations.EnableCollectionSynchronization(SubtitlesStreamsAll, lockStreams);\n BindingOperations.EnableCollectionSynchronization(DataStreams, lockStreams);\n\n BindingOperations.EnableCollectionSynchronization(Chapters, lockStreams);\n });\n\n ioopen = IOOpen;\n }\n #endregion\n\n #region Dispose / Dispose Packets\n public void DisposePackets()\n {\n if (UseAVSPackets)\n {\n AudioPackets.Clear();\n VideoPackets.Clear();\n for (int i = 0; i < subNum; i++)\n {\n SubtitlesPackets[i].Clear();\n }\n DataPackets.Clear();\n\n DisposePacketsReverse();\n }\n else\n Packets.Clear();\n\n hlsStartTime = AV_NOPTS_VALUE;\n }\n\n public void DisposePacketsReverse()\n {\n while (!VideoPacketsReverse.IsEmpty)\n {\n VideoPacketsReverse.TryDequeue(out var t1);\n while (!t1.IsEmpty)\n {\n t1.TryPop(out var t2);\n for (int i = 0; i < t2.Count; i++)\n {\n if (t2[i] == IntPtr.Zero) continue;\n AVPacket* packet = (AVPacket*)t2[i];\n av_packet_free(&packet);\n }\n }\n }\n\n while (!curReverseVideoStack.IsEmpty)\n {\n curReverseVideoStack.TryPop(out var t2);\n for (int i = 0; i < t2.Count; i++)\n {\n if (t2[i] == IntPtr.Zero) continue;\n AVPacket* packet = (AVPacket*)t2[i];\n av_packet_free(&packet);\n }\n }\n }\n public void Dispose()\n {\n if (Disposed)\n return;\n\n lock (lockActions)\n {\n if (Disposed)\n return;\n\n Stop();\n\n Url = null;\n hlsCtx = null;\n\n IsReversePlayback = false;\n curReverseStopPts = AV_NOPTS_VALUE;\n curReverseStartPts = AV_NOPTS_VALUE;\n hlsPrevSeqNo = AV_NOPTS_VALUE;\n lastSeekTime = 0;\n\n // Free Streams\n lock (lockStreams)\n {\n AudioStreams.Clear();\n VideoStreams.Clear();\n SubtitlesStreamsAll.Clear();\n DataStreams.Clear();\n Programs.Clear();\n\n Chapters.Clear();\n }\n EnabledStreams.Clear();\n AudioStream = null;\n VideoStream = null;\n for (int i = 0; i < subNum; i++)\n {\n SubtitlesStreams[i] = null;\n }\n DataStream = null;\n queryParams = null;\n queryCachedBytes = null;\n\n DisposePackets();\n\n if (fmtCtx != null)\n {\n Interrupter.CloseRequest();\n fixed (AVFormatContext** ptr = &fmtCtx) { avformat_close_input(ptr); fmtCtx = null; }\n }\n\n if (avoptCopy != null) fixed (AVDictionary** ptr = &avoptCopy) av_dict_free(ptr);\n if (packet != null) fixed (AVPacket** ptr = &packet) av_packet_free(ptr);\n\n CustomIOContext.Dispose();\n\n if (avioCtx != null)\n {\n av_free(avioCtx->buffer);\n fixed (AVIOContext** ptr = &avioCtx)\n {\n avio_context_free(ptr);\n }\n\n inputData = null;\n inputDataSize = 0;\n }\n\n TotalBytes = 0;\n Status = Status.Stopped;\n Disposed = true;\n\n Log.Info(\"Disposed\");\n }\n }\n #endregion\n\n #region Open / Seek / Run\n public string Open(string url) => Open(url, null);\n public string Open(Stream stream) => Open(null, stream);\n public string Open(string url, Stream stream)\n {\n bool gotLockActions = false;\n bool gotLockFmtCtx = false;\n string error = null;\n\n try\n {\n Monitor.Enter(lockActions,ref gotLockActions);\n Dispose();\n Monitor.Enter(lockFmtCtx, ref gotLockFmtCtx);\n Url = url;\n\n if (string.IsNullOrEmpty(url) && stream == null)\n return \"Invalid empty/null input\";\n\n Dictionary\n fmtOptExtra = null;\n AVInputFormat* inFmt = null;\n int ret = -1;\n\n Disposed = false;\n Status = Status.Opening;\n\n // Allocate / Prepare Format Context\n fmtCtx = avformat_alloc_context();\n if (Config.AllowInterrupts)\n fmtCtx->interrupt_callback.callback = Interrupter.interruptClbk;\n\n fmtCtx->flags |= (FmtFlags2)Config.FormatFlags;\n\n // Force Format (url as input and Config.FormatOpt for options)\n if (Config.ForceFormat != null)\n {\n inFmt = av_find_input_format(Config.ForceFormat);\n if (inFmt == null)\n return error = $\"[av_find_input_format] {Config.ForceFormat} not found\";\n }\n\n // Force Custom IO Stream Context (url should be null)\n if (stream != null)\n {\n CustomIOContext.Initialize(stream);\n stream.Seek(0, SeekOrigin.Begin);\n url = null;\n }\n\n /* Force Format with Url syntax to support format, url and options within the input url\n *\n * fmt://$format$[/]?$input$&$options$\n *\n * deprecate support for device://\n *\n * Examples:\n * See: https://ffmpeg.org/ffmpeg-devices.html for devices formats and options\n *\n * 1. fmt://gdigrab?title=Command Prompt&framerate=2\n * 2. fmt://gdigrab?desktop\n * 3. fmt://dshow?audio=Microphone (Relatek):video=Lenovo Camera\n * 4. fmt://rawvideo?C:\\root\\dev\\Flyleaf\\VideoSamples\\rawfile.raw&pixel_format=uyvy422&video_size=1920x1080&framerate=60\n *\n */\n else if (url.StartsWith(\"fmt://\") || url.StartsWith(\"device://\"))\n {\n string urlFromUrl = null;\n string fmtStr = \"\";\n int fmtStarts = url.IndexOf('/') + 2;\n int queryStarts = url.IndexOf('?');\n\n if (queryStarts == -1)\n fmtStr = url[fmtStarts..];\n else\n {\n fmtStr = url[fmtStarts..queryStarts];\n\n string query = url[(queryStarts + 1)..];\n int inputEnds = query.IndexOf('&');\n\n if (inputEnds == -1)\n urlFromUrl = query;\n else\n {\n urlFromUrl = query[..inputEnds];\n query = query[(inputEnds + 1)..];\n\n fmtOptExtra = Utils.ParseQueryString(query);\n }\n }\n\n url = urlFromUrl;\n fmtStr = fmtStr.Replace(\"/\", \"\");\n inFmt = av_find_input_format(fmtStr);\n if (inFmt == null)\n return error = $\"[av_find_input_format] {fmtStr} not found\";\n }\n else if (url.StartsWith(\"srt://\"))\n {\n ReadOnlySpan urlSpan = url.AsSpan();\n int queryPos = urlSpan.IndexOf('?');\n\n if (queryPos != -1)\n {\n fmtOptExtra = Utils.ParseQueryString(urlSpan.Slice(queryPos + 1));\n url = urlSpan[..queryPos].ToString();\n }\n }\n\n if (Config.FormatOptToUnderlying && url != null && (url.StartsWith(\"http://\") || url.StartsWith(\"https://\")))\n {\n queryParams = [];\n if (Config.DefaultHTTPQueryToUnderlying)\n {\n int queryStarts = url.IndexOf('?');\n if (queryStarts != -1)\n {\n var qp = Utils.ParseQueryString(url.AsSpan()[(queryStarts + 1)..]);\n foreach (var kv in qp)\n queryParams[kv.Key] = kv.Value;\n }\n }\n\n foreach (var kv in Config.ExtraHTTPQueryParamsToUnderlying)\n queryParams[kv.Key] = kv.Value;\n\n if (queryParams.Count > 0)\n {\n var queryCachedStr = \"?\";\n foreach (var kv in queryParams)\n queryCachedStr += kv.Value == null ? $\"{kv.Key}&\" : $\"{kv.Key}={kv.Value}&\";\n\n queryCachedStr = queryCachedStr[..^1];\n queryCachedBytes = Encoding.UTF8.GetBytes(queryCachedStr);\n }\n else\n queryParams = null;\n }\n\n if (Type == MediaType.Subs &&\n Utils.ExtensionsSubtitlesText.Contains(Utils.GetUrlExtention(url)) &&\n File.Exists(url))\n {\n // If the files can be read with text subtitles, load them all into memory and convert them to UTF8.\n // Because ffmpeg expects UTF8 text.\n try\n {\n FileInfo file = new(url);\n if (file.Length >= 10 * 1024 * 1024)\n {\n throw new InvalidOperationException($\"TEXT subtitle is too big (>=10MB) to load: {file.Length}\");\n }\n\n // Detects character encoding, reads text and converts to UTF8\n Encoding encoding = Encoding.UTF8;\n\n Encoding detected = TextEncodings.DetectEncoding(url);\n if (detected != null)\n {\n encoding = detected;\n }\n\n string content = File.ReadAllText(url, encoding);\n byte[] contentBytes = Encoding.UTF8.GetBytes(content);\n\n inputDataSize = contentBytes.Length;\n inputData = (byte*)av_malloc((nuint)inputDataSize);\n\n Span src = new(contentBytes);\n Span dst = new(inputData, inputDataSize);\n src.CopyTo(dst);\n\n avioCtx = avio_alloc_context(inputData, inputDataSize, 0, null, null, null, null);\n if (avioCtx == null)\n {\n throw new InvalidOperationException(\"avio_alloc_context\");\n }\n\n // Pass to ffmpeg by on-memory\n fmtCtx->pb = avioCtx;\n fmtCtx->flags |= FmtFlags2.CustomIo;\n }\n catch (Exception ex)\n {\n Log.Warn($\"Could not load text subtitles to memory: {ex.Message}\");\n }\n }\n\n // Some devices required to be opened from a UI or STA thread | after 20-40 sec. of demuxing -> [gdigrab @ 0000019affe3f2c0] Failed to capture image (error 6) or (error 8)\n bool isDevice = inFmt != null && inFmt->priv_class != null && (\n inFmt->priv_class->category.HasFlag(AVClassCategory.DeviceAudioInput) ||\n inFmt->priv_class->category.HasFlag(AVClassCategory.DeviceAudioOutput) ||\n inFmt->priv_class->category.HasFlag(AVClassCategory.DeviceInput) ||\n inFmt->priv_class->category.HasFlag(AVClassCategory.DeviceOutput) ||\n inFmt->priv_class->category.HasFlag(AVClassCategory.DeviceVideoInput) ||\n inFmt->priv_class->category.HasFlag(AVClassCategory.DeviceVideoOutput)\n );\n\n // Open Format Context\n allowReadInterrupts = true; // allow Open interrupts always\n Interrupter.OpenRequest();\n\n // Nesting the io_open (to pass the options to the underlying formats)\n if (Config.FormatOptToUnderlying)\n {\n ioopenDefault = (AVFormatContext_io_open)Marshal.GetDelegateForFunctionPointer(fmtCtx->io_open.Pointer, typeof(AVFormatContext_io_open));\n fmtCtx->io_open = ioopen;\n }\n\n if (isDevice)\n {\n string fmtName = Utils.BytePtrToStringUTF8(inFmt->name);\n\n if (fmtName == \"decklink\") // avoid using UI thread for decklink (STA should be enough for CoInitialize/CoCreateInstance)\n Utils.STAInvoke(() => OpenFormat(url, inFmt, fmtOptExtra, out ret));\n else\n Utils.UIInvoke(() => OpenFormat(url, inFmt, fmtOptExtra, out ret));\n }\n else\n OpenFormat(url, inFmt, fmtOptExtra, out ret);\n\n if ((ret == AVERROR_EXIT && !Interrupter.Timedout) || Status != Status.Opening || Interrupter.ForceInterrupt == 1) { if (ret < 0) fmtCtx = null; return error = \"Cancelled\"; }\n if (ret < 0) { fmtCtx = null; return error = Interrupter.Timedout ? \"[avformat_open_input] Timeout\" : $\"[avformat_open_input] {FFmpegEngine.ErrorCodeToMsg(ret)} ({ret})\"; }\n\n // Find Streams Info\n if (Config.AllowFindStreamInfo)\n {\n /* For some reason HdmvPgsSubtitle requires more analysis (even when it has already all the information)\n *\n * Increases delay & memory and it will not free it after analysis (fmtctx internal buffer)\n * - avformat_flush will release it but messes with the initial seek position (possible seek to start to force it releasing it but still we have the delay)\n *\n * Consider\n * - DVD/Blu-ray/mpegts only? (possible HLS -> mpegts?*)\n * - Re-open in case of \"Consider increasing the value for the 'analyzeduration'\" (catch from ffmpeg log)\n *\n * https://github.com/SuRGeoNix/Flyleaf/issues/502\n */\n\n if (Utils.BytePtrToStringUTF8(fmtCtx->iformat->name) == \"mpegts\")\n {\n bool requiresMoreAnalyse = false;\n\n for (int i = 0; i < fmtCtx->nb_streams; i++)\n if (fmtCtx->streams[i]->codecpar->codec_id == AVCodecID.HdmvPgsSubtitle ||\n fmtCtx->streams[i]->codecpar->codec_id == AVCodecID.DvdSubtitle\n )\n { requiresMoreAnalyse = true; break; }\n\n if (requiresMoreAnalyse)\n {\n fmtCtx->probesize = Math.Max(fmtCtx->probesize, 5000 * (long)1024 * 1024); // Bytes\n fmtCtx->max_analyze_duration = Math.Max(fmtCtx->max_analyze_duration, 1000 * (long)1000 * 1000); // Mcs\n }\n }\n\n ret = avformat_find_stream_info(fmtCtx, null);\n if (ret == AVERROR_EXIT || Status != Status.Opening || Interrupter.ForceInterrupt == 1) return error = \"Cancelled\";\n if (ret < 0) return error = $\"[avformat_find_stream_info] {FFmpegEngine.ErrorCodeToMsg(ret)} ({ret})\";\n }\n\n // Prevent Multiple Immediate exit requested on eof (maybe should not use avio_feof() to test for the end)\n if (fmtCtx->pb != null)\n fmtCtx->pb->eof_reached = 0;\n\n bool hasVideo = FillInfo();\n\n if (Type == MediaType.Video && !hasVideo && AudioStreams.Count == 0)\n return error = $\"No audio / video stream found\";\n else if (Type == MediaType.Audio && AudioStreams.Count == 0)\n return error = $\"No audio stream found\";\n else if (Type == MediaType.Subs && SubtitlesStreamsAll.Count == 0)\n return error = $\"No subtitles stream found\";\n\n packet = av_packet_alloc();\n Status = Status.Stopped;\n allowReadInterrupts = Config.AllowReadInterrupts && !Config.ExcludeInterruptFmts.Contains(Name);\n\n return error = null;\n }\n catch (Exception ex)\n {\n return error = $\"Unknown: {ex.Message}\";\n }\n finally\n {\n if (error != null)\n Dispose();\n\n if (gotLockFmtCtx) Monitor.Exit(lockFmtCtx);\n if (gotLockActions) Monitor.Exit(lockActions);\n }\n }\n\n int IOOpen(AVFormatContext* s, AVIOContext** pb, byte* urlb, IOFlags flags, AVDictionary** avFmtOpts)\n {\n int ret;\n AVDictionaryEntry *t = null;\n\n if (avoptCopy != null)\n {\n while ((t = av_dict_get(avoptCopy, \"\", t, DictReadFlags.IgnoreSuffix)) != null)\n _ = av_dict_set(avFmtOpts, Utils.BytePtrToStringUTF8(t->key), Utils.BytePtrToStringUTF8(t->value), 0);\n }\n\n if (queryParams == null)\n ret = ioopenDefault(s, pb, urlb, flags, avFmtOpts);\n else\n {\n int urlLength = 0;\n int queryPos = -1;\n while (urlb[urlLength] != '\\0')\n {\n if (urlb[urlLength] == '?' && queryPos == -1 && urlb[urlLength + 1] != '\\0')\n queryPos = urlLength;\n\n urlLength++;\n }\n\n // urlNoQuery + ? + queryCachedBytes\n if (queryPos == -1)\n {\n ReadOnlySpan urlNoQuery = new(urlb, urlLength);\n int newLength = urlLength + queryCachedBytes.Length + 1;\n Span urlSpan = newLength < 1024 ? stackalloc byte[newLength] : new byte[newLength];// new(urlPtr, newLength);\n urlNoQuery.CopyTo(urlSpan);\n queryCachedBytes.AsSpan().CopyTo(urlSpan[urlNoQuery.Length..]);\n\n fixed(byte* urlPtr = urlSpan)\n ret = ioopenDefault(s, pb, urlPtr, flags, avFmtOpts);\n }\n\n // urlNoQuery + ? + existingParams/queryParams combined\n else\n {\n ReadOnlySpan urlNoQuery = new(urlb, queryPos);\n ReadOnlySpan urlQuery = new(urlb + queryPos + 1, urlLength - queryPos - 1);\n var qps = Utils.ParseQueryString(Encoding.UTF8.GetString(urlQuery));\n\n foreach (var kv in queryParams)\n if (!qps.ContainsKey(kv.Key))\n qps[kv.Key] = kv.Value;\n\n string newQuery = \"?\";\n foreach (var kv in qps)\n newQuery += kv.Value == null ? $\"{kv.Key}&\" : $\"{kv.Key}={kv.Value}&\";\n\n int newLength = urlNoQuery.Length + newQuery.Length + 1;\n Span urlSpan = newLength < 1024 ? stackalloc byte[newLength] : new byte[newLength];// new(urlPtr, newLength);\n urlNoQuery.CopyTo(urlSpan);\n Encoding.UTF8.GetBytes(newQuery).AsSpan().CopyTo(urlSpan[urlNoQuery.Length..]);\n\n fixed(byte* urlPtr = urlSpan)\n ret = ioopenDefault(s, pb, urlPtr, flags, avFmtOpts);\n }\n }\n\n return ret;\n }\n\n private void OpenFormat(string url, AVInputFormat* inFmt, Dictionary opt, out int ret)\n {\n AVDictionary* avopt = null;\n var curOpt = Type == MediaType.Video ? Config.FormatOpt : (Type == MediaType.Audio ? Config.AudioFormatOpt : Config.SubtitlesFormatOpt);\n\n if (curOpt != null)\n foreach (var optKV in curOpt)\n av_dict_set(&avopt, optKV.Key, optKV.Value, 0);\n\n if (opt != null)\n foreach (var optKV in opt)\n av_dict_set(&avopt, optKV.Key, optKV.Value, 0);\n\n if (Config.FormatOptToUnderlying)\n fixed(AVDictionary** ptr = &avoptCopy)\n av_dict_copy(ptr, avopt, 0);\n\n fixed(AVFormatContext** fmtCtxPtr = &fmtCtx)\n ret = avformat_open_input(fmtCtxPtr, url, inFmt, avopt == null ? null : &avopt);\n\n if (avopt != null)\n {\n if (ret >= 0)\n {\n AVDictionaryEntry *t = null;\n\n while ((t = av_dict_get(avopt, \"\", t, DictReadFlags.IgnoreSuffix)) != null)\n Log.Debug($\"Ignoring format option {Utils.BytePtrToStringUTF8(t->key)}\");\n }\n\n av_dict_free(&avopt);\n }\n }\n private bool FillInfo()\n {\n Name = Utils.BytePtrToStringUTF8(fmtCtx->iformat->name);\n LongName = Utils.BytePtrToStringUTF8(fmtCtx->iformat->long_name);\n Extensions = Utils.BytePtrToStringUTF8(fmtCtx->iformat->extensions);\n\n StartTime = fmtCtx->start_time != AV_NOPTS_VALUE ? fmtCtx->start_time * 10 : 0;\n StartRealTime = fmtCtx->start_time_realtime != AV_NOPTS_VALUE ? fmtCtx->start_time_realtime * 10 : 0;\n Duration = fmtCtx->duration > 0 ? fmtCtx->duration * 10 : 0;\n\n // TBR: Possible we can get Apple HTTP Live Streaming/hls with HLSPlaylist->finished with Duration != 0\n if (Engine.Config.FFmpegHLSLiveSeek && Duration == 0 && Name == \"hls\" && Environment.Is64BitProcess) // HLSContext cast is not safe\n {\n hlsCtx = (HLSContext*) fmtCtx->priv_data;\n StartTime = 0;\n //UpdateHLSTime(); Maybe with default 0 playlist\n }\n\n if (fmtCtx->nb_streams == 1 && fmtCtx->streams[0]->codecpar->codec_type == AVMediaType.Subtitle) // External Streams (mainly for .sub will have as start time the first subs timestamp)\n StartTime = 0;\n\n IsLive = Duration == 0 || hlsCtx != null;\n\n bool hasVideo = false;\n AVStreamToStream = new Dictionary();\n\n Metadata.Clear();\n AVDictionaryEntry* b = null;\n while (true)\n {\n b = av_dict_get(fmtCtx->metadata, \"\", b, DictReadFlags.IgnoreSuffix);\n if (b == null) break;\n Metadata.Add(Utils.BytePtrToStringUTF8(b->key), Utils.BytePtrToStringUTF8(b->value));\n }\n\n Chapters.Clear();\n string dump = \"\";\n for (int i=0; inb_chapters; i++)\n {\n var chp = fmtCtx->chapters[i];\n double tb = av_q2d(chp->time_base) * 10000.0 * 1000.0;\n string title = \"\";\n\n b = null;\n while (true)\n {\n b = av_dict_get(chp->metadata, \"\", b, DictReadFlags.IgnoreSuffix);\n if (b == null) break;\n if (Utils.BytePtrToStringUTF8(b->key).ToLower() == \"title\")\n title = Utils.BytePtrToStringUTF8(b->value);\n }\n\n if (CanDebug)\n dump += $\"[Chapter {i+1,-2}] {Utils.TicksToTime((long)(chp->start * tb) - StartTime)} - {Utils.TicksToTime((long)(chp->end * tb) - StartTime)} | {title}\\r\\n\";\n\n Chapters.Add(new Chapter()\n {\n StartTime = (long)((chp->start * tb) - StartTime),\n EndTime = (long)((chp->end * tb) - StartTime),\n Title = title\n });\n }\n\n if (CanDebug && dump != \"\") Log.Debug($\"Chapters\\r\\n\\r\\n{dump}\");\n\n bool audioHasEng = false;\n bool subsHasEng = false;\n\n lock (lockStreams)\n {\n for (int i=0; inb_streams; i++)\n {\n fmtCtx->streams[i]->discard = AVDiscard.All;\n\n switch (fmtCtx->streams[i]->codecpar->codec_type)\n {\n case AVMediaType.Audio:\n AudioStreams.Add(new AudioStream(this, fmtCtx->streams[i]));\n AVStreamToStream.Add(fmtCtx->streams[i]->index, AudioStreams[^1]);\n audioHasEng = AudioStreams[^1].Language == Language.English;\n\n break;\n\n case AVMediaType.Video:\n if ((fmtCtx->streams[i]->disposition & DispositionFlags.AttachedPic) != 0)\n { Log.Info($\"Excluding image stream #{i}\"); continue; }\n\n // TBR: When AllowFindStreamInfo = false we can get valid pixel format during decoding (in case of remuxing only this might crash, possible check if usedecoders?)\n if (((AVPixelFormat)fmtCtx->streams[i]->codecpar->format) == AVPixelFormat.None && Config.AllowFindStreamInfo)\n {\n Log.Info($\"Excluding invalid video stream #{i}\");\n continue;\n }\n VideoStreams.Add(new VideoStream(this, fmtCtx->streams[i]));\n AVStreamToStream.Add(fmtCtx->streams[i]->index, VideoStreams[^1]);\n hasVideo |= !Config.AllowFindStreamInfo || VideoStreams[^1].PixelFormat != AVPixelFormat.None;\n\n break;\n\n case AVMediaType.Subtitle:\n SubtitlesStreamsAll.Add(new SubtitlesStream(this, fmtCtx->streams[i]));\n AVStreamToStream.Add(fmtCtx->streams[i]->index, SubtitlesStreamsAll[^1]);\n subsHasEng = SubtitlesStreamsAll[^1].Language == Language.English;\n break;\n\n case AVMediaType.Data:\n DataStreams.Add(new DataStream(this, fmtCtx->streams[i]));\n AVStreamToStream.Add(fmtCtx->streams[i]->index, DataStreams[^1]);\n\n break;\n\n default:\n Log.Info($\"#[Unknown #{i}] {fmtCtx->streams[i]->codecpar->codec_type}\");\n break;\n }\n }\n\n if (!audioHasEng)\n for (int i=0; inb_programs > 0)\n {\n for (int i = 0; i < fmtCtx->nb_programs; i++)\n {\n fmtCtx->programs[i]->discard = AVDiscard.All;\n Program program = new(fmtCtx->programs[i], this);\n Programs.Add(program);\n }\n }\n\n Extension = GetValidExtension();\n }\n\n PrintDump();\n return hasVideo;\n }\n\n public int SeekInQueue(long ticks, bool forward = false)\n {\n lock (lockActions)\n {\n if (Disposed) return -1;\n\n /* Seek within current bufffered queue\n *\n * 10 seconds because of video keyframe distances or 1 seconds for other (can be fixed also with CurTime+X seek instead of timestamps)\n * For subtitles it should keep (prev packet) the last presented as it can have a lot of distance with CurTime (cur packet)\n * It doesn't work for HLS live streams\n * It doesn't work for decoders buffered queue (which is small only subs might be an issue if we have large decoder queue)\n */\n\n long startTime = StartTime;\n\n if (hlsCtx != null)\n {\n ticks += hlsStartTime - (hlsCtx->first_timestamp * 10);\n startTime = hlsStartTime;\n }\n\n if (ticks + (VideoStream != null && forward ? (10000 * 10000) : 1000 * 10000) > CurTime + startTime && ticks < CurTime + startTime + BufferedDuration)\n {\n bool found = false;\n while (VideoPackets.Count > 0)\n {\n var packet = VideoPackets.Peek();\n if (packet->pts != AV_NOPTS_VALUE && ticks < packet->pts * VideoStream.Timebase && (packet->flags & PktFlags.Key) != 0)\n {\n found = true;\n ticks = (long) (packet->pts * VideoStream.Timebase);\n\n break;\n }\n\n VideoPackets.Dequeue();\n av_packet_free(&packet);\n }\n\n while (AudioPackets.Count > 0)\n {\n var packet = AudioPackets.Peek();\n if (packet->pts != AV_NOPTS_VALUE && (packet->pts + packet->duration) * AudioStream.Timebase >= ticks)\n {\n if (Type == MediaType.Audio || VideoStream == null)\n found = true;\n\n break;\n }\n\n AudioPackets.Dequeue();\n av_packet_free(&packet);\n }\n\n for (int i = 0; i < subNum; i++)\n {\n while (SubtitlesPackets[i].Count > 0)\n {\n var packet = SubtitlesPackets[i].Peek();\n if (packet->pts != AV_NOPTS_VALUE && ticks < (packet->pts + packet->duration) * SubtitlesStreams[i].Timebase)\n {\n if (Type == MediaType.Subs)\n {\n found = true;\n }\n\n break;\n }\n\n SubtitlesPackets[i].Dequeue();\n av_packet_free(&packet);\n }\n }\n\n while (DataPackets.Count > 0)\n {\n var packet = DataPackets.Peek();\n if (packet->pts != AV_NOPTS_VALUE && ticks < (packet->pts + packet->duration) * DataStream.Timebase)\n {\n if (Type == MediaType.Data)\n found = true;\n\n break;\n }\n\n DataPackets.Dequeue();\n av_packet_free(&packet);\n }\n\n if (found)\n {\n Log.Debug(\"[Seek] Found in Queue\");\n return 0;\n }\n }\n\n return -1;\n }\n }\n public int Seek(long ticks, bool forward = false)\n {\n /* Current Issues\n *\n * HEVC/MPEG-TS: Fails to seek to keyframe https://blog.csdn.net/Annie_heyeqq/article/details/113649501 | https://trac.ffmpeg.org/ticket/9412\n * AVSEEK_FLAG_BACKWARD will not work on .dav even if it returns 0 (it will work after it fills the index table)\n * Strange delay (could be 200ms!) after seek on HEVC/yuv420p10le (10-bits) while trying to Present on swapchain (possible recreates texturearray?)\n * AVFMT_NOTIMESTAMPS unknown duration (can be calculated?) should perform byte seek instead (percentage based on total pb size)\n */\n\n lock (lockActions)\n {\n if (Disposed) return -1;\n\n int ret;\n long savedPbPos = 0;\n\n Interrupter.ForceInterrupt = 1;\n lock (lockFmtCtx)\n {\n Interrupter.ForceInterrupt = 0;\n\n // Flush required because of the interrupt\n if (fmtCtx->pb != null)\n {\n savedPbPos = fmtCtx->pb->pos;\n avio_flush(fmtCtx->pb);\n fmtCtx->pb->error = 0; // AVERROR_EXIT will stay forever and will cause the demuxer to go in Status Stopped instead of Ended (after interrupted seeks)\n fmtCtx->pb->eof_reached = 0;\n }\n avformat_flush(fmtCtx);\n\n // Forces seekable HLS\n if (hlsCtx != null)\n fmtCtx->ctx_flags &= ~FmtCtxFlags.Unseekable;\n\n Interrupter.SeekRequest();\n if (VideoStream != null)\n {\n if (CanDebug) Log.Debug($\"[Seek({(forward ? \"->\" : \"<-\")})] Requested at {new TimeSpan(ticks)}\");\n\n // TODO: After proper calculation of Duration\n //if (VideoStream.FixTimestamps && Duration > 0)\n //ret = av_seek_frame(fmtCtx, -1, (long)((ticks/(double)Duration) * avio_size(fmtCtx->pb)), AVSEEK_FLAG_BYTE);\n //else\n ret = ticks == StartTime // we should also call this if we seek anywhere within the first Gop\n ? avformat_seek_file(fmtCtx, -1, 0, 0, 0, 0)\n : av_seek_frame(fmtCtx, -1, ticks / 10, forward ? SeekFlags.Frame : SeekFlags.Backward);\n\n curReverseStopPts = AV_NOPTS_VALUE;\n curReverseStartPts= AV_NOPTS_VALUE;\n }\n else\n {\n if (CanDebug) Log.Debug($\"[Seek({(forward ? \"->\" : \"<-\")})] Requested at {new TimeSpan(ticks)} | ANY\");\n ret = forward ?\n avformat_seek_file(fmtCtx, -1, ticks / 10 , ticks / 10, long.MaxValue , SeekFlags.Any):\n avformat_seek_file(fmtCtx, -1, long.MinValue, ticks / 10, ticks / 10 , SeekFlags.Any);\n }\n\n if (ret < 0)\n {\n if (hlsCtx != null) fmtCtx->ctx_flags &= ~FmtCtxFlags.Unseekable;\n Log.Info($\"Seek failed 1/2 (retrying) {FFmpegEngine.ErrorCodeToMsg(ret)} ({ret})\");\n\n ret = VideoStream != null\n ? av_seek_frame(fmtCtx, -1, ticks / 10, forward ? SeekFlags.Backward : SeekFlags.Frame)\n : forward ?\n avformat_seek_file(fmtCtx, -1, long.MinValue, ticks / 10, ticks / 10 , SeekFlags.Any):\n avformat_seek_file(fmtCtx, -1, ticks / 10 , ticks / 10, long.MaxValue , SeekFlags.Any);\n\n if (ret < 0)\n {\n Log.Warn($\"Seek failed 2/2 {FFmpegEngine.ErrorCodeToMsg(ret)} ({ret})\");\n\n // Flush required because of seek failure (reset pb to last pos otherwise will be eof) - Mainly for NoTimestamps (TODO: byte seek/calc dur/percentage)\n if (fmtCtx->pb != null)\n {\n avio_flush(fmtCtx->pb);\n fmtCtx->pb->error = 0;\n fmtCtx->pb->eof_reached = 0;\n avio_seek(fmtCtx->pb, savedPbPos, 0);\n }\n avformat_flush(fmtCtx);\n }\n else\n lastSeekTime = ticks - StartTime - (hlsCtx != null ? hlsStartTime : 0);\n }\n else\n lastSeekTime = ticks - StartTime - (hlsCtx != null ? hlsStartTime : 0);\n\n DisposePackets();\n lock (lockStatus) if (Status == Status.Ended) Status = Status.Stopped;\n }\n\n return ret; // >= 0 for success\n }\n }\n\n protected override void RunInternal()\n {\n if (IsReversePlayback)\n {\n RunInternalReverse();\n return;\n }\n\n int ret = 0;\n int allowedErrors = Config.MaxErrors;\n bool gotAVERROR_EXIT = false;\n audioBufferLimitFired = false;\n long lastVideoPacketPts = 0;\n\n do\n {\n // Wait until not QueueFull\n if (BufferedDuration > Config.BufferDuration || (Config.BufferPackets != 0 && CurPackets.Count > Config.BufferPackets))\n {\n lock (lockStatus)\n if (Status == Status.Running) Status = Status.QueueFull;\n\n while (!PauseOnQueueFull && (BufferedDuration > Config.BufferDuration || (Config.BufferPackets != 0 && CurPackets.Count > Config.BufferPackets)) && Status == Status.QueueFull)\n Thread.Sleep(20);\n\n lock (lockStatus)\n {\n if (PauseOnQueueFull) { PauseOnQueueFull = false; Status = Status.Pausing; }\n if (Status != Status.QueueFull) break;\n Status = Status.Running;\n }\n }\n\n // Wait possible someone asks for lockFmtCtx\n else if (gotAVERROR_EXIT)\n {\n gotAVERROR_EXIT = false;\n Thread.Sleep(5);\n }\n\n // Demux Packet\n lock (lockFmtCtx)\n {\n Interrupter.ReadRequest();\n ret = av_read_frame(fmtCtx, packet);\n if (Interrupter.ForceInterrupt != 0)\n {\n av_packet_unref(packet);\n gotAVERROR_EXIT = true;\n continue;\n }\n\n // Possible check if interrupt/timeout and we dont seek to reset the backend pb->pos = 0?\n if (ret != 0)\n {\n av_packet_unref(packet);\n\n if (ret == AVERROR_EOF)\n {\n Status = Status.Ended;\n break;\n }\n\n if (Interrupter.Timedout)\n {\n Status = Status.Stopping;\n break;\n }\n\n allowedErrors--;\n if (CanWarn) Log.Warn($\"{FFmpegEngine.ErrorCodeToMsg(ret)} ({ret})\");\n\n if (allowedErrors == 0) { Log.Error(\"Too many errors!\"); Status = Status.Stopping; break; }\n\n gotAVERROR_EXIT = true;\n continue;\n }\n\n TotalBytes += packet->size;\n\n // Skip Disabled Streams | TODO: It's possible that the streams will changed (add/remove or even update/change of codecs)\n if (!EnabledStreams.Contains(packet->stream_index)) { av_packet_unref(packet); continue; }\n\n if (IsHLSLive)\n UpdateHLSTime();\n\n if (CanTrace)\n {\n var stream = AVStreamToStream[packet->stream_index];\n long dts = packet->dts == AV_NOPTS_VALUE ? -1 : (long)(packet->dts * stream.Timebase);\n long pts = packet->pts == AV_NOPTS_VALUE ? -1 : (long)(packet->pts * stream.Timebase);\n Log.Trace($\"[{stream.Type}] DTS: {(dts == -1 ? \"-\" : Utils.TicksToTime(dts))} PTS: {(pts == -1 ? \"-\" : Utils.TicksToTime(pts))} | FLPTS: {(pts == -1 ? \"-\" : Utils.TicksToTime(pts - StartTime))} | CurTime: {Utils.TicksToTime(CurTime)} | Buffered: {Utils.TicksToTime(BufferedDuration)}\");\n }\n\n // Enqueue Packet (AVS Queue or Single Queue)\n if (UseAVSPackets)\n {\n switch (fmtCtx->streams[packet->stream_index]->codecpar->codec_type)\n {\n case AVMediaType.Audio:\n //Log($\"Audio => {Utils.TicksToTime((long)(packet->pts * AudioStream.Timebase))} | {Utils.TicksToTime(CurTime)}\");\n\n // Handles A/V de-sync and ffmpeg bug with 2^33 timestamps wrapping\n if (Config.MaxAudioPackets != 0 && AudioPackets.Count > Config.MaxAudioPackets)\n {\n av_packet_unref(packet);\n packet = av_packet_alloc();\n\n if (!audioBufferLimitFired)\n {\n audioBufferLimitFired = true;\n OnAudioLimit();\n }\n\n break;\n }\n\n AudioPackets.Enqueue(packet);\n packet = av_packet_alloc();\n\n break;\n\n case AVMediaType.Video:\n //Log($\"Video => {Utils.TicksToTime((long)(packet->pts * VideoStream.Timebase))} | {Utils.TicksToTime(CurTime)}\");\n lastVideoPacketPts = packet->pts;\n VideoPackets.Enqueue(packet);\n packet = av_packet_alloc();\n\n break;\n\n case AVMediaType.Subtitle:\n for (int i = 0; i < subNum; i++)\n {\n // Clone packets to support simultaneous display of the same subtitle\n if (packet->stream_index == SubtitlesStreams[i]?.StreamIndex)\n {\n SubtitlesPackets[i].Enqueue(av_packet_clone(packet));\n }\n }\n\n // cloned, so free packet\n av_packet_unref(packet);\n\n break;\n\n case AVMediaType.Data:\n // Some data streams only have nopts, set pts to last video packet pts\n if (packet->pts == AV_NOPTS_VALUE)\n packet->pts = lastVideoPacketPts;\n DataPackets.Enqueue(packet);\n packet = av_packet_alloc();\n\n break;\n\n default:\n av_packet_unref(packet);\n break;\n }\n }\n else\n {\n Packets.Enqueue(packet);\n packet = av_packet_alloc();\n }\n }\n } while (Status == Status.Running);\n }\n private void RunInternalReverse()\n {\n int ret = 0;\n int allowedErrors = Config.MaxErrors;\n bool gotAVERROR_EXIT = false;\n\n // To demux further for buffering (related to BufferDuration)\n int maxQueueSize = 2;\n curReverseSeekOffset = av_rescale_q(3 * 1000 * 10000 / 10, Engine.FFmpeg.AV_TIMEBASE_Q, VideoStream.AVStream->time_base);\n\n do\n {\n // Wait until not QueueFull\n if (VideoPacketsReverse.Count > maxQueueSize)\n {\n lock (lockStatus)\n if (Status == Status.Running) Status = Status.QueueFull;\n\n while (!PauseOnQueueFull && VideoPacketsReverse.Count > maxQueueSize && Status == Status.QueueFull) { Thread.Sleep(20); }\n\n lock (lockStatus)\n {\n if (PauseOnQueueFull) { PauseOnQueueFull = false; Status = Status.Pausing; }\n if (Status != Status.QueueFull) break;\n Status = Status.Running;\n }\n }\n\n // Wait possible someone asks for lockFmtCtx\n else if (gotAVERROR_EXIT)\n {\n gotAVERROR_EXIT = false;\n Thread.Sleep(5);\n }\n\n // Demux Packet\n lock (lockFmtCtx)\n {\n Interrupter.ReadRequest();\n ret = av_read_frame(fmtCtx, packet);\n if (Interrupter.ForceInterrupt != 0)\n {\n av_packet_unref(packet); gotAVERROR_EXIT = true;\n continue;\n }\n\n // Possible check if interrupt/timeout and we dont seek to reset the backend pb->pos = 0?\n if (ret != 0)\n {\n av_packet_unref(packet);\n\n if (ret == AVERROR_EOF)\n {\n if (curReverseVideoPackets.Count > 0)\n {\n var drainPacket = av_packet_alloc();\n drainPacket->data = null;\n drainPacket->size = 0;\n curReverseVideoPackets.Add((IntPtr)drainPacket);\n curReverseVideoStack.Push(curReverseVideoPackets);\n curReverseVideoPackets = new List();\n }\n\n if (!curReverseVideoStack.IsEmpty)\n {\n VideoPacketsReverse.Enqueue(curReverseVideoStack);\n curReverseVideoStack = new ConcurrentStack>();\n }\n\n if (curReverseStartPts != AV_NOPTS_VALUE && curReverseStartPts <= VideoStream.StartTimePts)\n {\n Status = Status.Ended;\n break;\n }\n\n //Log($\"[][][SEEK END] {curReverseStartPts} | {Utils.TicksToTime((long) (curReverseStartPts * VideoStream.Timebase))}\");\n Interrupter.SeekRequest();\n ret = av_seek_frame(fmtCtx, VideoStream.StreamIndex, Math.Max(curReverseStartPts - curReverseSeekOffset, VideoStream.StartTimePts), SeekFlags.Backward);\n\n if (ret != 0)\n {\n Status = Status.Stopping;\n break;\n }\n\n curReverseStopPts = curReverseStartPts;\n curReverseStartPts = AV_NOPTS_VALUE;\n continue;\n }\n\n allowedErrors--;\n if (CanWarn) Log.Warn($\"{ FFmpegEngine.ErrorCodeToMsg(ret)} ({ret})\");\n\n if (allowedErrors == 0) { Log.Error(\"Too many errors!\"); Status = Status.Stopping; break; }\n\n gotAVERROR_EXIT = true;\n continue;\n }\n\n if (VideoStream.StreamIndex != packet->stream_index) { av_packet_unref(packet); continue; }\n\n if ((packet->flags & PktFlags.Key) != 0)\n {\n if (curReverseStartPts == AV_NOPTS_VALUE)\n curReverseStartPts = packet->pts;\n\n if (curReverseVideoPackets.Count > 0)\n {\n var drainPacket = av_packet_alloc();\n drainPacket->data = null;\n drainPacket->size = 0;\n curReverseVideoPackets.Add((IntPtr)drainPacket);\n curReverseVideoStack.Push(curReverseVideoPackets);\n curReverseVideoPackets = new List();\n }\n }\n\n if (packet->pts != AV_NOPTS_VALUE && (\n (curReverseStopRequestedPts != AV_NOPTS_VALUE && curReverseStopRequestedPts <= packet->pts) ||\n (curReverseStopPts == AV_NOPTS_VALUE && (packet->flags & PktFlags.Key) != 0 && packet->pts != curReverseStartPts) ||\n (packet->pts == curReverseStopPts)\n ))\n {\n if (curReverseStartPts == AV_NOPTS_VALUE || curReverseStopPts == curReverseStartPts)\n {\n curReverseSeekOffset *= 2;\n if (curReverseStartPts == AV_NOPTS_VALUE) curReverseStartPts = curReverseStopPts;\n if (curReverseStartPts == AV_NOPTS_VALUE) curReverseStartPts = curReverseStopRequestedPts;\n }\n\n curReverseStopRequestedPts = AV_NOPTS_VALUE;\n\n if ((packet->flags & PktFlags.Key) == 0 && curReverseVideoPackets.Count > 0)\n {\n var drainPacket = av_packet_alloc();\n drainPacket->data = null;\n drainPacket->size = 0;\n curReverseVideoPackets.Add((IntPtr)drainPacket);\n curReverseVideoStack.Push(curReverseVideoPackets);\n curReverseVideoPackets = new List();\n }\n\n if (!curReverseVideoStack.IsEmpty)\n {\n VideoPacketsReverse.Enqueue(curReverseVideoStack);\n curReverseVideoStack = new ConcurrentStack>();\n }\n\n av_packet_unref(packet);\n\n if (curReverseStartPts != AV_NOPTS_VALUE && curReverseStartPts <= VideoStream.StartTimePts)\n {\n Status = Status.Ended;\n break;\n }\n\n //Log($\"[][][SEEK] {curReverseStartPts} | {Utils.TicksToTime((long) (curReverseStartPts * VideoStream.Timebase))}\");\n Interrupter.SeekRequest();\n ret = av_seek_frame(fmtCtx, VideoStream.StreamIndex, Math.Max(curReverseStartPts - curReverseSeekOffset, 0), SeekFlags.Backward);\n\n if (ret != 0)\n {\n Status = Status.Stopping;\n break;\n }\n\n curReverseStopPts = curReverseStartPts;\n curReverseStartPts = AV_NOPTS_VALUE;\n }\n else\n {\n if (curReverseStartPts != AV_NOPTS_VALUE)\n {\n curReverseVideoPackets.Add((IntPtr)packet);\n packet = av_packet_alloc();\n }\n else\n av_packet_unref(packet);\n }\n }\n\n } while (Status == Status.Running);\n }\n\n public void EnableReversePlayback(long timestamp)\n {\n IsReversePlayback = true;\n Seek(StartTime + timestamp);\n curReverseStopRequestedPts = av_rescale_q((StartTime + timestamp) / 10, Engine.FFmpeg.AV_TIMEBASE_Q, VideoStream.AVStream->time_base);\n }\n public void DisableReversePlayback() => IsReversePlayback = false;\n #endregion\n\n #region Switch Programs / Streams\n public bool IsProgramEnabled(StreamBase stream)\n {\n for (int i=0; iprograms[i]->discard != AVDiscard.All)\n return true;\n\n return false;\n }\n public void EnableProgram(StreamBase stream)\n {\n if (IsProgramEnabled(stream))\n {\n if (CanDebug) Log.Debug($\"[Stream #{stream.StreamIndex}] Program already enabled\");\n return;\n }\n\n for (int i=0; iprograms[i]->discard = AVDiscard.Default;\n return;\n }\n }\n public void DisableProgram(StreamBase stream)\n {\n for (int i=0; iprograms[i]->discard != AVDiscard.All)\n {\n bool isNeeded = false;\n for (int l2=0; l2programs[i]->discard = AVDiscard.All;\n }\n else if (CanDebug)\n Log.Debug($\"[Stream #{stream.StreamIndex}] Program #{i} is needed\");\n }\n }\n\n public void EnableStream(StreamBase stream)\n {\n lock (lockFmtCtx)\n {\n if (Disposed || stream == null || EnabledStreams.Contains(stream.StreamIndex))\n {\n // If it detects that the primary and secondary are trying to select the same subtitle\n // Put the same instance in SubtitlesStreams and return.\n if (stream != null && stream.Type == MediaType.Subs && EnabledStreams.Contains(stream.StreamIndex))\n {\n SubtitlesStreams[SubtitlesSelectedHelper.CurIndex] = (SubtitlesStream)stream;\n // Necessary to update UI immediately\n stream.Enabled = stream.Enabled;\n }\n return;\n };\n\n EnabledStreams.Add(stream.StreamIndex);\n fmtCtx->streams[stream.StreamIndex]->discard = AVDiscard.Default;\n stream.Enabled = true;\n EnableProgram(stream);\n\n switch (stream.Type)\n {\n case MediaType.Audio:\n AudioStream = (AudioStream) stream;\n if (VideoStream == null)\n {\n if (AudioStream.HLSPlaylist != null)\n {\n IsHLSLive = true;\n HLSPlaylist = AudioStream.HLSPlaylist;\n UpdateHLSTime();\n }\n else\n {\n HLSPlaylist = null;\n IsHLSLive = false;\n }\n }\n\n break;\n\n case MediaType.Video:\n VideoStream = (VideoStream) stream;\n VideoPackets.frameDuration = VideoStream.FrameDuration > 0 ? VideoStream.FrameDuration : 30 * 1000 * 10000;\n if (VideoStream.HLSPlaylist != null)\n {\n IsHLSLive = true;\n HLSPlaylist = VideoStream.HLSPlaylist;\n UpdateHLSTime();\n }\n else\n {\n HLSPlaylist = null;\n IsHLSLive = false;\n }\n\n break;\n\n case MediaType.Subs:\n SubtitlesStreams[SubtitlesSelectedHelper.CurIndex] = (SubtitlesStream)stream;\n\n break;\n\n case MediaType.Data:\n DataStream = (DataStream) stream;\n\n break;\n }\n\n if (UseAVSPackets)\n CurPackets = VideoStream != null ? VideoPackets : (AudioStream != null ? AudioPackets : (SubtitlesStreams[0] != null ? SubtitlesPackets[0] : DataPackets));\n\n if (CanInfo) Log.Info($\"[{stream.Type} #{stream.StreamIndex}] Enabled\");\n }\n }\n public void DisableStream(StreamBase stream)\n {\n lock (lockFmtCtx)\n {\n if (Disposed || stream == null || !EnabledStreams.Contains(stream.StreamIndex)) return;\n\n // If it is the same subtitle, do not disable it.\n if (stream.Type == MediaType.Subs && SubtitlesStreams[0] != null && SubtitlesStreams[0] == SubtitlesStreams[1])\n {\n // clear only what is needed\n SubtitlesStreams[SubtitlesSelectedHelper.CurIndex] = null;\n SubtitlesPackets[SubtitlesSelectedHelper.CurIndex].Clear();\n // Necessary to update UI immediately\n stream.Enabled = stream.Enabled;\n return;\n }\n\n /* AVDISCARD_ALL causes syncing issues between streams (TBR: bandwidth?)\n * 1) While switching video streams will not switch at the same timestamp\n * 2) By disabling video stream after a seek, audio will not seek properly\n * 3) HLS needs to update hlsCtx->first_time and read at least on package before seek to be accurate\n */\n\n fmtCtx->streams[stream.StreamIndex]->discard = AVDiscard.All;\n EnabledStreams.Remove(stream.StreamIndex);\n stream.Enabled = false;\n DisableProgram(stream);\n\n switch (stream.Type)\n {\n case MediaType.Audio:\n AudioStream = null;\n if (VideoStream != null)\n {\n if (VideoStream.HLSPlaylist != null)\n {\n IsHLSLive = true;\n HLSPlaylist = VideoStream.HLSPlaylist;\n UpdateHLSTime();\n }\n else\n {\n HLSPlaylist = null;\n IsHLSLive = false;\n }\n }\n\n AudioPackets.Clear();\n\n break;\n\n case MediaType.Video:\n VideoStream = null;\n if (AudioStream != null)\n {\n if (AudioStream.HLSPlaylist != null)\n {\n IsHLSLive = true;\n HLSPlaylist = AudioStream.HLSPlaylist;\n UpdateHLSTime();\n }\n else\n {\n HLSPlaylist = null;\n IsHLSLive = false;\n }\n }\n\n VideoPackets.Clear();\n break;\n\n case MediaType.Subs:\n SubtitlesStreams[SubtitlesSelectedHelper.CurIndex] = null;\n SubtitlesPackets[SubtitlesSelectedHelper.CurIndex].Clear();\n\n break;\n\n case MediaType.Data:\n DataStream = null;\n DataPackets.Clear();\n\n break;\n }\n\n if (UseAVSPackets)\n CurPackets = VideoStream != null ? VideoPackets : (AudioStream != null ? AudioPackets : SubtitlesPackets[0]);\n\n if (CanInfo) Log.Info($\"[{stream.Type} #{stream.StreamIndex}] Disabled\");\n }\n }\n public void SwitchStream(StreamBase stream)\n {\n lock (lockFmtCtx)\n {\n if (stream.Type == MediaType.Audio)\n DisableStream(AudioStream);\n else if (stream.Type == MediaType.Video)\n DisableStream(VideoStream);\n else if (stream.Type == MediaType.Subs)\n DisableStream(SubtitlesStreams[SubtitlesSelectedHelper.CurIndex]);\n else\n DisableStream(DataStream);\n\n EnableStream(stream);\n }\n }\n #endregion\n\n #region Misc\n internal void UpdateHLSTime()\n {\n // TBR: Access Violation\n // [hls @ 00000269f9cdb400] Media sequence changed unexpectedly: 150070 -> 0\n\n if (hlsPrevSeqNo != HLSPlaylist->cur_seq_no)\n {\n hlsPrevSeqNo = HLSPlaylist->cur_seq_no;\n hlsStartTime = AV_NOPTS_VALUE;\n\n hlsCurDuration = 0;\n long duration = 0;\n\n for (long i=0; icur_seq_no - HLSPlaylist->start_seq_no; i++)\n {\n hlsCurDuration += HLSPlaylist->segments[i]->duration;\n duration += HLSPlaylist->segments[i]->duration;\n }\n\n for (long i=HLSPlaylist->cur_seq_no - HLSPlaylist->start_seq_no; in_segments; i++)\n duration += HLSPlaylist->segments[i]->duration;\n\n hlsCurDuration *= 10;\n duration *= 10;\n Duration = duration;\n }\n\n if (hlsStartTime == AV_NOPTS_VALUE && CurPackets.LastTimestamp != AV_NOPTS_VALUE)\n {\n hlsStartTime = CurPackets.LastTimestamp - hlsCurDuration;\n CurPackets.UpdateCurTime();\n }\n }\n\n private string GetValidExtension()\n {\n // TODO\n // Should check for all supported output formats (there is no list in ffmpeg.autogen ?)\n // Should check for inner input format (not outer protocol eg. hls/rtsp)\n // Should check for raw codecs it can be mp4/mov but it will not work in mp4 only in mov (or avi for raw)\n\n if (Name == \"mpegts\")\n return \"ts\";\n else if (Name == \"mpeg\")\n return \"mpeg\";\n\n List supportedOutput = new() { \"mp4\", \"avi\", \"flv\", \"flac\", \"mpeg\", \"mpegts\", \"mkv\", \"ogg\", \"ts\"};\n string defaultExtenstion = \"mp4\";\n bool hasPcm = false;\n bool isRaw = false;\n\n foreach (var stream in AudioStreams)\n if (stream.Codec.Contains(\"pcm\")) hasPcm = true;\n\n foreach (var stream in VideoStreams)\n if (stream.Codec.Contains(\"raw\")) isRaw = true;\n\n if (isRaw) defaultExtenstion = \"avi\";\n\n // MP4 container doesn't support PCM\n if (hasPcm) defaultExtenstion = \"mkv\";\n\n // TODO\n // Check also shortnames\n //if (Name == \"mpegts\") return \"ts\";\n //if ((fmtCtx->iformat->flags & AVFMT_TS_DISCONT) != 0) should be mp4 or container that supports segments\n\n if (string.IsNullOrEmpty(Extensions)) return defaultExtenstion;\n string[] extensions = Extensions.Split(',');\n if (extensions == null || extensions.Length < 1) return defaultExtenstion;\n\n // Try to set the output container same as input\n for (int i=0; istart_time * 10)}/{Utils.TicksToTime(fmtCtx->duration * 10)} | {Utils.TicksToTime(StartTime)}/{Utils.TicksToTime(Duration)}\";\n\n foreach(var stream in VideoStreams) dump += \"\\r\\n\" + stream.GetDump();\n foreach(var stream in AudioStreams) dump += \"\\r\\n\" + stream.GetDump();\n foreach(var stream in SubtitlesStreamsAll) dump += \"\\r\\n\" + stream.GetDump();\n\n if (fmtCtx->nb_programs > 0)\n dump += $\"\\r\\n[Programs] {fmtCtx->nb_programs}\";\n\n for (int i=0; inb_programs; i++)\n {\n dump += $\"\\r\\n\\tProgram #{i}\";\n\n if (fmtCtx->programs[i]->nb_stream_indexes > 0)\n dump += $\"\\r\\n\\t\\tStreams [{fmtCtx->programs[i]->nb_stream_indexes}]: \";\n\n for (int l=0; lprograms[i]->nb_stream_indexes; l++)\n dump += $\"{fmtCtx->programs[i]->stream_index[l]},\";\n\n if (fmtCtx->programs[i]->nb_stream_indexes > 0)\n dump = dump[..^1];\n }\n\n if (CanInfo) Log.Info($\"Format Context Info {dump}\\r\\n\");\n }\n\n /// \n /// Gets next VideoPacket from the existing queue or demuxes it if required (Demuxer must not be running)\n /// \n /// 0 on success\n public int GetNextVideoPacket()\n {\n if (VideoPackets.Count > 0)\n {\n packet = VideoPackets.Dequeue();\n return 0;\n }\n else\n return GetNextPacket(VideoStream.StreamIndex);\n }\n\n /// \n /// Pushes the demuxer to the next available packet (Demuxer must not be running)\n /// \n /// Packet's stream index\n /// 0 on success\n public int GetNextPacket(int streamIndex = -1)\n {\n int ret;\n\n while (true)\n {\n Interrupter.ReadRequest();\n ret = av_read_frame(fmtCtx, packet);\n\n if (ret != 0)\n {\n av_packet_unref(packet);\n\n if ((ret == AVERROR_EXIT && fmtCtx->pb != null && fmtCtx->pb->eof_reached != 0) || ret == AVERROR_EOF)\n {\n packet = av_packet_alloc();\n packet->data = null;\n packet->size = 0;\n\n Stop();\n Status = Status.Ended;\n }\n\n return ret;\n }\n\n if (streamIndex != -1)\n {\n if (packet->stream_index == streamIndex)\n return 0;\n }\n else if (EnabledStreams.Contains(packet->stream_index))\n return 0;\n\n av_packet_unref(packet);\n }\n }\n #endregion\n}\n\npublic unsafe class PacketQueue\n{\n // TODO: DTS might not be available without avformat_find_stream_info (should changed based on packet->duration and fallback should be removed)\n readonly Demuxer demuxer;\n readonly ConcurrentQueue packets = new();\n public long frameDuration = 30 * 1000 * 10000; // in case of negative buffer duration calculate it based on packets count / FPS\n\n public long Bytes { get; private set; }\n public long BufferedDuration { get; private set; }\n public long CurTime { get; private set; }\n public int Count => packets.Count;\n public bool IsEmpty => packets.IsEmpty;\n\n public long FirstTimestamp { get; private set; } = AV_NOPTS_VALUE;\n public long LastTimestamp { get; private set; } = AV_NOPTS_VALUE;\n\n public PacketQueue(Demuxer demuxer)\n => this.demuxer = demuxer;\n\n public void Clear()\n {\n lock(packets)\n {\n while (!packets.IsEmpty)\n {\n packets.TryDequeue(out IntPtr packetPtr);\n if (packetPtr == IntPtr.Zero) continue;\n AVPacket* packet = (AVPacket*)packetPtr;\n av_packet_free(&packet);\n }\n\n FirstTimestamp = AV_NOPTS_VALUE;\n LastTimestamp = AV_NOPTS_VALUE;\n Bytes = 0;\n BufferedDuration = 0;\n CurTime = 0;\n }\n }\n\n public void Enqueue(AVPacket* packet)\n {\n lock (packets)\n {\n packets.Enqueue((IntPtr)packet);\n\n if (packet->dts != AV_NOPTS_VALUE || packet->pts != AV_NOPTS_VALUE)\n {\n LastTimestamp = packet->dts != AV_NOPTS_VALUE ?\n (long)(packet->dts * demuxer.AVStreamToStream[packet->stream_index].Timebase):\n (long)(packet->pts * demuxer.AVStreamToStream[packet->stream_index].Timebase);\n\n if (FirstTimestamp == AV_NOPTS_VALUE)\n {\n FirstTimestamp = LastTimestamp;\n UpdateCurTime();\n }\n else\n {\n BufferedDuration = LastTimestamp - FirstTimestamp;\n if (BufferedDuration < 0)\n BufferedDuration = packets.Count * frameDuration;\n }\n }\n else\n BufferedDuration = packets.Count * frameDuration;\n\n Bytes += packet->size;\n }\n }\n\n public AVPacket* Dequeue()\n {\n lock(packets)\n if (packets.TryDequeue(out IntPtr packetPtr))\n {\n AVPacket* packet = (AVPacket*)packetPtr;\n\n if (packet->dts != AV_NOPTS_VALUE || packet->pts != AV_NOPTS_VALUE)\n {\n FirstTimestamp = packet->dts != AV_NOPTS_VALUE ?\n (long)(packet->dts * demuxer.AVStreamToStream[packet->stream_index].Timebase):\n (long)(packet->pts * demuxer.AVStreamToStream[packet->stream_index].Timebase);\n UpdateCurTime();\n }\n else\n BufferedDuration = packets.Count * frameDuration;\n\n return (AVPacket*)packetPtr;\n }\n\n return null;\n }\n\n public AVPacket* Peek()\n => packets.TryPeek(out IntPtr packetPtr)\n ? (AVPacket*)packetPtr\n : (AVPacket*)null;\n\n internal void UpdateCurTime()\n {\n if (demuxer.hlsCtx != null)\n {\n if (demuxer.hlsStartTime != AV_NOPTS_VALUE)\n {\n if (FirstTimestamp < demuxer.hlsStartTime)\n {\n demuxer.Duration += demuxer.hlsStartTime - FirstTimestamp;\n demuxer.hlsStartTime = FirstTimestamp;\n CurTime = 0;\n }\n else\n CurTime = FirstTimestamp - demuxer.hlsStartTime;\n }\n }\n else\n CurTime = FirstTimestamp - demuxer.StartTime;\n\n if (CurTime < 0)\n CurTime = 0;\n\n BufferedDuration = LastTimestamp - FirstTimestamp;\n\n if (BufferedDuration < 0)\n BufferedDuration = packets.Count * frameDuration;\n }\n}\n"], ["/LLPlayer/FlyleafLib/Utils/Logger.cs", "using System.Collections.Generic;\nusing System.Collections.Concurrent;\nusing System.IO;\nusing System.Text;\nusing System.Threading.Tasks;\n\nnamespace FlyleafLib;\n\npublic static class Logger\n{\n public static bool CanError => Engine.Config.LogLevel >= LogLevel.Error;\n public static bool CanWarn => Engine.Config.LogLevel >= LogLevel.Warn;\n public static bool CanInfo => Engine.Config.LogLevel >= LogLevel.Info;\n public static bool CanDebug => Engine.Config.LogLevel >= LogLevel.Debug;\n public static bool CanTrace => Engine.Config.LogLevel >= LogLevel.Trace;\n\n\n public static Action\n CustomOutput = DevNullPtr;\n internal static Action\n Output = DevNullPtr;\n static string lastOutput = \"\";\n\n static ConcurrentQueue\n fileData = new();\n static bool fileTaskRunning;\n static FileStream fileStream;\n static object lockFileStream = new();\n static Dictionary\n logLevels = new();\n\n static Logger()\n {\n foreach (LogLevel loglevel in Enum.GetValues(typeof(LogLevel)))\n logLevels.Add(loglevel, loglevel.ToString().PadRight(5, ' '));\n\n // Flush File Data on Application Exit\n System.Windows.Application.Current.Exit += (o, e) =>\n {\n lock (lockFileStream)\n {\n if (fileStream != null)\n {\n while (fileData.TryDequeue(out byte[] data))\n fileStream.Write(data, 0, data.Length);\n fileStream.Dispose();\n }\n }\n };\n }\n\n internal static void SetOutput()\n {\n string output = Engine.Config.LogOutput;\n\n if (string.IsNullOrEmpty(output))\n {\n if (lastOutput != \"\")\n {\n Output = DevNullPtr;\n lastOutput = \"\";\n }\n }\n else if (output.StartsWith(\":\"))\n {\n if (output == \":console\")\n {\n if (lastOutput != \":console\")\n {\n Output = Console.WriteLine;\n lastOutput = \":console\";\n }\n }\n else if (output == \":debug\")\n {\n if (lastOutput != \":debug\")\n {\n Output = DebugPtr;\n lastOutput = \":debug\";\n }\n }\n else if (output == \":custom\")\n {\n if (lastOutput != \":custom\")\n {\n Output = CustomOutput;\n lastOutput = \":custom\";\n }\n }\n else\n throw new Exception(\"Invalid log output\");\n }\n else\n {\n lock (lockFileStream)\n {\n // Flush File Data on Previously Opened File Stream\n if (fileStream != null)\n {\n while (fileData.TryDequeue(out byte[] data))\n fileStream.Write(data, 0, data.Length);\n fileStream.Dispose();\n }\n\n string dir = Path.GetDirectoryName(output);\n if (!string.IsNullOrEmpty(dir))\n Directory.CreateDirectory(dir);\n\n fileStream = new FileStream(output, Engine.Config.LogAppend ? FileMode.Append : FileMode.Create, FileAccess.Write);\n if (lastOutput != \":file\")\n {\n Output = FilePtr;\n lastOutput = \":file\";\n }\n }\n }\n }\n static void DebugPtr(string msg) => System.Diagnostics.Debug.WriteLine(msg);\n static void DevNullPtr(string msg) { }\n static void FilePtr(string msg)\n {\n fileData.Enqueue(Encoding.UTF8.GetBytes($\"{msg}\\r\\n\"));\n\n if (!fileTaskRunning && fileData.Count > Engine.Config.LogCachedLines)\n FlushFileData();\n }\n\n static void FlushFileData()\n {\n fileTaskRunning = true;\n\n Task.Run(() =>\n {\n lock (lockFileStream)\n {\n while (fileData.TryDequeue(out byte[] data))\n fileStream.Write(data, 0, data.Length);\n\n fileStream.Flush();\n }\n\n fileTaskRunning = false;\n });\n }\n\n /// \n /// Forces cached file data to be written to the file\n /// \n public static void ForceFlush()\n {\n if (!fileTaskRunning && fileStream != null)\n FlushFileData();\n }\n\n internal static void Log(string msg, LogLevel logLevel)\n {\n if (logLevel <= Engine.Config.LogLevel)\n Output($\"{DateTime.Now.ToString(Engine.Config.LogDateTimeFormat)} | {logLevels[logLevel]} | {msg}\");\n }\n}\n\npublic class LogHandler\n{\n public string Prefix;\n\n public LogHandler(string prefix = \"\")\n => Prefix = prefix;\n\n public void Error(string msg) => Logger.Log($\"{Prefix}{msg}\", LogLevel.Error);\n public void Info(string msg) => Logger.Log($\"{Prefix}{msg}\", LogLevel.Info);\n public void Warn(string msg) => Logger.Log($\"{Prefix}{msg}\", LogLevel.Warn);\n public void Debug(string msg) => Logger.Log($\"{Prefix}{msg}\", LogLevel.Debug);\n public void Trace(string msg) => Logger.Log($\"{Prefix}{msg}\", LogLevel.Trace);\n}\n\npublic enum LogLevel\n{\n Quiet = 0x00,\n Error = 0x10,\n Warn = 0x20,\n Info = 0x30,\n Debug = 0x40,\n Trace = 0x50\n}\n"], ["/LLPlayer/FlyleafLib/MediaPlayer/Audio.cs", "using System;\nusing System.Collections.ObjectModel;\n\nusing Vortice.Multimedia;\nusing Vortice.XAudio2;\n\nusing static Vortice.XAudio2.XAudio2;\n\nusing FlyleafLib.MediaFramework.MediaContext;\nusing FlyleafLib.MediaFramework.MediaFrame;\nusing FlyleafLib.MediaFramework.MediaStream;\n\nusing static FlyleafLib.Logger;\n\nnamespace FlyleafLib.MediaPlayer;\n\npublic class Audio : NotifyPropertyChanged\n{\n public event EventHandler SamplesAdded;\n\n #region Properties\n /// \n /// Embedded Streams\n /// \n public ObservableCollection\n Streams => decoder?.VideoDemuxer.AudioStreams; // TBR: We miss AudioDemuxer embedded streams\n\n /// \n /// Whether the input has audio and it is configured\n /// \n public bool IsOpened { get => isOpened; internal set => Set(ref _IsOpened, value); }\n internal bool _IsOpened, isOpened;\n\n public string Codec { get => codec; internal set => Set(ref _Codec, value); }\n internal string _Codec, codec;\n\n ///// \n ///// Audio bitrate (Kbps)\n ///// \n public double BitRate { get => bitRate; internal set => Set(ref _BitRate, value); }\n internal double _BitRate, bitRate;\n\n public int Bits { get => bits; internal set => Set(ref _Bits, value); }\n internal int _Bits, bits;\n\n public int Channels { get => channels; internal set => Set(ref _Channels, value); }\n internal int _Channels, channels;\n\n /// \n /// Audio player's channels out (currently 2 channels supported only)\n /// \n public int ChannelsOut { get; } = 2;\n\n public string ChannelLayout { get => channelLayout; internal set => Set(ref _ChannelLayout, value); }\n internal string _ChannelLayout, channelLayout;\n\n ///// \n ///// Total Dropped Frames\n ///// \n public int FramesDropped { get => framesDropped; internal set => Set(ref _FramesDropped, value); }\n internal int _FramesDropped, framesDropped;\n\n public int FramesDisplayed { get => framesDisplayed; internal set => Set(ref _FramesDisplayed, value); }\n internal int _FramesDisplayed, framesDisplayed;\n\n public string SampleFormat { get => sampleFormat; internal set => Set(ref _SampleFormat, value); }\n internal string _SampleFormat, sampleFormat;\n\n /// \n /// Audio sample rate (in/out)\n /// \n public int SampleRate { get => sampleRate; internal set => Set(ref _SampleRate, value); }\n internal int _SampleRate, sampleRate;\n\n /// \n /// Audio player's volume / amplifier (valid values 0 - no upper limit)\n /// \n public int Volume\n {\n get\n {\n lock (locker)\n return sourceVoice == null || Mute ? _Volume : (int) ((decimal)sourceVoice.Volume * 100);\n }\n set\n {\n if (value > Config.Player.VolumeMax || value < 0)\n return;\n\n if (value == 0)\n Mute = true;\n else if (Mute)\n {\n _Volume = value;\n Mute = false;\n }\n else\n {\n if (sourceVoice != null)\n sourceVoice.Volume = Math.Max(0, value / 100.0f);\n }\n\n Set(ref _Volume, value, false);\n }\n }\n int _Volume;\n\n /// \n /// Audio player's mute\n /// \n public bool Mute\n {\n get => mute;\n set\n {\n lock (locker)\n {\n if (sourceVoice == null)\n return;\n\n sourceVoice.Volume = value ? 0 : _Volume / 100.0f;\n }\n\n Set(ref mute, value, false);\n }\n }\n private bool mute = false;\n\n /// \n /// Audio player's current device (available devices can be found on )/>\n /// \n public AudioEngine.AudioEndpoint Device\n {\n get => _Device;\n set\n {\n if ((value == null && _Device == Engine.Audio.DefaultDevice) || value == _Device)\n return;\n\n _Device = value ?? Engine.Audio.DefaultDevice;\n Initialize();\n RaiseUI(nameof(Device));\n }\n }\n internal AudioEngine.AudioEndpoint _Device = Engine.Audio.DefaultDevice;\n #endregion\n\n #region Declaration\n public Player Player => player;\n\n Player player;\n Config Config => player.Config;\n DecoderContext decoder => player?.decoder;\n\n Action uiAction;\n internal readonly object\n locker = new();\n\n IXAudio2 xaudio2;\n internal IXAudio2MasteringVoice\n masteringVoice;\n internal IXAudio2SourceVoice\n sourceVoice;\n WaveFormat waveFormat = new(48000, 16, 2); // Output Audio Device\n AudioBuffer audioBuffer = new();\n internal double Timebase;\n internal ulong submittedSamples;\n #endregion\n\n public Audio(Player player)\n {\n this.player = player;\n\n uiAction = () =>\n {\n IsOpened = IsOpened;\n Codec = Codec;\n BitRate = BitRate;\n Bits = Bits;\n Channels = Channels;\n ChannelLayout = ChannelLayout;\n SampleFormat = SampleFormat;\n SampleRate = SampleRate;\n\n FramesDisplayed = FramesDisplayed;\n FramesDropped = FramesDropped;\n };\n\n // Set default volume\n Volume = Math.Min(Config.Player.VolumeDefault, Config.Player.VolumeMax);\n Initialize();\n }\n\n internal void Initialize()\n {\n lock (locker)\n {\n if (Engine.Audio.Failed)\n {\n Config.Audio.Enabled = false;\n return;\n }\n\n sampleRate = decoder != null && decoder.AudioStream != null && decoder.AudioStream.SampleRate > 0 ? decoder.AudioStream.SampleRate : 48000;\n player.Log.Info($\"Initialiazing audio ({Device.Name} - {Device.Id} @ {SampleRate}Hz)\");\n\n Dispose();\n\n try\n {\n xaudio2 = XAudio2Create();\n\n try\n {\n masteringVoice = xaudio2.CreateMasteringVoice(0, 0, AudioStreamCategory.GameEffects, _Device == Engine.Audio.DefaultDevice ? null : _Device.Id);\n }\n catch (Exception) // Win 7/8 compatibility issue https://social.msdn.microsoft.com/Forums/en-US/4989237b-814c-4a7a-8a35-00714d36b327/xaudio2-how-to-get-device-id-for-mastering-voice?forum=windowspro-audiodevelopment\n {\n masteringVoice = xaudio2.CreateMasteringVoice(0, 0, AudioStreamCategory.GameEffects, _Device == Engine.Audio.DefaultDevice ? null : (@\"\\\\?\\swd#mmdevapi#\" + _Device.Id.ToLower() + @\"#{e6327cad-dcec-4949-ae8a-991e976a79d2}\"));\n }\n\n sourceVoice = xaudio2.CreateSourceVoice(waveFormat, false);\n sourceVoice.SetSourceSampleRate((uint)SampleRate);\n sourceVoice.Start();\n\n submittedSamples = 0;\n Timebase = 1000 * 10000.0 / sampleRate;\n masteringVoice.Volume = Config.Player.VolumeMax / 100.0f;\n sourceVoice.Volume = mute ? 0 : Math.Max(0, _Volume / 100.0f);\n }\n catch (Exception e)\n {\n player.Log.Info($\"Audio initialization failed ({e.Message})\");\n Config.Audio.Enabled = false;\n }\n }\n }\n internal void Dispose()\n {\n lock (locker)\n {\n if (xaudio2 == null)\n return;\n\n xaudio2. Dispose();\n sourceVoice?. Dispose();\n masteringVoice?.Dispose();\n xaudio2 = null;\n sourceVoice = null;\n masteringVoice = null;\n }\n }\n\n // TBR: Very rarely could crash the app on audio device change while playing? Requires two locks (Audio's locker and aFrame)\n // The process was terminated due to an internal error in the .NET Runtime at IP 00007FFA6725DA03 (00007FFA67090000) with exit code c0000005.\n [System.Security.SecurityCritical]\n internal void AddSamples(AudioFrame aFrame)\n {\n lock (locker) // required for submittedSamples only? (ClearBuffer() can be called during audio decocder circular buffer reallocation)\n {\n try\n {\n if (CanTrace)\n player.Log.Trace($\"[A] Presenting {Utils.TicksToTime(player.aFrame.timestamp)}\");\n\n framesDisplayed++;\n\n submittedSamples += (ulong) (aFrame.dataLen / 4); // ASampleBytes\n SamplesAdded?.Invoke(this, aFrame);\n\n audioBuffer.AudioDataPointer= aFrame.dataPtr;\n audioBuffer.AudioBytes = (uint)aFrame.dataLen;\n sourceVoice.SubmitSourceBuffer(audioBuffer);\n }\n catch (Exception e) // Happens on audio device changed/removed\n {\n if (CanDebug)\n player.Log.Debug($\"[Audio] Submitting samples failed ({e.Message})\");\n\n ClearBuffer(); // TBR: Inform player to resync audio?\n }\n }\n }\n internal long GetBufferedDuration() { lock (locker) { return (long) ((submittedSamples - sourceVoice.State.SamplesPlayed) * Timebase); } }\n internal long GetDeviceDelay() { lock (locker) { return (long) ((xaudio2.PerformanceData.CurrentLatencyInSamples * Timebase) - 80000); } } // TODO: VBlack delay (8ms correction for now)\n internal void ClearBuffer()\n {\n lock (locker)\n {\n if (sourceVoice == null)\n return;\n\n sourceVoice.Stop();\n sourceVoice.FlushSourceBuffers();\n sourceVoice.Start();\n submittedSamples = sourceVoice.State.SamplesPlayed;\n }\n }\n\n internal void Reset()\n {\n codec = null;\n bitRate = 0;\n bits = 0;\n channels = 0;\n channelLayout = null;\n sampleFormat = null;\n isOpened = false;\n\n ClearBuffer();\n player.UIAdd(uiAction);\n }\n internal void Refresh()\n {\n if (decoder.AudioStream == null) { Reset(); return; }\n\n codec = decoder.AudioStream.Codec;\n bits = decoder.AudioStream.Bits;\n channels = decoder.AudioStream.Channels;\n channelLayout = decoder.AudioStream.ChannelLayoutStr;\n sampleFormat = decoder.AudioStream.SampleFormatStr;\n isOpened =!decoder.AudioDecoder.Disposed;\n\n framesDisplayed = 0;\n framesDropped = 0;\n\n if (SampleRate!= decoder.AudioStream.SampleRate)\n Initialize();\n\n player.UIAdd(uiAction);\n }\n internal void Enable()\n {\n bool wasPlaying = player.IsPlaying;\n\n decoder.OpenSuggestedAudio();\n\n player.ReSync(decoder.AudioStream, (int) (player.CurTime / 10000), true);\n\n Refresh();\n player.UIAll();\n\n if (wasPlaying || Config.Player.AutoPlay)\n player.Play();\n }\n internal void Disable()\n {\n if (!IsOpened)\n return;\n\n decoder.CloseAudio();\n\n player.aFrame = null;\n\n if (!player.Video.IsOpened)\n {\n player.canPlay = false;\n player.UIAdd(() => player.CanPlay = player.CanPlay);\n }\n\n Reset();\n player.UIAll();\n }\n\n public void DelayAdd() => Config.Audio.Delay += Config.Player.AudioDelayOffset;\n public void DelayAdd2() => Config.Audio.Delay += Config.Player.AudioDelayOffset2;\n public void DelayRemove() => Config.Audio.Delay -= Config.Player.AudioDelayOffset;\n public void DelayRemove2() => Config.Audio.Delay -= Config.Player.AudioDelayOffset2;\n public void Toggle() => Config.Audio.Enabled = !Config.Audio.Enabled;\n public void ToggleMute() => Mute = !Mute;\n public void VolumeUp()\n {\n if (Volume == Config.Player.VolumeMax) return;\n Volume = Math.Min(Volume + Config.Player.VolumeOffset, Config.Player.VolumeMax);\n }\n public void VolumeDown()\n {\n if (Volume == 0) return;\n Volume = Math.Max(Volume - Config.Player.VolumeOffset, 0);\n }\n\n /// \n /// Reloads filters from Config.Audio.Filters (experimental)\n /// \n /// 0 on success\n public int ReloadFilters() => player.AudioDecoder.ReloadFilters();\n\n /// \n /// \n /// Updates filter's property (experimental)\n /// Note: This will not update the property value in Config.Audio.Filters\n /// \n /// \n /// Filter's unique id specified in Config.Audio.Filters\n /// Filter's property to change\n /// Filter's property value\n /// 0 on success\n public int UpdateFilter(string filterId, string key, string value) => player.AudioDecoder.UpdateFilter(filterId, key, value);\n}\n"], ["/LLPlayer/FlyleafLib/Engine/Engine.FFmpeg.cs", "namespace FlyleafLib;\n\npublic class FFmpegEngine\n{\n public string Folder { get; private set; }\n public string Version { get; private set; }\n\n const int AV_LOG_BUFFER_SIZE = 5 * 1024;\n internal AVRational AV_TIMEBASE_Q;\n\n internal FFmpegEngine()\n {\n try\n {\n Engine.Log.Info($\"Loading FFmpeg libraries from '{Engine.Config.FFmpegPath}'\");\n Folder = Utils.GetFolderPath(Engine.Config.FFmpegPath);\n LoadLibraries(Folder, Engine.Config.FFmpegLoadProfile);\n\n uint ver = avformat_version();\n Version = $\"{ver >> 16}.{(ver >> 8) & 255}.{ver & 255}\";\n\n SetLogLevel();\n AV_TIMEBASE_Q = av_get_time_base_q();\n Engine.Log.Info($\"FFmpeg Loaded (Profile: {Engine.Config.FFmpegLoadProfile}, Location: {Folder}, FmtVer: {Version})\");\n } catch (Exception e)\n {\n Engine.Log.Error($\"Loading FFmpeg libraries '{Engine.Config.FFmpegPath}' failed\\r\\n{e.Message}\\r\\n{e.StackTrace}\");\n throw new Exception($\"Loading FFmpeg libraries '{Engine.Config.FFmpegPath}' failed\");\n }\n }\n\n internal static void SetLogLevel()\n {\n if (Engine.Config.FFmpegLogLevel != Flyleaf.FFmpeg.LogLevel.Quiet)\n {\n av_log_set_level(Engine.Config.FFmpegLogLevel);\n av_log_set_callback(LogFFmpeg);\n }\n else\n {\n av_log_set_level(Flyleaf.FFmpeg.LogLevel.Quiet);\n av_log_set_callback(null);\n }\n }\n\n internal unsafe static av_log_set_callback_callback LogFFmpeg = (p0, level, format, vl) =>\n {\n if (level > av_log_get_level())\n return;\n\n byte* buffer = stackalloc byte[AV_LOG_BUFFER_SIZE];\n int printPrefix = 1;\n av_log_format_line2(p0, level, format, vl, buffer, AV_LOG_BUFFER_SIZE, &printPrefix);\n string line = Utils.BytePtrToStringUTF8(buffer);\n\n Logger.Output($\"FFmpeg|{level,-7}|{line.Trim()}\");\n };\n\n internal unsafe static string ErrorCodeToMsg(int error)\n {\n byte* buffer = stackalloc byte[AV_LOG_BUFFER_SIZE];\n av_strerror(error, buffer, AV_LOG_BUFFER_SIZE);\n return Utils.BytePtrToStringUTF8(buffer);\n }\n}\n"], ["/LLPlayer/FlyleafLib/Plugins/PluginBase.cs", "using System.Collections.Generic;\nusing System.Collections.ObjectModel;\nusing System.IO;\n\nusing FlyleafLib.MediaFramework.MediaContext;\nusing FlyleafLib.MediaFramework.MediaPlaylist;\nusing FlyleafLib.MediaFramework.MediaStream;\n\nusing static FlyleafLib.Utils;\n\nnamespace FlyleafLib.Plugins;\n\npublic abstract class PluginBase : PluginType, IPlugin\n{\n public ObservableDictionary\n Options => Config?.Plugins[Name];\n public Config Config => Handler.Config;\n\n public Playlist Playlist => Handler.Playlist;\n public PlaylistItem Selected => Handler.Playlist.Selected;\n\n public DecoderContext decoder => (DecoderContext) Handler;\n\n public PluginHandler Handler { get; internal set; }\n public LogHandler Log { get; internal set; }\n public bool Disposed { get; protected set;} = true;\n public int Priority { get; set; } = 1000;\n\n public virtual void OnLoaded() { }\n public virtual void OnInitializing() { }\n public virtual void OnInitialized() { }\n\n public virtual void OnInitializingSwitch() { }\n public virtual void OnInitializedSwitch() { }\n\n public virtual void OnBuffering() { }\n public virtual void OnBufferingCompleted() { }\n\n public virtual void OnOpen() { }\n public virtual void OnOpenExternalAudio() { }\n public virtual void OnOpenExternalVideo() { }\n public virtual void OnOpenExternalSubtitles() { }\n\n public virtual void Dispose() { }\n\n public void AddExternalStream(ExternalStream extStream, object tag = null, PlaylistItem item = null)\n {\n item ??= Playlist.Selected;\n\n if (item != null)\n PlaylistItem.AddExternalStream(extStream, item, Name, tag);\n }\n\n public void AddPlaylistItem(PlaylistItem item, object tag = null)\n => Playlist.AddItem(item, Name, tag);\n\n public void AddTag(object tag, PlaylistItem item = null)\n {\n item ??= Playlist.Selected;\n\n item?.AddTag(tag, Name);\n }\n\n public object GetTag(ExternalStream extStream)\n => extStream?.GetTag(Name);\n\n public object GetTag(PlaylistItem item)\n => item?.GetTag(Name);\n\n public virtual Dictionary GetDefaultOptions() => new();\n}\npublic class PluginType\n{\n public Type Type { get; internal set; }\n public string Name { get; internal set; }\n public Version Version { get; internal set; }\n}\npublic class OpenResults\n{\n public string Error;\n public bool Success => Error == null;\n\n public OpenResults() { }\n public OpenResults(string error) => Error = error;\n}\n\npublic class OpenSubtitlesResults : OpenResults\n{\n public ExternalSubtitlesStream ExternalSubtitlesStream;\n public OpenSubtitlesResults(ExternalSubtitlesStream extStream, string error = null) : base(error) => ExternalSubtitlesStream = extStream;\n}\n\npublic interface IPlugin : IDisposable\n{\n string Name { get; }\n Version Version { get; }\n PluginHandler Handler { get; }\n int Priority { get; }\n\n void OnLoaded();\n void OnInitializing();\n void OnInitialized();\n void OnInitializingSwitch();\n void OnInitializedSwitch();\n\n void OnBuffering();\n void OnBufferingCompleted();\n\n void OnOpenExternalAudio();\n void OnOpenExternalVideo();\n void OnOpenExternalSubtitles();\n}\n\npublic interface IOpen : IPlugin\n{\n bool CanOpen();\n OpenResults Open();\n OpenResults OpenItem();\n}\npublic interface IOpenSubtitles : IPlugin\n{\n OpenSubtitlesResults Open(string url);\n OpenSubtitlesResults Open(Stream iostream);\n}\n\npublic interface IScrapeItem : IPlugin\n{\n void ScrapeItem(PlaylistItem item);\n}\n\npublic interface ISuggestPlaylistItem : IPlugin\n{\n PlaylistItem SuggestItem();\n}\n\npublic interface ISuggestExternalAudio : IPlugin\n{\n ExternalAudioStream SuggestExternalAudio();\n}\npublic interface ISuggestExternalVideo : IPlugin\n{\n ExternalVideoStream SuggestExternalVideo();\n}\n\npublic interface ISuggestAudioStream : IPlugin\n{\n AudioStream SuggestAudio(ObservableCollection streams);\n}\npublic interface ISuggestVideoStream : IPlugin\n{\n VideoStream SuggestVideo(ObservableCollection streams);\n}\n\npublic interface ISuggestSubtitlesStream : IPlugin\n{\n SubtitlesStream SuggestSubtitles(ObservableCollection streams, List langs);\n}\n\npublic interface ISuggestSubtitles : IPlugin\n{\n /// \n /// Suggests from all the available subtitles\n /// \n /// Embedded stream\n /// External stream\n void SuggestSubtitles(out SubtitlesStream stream, out ExternalSubtitlesStream extStream);\n}\n\npublic interface ISuggestBestExternalSubtitles : IPlugin\n{\n /// \n /// Suggests only if best match exists (to avoid search local/online)\n /// \n /// \n ExternalSubtitlesStream SuggestBestExternalSubtitles();\n}\n\npublic interface ISearchLocalSubtitles : IPlugin\n{\n void SearchLocalSubtitles();\n}\n\npublic interface ISearchOnlineSubtitles : IPlugin\n{\n void SearchOnlineSubtitles();\n}\n\npublic interface IDownloadSubtitles : IPlugin\n{\n bool DownloadSubtitles(ExternalSubtitlesStream extStream);\n}\n"], ["/LLPlayer/FlyleafLib/MediaPlayer/Translation/Services/ITranslateSettings.cs", "using System.Collections.Generic;\nusing System.Collections.ObjectModel;\nusing System.ComponentModel;\nusing System.Diagnostics;\nusing System.Linq;\nusing System.Net.Http;\nusing System.Text;\nusing System.Text.Json.Serialization;\nusing System.Threading.Tasks;\nusing FlyleafLib.Controls.WPF;\n\nnamespace FlyleafLib.MediaPlayer.Translation.Services;\n\npublic interface ITranslateSettings : INotifyPropertyChanged;\n\npublic class GoogleV1TranslateSettings : NotifyPropertyChanged, ITranslateSettings\n{\n private const string DefaultEndpoint = \"https://translate.googleapis.com\";\n\n public string Endpoint\n {\n get;\n set\n {\n if (Set(ref field, value))\n {\n CmdSetDefaultEndpoint.OnCanExecuteChanged();\n }\n }\n } = DefaultEndpoint;\n\n [JsonIgnore]\n public RelayCommand CmdSetDefaultEndpoint => field ??= new(_ =>\n {\n Endpoint = DefaultEndpoint;\n }, _ => Endpoint != DefaultEndpoint);\n\n public int TimeoutMs { get; set => Set(ref field, value); } = 10000;\n\n public Dictionary Regions { get; set; } = new(GoogleV1TranslateService.DefaultRegions);\n\n /// \n /// for Settings\n /// \n [JsonIgnore]\n public ObservableCollection LanguageRegions\n {\n get\n {\n if (field == null)\n {\n field = LoadLanguageRegions();\n\n foreach (var pref in field)\n {\n pref.PropertyChanged += (sender, args) =>\n {\n if (args.PropertyName == nameof(Services.LanguageRegions.SelectedRegionMember))\n {\n // Apply changes in setting\n Regions[pref.ISO6391] = pref.SelectedRegionMember.Code;\n }\n };\n }\n }\n\n return field;\n }\n }\n\n private ObservableCollection LoadLanguageRegions()\n {\n List preferences = [\n new()\n {\n Name = \"Chinese\",\n ISO6391 = \"zh\",\n Regions =\n [\n // priority to the above\n new LanguageRegionMember { Name = \"Chinese (Simplified)\", Code = \"zh-CN\" },\n new LanguageRegionMember { Name = \"Chinese (Traditional)\", Code = \"zh-TW\" }\n ],\n },\n new()\n {\n Name = \"French\",\n ISO6391 = \"fr\",\n Regions =\n [\n new LanguageRegionMember { Name = \"French (French)\", Code = \"fr-FR\" },\n new LanguageRegionMember { Name = \"French (Canadian)\", Code = \"fr-CA\" }\n ],\n },\n new()\n {\n Name = \"Portuguese\",\n ISO6391 = \"pt\",\n Regions =\n [\n new LanguageRegionMember { Name = \"Portuguese (Portugal)\", Code = \"pt-PT\" },\n new LanguageRegionMember { Name = \"Portuguese (Brazil)\", Code = \"pt-BR\" }\n ],\n }\n ];\n\n foreach (LanguageRegions p in preferences)\n {\n if (Regions.TryGetValue(p.ISO6391, out string code))\n {\n // loaded from config\n p.SelectedRegionMember = p.Regions.FirstOrDefault(r => r.Code == code);\n }\n else\n {\n // select first\n p.SelectedRegionMember = p.Regions.First();\n }\n }\n\n return new ObservableCollection(preferences);\n }\n}\n\npublic class DeepLTranslateSettings : NotifyPropertyChanged, ITranslateSettings\n{\n public string ApiKey { get; set => Set(ref field, value); }\n\n public int TimeoutMs { get; set => Set(ref field, value); } = 10000;\n}\n\npublic class DeepLXTranslateSettings : NotifyPropertyChanged, ITranslateSettings\n{\n public string Endpoint { get; set => Set(ref field, value); } = \"http://127.0.0.1:1188\";\n\n public int TimeoutMs { get; set => Set(ref field, value); } = 10000;\n}\n\npublic abstract class OpenAIBaseTranslateSettings : NotifyPropertyChanged, ITranslateSettings\n{\n protected OpenAIBaseTranslateSettings()\n {\n // ReSharper disable once VirtualMemberCallInConstructor\n Endpoint = DefaultEndpoint;\n }\n\n public abstract TranslateServiceType ServiceType { get; }\n public string Endpoint\n {\n get;\n set\n {\n if (Set(ref field, value))\n {\n CmdSetDefaultEndpoint.OnCanExecuteChanged();\n }\n }\n }\n [JsonIgnore]\n protected virtual bool ReuseConnection => true;\n\n public abstract string DefaultEndpoint { get; }\n\n [JsonIgnore]\n public virtual string ChatPath\n {\n get => \"/v1/chat/completions\";\n set => throw new NotImplementedException();\n }\n\n public string Model { get; set => Set(ref field, value); }\n\n [JsonIgnore]\n public virtual bool ModelRequired => true;\n\n [JsonIgnore]\n public virtual bool ReasonStripRequired => true;\n\n public int TimeoutMs { get; set => Set(ref field, value); } = 15000;\n public int TimeoutHealthMs { get; set => Set(ref field, value); } = 2000;\n\n #region LLM Parameters\n public double Temperature\n {\n get;\n set\n {\n if (value is >= 0.0 and <= 2.0)\n {\n Set(ref field, Math.Round(value, 2));\n }\n }\n } = 0.0;\n\n public bool TemperatureManual { get; set => Set(ref field, value); } = true;\n\n public double TopP\n {\n get;\n set\n {\n if (value is >= 0.0 and <= 1.0)\n {\n Set(ref field, Math.Round(value, 2));\n }\n }\n } = 1;\n\n public bool TopPManual { get; set => Set(ref field, value); }\n\n public int? MaxTokens\n {\n get;\n set => Set(ref field, value is <= 0 ? null : value);\n }\n\n public int? MaxCompletionTokens\n {\n get;\n set => Set(ref field, value is <= 0 ? null : value);\n }\n #endregion\n\n /// \n /// GetHttpClient\n /// \n /// \n /// \n /// \n internal virtual HttpClient GetHttpClient(bool healthCheck = false)\n {\n if (string.IsNullOrWhiteSpace(Endpoint))\n {\n throw new TranslationConfigException(\n $\"Endpoint for {ServiceType} is not configured.\");\n }\n\n if (!healthCheck)\n {\n if (ModelRequired && string.IsNullOrWhiteSpace(Model))\n {\n throw new TranslationConfigException(\n $\"Model for {ServiceType} is not configured.\");\n }\n }\n\n // In KoboldCpp, if this is not set, even if it is sent with Connection: close,\n // the connection will be reused and an error will occur.\n HttpMessageHandler handler = ReuseConnection ?\n new HttpClientHandler() :\n new SocketsHttpHandler\n {\n PooledConnectionLifetime = TimeSpan.Zero,\n PooledConnectionIdleTimeout = TimeSpan.Zero,\n };\n\n HttpClient client = new(handler);\n client.BaseAddress = new Uri(Endpoint);\n client.Timeout = TimeSpan.FromMilliseconds(healthCheck ? TimeoutHealthMs : TimeoutMs);\n if (!ReuseConnection)\n {\n client.DefaultRequestHeaders.ConnectionClose = true;\n }\n\n return client;\n }\n\n #region For Settings\n [JsonIgnore]\n public ObservableCollection AvailableModels { get; } = new();\n\n [JsonIgnore]\n public string Status\n {\n get;\n set\n {\n if (Set(ref field, value))\n {\n Raise(nameof(StatusAvailable));\n }\n }\n }\n\n [JsonIgnore]\n public bool StatusAvailable => !string.IsNullOrEmpty(Status);\n\n [JsonIgnore]\n public RelayCommand CmdSetDefaultEndpoint => field ??= new(_ =>\n {\n Endpoint = DefaultEndpoint;\n }, _ => Endpoint != DefaultEndpoint);\n\n [JsonIgnore]\n public RelayCommand CmdCheckEndpoint => new(async void (_) =>\n {\n try\n {\n Status = \"Checking...\";\n await LoadModels();\n Status = \"OK\";\n }\n catch (Exception ex)\n {\n Status = GetErrorDetails($\"NG: {ex.Message}\", ex);\n }\n });\n\n [JsonIgnore]\n public RelayCommand CmdGetModels => new(async void (_) =>\n {\n try\n {\n Status = \"Checking...\";\n await LoadModels();\n Status = \"\"; // clear\n }\n catch (Exception ex)\n {\n Status = GetErrorDetails($\"NG: {ex.Message}\", ex);\n }\n });\n\n [JsonIgnore]\n public RelayCommand CmdHelloModel => new(async void (_) =>\n {\n Stopwatch sw = new();\n sw.Start();\n try\n {\n Status = \"Waiting...\";\n\n await OpenAIBaseTranslateService.Hello(this);\n\n Status = $\"OK in {sw.Elapsed.TotalSeconds} secs\";\n }\n catch (Exception ex)\n {\n Status = GetErrorDetails($\"NG in {sw.Elapsed.TotalSeconds} secs: {ex.Message}\", ex);\n }\n });\n\n private async Task LoadModels()\n {\n string prevModel = Model;\n AvailableModels.Clear();\n\n var models = await OpenAIBaseTranslateService.GetLoadedModels(this);\n foreach (var model in models)\n {\n AvailableModels.Add(model);\n }\n\n if (!string.IsNullOrEmpty(prevModel))\n {\n Model = AvailableModels.FirstOrDefault(m => m == prevModel);\n }\n }\n\n internal static string GetErrorDetails(string header, Exception ex)\n {\n StringBuilder sb = new();\n sb.Append(header);\n\n if (ex.Data.Contains(\"status_code\") && (string)ex.Data[\"status_code\"] != \"-1\")\n {\n sb.AppendLine();\n sb.AppendLine();\n sb.Append($\"status_code: {ex.Data[\"status_code\"]}\");\n }\n\n if (ex.Data.Contains(\"response\") && (string)ex.Data[\"response\"] != \"\")\n {\n sb.AppendLine();\n sb.Append($\"response: {ex.Data[\"response\"]}\");\n }\n\n return sb.ToString();\n }\n #endregion\n}\n\npublic class OllamaTranslateSettings : OpenAIBaseTranslateSettings\n{\n public OllamaTranslateSettings()\n {\n TimeoutMs = 20000;\n }\n\n [JsonIgnore]\n public override TranslateServiceType ServiceType => TranslateServiceType.Ollama;\n [JsonIgnore]\n public override string DefaultEndpoint => \"http://127.0.0.1:11434\";\n}\n\npublic class LMStudioTranslateSettings : OpenAIBaseTranslateSettings\n{\n public LMStudioTranslateSettings()\n {\n TimeoutMs = 20000;\n }\n\n [JsonIgnore]\n public override TranslateServiceType ServiceType => TranslateServiceType.LMStudio;\n [JsonIgnore]\n public override string DefaultEndpoint => \"http://127.0.0.1:1234\";\n [JsonIgnore]\n public override bool ModelRequired => false;\n}\n\npublic class KoboldCppTranslateSettings : OpenAIBaseTranslateSettings\n{\n public KoboldCppTranslateSettings()\n {\n TimeoutMs = 20000;\n }\n\n [JsonIgnore]\n public override TranslateServiceType ServiceType => TranslateServiceType.KoboldCpp;\n [JsonIgnore]\n public override string DefaultEndpoint => \"http://127.0.0.1:5001\";\n\n // Disabled due to error when reusing connections\n [JsonIgnore]\n protected override bool ReuseConnection => false;\n\n [JsonIgnore]\n public override bool ModelRequired => false;\n}\n\npublic class OpenAITranslateSettings : OpenAIBaseTranslateSettings\n{\n [JsonIgnore]\n public override TranslateServiceType ServiceType => TranslateServiceType.OpenAI;\n [JsonIgnore]\n public override string DefaultEndpoint => \"https://api.openai.com\";\n public string ApiKey { get; set => Set(ref field, value); }\n\n [JsonIgnore]\n public override bool ReasonStripRequired => false;\n\n /// \n /// GetHttpClient\n /// \n /// \n /// \n /// \n internal override HttpClient GetHttpClient(bool healthCheck = false)\n {\n if (string.IsNullOrWhiteSpace(ApiKey))\n {\n throw new TranslationConfigException(\n $\"API Key for {ServiceType} is not configured.\");\n }\n\n HttpClient client = base.GetHttpClient(healthCheck);\n client.DefaultRequestHeaders.Add(\"Authorization\", $\"Bearer {ApiKey}\");\n\n return client;\n }\n}\n\npublic class OpenAILikeTranslateSettings : OpenAIBaseTranslateSettings\n{\n [JsonIgnore]\n public override TranslateServiceType ServiceType => TranslateServiceType.OpenAILike;\n [JsonIgnore]\n public override string DefaultEndpoint => \"https://api.openai.com\";\n\n private const string DefaultChatPath = \"/v1/chat/completions\";\n public override string ChatPath\n {\n get;\n set\n {\n if (Set(ref field, value))\n {\n CmdSetDefaultChatPath.OnCanExecuteChanged();\n }\n }\n } = DefaultChatPath;\n\n [JsonIgnore]\n public RelayCommand CmdSetDefaultChatPath => field ??= new(_ =>\n {\n ChatPath = DefaultChatPath;\n }, _ => ChatPath != DefaultChatPath);\n\n [JsonIgnore]\n public override bool ModelRequired => false;\n public string ApiKey { get; set => Set(ref field, value); }\n\n /// \n /// GetHttpClient\n /// \n /// \n /// \n /// \n internal override HttpClient GetHttpClient(bool healthCheck = false)\n {\n HttpClient client = base.GetHttpClient(healthCheck);\n\n // optional ApiKey\n if (!string.IsNullOrWhiteSpace(ApiKey))\n {\n client.DefaultRequestHeaders.Add(\"Authorization\", $\"Bearer {ApiKey}\");\n }\n\n return client;\n }\n}\n\npublic class ClaudeTranslateSettings : OpenAIBaseTranslateSettings\n{\n [JsonIgnore]\n public override TranslateServiceType ServiceType => TranslateServiceType.Claude;\n [JsonIgnore]\n public override string DefaultEndpoint => \"https://api.anthropic.com\";\n public string ApiKey { get; set => Set(ref field, value); }\n\n [JsonIgnore]\n public override bool ReasonStripRequired => false;\n\n internal override HttpClient GetHttpClient(bool healthCheck = false)\n {\n if (string.IsNullOrWhiteSpace(ApiKey))\n {\n throw new TranslationConfigException(\n $\"API Key for {ServiceType} is not configured.\");\n }\n\n HttpClient client = base.GetHttpClient(healthCheck);\n client.DefaultRequestHeaders.Add(\"x-api-key\", ApiKey);\n client.DefaultRequestHeaders.Add(\"anthropic-version\", \"2023-06-01\");\n\n return client;\n }\n}\n\npublic class LiteLLMTranslateSettings : OpenAIBaseTranslateSettings\n{\n [JsonIgnore]\n public override TranslateServiceType ServiceType => TranslateServiceType.LiteLLM;\n [JsonIgnore]\n public override string DefaultEndpoint => \"http://127.0.0.1:4000\";\n}\n\npublic class LanguageRegionMember : NotifyPropertyChanged, IEquatable\n{\n public string Name { get; set; }\n public string Code { get; set; }\n\n public bool Equals(LanguageRegionMember other)\n {\n if (other is null) return false;\n if (ReferenceEquals(this, other)) return true;\n return Code == other.Code;\n }\n\n public override bool Equals(object obj) => obj is LanguageRegionMember o && Equals(o);\n\n public override int GetHashCode()\n {\n return (Code != null ? Code.GetHashCode() : 0);\n }\n}\n\npublic class LanguageRegions : NotifyPropertyChanged\n{\n public string ISO6391 { get; set; }\n public string Name { get; set; }\n public List Regions { get; set; }\n\n public LanguageRegionMember SelectedRegionMember { get; set => Set(ref field, value); }\n}\n"], ["/LLPlayer/FlyleafLib/MediaFramework/MediaContext/DecoderContext.Open.cs", "using System;\nusing System.Collections.Generic;\nusing System.IO;\nusing System.Linq;\nusing System.Threading.Tasks;\n\nusing FlyleafLib.MediaFramework.MediaDemuxer;\nusing FlyleafLib.MediaFramework.MediaPlaylist;\nusing FlyleafLib.MediaFramework.MediaStream;\nusing FlyleafLib.MediaPlayer;\nusing static FlyleafLib.Logger;\nusing static FlyleafLib.Utils;\n\nnamespace FlyleafLib.MediaFramework.MediaContext;\n\npublic partial class DecoderContext\n{\n #region Events\n public event EventHandler OpenCompleted;\n public event EventHandler OpenSessionCompleted;\n public event EventHandler OpenSubtitlesCompleted;\n public event EventHandler OpenPlaylistItemCompleted;\n\n public event EventHandler OpenAudioStreamCompleted;\n public event EventHandler OpenVideoStreamCompleted;\n public event EventHandler OpenSubtitlesStreamCompleted;\n public event EventHandler OpenDataStreamCompleted;\n\n public event EventHandler OpenExternalAudioStreamCompleted;\n public event EventHandler OpenExternalVideoStreamCompleted;\n public event EventHandler OpenExternalSubtitlesStreamCompleted;\n\n public class OpenCompletedArgs\n {\n public string Url;\n public Stream IOStream;\n public string Error;\n public bool Success => Error == null;\n public OpenCompletedArgs(string url = null, Stream iostream = null, string error = null) { Url = url; IOStream = iostream; Error = error; }\n }\n public class OpenSubtitlesCompletedArgs\n {\n public string Url;\n public string Error;\n public bool Success => Error == null;\n public OpenSubtitlesCompletedArgs(string url = null, string error = null) { Url = url; Error = error; }\n }\n public class OpenSessionCompletedArgs\n {\n public Session Session;\n public string Error;\n public bool Success => Error == null;\n public OpenSessionCompletedArgs(Session session = null, string error = null) { Session = session; Error = error; }\n }\n public class OpenPlaylistItemCompletedArgs\n {\n public PlaylistItem Item;\n public PlaylistItem OldItem;\n public string Error;\n public bool Success => Error == null;\n public OpenPlaylistItemCompletedArgs(PlaylistItem item = null, PlaylistItem oldItem = null, string error = null) { Item = item; OldItem = oldItem; Error = error; }\n }\n public class StreamOpenedArgs\n {\n public StreamBase Stream;\n public StreamBase OldStream;\n public string Error;\n public bool Success => Error == null;\n public StreamOpenedArgs(StreamBase stream = null, StreamBase oldStream = null, string error = null) { Stream = stream; OldStream= oldStream; Error = error; }\n }\n public class OpenAudioStreamCompletedArgs : StreamOpenedArgs\n {\n public new AudioStream Stream => (AudioStream)base.Stream;\n public new AudioStream OldStream=> (AudioStream)base.OldStream;\n public OpenAudioStreamCompletedArgs(AudioStream stream = null, AudioStream oldStream = null, string error = null): base(stream, oldStream, error) { }\n }\n public class OpenVideoStreamCompletedArgs : StreamOpenedArgs\n {\n public new VideoStream Stream => (VideoStream)base.Stream;\n public new VideoStream OldStream=> (VideoStream)base.OldStream;\n public OpenVideoStreamCompletedArgs(VideoStream stream = null, VideoStream oldStream = null, string error = null): base(stream, oldStream, error) { }\n }\n public class OpenSubtitlesStreamCompletedArgs : StreamOpenedArgs\n {\n public new SubtitlesStream Stream => (SubtitlesStream)base.Stream;\n public new SubtitlesStream OldStream=> (SubtitlesStream)base.OldStream;\n public OpenSubtitlesStreamCompletedArgs(SubtitlesStream stream = null, SubtitlesStream oldStream = null, string error = null): base(stream, oldStream, error) { }\n }\n public class OpenDataStreamCompletedArgs : StreamOpenedArgs\n {\n public new DataStream Stream => (DataStream)base.Stream;\n public new DataStream OldStream => (DataStream)base.OldStream;\n public OpenDataStreamCompletedArgs(DataStream stream = null, DataStream oldStream = null, string error = null) : base(stream, oldStream, error) { }\n }\n public class ExternalStreamOpenedArgs : EventArgs\n {\n public ExternalStream ExtStream;\n public ExternalStream OldExtStream;\n public string Error;\n public bool Success => Error == null;\n public ExternalStreamOpenedArgs(ExternalStream extStream = null, ExternalStream oldExtStream = null, string error = null) { ExtStream = extStream; OldExtStream= oldExtStream; Error = error; }\n }\n public class OpenExternalAudioStreamCompletedArgs : ExternalStreamOpenedArgs\n {\n public new ExternalAudioStream ExtStream => (ExternalAudioStream)base.ExtStream;\n public new ExternalAudioStream OldExtStream=> (ExternalAudioStream)base.OldExtStream;\n public OpenExternalAudioStreamCompletedArgs(ExternalAudioStream extStream = null, ExternalAudioStream oldExtStream = null, string error = null) : base(extStream, oldExtStream, error) { }\n }\n public class OpenExternalVideoStreamCompletedArgs : ExternalStreamOpenedArgs\n {\n public new ExternalVideoStream ExtStream => (ExternalVideoStream)base.ExtStream;\n public new ExternalVideoStream OldExtStream=> (ExternalVideoStream)base.OldExtStream;\n public OpenExternalVideoStreamCompletedArgs(ExternalVideoStream extStream = null, ExternalVideoStream oldExtStream = null, string error = null) : base(extStream, oldExtStream, error) { }\n }\n public class OpenExternalSubtitlesStreamCompletedArgs : ExternalStreamOpenedArgs\n {\n public new ExternalSubtitlesStream ExtStream => (ExternalSubtitlesStream)base.ExtStream;\n public new ExternalSubtitlesStream OldExtStream=> (ExternalSubtitlesStream)base.OldExtStream;\n public OpenExternalSubtitlesStreamCompletedArgs(ExternalSubtitlesStream extStream = null, ExternalSubtitlesStream oldExtStream = null, string error = null) : base(extStream, oldExtStream, error) { }\n }\n\n private void OnOpenCompleted(OpenCompletedArgs args = null)\n {\n if (shouldDispose)\n {\n Dispose();\n return;\n }\n\n VideoDecoder.Renderer?.ClearScreen();\n if (CanInfo) Log.Info($\"[Open] {args.Url ?? \"None\"} {(!args.Success ? \" [Error: \" + args.Error + \"]\": \"\")}\");\n OpenCompleted?.Invoke(this, args);\n }\n private void OnOpenSessionCompleted(OpenSessionCompletedArgs args = null)\n {\n if (shouldDispose)\n {\n Dispose();\n return;\n }\n\n VideoDecoder.Renderer?.ClearScreen();\n if (CanInfo) Log.Info($\"[OpenSession] {args.Session.Url ?? \"None\"} - Item: {args.Session.PlaylistItem} {(!args.Success ? \" [Error: \" + args.Error + \"]\": \"\")}\");\n OpenSessionCompleted?.Invoke(this, args);\n }\n private void OnOpenSubtitles(OpenSubtitlesCompletedArgs args = null)\n {\n if (shouldDispose)\n {\n Dispose();\n return;\n }\n\n if (CanInfo) Log.Info($\"[OpenSubtitles] {args.Url ?? \"None\"} {(!args.Success ? \" [Error: \" + args.Error + \"]\": \"\")}\");\n OpenSubtitlesCompleted?.Invoke(this, args);\n }\n private void OnOpenPlaylistItemCompleted(OpenPlaylistItemCompletedArgs args = null)\n {\n if (shouldDispose)\n {\n Dispose();\n return;\n }\n\n VideoDecoder.Renderer?.ClearScreen();\n if (CanInfo) Log.Info($\"[OpenPlaylistItem] {(args.OldItem != null ? args.OldItem.Title : \"None\")} => {(args.Item != null ? args.Item.Title : \"None\")}{(!args.Success ? \" [Error: \" + args.Error + \"]\": \"\")}\");\n OpenPlaylistItemCompleted?.Invoke(this, args);\n }\n private void OnOpenAudioStreamCompleted(OpenAudioStreamCompletedArgs args = null)\n {\n if (shouldDispose)\n {\n Dispose();\n return;\n }\n\n ClosedAudioStream = null;\n MainDemuxer = !VideoDemuxer.Disposed ? VideoDemuxer : AudioDemuxer;\n\n if (CanInfo) Log.Info($\"[OpenAudioStream] #{(args.OldStream != null ? args.OldStream.StreamIndex.ToString() : \"_\")} => #{(args.Stream != null ? args.Stream.StreamIndex.ToString() : \"_\")}{(!args.Success ? \" [Error: \" + args.Error + \"]\": \"\")}\");\n OpenAudioStreamCompleted?.Invoke(this, args);\n }\n private void OnOpenVideoStreamCompleted(OpenVideoStreamCompletedArgs args = null)\n {\n if (shouldDispose)\n {\n Dispose();\n return;\n }\n\n ClosedVideoStream = null;\n MainDemuxer = !VideoDemuxer.Disposed ? VideoDemuxer : AudioDemuxer;\n\n if (CanInfo) Log.Info($\"[OpenVideoStream] #{(args.OldStream != null ? args.OldStream.StreamIndex.ToString() : \"_\")} => #{(args.Stream != null ? args.Stream.StreamIndex.ToString() : \"_\")}{(!args.Success ? \" [Error: \" + args.Error + \"]\": \"\")}\");\n OpenVideoStreamCompleted?.Invoke(this, args);\n }\n private void OnOpenSubtitlesStreamCompleted(OpenSubtitlesStreamCompletedArgs args = null)\n {\n if (shouldDispose)\n {\n Dispose();\n return;\n }\n\n if (CanInfo) Log.Info($\"[OpenSubtitlesStream] #{(args.OldStream != null ? args.OldStream.StreamIndex.ToString() : \"_\")} => #{(args.Stream != null ? args.Stream.StreamIndex.ToString() : \"_\")}{(!args.Success ? \" [Error: \" + args.Error + \"]\": \"\")}\");\n OpenSubtitlesStreamCompleted?.Invoke(this, args);\n }\n private void OnOpenDataStreamCompleted(OpenDataStreamCompletedArgs args = null)\n {\n if (shouldDispose)\n {\n Dispose();\n return;\n }\n\n if (CanInfo)\n Log.Info($\"[OpenDataStream] #{(args.OldStream != null ? args.OldStream.StreamIndex.ToString() : \"_\")} => #{(args.Stream != null ? args.Stream.StreamIndex.ToString() : \"_\")}{(!args.Success ? \" [Error: \" + args.Error + \"]\" : \"\")}\");\n OpenDataStreamCompleted?.Invoke(this, args);\n }\n private void OnOpenExternalAudioStreamCompleted(OpenExternalAudioStreamCompletedArgs args = null)\n {\n if (shouldDispose)\n {\n Dispose();\n return;\n }\n\n ClosedAudioStream = null;\n MainDemuxer = !VideoDemuxer.Disposed ? VideoDemuxer : AudioDemuxer;\n\n if (CanInfo) Log.Info($\"[OpenExternalAudioStream] {(args.OldExtStream != null ? args.OldExtStream.Url : \"None\")} => {(args.ExtStream != null ? args.ExtStream.Url : \"None\")}{(!args.Success ? \" [Error: \" + args.Error + \"]\": \"\")}\");\n OpenExternalAudioStreamCompleted?.Invoke(this, args);\n }\n private void OnOpenExternalVideoStreamCompleted(OpenExternalVideoStreamCompletedArgs args = null)\n {\n if (shouldDispose)\n {\n Dispose();\n return;\n }\n\n ClosedVideoStream = null;\n MainDemuxer = !VideoDemuxer.Disposed ? VideoDemuxer : AudioDemuxer;\n\n if (CanInfo) Log.Info($\"[OpenExternalVideoStream] {(args.OldExtStream != null ? args.OldExtStream.Url : \"None\")} => {(args.ExtStream != null ? args.ExtStream.Url : \"None\")}{(!args.Success ? \" [Error: \" + args.Error + \"]\": \"\")}\");\n OpenExternalVideoStreamCompleted?.Invoke(this, args);\n }\n private void OnOpenExternalSubtitlesStreamCompleted(OpenExternalSubtitlesStreamCompletedArgs args = null)\n {\n if (shouldDispose)\n {\n Dispose();\n return;\n }\n\n if (CanInfo) Log.Info($\"[OpenExternalSubtitlesStream] {(args.OldExtStream != null ? args.OldExtStream.Url : \"None\")} => {(args.ExtStream != null ? args.ExtStream.Url : \"None\")}{(!args.Success ? \" [Error: \" + args.Error + \"]\": \"\")}\");\n OpenExternalSubtitlesStreamCompleted?.Invoke(this, args);\n }\n #endregion\n\n #region Open\n public OpenCompletedArgs Open(string url, bool defaultPlaylistItem = true, bool defaultVideo = true, bool defaultAudio = true, bool defaultSubtitles = true)\n => Open((object)url, defaultPlaylistItem, defaultVideo, defaultAudio, defaultSubtitles);\n public OpenCompletedArgs Open(Stream iostream, bool defaultPlaylistItem = true, bool defaultVideo = true, bool defaultAudio = true, bool defaultSubtitles = true)\n => Open((object)iostream, defaultPlaylistItem, defaultVideo, defaultAudio, defaultSubtitles);\n\n internal OpenCompletedArgs Open(object input, bool defaultPlaylistItem = true, bool defaultVideo = true, bool defaultAudio = true, bool defaultSubtitles = true)\n {\n OpenCompletedArgs args = new();\n\n try\n {\n Initialize();\n\n if (input is Stream)\n {\n Playlist.IOStream = (Stream)input;\n }\n else\n Playlist.Url = input.ToString(); // TBR: check UI update\n\n args.Url = Playlist.Url;\n args.IOStream = Playlist.IOStream;\n args.Error = Open().Error;\n\n if (Playlist.Items.Count == 0 && args.Success)\n args.Error = \"No playlist items were found\";\n\n if (!args.Success)\n return args;\n\n if (!defaultPlaylistItem)\n return args;\n\n args.Error = Open(SuggestItem(), defaultVideo, defaultAudio, defaultSubtitles).Error;\n\n return args;\n\n } catch (Exception e)\n {\n args.Error = !args.Success ? args.Error + \"\\r\\n\" + e.Message : e.Message;\n return args;\n }\n finally\n {\n OnOpenCompleted(args);\n }\n }\n public new OpenSubtitlesCompletedArgs OpenSubtitles(string url)\n {\n OpenSubtitlesCompletedArgs args = new();\n\n try\n {\n var res = base.OpenSubtitles(url);\n args.Error = res == null ? \"No external subtitles stream found\" : res.Error;\n\n if (args.Success)\n args.Error = Open(res.ExternalSubtitlesStream).Error;\n\n return args;\n\n } catch (Exception e)\n {\n args.Error = !args.Success ? args.Error + \"\\r\\n\" + e.Message : e.Message;\n return args;\n }\n finally\n {\n OnOpenSubtitles(args);\n }\n }\n public OpenSessionCompletedArgs Open(Session session)\n {\n OpenSessionCompletedArgs args = new(session);\n\n try\n {\n // Open\n if (session.Url != null && session.Url != Playlist.Url) // && session.Url != Playlist.DirectUrl)\n {\n args.Error = Open(session.Url, false, false, false, false).Error;\n if (!args.Success)\n return args;\n }\n\n // Open Item\n if (session.PlaylistItem != -1)\n {\n args.Error = Open(Playlist.Items[session.PlaylistItem], false, false, false).Error;\n if (!args.Success)\n return args;\n }\n\n // Open Streams\n if (session.ExternalVideoStream != -1)\n {\n args.Error = Open(Playlist.Selected.ExternalVideoStreams[session.ExternalVideoStream], false, session.VideoStream).Error;\n if (!args.Success)\n return args;\n }\n else if (session.VideoStream != -1)\n {\n args.Error = Open(VideoDemuxer.AVStreamToStream[session.VideoStream], false).Error;\n if (!args.Success)\n return args;\n }\n\n string tmpErr = null;\n if (session.ExternalAudioStream != -1)\n tmpErr = Open(Playlist.Selected.ExternalAudioStreams[session.ExternalAudioStream], false, session.AudioStream).Error;\n else if (session.AudioStream != -1)\n tmpErr = Open(VideoDemuxer.AVStreamToStream[session.AudioStream], false).Error;\n\n if (tmpErr != null & VideoStream == null)\n {\n args.Error = tmpErr;\n return args;\n }\n\n if (session.ExternalSubtitlesUrl != null)\n OpenSubtitles(session.ExternalSubtitlesUrl);\n else if (session.SubtitlesStream != -1)\n Open(VideoDemuxer.AVStreamToStream[session.SubtitlesStream]);\n\n Config.Audio.SetDelay(session.AudioDelay);\n\n for (int i = 0; i < subNum; i++)\n {\n Config.Subtitles[i].SetDelay(session.SubtitlesDelay);\n }\n\n if (session.CurTime > 1 * (long)1000 * 10000)\n Seek(session.CurTime / 10000);\n\n return args;\n } catch (Exception e)\n {\n args.Error = !args.Success ? args.Error + \"\\r\\n\" + e.Message : e.Message;\n return args;\n } finally\n {\n OnOpenSessionCompleted(args);\n }\n }\n public OpenPlaylistItemCompletedArgs Open(PlaylistItem item, bool defaultVideo = true, bool defaultAudio = true, bool defaultSubtitles = true)\n {\n OpenPlaylistItemCompletedArgs args = new(item);\n\n try\n {\n long stoppedTime = GetCurTime();\n InitializeSwitch();\n\n // Disables old item\n if (Playlist.Selected != null)\n {\n args.OldItem = Playlist.Selected;\n Playlist.Selected.Enabled = false;\n }\n\n if (item == null)\n {\n args.Error = \"Cancelled\";\n return args;\n }\n\n Playlist.Selected = item;\n Playlist.Selected.Enabled = true;\n\n // We reset external streams of the current item and not the old one\n if (Playlist.Selected.ExternalAudioStream != null)\n {\n Playlist.Selected.ExternalAudioStream.Enabled = false;\n Playlist.Selected.ExternalAudioStream = null;\n }\n\n if (Playlist.Selected.ExternalVideoStream != null)\n {\n Playlist.Selected.ExternalVideoStream.Enabled = false;\n Playlist.Selected.ExternalVideoStream = null;\n }\n\n for (int i = 0; i < subNum; i++)\n {\n if (Playlist.Selected.ExternalSubtitlesStreams[i] != null)\n {\n Playlist.Selected.ExternalSubtitlesStreams[i].Enabled = false;\n Playlist.Selected.ExternalSubtitlesStreams[i] = null;\n }\n }\n\n args.Error = OpenItem().Error;\n\n if (!args.Success)\n return args;\n\n if (Playlist.Selected.Url != null || Playlist.Selected.IOStream != null)\n args.Error = OpenDemuxerInput(VideoDemuxer, Playlist.Selected);\n\n if (!args.Success)\n return args;\n\n if (defaultVideo && Config.Video.Enabled)\n args.Error = OpenSuggestedVideo(defaultAudio);\n else if (defaultAudio && Config.Audio.Enabled)\n args.Error = OpenSuggestedAudio();\n\n if ((defaultVideo || defaultAudio) && AudioStream == null && VideoStream == null)\n {\n args.Error ??= \"No audio/video found\";\n\n return args;\n }\n\n if (defaultSubtitles && Config.Subtitles.Enabled)\n {\n if (Playlist.Selected.ExternalSubtitlesStreams[0] != null)\n Open(Playlist.Selected.ExternalSubtitlesStreams[0]);\n else\n OpenSuggestedSubtitles();\n }\n\n if (Config.Data.Enabled)\n {\n OpenSuggestedData();\n }\n\n LoadPlaylistChapters();\n\n return args;\n } catch (Exception e)\n {\n args.Error = !args.Success ? args.Error + \"\\r\\n\" + e.Message : e.Message;\n return args;\n } finally\n {\n OnOpenPlaylistItemCompleted(args);\n }\n }\n public ExternalStreamOpenedArgs Open(ExternalStream extStream, bool defaultAudio = false, int streamIndex = -1) // -2: None, -1: Suggest, >=0: specified\n {\n ExternalStreamOpenedArgs args = null;\n\n try\n {\n Demuxer demuxer;\n\n if (extStream is ExternalVideoStream)\n {\n args = new OpenExternalVideoStreamCompletedArgs((ExternalVideoStream) extStream, Playlist.Selected.ExternalVideoStream);\n\n if (args.OldExtStream != null)\n args.OldExtStream.Enabled = false;\n\n Playlist.Selected.ExternalVideoStream = (ExternalVideoStream) extStream;\n\n foreach(var plugin in Plugins.Values)\n plugin.OnOpenExternalVideo();\n\n demuxer = VideoDemuxer;\n }\n else if (extStream is ExternalAudioStream)\n {\n args = new OpenExternalAudioStreamCompletedArgs((ExternalAudioStream) extStream, Playlist.Selected.ExternalAudioStream);\n\n if (args.OldExtStream != null)\n args.OldExtStream.Enabled = false;\n\n Playlist.Selected.ExternalAudioStream = (ExternalAudioStream) extStream;\n\n foreach(var plugin in Plugins.Values)\n plugin.OnOpenExternalAudio();\n\n demuxer = AudioDemuxer;\n }\n else\n {\n int i = SubtitlesSelectedHelper.CurIndex;\n args = new OpenExternalSubtitlesStreamCompletedArgs((ExternalSubtitlesStream) extStream, Playlist.Selected.ExternalSubtitlesStreams[i]);\n\n if (args.OldExtStream != null)\n args.OldExtStream.Enabled = false;\n\n Playlist.Selected.ExternalSubtitlesStreams[i] = (ExternalSubtitlesStream) extStream;\n\n if (!Playlist.Selected.ExternalSubtitlesStreams[i].Downloaded)\n DownloadSubtitles(Playlist.Selected.ExternalSubtitlesStreams[i]);\n\n foreach(var plugin in Plugins.Values)\n plugin.OnOpenExternalSubtitles();\n\n demuxer = SubtitlesDemuxers[i];\n }\n\n // Open external stream\n args.Error = OpenDemuxerInput(demuxer, extStream);\n\n if (!args.Success)\n return args;\n\n // Update embedded streams with the external stream pointer\n foreach (var embStream in demuxer.VideoStreams)\n embStream.ExternalStream = extStream;\n foreach (var embStream in demuxer.AudioStreams)\n embStream.ExternalStream = extStream;\n foreach (var embStream in demuxer.SubtitlesStreamsAll)\n {\n embStream.ExternalStream = extStream;\n embStream.ExternalStreamAdded(); // Copies VobSub's .idx file to extradata (based on external url .sub)\n }\n\n // Open embedded stream\n if (streamIndex != -2)\n {\n StreamBase suggestedStream = null;\n if (streamIndex != -1 && (streamIndex >= demuxer.AVStreamToStream.Count || streamIndex < 0 || demuxer.AVStreamToStream[streamIndex].Type != extStream.Type))\n {\n args.Error = $\"Invalid stream index {streamIndex}\";\n demuxer.Dispose();\n return args;\n }\n\n if (demuxer.Type == MediaType.Video)\n suggestedStream = streamIndex == -1 ? SuggestVideo(demuxer.VideoStreams) : demuxer.AVStreamToStream[streamIndex];\n else if (demuxer.Type == MediaType.Audio)\n suggestedStream = streamIndex == -1 ? SuggestAudio(demuxer.AudioStreams) : demuxer.AVStreamToStream[streamIndex];\n else if (demuxer.Type == MediaType.Subs)\n {\n System.Collections.Generic.List langs = Config.Subtitles.Languages.ToList();\n langs.Add(Language.Unknown);\n suggestedStream = streamIndex == -1 ? SuggestSubtitles(demuxer.SubtitlesStreamsAll, langs) : demuxer.AVStreamToStream[streamIndex];\n }\n else\n {\n suggestedStream = demuxer.AVStreamToStream[streamIndex];\n }\n\n if (suggestedStream == null)\n {\n demuxer.Dispose();\n args.Error = \"No embedded streams found\";\n return args;\n }\n\n args.Error = Open(suggestedStream, defaultAudio).Error;\n if (!args.Success)\n return args;\n }\n\n LoadPlaylistChapters();\n\n extStream.Enabled = true;\n\n return args;\n } catch (Exception e)\n {\n args.Error = !args.Success ? args.Error + \"\\r\\n\" + e.Message : e.Message;\n return args;\n } finally\n {\n if (extStream is ExternalVideoStream)\n OnOpenExternalVideoStreamCompleted((OpenExternalVideoStreamCompletedArgs)args);\n else if (extStream is ExternalAudioStream)\n OnOpenExternalAudioStreamCompleted((OpenExternalAudioStreamCompletedArgs)args);\n else\n OnOpenExternalSubtitlesStreamCompleted((OpenExternalSubtitlesStreamCompletedArgs)args);\n }\n }\n\n public StreamOpenedArgs OpenVideoStream(VideoStream stream, bool defaultAudio = true)\n => Open(stream, defaultAudio);\n public StreamOpenedArgs OpenAudioStream(AudioStream stream)\n => Open(stream);\n public StreamOpenedArgs OpenSubtitlesStream(SubtitlesStream stream)\n => Open(stream);\n public StreamOpenedArgs OpenDataStream(DataStream stream)\n => Open(stream);\n private StreamOpenedArgs Open(StreamBase stream, bool defaultAudio = false)\n {\n StreamOpenedArgs args = null;\n\n try\n {\n lock (stream.Demuxer.lockActions)\n lock (stream.Demuxer.lockFmtCtx)\n {\n var oldStream = stream.Type == MediaType.Video ? VideoStream : (stream.Type == MediaType.Audio ? AudioStream : (StreamBase)DataStream);\n if (stream.Type == MediaType.Subs)\n {\n oldStream = SubtitlesStreams[SubtitlesSelectedHelper.CurIndex];\n }\n\n // Close external demuxers when opening embedded\n if (stream.Demuxer.Type == MediaType.Video)\n {\n // TBR: if (stream.Type == MediaType.Video) | We consider that we can't have Embedded and External Video Streams at the same time\n if (stream.Type == MediaType.Audio) // TBR: && VideoStream != null)\n {\n if (!EnableDecoding) AudioDemuxer.Dispose();\n if (Playlist.Selected.ExternalAudioStream != null)\n {\n Playlist.Selected.ExternalAudioStream.Enabled = false;\n Playlist.Selected.ExternalAudioStream = null;\n }\n }\n else if (stream.Type == MediaType.Subs)\n {\n int i = SubtitlesSelectedHelper.CurIndex;\n if (!EnableDecoding) \n SubtitlesDemuxers[i].Dispose();\n\n if (Playlist.Selected.ExternalSubtitlesStreams[i] != null)\n {\n Playlist.Selected.ExternalSubtitlesStreams[i].Enabled = false;\n Playlist.Selected.ExternalSubtitlesStreams[i] = null;\n }\n }\n else if (stream.Type == MediaType.Data)\n {\n if (!EnableDecoding) DataDemuxer.Dispose();\n }\n }\n else if (!EnableDecoding)\n {\n // Disable embeded audio when enabling external audio (TBR)\n if (stream.Demuxer.Type == MediaType.Audio && stream.Type == MediaType.Audio && AudioStream != null && AudioStream.Demuxer.Type == MediaType.Video)\n {\n foreach (var aStream in VideoDemuxer.AudioStreams)\n VideoDemuxer.DisableStream(aStream);\n }\n }\n\n // Open Codec / Enable on demuxer\n if (EnableDecoding)\n {\n string ret = GetDecoderPtr(stream).Open(stream);\n\n if (ret != null)\n {\n return stream.Type == MediaType.Video\n ? (args = new OpenVideoStreamCompletedArgs((VideoStream)stream, (VideoStream)oldStream, $\"Failed to open video stream #{stream.StreamIndex}\\r\\n{ret}\"))\n : stream.Type == MediaType.Audio\n ? (args = new OpenAudioStreamCompletedArgs((AudioStream)stream, (AudioStream)oldStream, $\"Failed to open audio stream #{stream.StreamIndex}\\r\\n{ret}\"))\n : stream.Type == MediaType.Subs\n ? (args = new OpenSubtitlesStreamCompletedArgs((SubtitlesStream)stream, (SubtitlesStream)oldStream, $\"Failed to open subtitles stream #{stream.StreamIndex}\\r\\n{ret}\"))\n : (args = new OpenDataStreamCompletedArgs((DataStream)stream, (DataStream)oldStream, $\"Failed to open data stream #{stream.StreamIndex}\\r\\n{ret}\"));\n }\n }\n else\n stream.Demuxer.EnableStream(stream);\n\n // Open Audio based on new Video Stream (if not the same suggestion)\n if (defaultAudio && stream.Type == MediaType.Video && Config.Audio.Enabled)\n {\n bool requiresChange = true;\n SuggestAudio(out var aStream, out var aExtStream, VideoDemuxer.AudioStreams);\n\n if (AudioStream != null)\n {\n // External audio streams comparison\n if (Playlist.Selected.ExternalAudioStream != null && aExtStream != null && aExtStream.Index == Playlist.Selected.ExternalAudioStream.Index)\n requiresChange = false;\n // Embedded audio streams comparison\n else if (Playlist.Selected.ExternalAudioStream == null && aStream != null && aStream.StreamIndex == AudioStream.StreamIndex)\n requiresChange = false;\n }\n\n if (!requiresChange)\n {\n if (CanDebug) Log.Debug($\"Audio no need to follow video\");\n }\n else\n {\n if (aStream != null)\n Open(aStream);\n else if (aExtStream != null)\n Open(aExtStream);\n\n //RequiresResync = true;\n }\n }\n\n return stream.Type == MediaType.Video\n ? (args = new OpenVideoStreamCompletedArgs((VideoStream)stream, (VideoStream)oldStream))\n : stream.Type == MediaType.Audio\n ? (args = new OpenAudioStreamCompletedArgs((AudioStream)stream, (AudioStream)oldStream))\n : stream.Type == MediaType.Subs\n ? (args = new OpenSubtitlesStreamCompletedArgs((SubtitlesStream)stream, (SubtitlesStream)oldStream))\n : (args = new OpenDataStreamCompletedArgs((DataStream)stream, (DataStream)oldStream));\n }\n } catch(Exception e)\n {\n return args = new StreamOpenedArgs(null, null, e.Message);\n } finally\n {\n if (stream.Type == MediaType.Video)\n OnOpenVideoStreamCompleted((OpenVideoStreamCompletedArgs)args);\n else if (stream.Type == MediaType.Audio)\n OnOpenAudioStreamCompleted((OpenAudioStreamCompletedArgs)args);\n else if (stream.Type == MediaType.Subs)\n OnOpenSubtitlesStreamCompleted((OpenSubtitlesStreamCompletedArgs)args);\n else\n OnOpenDataStreamCompleted((OpenDataStreamCompletedArgs)args);\n }\n }\n\n public string OpenSuggestedVideo(bool defaultAudio = false)\n {\n VideoStream stream;\n ExternalVideoStream extStream;\n string error = null;\n\n if (ClosedVideoStream != null)\n {\n Log.Debug(\"[Video] Found previously closed stream\");\n\n extStream = ClosedVideoStream.Item1;\n if (extStream != null)\n return Open(extStream, false, ClosedVideoStream.Item2 >= 0 ? ClosedVideoStream.Item2 : -1).Error;\n\n stream = ClosedVideoStream.Item2 >= 0 ? (VideoStream)VideoDemuxer.AVStreamToStream[ClosedVideoStream.Item2] : null;\n }\n else\n SuggestVideo(out stream, out extStream, VideoDemuxer.VideoStreams);\n\n if (stream != null)\n error = Open(stream, defaultAudio).Error;\n else if (extStream != null)\n error = Open(extStream, defaultAudio).Error;\n else if (defaultAudio && Config.Audio.Enabled)\n error = OpenSuggestedAudio(); // We still need audio if no video exists\n\n return error;\n }\n public string OpenSuggestedAudio()\n {\n AudioStream stream = null;\n ExternalAudioStream extStream = null;\n string error = null;\n\n if (ClosedAudioStream != null)\n {\n Log.Debug(\"[Audio] Found previously closed stream\");\n\n extStream = ClosedAudioStream.Item1;\n if (extStream != null)\n return Open(extStream, false, ClosedAudioStream.Item2 >= 0 ? ClosedAudioStream.Item2 : -1).Error;\n\n stream = ClosedAudioStream.Item2 >= 0 ? (AudioStream)VideoDemuxer.AVStreamToStream[ClosedAudioStream.Item2] : null;\n }\n else\n SuggestAudio(out stream, out extStream, VideoDemuxer.AudioStreams);\n\n if (stream != null)\n error = Open(stream).Error;\n else if (extStream != null)\n error = Open(extStream).Error;\n\n return error;\n }\n public void OpenSuggestedSubtitles(int? subIndex = -1)\n {\n long sessionId = OpenItemCounter;\n\n try\n {\n // High Suggest (first lang priority + high rating + already converted/downloaded)\n // 1. Check embedded steams for high suggest\n if (Config.Subtitles.Languages.Count > 0)\n {\n foreach (var stream in VideoDemuxer.SubtitlesStreamsAll)\n {\n if (stream.Language == Config.Subtitles.Languages[0])\n {\n Log.Debug(\"[Subtitles] Found high suggested embedded stream\");\n Open(stream);\n return;\n }\n }\n }\n\n // 2. Check external streams for high suggest\n if (Playlist.Selected.ExternalSubtitlesStreamsAll.Count > 0)\n {\n var extStream = SuggestBestExternalSubtitles();\n if (extStream != null)\n {\n Log.Debug(\"[Subtitles] Found high suggested external stream\");\n Open(extStream);\n return;\n }\n }\n\n // 3. Search offline if allowed\n if (SearchLocalSubtitles())\n {\n // 3.1 Check external streams for high suggest (again for the new additions if any)\n ExternalSubtitlesStream extStream = SuggestBestExternalSubtitles();\n if (extStream != null)\n {\n Log.Debug(\"[Subtitles] Found high suggested local external stream\");\n Open(extStream);\n return;\n }\n }\n\n } catch (Exception e)\n {\n Log.Debug($\"OpenSuggestedSubtitles canceled? [{e.Message}]\");\n return;\n }\n\n Task.Run(() =>\n {\n try\n {\n if (sessionId != OpenItemCounter)\n {\n Log.Debug(\"OpenSuggestedSubtitles canceled\");\n return;\n }\n\n if (sessionId != OpenItemCounter)\n {\n Log.Debug(\"OpenSuggestedSubtitles canceled\");\n return;\n }\n\n // 4. Search online if allowed (not async)\n SearchOnlineSubtitles();\n\n if (sessionId != OpenItemCounter)\n {\n Log.Debug(\"OpenSuggestedSubtitles canceled\");\n return;\n }\n\n // 5. (Any) Check embedded/external streams for config languages (including 'undefined')\n SuggestSubtitles(out var stream, out ExternalSubtitlesStream extStream);\n\n if (stream != null)\n Open(stream);\n else if (extStream != null)\n Open(extStream);\n } catch (Exception e)\n {\n Log.Debug($\"OpenSuggestedSubtitles canceled? [{e.Message}]\");\n }\n });\n }\n public string OpenSuggestedData()\n {\n DataStream stream;\n string error = null;\n\n SuggestData(out stream, VideoDemuxer.DataStreams);\n\n if (stream != null)\n error = Open(stream).Error;\n\n return error;\n }\n\n public string OpenDemuxerInput(Demuxer demuxer, DemuxerInput demuxerInput)\n {\n OpenedPlugin?.OnBuffering();\n\n string error = null;\n\n Dictionary formatOpt = null;\n Dictionary copied = null;\n\n try\n {\n // Set HTTP Config\n if (Playlist.InputType == InputType.Web)\n {\n formatOpt = Config.Demuxer.GetFormatOptPtr(demuxer.Type);\n copied = new Dictionary();\n\n foreach (var opt in formatOpt)\n copied.Add(opt.Key, opt.Value);\n\n if (demuxerInput.UserAgent != null)\n formatOpt[\"user_agent\"] = demuxerInput.UserAgent;\n\n if (demuxerInput.Referrer != null)\n formatOpt[\"referer\"] = demuxerInput.Referrer;\n\n // this can cause issues\n //else if (!formatOpt.ContainsKey(\"referer\") && Playlist.Url != null)\n // formatOpt[\"referer\"] = Playlist.Url;\n\n if (demuxerInput.HTTPHeaders != null)\n {\n formatOpt[\"headers\"] = \"\";\n foreach(var header in demuxerInput.HTTPHeaders)\n formatOpt[\"headers\"] += header.Key + \": \" + header.Value + \"\\r\\n\";\n }\n }\n\n // Open Demuxer Input\n if (demuxerInput.Url != null)\n {\n error = demuxer.Open(demuxerInput.Url);\n\n if (error != null && !string.IsNullOrEmpty(demuxerInput.UrlFallback))\n {\n Log.Warn($\"Fallback to {demuxerInput.UrlFallback}\");\n error = demuxer.Open(demuxerInput.UrlFallback);\n }\n }\n else if (demuxerInput.IOStream != null)\n error = demuxer.Open(demuxerInput.IOStream);\n\n return error;\n } finally\n {\n // Restore HTTP Config\n if (Playlist.InputType == InputType.Web)\n {\n formatOpt.Clear();\n foreach(var opt in copied)\n formatOpt.Add(opt.Key, opt.Value);\n }\n\n OpenedPlugin?.OnBufferingCompleted();\n }\n }\n\n private void LoadPlaylistChapters()\n {\n if (Playlist.Selected != null && Playlist.Selected.Chapters.Count > 0 && MainDemuxer.Chapters.Count == 0)\n {\n foreach (var chapter in Playlist.Selected.Chapters)\n {\n MainDemuxer.Chapters.Add(chapter);\n }\n }\n }\n #endregion\n\n #region Close (Only For EnableDecoding)\n public void CloseAudio()\n {\n ClosedAudioStream = new Tuple(Playlist.Selected.ExternalAudioStream, AudioStream != null ? AudioStream.StreamIndex : -1);\n\n if (Playlist.Selected.ExternalAudioStream != null)\n {\n Playlist.Selected.ExternalAudioStream.Enabled = false;\n Playlist.Selected.ExternalAudioStream = null;\n }\n\n AudioDecoder.Dispose(true);\n }\n public void CloseVideo()\n {\n ClosedVideoStream = new Tuple(Playlist.Selected.ExternalVideoStream, VideoStream != null ? VideoStream.StreamIndex : -1);\n\n if (Playlist.Selected.ExternalVideoStream != null)\n {\n Playlist.Selected.ExternalVideoStream.Enabled = false;\n Playlist.Selected.ExternalVideoStream = null;\n }\n\n VideoDecoder.Dispose(true);\n VideoDecoder.Renderer?.ClearScreen();\n }\n public void CloseSubtitles(int subIndex)\n {\n if (Playlist.Selected.ExternalSubtitlesStreams[subIndex] != null)\n {\n Playlist.Selected.ExternalSubtitlesStreams[subIndex].Enabled = false;\n Playlist.Selected.ExternalSubtitlesStreams[subIndex] = null;\n }\n\n SubtitlesDecoders[subIndex].Dispose(true);\n }\n public void CloseData()\n {\n DataDecoder.Dispose(true);\n }\n #endregion\n}\n"], ["/LLPlayer/FlyleafLib/Plugins/OpenDefault.cs", "using System;\nusing System.IO;\n\nusing FlyleafLib.MediaFramework.MediaPlaylist;\n\nnamespace FlyleafLib.Plugins;\n\npublic class OpenDefault : PluginBase, IOpen, IScrapeItem\n{\n /* TODO\n *\n * 1) Current Url Syntax issues\n * ..\\..\\..\\..\\folder\\file.mp3 | Cannot handle this\n * file:///C:/folder/fi%20le.mp3 | FFmpeg & File.Exists cannot handle this\n *\n */\n\n public new int Priority { get; set; } = 3000;\n\n public bool CanOpen() => true;\n\n public OpenResults Open()\n {\n try\n {\n if (Playlist.IOStream != null)\n {\n AddPlaylistItem(new()\n {\n IOStream= Playlist.IOStream,\n Title = \"Custom IO Stream\",\n FileSize= Playlist.IOStream.Length\n });\n\n Handler.OnPlaylistCompleted();\n\n return new();\n }\n\n // Proper Url Format\n string scheme;\n bool isWeb = false;\n string uriType = \"\";\n string ext = Utils.GetUrlExtention(Playlist.Url);\n string localPath= null;\n\n try\n {\n Uri uri = new(Playlist.Url);\n scheme = uri.Scheme.ToLower();\n isWeb = scheme.StartsWith(\"http\");\n uriType = uri.IsFile ? \"file\" : (uri.IsUnc ? \"unc\" : \"\");\n localPath = uri.LocalPath;\n } catch { }\n\n\n // Playlists (M3U, M3U8, PLS | TODO: WPL, XSPF)\n if (ext == \"m3u\")// || ext == \"m3u8\")\n {\n Playlist.InputType = InputType.Web; // TBR: Can be mixed\n Playlist.FolderBase = Path.GetTempPath();\n\n var items = isWeb ? M3UPlaylist.ParseFromHttp(Playlist.Url) : M3UPlaylist.Parse(Playlist.Url);\n\n foreach(var mitem in items)\n {\n AddPlaylistItem(new()\n {\n Title = mitem.Title,\n Url = mitem.Url,\n DirectUrl = mitem.Url,\n UserAgent = mitem.UserAgent,\n Referrer = mitem.Referrer\n });\n }\n\n Handler.OnPlaylistCompleted();\n\n return new();\n }\n else if (ext == \"pls\")\n {\n Playlist.InputType = InputType.Web; // TBR: Can be mixed\n Playlist.FolderBase = Path.GetTempPath();\n\n var items = PLSPlaylist.Parse(Playlist.Url);\n\n foreach(var mitem in items)\n {\n AddPlaylistItem(new PlaylistItem()\n {\n Title = mitem.Title,\n Url = mitem.Url,\n DirectUrl = mitem.Url,\n // Duration\n });\n }\n\n Handler.OnPlaylistCompleted();\n\n return new();\n }\n\n FileInfo fi = null;\n // Single Playlist Item\n if (uriType == \"file\")\n {\n Playlist.InputType = InputType.File;\n if (File.Exists(Playlist.Url))\n {\n fi = new(Playlist.Url);\n Playlist.FolderBase = fi.DirectoryName;\n }\n }\n else if (isWeb)\n {\n Playlist.InputType = InputType.Web;\n Playlist.FolderBase = Path.GetTempPath();\n }\n else if (uriType == \"unc\")\n {\n Playlist.InputType = InputType.UNC;\n Playlist.FolderBase = Path.GetTempPath();\n }\n else\n {\n //Playlist.InputType = InputType.Unknown;\n Playlist.FolderBase = Path.GetTempPath();\n }\n\n PlaylistItem item = new()\n {\n Url = Playlist.Url,\n DirectUrl = Playlist.Url\n };\n\n if (fi == null && File.Exists(Playlist.Url))\n {\n fi = new(Playlist.Url);\n item.Title = fi.Name;\n item.FileSize = fi.Length;\n }\n else\n {\n if (localPath != null)\n item.Title = Path.GetFileName(localPath);\n\n if (item.Title == null || item.Title.Trim().Length == 0)\n item.Title = Playlist.Url;\n }\n\n AddPlaylistItem(item);\n Handler.OnPlaylistCompleted();\n\n return new();\n } catch (Exception e)\n {\n return new(e.Message);\n }\n }\n\n public OpenResults OpenItem() => new();\n\n public void ScrapeItem(PlaylistItem item)\n {\n // Update Title (TBR: don't mess with other media types - only movies/tv shows)\n if (Playlist.InputType != InputType.File && Playlist.InputType != InputType.UNC && Playlist.InputType != InputType.Torrent)\n return;\n\n item.FillMediaParts();\n }\n}\n"], ["/LLPlayer/FlyleafLib/MediaPlayer/Player.Playback.cs", "using System;\nusing System.Runtime.InteropServices;\nusing System.Threading;\nusing System.Threading.Tasks;\nusing System.Windows;\nusing System.Windows.Media;\nusing System.Windows.Media.Imaging;\nusing FlyleafLib.MediaFramework.MediaDecoder;\nusing FlyleafLib.MediaFramework.MediaFrame;\nusing static FlyleafLib.Utils;\nusing static FlyleafLib.Logger;\n\nnamespace FlyleafLib.MediaPlayer;\n\npartial class Player\n{\n string stoppedWithError = null;\n\n /// \n /// Fires on playback stopped by an error or completed / ended successfully \n /// Warning: Uses Invoke and it comes from playback thread so you can't pause/stop etc. You need to use another thread if you have to.\n /// \n public event EventHandler PlaybackStopped;\n protected virtual void OnPlaybackStopped(string error = null)\n {\n if (error != null && LastError == null)\n {\n lastError = error;\n UI(() => LastError = LastError);\n }\n\n PlaybackStopped?.Invoke(this, new PlaybackStoppedArgs(error));\n }\n\n /// \n /// Fires on seek completed for the specified ms (ms will be -1 on failure)\n /// \n public event EventHandler SeekCompleted;\n\n /// \n /// Plays AVS streams\n /// \n public void Play()\n {\n lock (lockActions)\n {\n if (!CanPlay || Status == Status.Playing || Status == Status.Ended)\n return;\n\n status = Status.Playing;\n UI(() => Status = Status);\n }\n\n while (taskPlayRuns || taskSeekRuns) Thread.Sleep(5);\n taskPlayRuns = true;\n\n Thread t = new(() =>\n {\n try\n {\n Engine.TimeBeginPeriod1();\n NativeMethods.SetThreadExecutionState(NativeMethods.EXECUTION_STATE.ES_CONTINUOUS | NativeMethods.EXECUTION_STATE.ES_SYSTEM_REQUIRED | NativeMethods.EXECUTION_STATE.ES_DISPLAY_REQUIRED);\n\n onBufferingStarted = 0;\n onBufferingCompleted = 0;\n requiresBuffering = true;\n\n if (LastError != null)\n {\n lastError = null;\n UI(() => LastError = LastError);\n }\n\n if (Config.Player.Usage == Usage.Audio || !Video.IsOpened)\n ScreamerAudioOnly();\n else\n {\n if (ReversePlayback)\n {\n shouldFlushNext = true;\n ScreamerReverse();\n }\n else\n {\n shouldFlushPrev = true;\n Screamer();\n }\n\n }\n\n }\n catch (Exception ex)\n {\n Log.Error($\"Playback failed ({ex.Message})\");\n RaiseUnknownErrorOccurred($\"Playback failed: {ex.Message}\", UnknownErrorType.Playback, ex);\n }\n finally\n {\n VideoDecoder.DisposeFrame(vFrame);\n vFrame = null;\n for (int i = 0; i < subNum; i++)\n {\n sFrames[i] = null;\n }\n\n if (Status == Status.Stopped)\n decoder?.Initialize();\n else if (decoder != null)\n {\n decoder.PauseOnQueueFull();\n decoder.PauseDecoders();\n }\n\n Audio.ClearBuffer();\n Engine.TimeEndPeriod1();\n NativeMethods.SetThreadExecutionState(NativeMethods.EXECUTION_STATE.ES_CONTINUOUS);\n stoppedWithError = null;\n\n if (IsPlaying)\n {\n if (decoderHasEnded)\n status = Status.Ended;\n else\n {\n if (Video.IsOpened && VideoDemuxer.Interrupter.Timedout)\n stoppedWithError = \"Timeout\";\n else if (onBufferingStarted - 1 == onBufferingCompleted)\n {\n stoppedWithError = \"Playback stopped unexpectedly\";\n OnBufferingCompleted(\"Buffering failed\");\n }\n else\n {\n if (!ReversePlayback)\n {\n if (isLive || Math.Abs(Duration - CurTime) > 3 * 1000 * 10000)\n stoppedWithError = \"Playback stopped unexpectedly\";\n }\n else if (CurTime > 3 * 1000 * 10000)\n stoppedWithError = \"Playback stopped unexpectedly\";\n }\n\n status = Status.Paused;\n }\n }\n\n OnPlaybackStopped(stoppedWithError);\n if (CanDebug) Log.Debug($\"[SCREAMER] Finished (Status: {Status}, Error: {stoppedWithError})\");\n\n UI(() =>\n {\n Status = Status;\n UpdateCurTime();\n });\n\n taskPlayRuns = false;\n }\n });\n t.Priority = Config.Player.ThreadPriority;\n t.Name = $\"[#{PlayerId}] Playback\";\n t.IsBackground = true;\n t.Start();\n }\n\n /// \n /// Pauses AVS streams\n /// \n public void Pause()\n {\n lock (lockActions)\n {\n if (!CanPlay || Status == Status.Ended)\n return;\n\n status = Status.Paused;\n UI(() => Status = Status);\n\n while (taskPlayRuns) Thread.Sleep(5);\n }\n }\n\n public void TogglePlayPause()\n {\n if (IsPlaying)\n Pause();\n else\n Play();\n }\n\n public void ToggleReversePlayback()\n => ReversePlayback = !ReversePlayback;\n\n public void ToggleLoopPlayback()\n => LoopPlayback = !LoopPlayback;\n\n /// \n /// Seeks backwards or forwards based on the specified ms to the nearest keyframe\n /// \n /// \n /// \n public void Seek(int ms, bool forward = false) => Seek(ms, forward, false);\n\n /// \n /// Seeks at the exact timestamp (with half frame distance accuracy)\n /// \n /// \n /// \n public void SeekAccurate(TimeSpan time, int subIndex = -1)\n {\n int ms = (int)time.TotalMilliseconds;\n if (subIndex != -1 && time.Microseconds > 0)\n {\n // When seeking subtitles, rounding down the milliseconds or less will cause the previous subtitle\n // ASR subtitles are in microseconds, so if you truncate, you'll end up one before the current subtitle.\n ms += 1;\n }\n\n SeekAccurate(ms, subIndex);\n }\n\n /// \n /// Seeks at the exact timestamp (with half frame distance accuracy)\n /// \n /// \n /// \n public void SeekAccurate(int ms, int subIndex = -1)\n {\n if (subIndex >= 0)\n {\n ms += (int)(Config.Subtitles[subIndex].Delay / 10000);\n }\n\n Seek(ms, false, !IsLive);\n }\n\n public void ToggleSeekAccurate()\n => Config.Player.SeekAccurate = !Config.Player.SeekAccurate;\n\n private void Seek(int ms, bool forward, bool accurate)\n {\n if (!CanPlay)\n return;\n\n lock (seeks)\n {\n _CurTime = curTime = ms * (long)10000;\n seeks.Push(new SeekData(ms, forward, accurate));\n }\n\n // Set timestamp to Manager immediately after seek to enable continuous seek\n // (Without this, seek is called with the same timestamp on successive calls, so it will seek to the same subtitle.)\n SubtitlesManager.SetCurrentTime(new TimeSpan(curTime));\n\n Raise(nameof(CurTime));\n Raise(nameof(RemainingDuration));\n\n if (Status == Status.Playing)\n return;\n\n lock (seeks)\n {\n if (taskSeekRuns)\n return;\n\n taskSeekRuns = true;\n }\n\n Task.Run(() =>\n {\n int ret;\n bool wasEnded = false;\n SeekData seekData = null;\n\n try\n {\n Engine.TimeBeginPeriod1();\n\n while (true)\n {\n lock (seeks)\n {\n if (!(seeks.TryPop(out seekData) && CanPlay && !IsPlaying))\n {\n taskSeekRuns = false;\n break;\n }\n\n seeks.Clear();\n }\n\n if (Status == Status.Ended)\n {\n wasEnded = true;\n status = Status.Paused;\n UI(() => Status = Status);\n }\n\n for (int i = 0; i < subNum; i++)\n {\n // Display subtitles from cache when seeking while paused\n bool display = false;\n var cur = SubtitlesManager[i].GetCurrent();\n if (cur != null)\n {\n if (!string.IsNullOrEmpty(cur.DisplayText))\n {\n SubtitleDisplay(cur.DisplayText, i, cur.UseTranslated);\n display = true;\n }\n else if (cur.IsBitmap && cur.Bitmap != null)\n {\n SubtitleDisplay(cur.Bitmap, i);\n display = true;\n }\n\n if (display)\n {\n sFramesPrev[i] = new SubtitlesFrame\n {\n timestamp = cur.StartTime.Ticks + Config.Subtitles[i].Delay,\n duration = (uint)cur.Duration.TotalMilliseconds,\n isTranslated = cur.UseTranslated\n };\n }\n }\n\n // clear subtitles\n // but do not clear when cache hit\n if (!display && sFramesPrev[i] != null)\n {\n sFramesPrev[i] = null;\n SubtitleClear(i);\n }\n }\n\n if (!Video.IsOpened)\n {\n if (AudioDecoder.OnVideoDemuxer)\n {\n ret = decoder.Seek(seekData.ms, seekData.forward);\n if (CanWarn && ret < 0)\n Log.Warn(\"Seek failed 2\");\n\n VideoDemuxer.Start();\n SeekCompleted?.Invoke(this, -1);\n }\n else\n {\n ret = decoder.SeekAudio(seekData.ms, seekData.forward);\n if (CanWarn && ret < 0)\n Log.Warn(\"Seek failed 3\");\n\n AudioDemuxer.Start();\n SeekCompleted?.Invoke(this, -1);\n }\n\n decoder.PauseOnQueueFull();\n SeekCompleted?.Invoke(this, seekData.ms);\n }\n else\n {\n decoder.PauseDecoders();\n ret = decoder.Seek(seekData.accurate ? Math.Max(0, seekData.ms - (int) new TimeSpan(Config.Player.SeekAccurateFixMargin).TotalMilliseconds) : seekData.ms, seekData.forward, !seekData.accurate); // 3sec ffmpeg bug for seek accurate when fails to seek backwards (see videodecoder getframe)\n if (ret < 0)\n {\n if (CanWarn) Log.Warn(\"Seek failed\");\n SeekCompleted?.Invoke(this, -1);\n }\n else if (!ReversePlayback && CanPlay)\n {\n decoder.GetVideoFrame(seekData.accurate ? seekData.ms * (long)10000 : -1);\n ShowOneFrame();\n VideoDemuxer.Start();\n AudioDemuxer.Start();\n //for (int i = 0; i < subNum; i++)\n //{\n // SubtitlesDemuxers[i].Start();\n //}\n DataDemuxer.Start();\n decoder.PauseOnQueueFull();\n SeekCompleted?.Invoke(this, seekData.ms);\n }\n }\n\n Thread.Sleep(20);\n }\n }\n catch (Exception e)\n {\n lock (seeks) taskSeekRuns = false;\n Log.Error($\"Seek failed ({e.Message})\");\n }\n finally\n {\n decoder.OpenedPlugin?.OnBufferingCompleted();\n Engine.TimeEndPeriod1();\n if ((wasEnded && Config.Player.AutoPlay) || stoppedWithError != null) // TBR: Possible race condition with if (Status == Status.Playing)\n Play();\n }\n });\n }\n\n /// \n /// Flushes the buffer (demuxers (packets) and decoders (frames))\n /// This is useful mainly for live streams to push the playback at very end (low latency)\n /// \n public void Flush()\n {\n decoder.Flush();\n OSDMessage = \"Buffer Flushed\";\n }\n\n /// \n /// Stops and Closes AVS streams\n /// \n public void Stop()\n {\n lock (lockActions)\n {\n Initialize();\n renderer?.Flush();\n }\n }\n public void SubtitleClear()\n {\n for (int i = 0; i < subNum; i++)\n {\n SubtitleClear(i);\n }\n }\n\n public void SubtitleClear(int subIndex)\n {\n Subtitles[subIndex].Data.Clear();\n //renderer.ClearOverlayTexture();\n }\n\n /// \n /// Updated text format subtitle display\n /// \n /// \n /// \n /// \n public void SubtitleDisplay(string text, int subIndex, bool isTranslated)\n {\n UI(() =>\n {\n Subtitles[subIndex].Data.IsTranslated = isTranslated;\n Subtitles[subIndex].Data.Language = isTranslated\n ? Config.Subtitles.TranslateLanguage\n : SubtitlesManager[subIndex].Language;\n\n Subtitles[subIndex].Data.Text = text;\n Subtitles[subIndex].Data.Bitmap = null;\n });\n }\n\n public void SubtitleDisplay(SubtitleBitmapData bitmapData, int subIndex)\n {\n if (bitmapData.Sub.num_rects == 0)\n {\n return;\n }\n\n (byte[] data, AVSubtitleRect rect) = bitmapData.SubToBitmap(false);\n\n SubtitlesFrameBitmap bitmap = new()\n {\n data = data,\n width = rect.w,\n height = rect.h,\n x = rect.x,\n y = rect.y,\n };\n\n SubtitleDisplay(bitmap, subIndex);\n }\n\n /// \n /// Update bitmap format subtitle display\n /// \n /// \n /// \n public void SubtitleDisplay(SubtitlesFrameBitmap bitmap, int subIndex)\n {\n // TODO: L: refactor\n\n // Each subtitle has a different size and needs to be generated each time.\n WriteableBitmap wb = new(\n bitmap.width, bitmap.height,\n NativeMethods.DpiXSource, NativeMethods.DpiYSource,\n PixelFormats.Bgra32, null\n );\n Int32Rect rect = new(0, 0, bitmap.width, bitmap.height);\n wb.Lock();\n\n Marshal.Copy(bitmap.data, 0, wb.BackBuffer, bitmap.data.Length);\n\n wb.AddDirtyRect(rect);\n wb.Unlock();\n // Note that you will get a UI thread error if you don't call\n wb.Freeze();\n\n int x = bitmap.x;\n int y = bitmap.y;\n int w = bitmap.width;\n int h = bitmap.height;\n\n SubsBitmap subsBitmap = new()\n {\n X = x,\n Y = y,\n Width = w,\n Height = h,\n Source = wb,\n };\n\n UI(() =>\n {\n Subtitles[subIndex].Data.Bitmap = subsBitmap;\n Subtitles[subIndex].Data.Text = \"\";\n });\n }\n}\n\npublic class PlaybackStoppedArgs : EventArgs\n{\n public string Error { get; }\n public bool Success { get; }\n\n public PlaybackStoppedArgs(string error)\n {\n Error = error;\n Success = Error == null;\n }\n}\n\nclass SeekData\n{\n public int ms;\n public bool forward;\n public bool accurate;\n public SeekData(int ms, bool forward, bool accurate)\n { this.ms = ms; this.forward = forward && !accurate; this.accurate = accurate; }\n}\n"], ["/LLPlayer/FlyleafLib/MediaPlayer/Player.cs", "using System;\nusing System.Collections.Concurrent;\nusing System.Collections.Generic;\nusing System.Collections.ObjectModel;\nusing System.Threading;\n\nusing FlyleafLib.Controls;\nusing FlyleafLib.MediaFramework.MediaContext;\nusing FlyleafLib.MediaFramework.MediaDecoder;\nusing FlyleafLib.MediaFramework.MediaFrame;\nusing FlyleafLib.MediaFramework.MediaRenderer;\nusing FlyleafLib.MediaFramework.MediaPlaylist;\nusing FlyleafLib.MediaFramework.MediaDemuxer;\n\nusing static FlyleafLib.Utils;\nusing static FlyleafLib.Logger;\n\nnamespace FlyleafLib.MediaPlayer;\n\npublic unsafe partial class Player : NotifyPropertyChanged, IDisposable\n{\n #region Properties\n public bool IsDisposed { get; private set; }\n\n /// \n /// FlyleafHost (WinForms, WPF or WinUI)\n /// \n public IHostPlayer Host { get => _Host; set => Set(ref _Host, value); }\n IHostPlayer _Host;\n\n /// \n /// Player's Activity (Idle/Active/FullActive)\n /// \n public Activity Activity { get; private set; }\n\n /// \n /// Helper ICommands for WPF MVVM\n /// \n public Commands Commands { get; private set; }\n\n public Playlist Playlist => decoder.Playlist;\n\n /// \n /// Player's Audio (In/Out)\n /// \n public Audio Audio { get; private set; }\n\n /// \n /// Player's Video\n /// \n public Video Video { get; private set; }\n\n /// \n /// Player's Subtitles\n /// \n public Subtitles Subtitles { get; private set; }\n\n /// \n /// Player's Data\n /// \n public Data Data { get; private set; }\n\n /// \n /// Player's Renderer\n /// (Normally you should not access this directly)\n /// \n public Renderer renderer => decoder.VideoDecoder.Renderer;\n\n /// \n /// Player's Decoder Context\n /// (Normally you should not access this directly)\n /// \n public DecoderContext decoder { get; private set; }\n\n /// \n /// Audio Decoder\n /// (Normally you should not access this directly)\n /// \n public AudioDecoder AudioDecoder => decoder.AudioDecoder;\n\n /// \n /// Video Decoder\n /// (Normally you should not access this directly)\n /// \n public VideoDecoder VideoDecoder => decoder.VideoDecoder;\n\n /// \n /// Subtitles Decoder\n /// (Normally you should not access this directly)\n /// \n public SubtitlesDecoder[] SubtitlesDecoders => decoder.SubtitlesDecoders;\n\n /// \n /// Data Decoder\n /// (Normally you should not access this directly)\n /// \n public DataDecoder DataDecoder => decoder.DataDecoder;\n\n /// \n /// Main Demuxer (if video disabled or audio only can be AudioDemuxer instead of VideoDemuxer)\n /// (Normally you should not access this directly)\n /// \n public Demuxer MainDemuxer => decoder.MainDemuxer;\n\n /// \n /// Audio Demuxer\n /// (Normally you should not access this directly)\n /// \n public Demuxer AudioDemuxer => decoder.AudioDemuxer;\n\n /// \n /// Video Demuxer\n /// (Normally you should not access this directly)\n /// \n public Demuxer VideoDemuxer => decoder.VideoDemuxer;\n\n /// \n /// Subtitles Demuxer\n /// (Normally you should not access this directly)\n /// \n public Demuxer[] SubtitlesDemuxers => decoder.SubtitlesDemuxers;\n\n /// \n /// Subtitles Manager\n /// \n public SubtitlesManager SubtitlesManager => decoder.SubtitlesManager;\n\n /// \n /// Subtitles OCR\n /// \n public SubtitlesOCR SubtitlesOCR => decoder.SubtitlesOCR;\n\n /// \n /// Subtitles ASR\n /// \n public SubtitlesASR SubtitlesASR => decoder.SubtitlesASR;\n\n /// \n /// Data Demuxer\n /// (Normally you should not access this directly)\n /// \n public Demuxer DataDemuxer => decoder.DataDemuxer;\n\n\n /// \n /// Player's incremental unique id\n /// \n public int PlayerId { get; private set; }\n\n /// \n /// Player's configuration (set once in the constructor)\n /// \n public Config Config { get; protected set; }\n\n /// \n /// Player's Status\n /// \n public Status Status\n {\n get => status;\n private set\n {\n var prev = _Status;\n\n if (Set(ref _Status, value))\n {\n // Loop Playback\n if (value == Status.Ended)\n {\n if (LoopPlayback && !ReversePlayback)\n {\n int seekMs = (int)(MainDemuxer.StartTime == 0 ? 0 : MainDemuxer.StartTime / 10000);\n Seek(seekMs);\n }\n }\n\n if (prev == Status.Opening || value == Status.Opening)\n {\n Raise(nameof(IsOpening));\n }\n }\n }\n }\n\n Status _Status = Status.Stopped, status = Status.Stopped;\n public bool IsPlaying => status == Status.Playing;\n public bool IsOpening => status == Status.Opening;\n\n /// \n /// Whether the player's status is capable of accepting playback commands\n /// \n public bool CanPlay { get => canPlay; internal set => Set(ref _CanPlay, value); }\n internal bool _CanPlay, canPlay;\n\n /// \n /// The list of chapters\n /// \n public ObservableCollection\n Chapters => VideoDemuxer?.Chapters;\n\n /// \n /// Player's current time or user's current seek time (uses backward direction or accurate seek based on Config.Player.SeekAccurate)\n /// \n public long CurTime { get => curTime; set { if (Config.Player.SeekAccurate) SeekAccurate((int) (value/10000)); else Seek((int) (value/10000), false); } } // Note: forward seeking casues issues to some formats and can have serious delays (eg. dash with h264, dash with vp9 works fine)\n long _CurTime, curTime;\n internal void UpdateCurTime()\n {\n lock (seeks)\n {\n if (MainDemuxer == null || !seeks.IsEmpty)\n return;\n\n if (MainDemuxer.IsHLSLive)\n {\n curTime = MainDemuxer.CurTime; // *speed ?\n duration = MainDemuxer.Duration;\n Duration = Duration;\n }\n }\n\n if (Set(ref _CurTime, curTime, true, nameof(CurTime)))\n {\n Raise(nameof(RemainingDuration));\n }\n\n UpdateBufferedDuration();\n }\n internal void UpdateBufferedDuration()\n {\n if (_BufferedDuration != MainDemuxer.BufferedDuration)\n {\n _BufferedDuration = MainDemuxer.BufferedDuration;\n Raise(nameof(BufferedDuration));\n }\n }\n\n public long RemainingDuration => Duration - CurTime;\n\n /// \n /// Input's duration\n /// \n public long Duration\n {\n get => duration;\n private set\n {\n if (Set(ref _Duration, value))\n {\n Raise(nameof(RemainingDuration));\n }\n }\n }\n long _Duration, duration;\n\n /// \n /// Forces Player's and Demuxer's Duration to allow Seek\n /// \n /// Duration (Ticks)\n /// Demuxer must be opened before forcing the duration\n public void ForceDuration(long duration)\n {\n if (MainDemuxer == null)\n throw new ArgumentNullException(nameof(MainDemuxer));\n\n this.duration = duration;\n MainDemuxer.ForceDuration(duration);\n isLive = MainDemuxer.IsLive;\n UI(() =>\n {\n Duration= Duration;\n IsLive = IsLive;\n });\n }\n\n /// \n /// The current buffered duration in the demuxer\n /// \n public long BufferedDuration { get => MainDemuxer == null ? 0 : MainDemuxer.BufferedDuration;\n internal set => Set(ref _BufferedDuration, value); }\n long _BufferedDuration;\n\n /// \n /// Whether the input is live (duration might not be 0 on live sessions to allow live seek, eg. hls)\n /// \n public bool IsLive { get => isLive; private set => Set(ref _IsLive, value); }\n bool _IsLive, isLive;\n\n ///// \n ///// Total bitrate (Kbps)\n ///// \n public double BitRate { get => bitRate; internal set => Set(ref _BitRate, value); }\n internal double _BitRate, bitRate;\n\n /// \n /// Whether the player is recording\n /// \n public bool IsRecording\n {\n get => decoder != null && decoder.IsRecording;\n private set { if (_IsRecording == value) return; _IsRecording = value; UI(() => Set(ref _IsRecording, value, false)); }\n }\n bool _IsRecording;\n\n /// \n /// Pan X Offset to change the X location\n /// \n public int PanXOffset { get => renderer.PanXOffset; set { renderer.PanXOffset = value; Raise(nameof(PanXOffset)); } }\n\n /// \n /// Pan Y Offset to change the Y location\n /// \n public int PanYOffset { get => renderer.PanYOffset; set { renderer.PanYOffset = value; Raise(nameof(PanYOffset)); } }\n\n /// \n /// Playback's speed (x1 - x4)\n /// \n public double Speed {\n get => speed;\n set\n {\n double newValue = Math.Round(value, 3);\n if (value < 0.125)\n newValue = 0.125;\n else if (value > 16)\n newValue = 16;\n\n if (newValue == speed)\n return;\n\n AudioDecoder.Speed = newValue;\n VideoDecoder.Speed = newValue;\n speed = newValue;\n decoder.RequiresResync = true;\n requiresBuffering = true;\n for (int i = 0; i < subNum; i++)\n {\n sFramesPrev[i] = null;\n }\n SubtitleClear();\n UI(() =>\n {\n Raise(nameof(Speed));\n });\n }\n }\n double speed = 1;\n\n /// \n /// Pan zoom percentage (100 for 100%)\n /// \n public int Zoom\n {\n get => (int)(renderer.Zoom * 100);\n set { renderer.SetZoom(renderer.Zoom = value / 100.0); RaiseUI(nameof(Zoom)); }\n //set { renderer.SetZoomAndCenter(renderer.Zoom = value / 100.0, Renderer.ZoomCenterPoint); RaiseUI(nameof(Zoom)); } // should reset the zoom center point?\n }\n\n /// \n /// Pan rotation angle (for D3D11 VP allowed values are 0, 90, 180, 270 only)\n /// \n public uint Rotation { get => renderer.Rotation;\n set\n {\n renderer.Rotation = value;\n RaiseUI(nameof(Rotation));\n }\n }\n\n /// \n /// Pan Horizontal Flip (FlyleafVP only)\n /// \n public bool HFlip { get => renderer.HFlip; set => renderer.HFlip = value; }\n\n /// \n /// Pan Vertical Flip (FlyleafVP only)\n /// \n public bool VFlip { get => renderer.VFlip; set => renderer.VFlip = value; }\n\n /// \n /// Whether to use reverse playback mode\n /// \n public bool ReversePlayback\n {\n get => _ReversePlayback;\n\n set\n {\n if (_ReversePlayback == value)\n return;\n\n _ReversePlayback = value;\n UI(() => Set(ref _ReversePlayback, value, false));\n\n if (!Video.IsOpened || !CanPlay | IsLive)\n return;\n\n lock (lockActions)\n {\n bool shouldPlay = IsPlaying || (Status == Status.Ended && Config.Player.AutoPlay);\n Pause();\n dFrame = null;\n\n for (int i = 0; i < subNum; i++)\n {\n sFrames[i] = null;\n SubtitleClear(i);\n }\n\n decoder.StopThreads();\n decoder.Flush();\n\n if (Status == Status.Ended)\n {\n status = Status.Paused;\n UI(() => Status = Status);\n }\n\n if (value)\n {\n Speed = 1;\n VideoDemuxer.EnableReversePlayback(CurTime);\n }\n else\n {\n VideoDemuxer.DisableReversePlayback();\n\n var vFrame = VideoDecoder.GetFrame(VideoDecoder.GetFrameNumber(CurTime));\n VideoDecoder.DisposeFrame(vFrame);\n vFrame = null;\n decoder.RequiresResync = true;\n }\n\n reversePlaybackResync = false;\n if (shouldPlay) Play();\n }\n }\n }\n bool _ReversePlayback;\n\n public bool LoopPlayback { get; set => Set(ref field, value); }\n\n public object Tag { get => tag; set => Set(ref tag, value); }\n object tag;\n\n public string LastError { get => lastError; set => Set(ref _LastError, value); }\n string _LastError, lastError;\n\n public string OSDMessage { get; set => Set(ref field, value, false); }\n\n public event EventHandler KnownErrorOccurred;\n public event EventHandler UnknownErrorOccurred;\n\n bool decoderHasEnded => decoder != null && (VideoDecoder.Status == MediaFramework.Status.Ended || (VideoDecoder.Disposed && AudioDecoder.Status == MediaFramework.Status.Ended));\n #endregion\n\n #region Properties Internal\n readonly object lockActions = new();\n readonly object lockSubtitles= new();\n\n bool taskSeekRuns;\n bool taskPlayRuns;\n bool taskOpenAsyncRuns;\n\n readonly ConcurrentStack seeks = new();\n readonly ConcurrentQueue UIActions = new();\n\n internal AudioFrame aFrame;\n internal VideoFrame vFrame;\n internal SubtitlesFrame[] sFrames, sFramesPrev;\n internal DataFrame dFrame;\n internal PlayerStats stats = new();\n internal LogHandler Log;\n\n internal bool requiresBuffering;\n bool reversePlaybackResync;\n\n bool isVideoSwitch;\n bool isAudioSwitch;\n bool[] isSubsSwitches;\n bool isDataSwitch;\n #endregion\n\n public Player(Config config = null)\n {\n if (config != null)\n {\n if (config.Player.player != null)\n throw new Exception(\"Player's configuration is already assigned to another player\");\n\n Config = config;\n }\n else\n Config = new Config();\n\n PlayerId = GetUniqueId();\n Log = new LogHandler((\"[#\" + PlayerId + \"]\").PadRight(8, ' ') + \" [Player ] \");\n Log.Debug($\"Creating Player (Usage = {Config.Player.Usage})\");\n\n Activity = new Activity(this);\n Audio = new Audio(this);\n Video = new Video(this);\n Subtitles = new Subtitles(this);\n Data = new Data(this);\n Commands = new Commands(this);\n\n Config.SetPlayer(this);\n\n if (Config.Player.Usage == Usage.Audio)\n {\n Config.Video.Enabled = false;\n Config.Subtitles.Enabled = false;\n }\n\n decoder = new DecoderContext(Config, PlayerId) { Tag = this };\n Engine.AddPlayer(this);\n\n if (decoder.VideoDecoder.Renderer != null)\n decoder.VideoDecoder.Renderer.forceNotExtractor = true;\n\n //decoder.OpenPlaylistItemCompleted += Decoder_OnOpenExternalSubtitlesStreamCompleted;\n\n decoder.OpenAudioStreamCompleted += Decoder_OpenAudioStreamCompleted;\n decoder.OpenVideoStreamCompleted += Decoder_OpenVideoStreamCompleted;\n decoder.OpenSubtitlesStreamCompleted += Decoder_OpenSubtitlesStreamCompleted;\n decoder.OpenDataStreamCompleted += Decoder_OpenDataStreamCompleted;\n\n decoder.OpenExternalAudioStreamCompleted += Decoder_OpenExternalAudioStreamCompleted;\n decoder.OpenExternalVideoStreamCompleted += Decoder_OpenExternalVideoStreamCompleted;\n decoder.OpenExternalSubtitlesStreamCompleted += Decoder_OpenExternalSubtitlesStreamCompleted;\n\n AudioDecoder.CBufAlloc = () => { if (aFrame != null) aFrame.dataPtr = IntPtr.Zero; aFrame = null; Audio.ClearBuffer(); aFrame = null; };\n AudioDecoder.CodecChanged = Decoder_AudioCodecChanged;\n VideoDecoder.CodecChanged = Decoder_VideoCodecChanged;\n decoder.RecordingCompleted += (o, e) => { IsRecording = false; };\n Chapters.CollectionChanged += (o, e) => { RaiseUI(nameof(Chapters)); };\n\n // second subtitles\n sFrames = new SubtitlesFrame[subNum];\n sFramesPrev = new SubtitlesFrame[subNum];\n sDistanceMss = new int[subNum];\n isSubsSwitches = new bool[subNum];\n\n status = Status.Stopped;\n Reset();\n Log.Debug(\"Created\");\n }\n\n /// \n /// Disposes the Player and de-assigns it from FlyleafHost\n /// \n public void Dispose() => Engine.DisposePlayer(this);\n internal void DisposeInternal()\n {\n lock (lockActions)\n {\n if (IsDisposed)\n return;\n\n try\n {\n Initialize();\n Audio.Dispose();\n decoder.Dispose();\n Host?.Player_Disposed();\n Log.Info(\"Disposed\");\n } catch (Exception e) { Log.Warn($\"Disposed ({e.Message})\"); }\n\n IsDisposed = true;\n }\n }\n internal void RefreshMaxVideoFrames()\n {\n lock (lockActions)\n {\n if (!Video.isOpened)\n return;\n\n bool wasPlaying = IsPlaying;\n Pause();\n VideoDecoder.RefreshMaxVideoFrames();\n ReSync(decoder.VideoStream, (int) (CurTime / 10000), true);\n\n if (wasPlaying)\n Play();\n }\n }\n\n private void ResetMe()\n {\n canPlay = false;\n bitRate = 0;\n curTime = 0;\n duration = 0;\n isLive = false;\n lastError = null;\n\n UIAdd(() =>\n {\n BitRate = BitRate;\n Duration = Duration;\n IsLive = IsLive;\n Status = Status;\n CanPlay = CanPlay;\n LastError = LastError;\n BufferedDuration = 0;\n Set(ref _CurTime, curTime, true, nameof(CurTime));\n });\n }\n private void Reset()\n {\n ResetMe();\n Video.Reset();\n Audio.Reset();\n Subtitles.Reset();\n UIAll();\n }\n private void Initialize(Status status = Status.Stopped, bool andDecoder = true, bool isSwitch = false)\n {\n if (CanDebug) Log.Debug($\"Initializing\");\n\n lock (lockActions) // Required in case of OpenAsync and Stop requests\n {\n try\n {\n Engine.TimeBeginPeriod1();\n\n this.status = status;\n canPlay = false;\n isVideoSwitch = false;\n seeks.Clear();\n\n while (taskPlayRuns || taskSeekRuns) Thread.Sleep(5);\n\n if (andDecoder)\n {\n if (isSwitch)\n decoder.InitializeSwitch();\n else\n decoder.Initialize();\n }\n\n Reset();\n VideoDemuxer.DisableReversePlayback();\n ReversePlayback = false;\n\n if (CanDebug) Log.Debug($\"Initialized\");\n\n } catch (Exception e)\n {\n Log.Error($\"Initialize() Error: {e.Message}\");\n\n } finally\n {\n Engine.TimeEndPeriod1();\n }\n }\n }\n\n internal void UIAdd(Action action) => UIActions.Enqueue(action);\n internal void UIAll()\n {\n while (!UIActions.IsEmpty)\n if (UIActions.TryDequeue(out var action))\n UI(action);\n }\n\n public override bool Equals(object obj)\n => obj == null || !(obj is Player) ? false : ((Player)obj).PlayerId == PlayerId;\n public override int GetHashCode() => PlayerId.GetHashCode();\n\n // Avoid having this code in OnPaintBackground as it can cause designer issues (renderer will try to load FFmpeg.Autogen assembly because of HDR Data)\n internal bool WFPresent() { if (renderer == null || renderer.SCDisposed) return false; renderer?.Present(); return true; }\n\n internal void RaiseKnownErrorOccurred(string message, KnownErrorType errorType)\n {\n KnownErrorOccurred?.Invoke(this, new KnownErrorOccurredEventArgs\n {\n Message = message,\n ErrorType = errorType\n });\n }\n\n internal void RaiseUnknownErrorOccurred(string message, UnknownErrorType errorType, Exception exception = null)\n {\n UnknownErrorOccurred?.Invoke(this, new UnknownErrorOccurredEventArgs\n {\n Message = message,\n ErrorType = errorType,\n Exception = exception\n });\n }\n}\n\npublic enum KnownErrorType\n{\n Configuration,\n ASR\n}\n\npublic class KnownErrorOccurredEventArgs : EventArgs\n{\n public required string Message { get; init; }\n public required KnownErrorType ErrorType { get; init; }\n}\n\npublic enum UnknownErrorType\n{\n Translation,\n Subtitles,\n ASR,\n Playback,\n Network\n}\n\npublic class UnknownErrorOccurredEventArgs : EventArgs\n{\n public required string Message { get; init; }\n public required UnknownErrorType ErrorType { get; init; }\n public Exception Exception { get; init; }\n}\n\npublic enum Status\n{\n Opening,\n Failed,\n Stopped,\n Paused,\n Playing,\n Ended\n}\npublic enum Usage\n{\n AVS,\n Audio\n}\n"], ["/LLPlayer/FlyleafLib/MediaPlayer/Player.Open.cs", "using System;\nusing System.Collections.Concurrent;\nusing System.IO;\nusing System.Threading.Tasks;\n\nusing FlyleafLib.MediaFramework.MediaDecoder;\nusing FlyleafLib.MediaFramework.MediaPlaylist;\nusing FlyleafLib.MediaFramework.MediaStream;\n\nusing static FlyleafLib.Logger;\nusing static FlyleafLib.MediaFramework.MediaContext.DecoderContext;\nusing static FlyleafLib.Utils;\n\nnamespace FlyleafLib.MediaPlayer;\n\nunsafe partial class Player\n{\n #region Events\n\n public event EventHandler Opening; // Will be also used for subtitles\n public event EventHandler OpenCompleted; // Will be also used for subtitles\n public event EventHandler OpenPlaylistItemCompleted;\n public event EventHandler OpenSessionCompleted;\n\n public event EventHandler OpenAudioStreamCompleted;\n public event EventHandler OpenVideoStreamCompleted;\n public event EventHandler OpenSubtitlesStreamCompleted;\n public event EventHandler OpenDataStreamCompleted;\n\n public event EventHandler OpenExternalAudioStreamCompleted;\n public event EventHandler OpenExternalVideoStreamCompleted;\n public event EventHandler OpenExternalSubtitlesStreamCompleted;\n\n private void OnOpening(OpeningArgs args = null)\n => Opening?.Invoke(this, args);\n private void OnOpenCompleted(OpenCompletedArgs args = null)\n => OpenCompleted?.Invoke(this, args);\n private void OnOpenSessionCompleted(OpenSessionCompletedArgs args = null)\n => OpenSessionCompleted?.Invoke(this, args);\n private void OnOpenPlaylistItemCompleted(OpenPlaylistItemCompletedArgs args = null)\n => OpenPlaylistItemCompleted?.Invoke(this, args);\n\n private void OnOpenAudioStreamCompleted(OpenAudioStreamCompletedArgs args = null)\n => OpenAudioStreamCompleted?.Invoke(this, args);\n private void OnOpenVideoStreamCompleted(OpenVideoStreamCompletedArgs args = null)\n => OpenVideoStreamCompleted?.Invoke(this, args);\n private void OnOpenSubtitlesStreamCompleted(OpenSubtitlesStreamCompletedArgs args = null)\n => OpenSubtitlesStreamCompleted?.Invoke(this, args);\n private void OnOpenDataStreamCompleted(OpenDataStreamCompletedArgs args = null)\n => OpenDataStreamCompleted?.Invoke(this, args);\n\n private void OnOpenExternalAudioStreamCompleted(OpenExternalAudioStreamCompletedArgs args = null)\n => OpenExternalAudioStreamCompleted?.Invoke(this, args);\n private void OnOpenExternalVideoStreamCompleted(OpenExternalVideoStreamCompletedArgs args = null)\n => OpenExternalVideoStreamCompleted?.Invoke(this, args);\n private void OnOpenExternalSubtitlesStreamCompleted(OpenExternalSubtitlesStreamCompletedArgs args = null)\n => OpenExternalSubtitlesStreamCompleted?.Invoke(this, args);\n #endregion\n\n #region Decoder Events\n private void Decoder_AudioCodecChanged(DecoderBase x)\n {\n Audio.Refresh();\n UIAll();\n }\n private void Decoder_VideoCodecChanged(DecoderBase x)\n {\n Video.Refresh();\n UIAll();\n }\n\n private void Decoder_OpenAudioStreamCompleted(object sender, OpenAudioStreamCompletedArgs e)\n {\n Config.Audio.SetDelay(0);\n Audio.Refresh();\n canPlay = Video.IsOpened || Audio.IsOpened;\n isLive = MainDemuxer.IsLive;\n duration= MainDemuxer.Duration;\n\n UIAdd(() =>\n {\n IsLive = IsLive;\n CanPlay = CanPlay;\n Duration=Duration;\n });\n UIAll();\n }\n private void Decoder_OpenVideoStreamCompleted(object sender, OpenVideoStreamCompletedArgs e)\n {\n Video.Refresh();\n canPlay = Video.IsOpened || Audio.IsOpened;\n isLive = MainDemuxer.IsLive;\n duration= MainDemuxer.Duration;\n\n UIAdd(() =>\n {\n IsLive = IsLive;\n CanPlay = CanPlay;\n Duration=Duration;\n });\n UIAll();\n }\n private void Decoder_OpenSubtitlesStreamCompleted(object sender, OpenSubtitlesStreamCompletedArgs e)\n {\n int i = SubtitlesSelectedHelper.CurIndex;\n\n Config.Subtitles[i].SetDelay(0);\n Subtitles[i].Refresh();\n UIAll();\n\n if (IsPlaying && Config.Subtitles.Enabled) // TBR (First run mainly with -from DecoderContext->OpenSuggestedSubtitles-> Task.Run causes late open, possible resync?)\n {\n if (!Subtitles[i].IsOpened)\n {\n return;\n }\n\n lock (lockSubtitles)\n {\n if (SubtitlesDecoders[i].OnVideoDemuxer)\n {\n SubtitlesDecoders[i].Start();\n }\n //else// if (!decoder.RequiresResync)\n //{\n // SubtitlesDemuxers[i].Start();\n // SubtitlesDecoders[i].Start();\n //}\n }\n }\n }\n\n private void Decoder_OpenDataStreamCompleted(object sender, OpenDataStreamCompletedArgs e)\n {\n Data.Refresh();\n UIAll();\n if (Config.Data.Enabled)\n {\n lock (lockSubtitles)\n if (DataDecoder.OnVideoDemuxer)\n DataDecoder.Start();\n else// if (!decoder.RequiresResync)\n {\n DataDemuxer.Start();\n DataDecoder.Start();\n }\n }\n }\n\n private void Decoder_OpenExternalAudioStreamCompleted(object sender, OpenExternalAudioStreamCompletedArgs e)\n {\n if (!e.Success)\n {\n canPlay = Video.IsOpened || Audio.IsOpened;\n UIAdd(() => CanPlay = CanPlay);\n UIAll();\n }\n }\n private void Decoder_OpenExternalVideoStreamCompleted(object sender, OpenExternalVideoStreamCompletedArgs e)\n {\n if (!e.Success)\n {\n canPlay = Video.IsOpened || Audio.IsOpened;\n UIAdd(() => CanPlay = CanPlay);\n UIAll();\n }\n }\n private void Decoder_OpenExternalSubtitlesStreamCompleted(object sender, OpenExternalSubtitlesStreamCompletedArgs e)\n {\n if (e.Success)\n {\n lock (lockSubtitles)\n ReSync(decoder.SubtitlesStreams[SubtitlesSelectedHelper.CurIndex], decoder.GetCurTimeMs());\n }\n }\n #endregion\n\n #region Open Implementation\n private OpenCompletedArgs OpenInternal(object url_iostream, bool defaultPlaylistItem = true, bool defaultVideo = true, bool defaultAudio = true, bool defaultSubtitles = true)\n {\n OpenCompletedArgs args = new();\n\n try\n {\n if (url_iostream == null)\n {\n args.Error = \"Invalid empty/null input\";\n return args;\n }\n\n if (CanInfo) Log.Info($\"Opening {url_iostream}\");\n\n Initialize(Status.Opening);\n var args2 = decoder.Open(url_iostream, defaultPlaylistItem, defaultVideo, defaultAudio, defaultSubtitles);\n\n args.Url = args2.Url;\n args.IOStream = args2.IOStream;\n args.Error = args2.Error;\n\n if (!args.Success)\n {\n status = Status.Failed;\n lastError = args.Error;\n }\n else if (CanPlay)\n {\n status = Status.Paused;\n\n if (Config.Player.AutoPlay)\n Play();\n }\n else if (!defaultVideo && !defaultAudio)\n {\n isLive = MainDemuxer.IsLive;\n duration= MainDemuxer.Duration;\n UIAdd(() =>\n {\n IsLive = IsLive;\n Duration=Duration;\n });\n }\n\n UIAdd(() =>\n {\n LastError=LastError;\n Status = Status;\n });\n\n UIAll();\n\n return args;\n\n } catch (Exception e)\n {\n args.Error = !args.Success ? args.Error + \"\\r\\n\" + e.Message : e.Message;\n return args;\n } finally\n {\n OnOpenCompleted(args);\n }\n }\n private OpenCompletedArgs OpenSubtitles(string url)\n {\n OpenCompletedArgs args = new(url, null, null, true);\n\n try\n {\n if (CanInfo) Log.Info($\"Opening subtitles {url}\");\n\n if (!Video.IsOpened)\n {\n args.Error = \"Cannot open subtitles without video\";\n return args;\n }\n\n Config.Subtitles.SetEnabled(true);\n args.Error = decoder.OpenSubtitles(url).Error;\n\n if (args.Success)\n ReSync(decoder.SubtitlesStreams[SubtitlesSelectedHelper.CurIndex]);\n\n return args;\n\n } catch (Exception e)\n {\n args.Error = !args.Success ? args.Error + \"\\r\\n\" + e.Message : e.Message;\n return args;\n } finally\n {\n OnOpenCompleted(args);\n }\n }\n\n /// \n /// Opens a new media file (audio/subtitles/video)\n /// \n /// Media file's url\n /// Whether to open the first/default item in case of playlist\n /// Whether to open the default video stream from plugin suggestions\n /// Whether to open the default audio stream from plugin suggestions\n /// Whether to open the default subtitles stream from plugin suggestions\n /// Forces input url to be handled as subtitles\n /// \n public OpenCompletedArgs Open(string url, bool defaultPlaylistItem = true, bool defaultVideo = true, bool defaultAudio = true, bool defaultSubtitles = true, bool forceSubtitles = false)\n {\n if (forceSubtitles || ExtensionsSubtitles.Contains(GetUrlExtention(url)))\n {\n OnOpening(new() { Url = url, IsSubtitles = true});\n return OpenSubtitles(url);\n }\n else\n {\n OnOpening(new() { Url = url });\n return OpenInternal(url, defaultPlaylistItem, defaultVideo, defaultAudio, defaultSubtitles);\n }\n }\n\n /// \n /// Opens a new media file (audio/subtitles/video) without blocking\n /// You can get the results from \n /// \n /// Media file's url\n /// Whether to open the first/default item in case of playlist\n /// Whether to open the default video stream from plugin suggestions\n /// Whether to open the default audio stream from plugin suggestions\n /// Whether to open the default subtitles stream from plugin suggestions\n public void OpenAsync(string url, bool defaultPlaylistItem = true, bool defaultVideo = true, bool defaultAudio = true, bool defaultSubtitles = true)\n => OpenAsyncPush(url, defaultPlaylistItem, defaultVideo, defaultAudio, defaultSubtitles);\n\n /// \n /// Opens a new media I/O stream (audio/video) without blocking\n /// \n /// Media stream\n /// Whether to open the first/default item in case of playlist\n /// Whether to open the default video stream from plugin suggestions\n /// Whether to open the default audio stream from plugin suggestions\n /// Whether to open the default subtitles stream from plugin suggestions\n /// \n public OpenCompletedArgs Open(Stream iostream, bool defaultPlaylistItem = true, bool defaultVideo = true, bool defaultAudio = true, bool defaultSubtitles = true)\n {\n OnOpening(new() { IOStream = iostream });\n return OpenInternal(iostream, defaultPlaylistItem, defaultVideo, defaultAudio, defaultSubtitles);\n }\n\n /// \n /// Opens a new media I/O stream (audio/video) without blocking\n /// You can get the results from \n /// \n /// Media stream\n /// Whether to open the first/default item in case of playlist\n /// Whether to open the default video stream from plugin suggestions\n /// Whether to open the default audio stream from plugin suggestions\n /// Whether to open the default subtitles stream from plugin suggestions\n public void OpenAsync(Stream iostream, bool defaultPlaylistItem = true, bool defaultVideo = true, bool defaultAudio = true, bool defaultSubtitles = true)\n => OpenAsyncPush(iostream, defaultPlaylistItem, defaultVideo, defaultAudio, defaultSubtitles);\n\n /// \n /// Opens a new media session\n /// \n /// Media session\n /// \n public OpenSessionCompletedArgs Open(Session session)\n {\n OpenSessionCompletedArgs args = new(session);\n\n try\n {\n Playlist.Selected?.AddTag(GetCurrentSession(), playerSessionTag);\n\n Initialize(Status.Opening, true, session.isReopen);\n args.Error = decoder.Open(session).Error;\n\n if (!args.Success || !CanPlay)\n {\n status = Status.Failed;\n lastError = args.Error;\n }\n else\n {\n status = Status.Paused;\n\n if (Config.Player.AutoPlay)\n Play();\n }\n\n UIAdd(() =>\n {\n LastError=LastError;\n Status = Status;\n });\n\n UIAll();\n\n return args;\n } catch (Exception e)\n {\n args.Error = !args.Success ? args.Error + \"\\r\\n\" + e.Message : e.Message;\n return args;\n } finally\n {\n OnOpenSessionCompleted(args);\n }\n }\n\n /// \n /// Opens a new media session without blocking\n /// \n /// Media session\n public void OpenAsync(Session session) => OpenAsyncPush(session);\n\n /// \n /// Opens a playlist item \n /// \n /// The playlist item to open\n /// Whether to open the default video stream from plugin suggestions\n /// Whether to open the default audio stream from plugin suggestions\n /// Whether to open the default subtitles stream from plugin suggestions\n /// \n public OpenPlaylistItemCompletedArgs Open(PlaylistItem item, bool defaultVideo = true, bool defaultAudio = true, bool defaultSubtitles = true)\n {\n OpenPlaylistItemCompletedArgs args = new(item, Playlist.Selected);\n\n try\n {\n Playlist.Selected?.AddTag(GetCurrentSession(), playerSessionTag);\n\n Initialize(Status.Opening, true, true);\n\n // TODO: Config.Player.Reopen? to reopen session if (item.OpenedCounter > 0)\n args = decoder.Open(item, defaultVideo, defaultAudio, defaultSubtitles);\n\n if (!args.Success)\n {\n status = Status.Failed;\n lastError = args.Error;\n }\n else if (CanPlay)\n {\n status = Status.Paused;\n\n if (Config.Player.AutoPlay)\n Play();\n // TODO: else Show on frame?\n }\n else if (!defaultVideo && !defaultAudio)\n {\n isLive = MainDemuxer.IsLive;\n duration= MainDemuxer.Duration;\n UIAdd(() =>\n {\n IsLive = IsLive;\n Duration=Duration;\n });\n }\n\n UIAdd(() =>\n {\n LastError=LastError;\n Status = Status;\n });\n\n UIAll();\n\n return args;\n\n } catch (Exception e)\n {\n args.Error = !args.Success ? args.Error + \"\\r\\n\" + e.Message : e.Message;\n return args;\n } finally\n {\n OnOpenPlaylistItemCompleted(args);\n }\n }\n\n /// \n /// Opens a playlist item without blocking\n /// You can get the results from \n /// \n /// The playlist item to open\n /// Whether to open the default video stream from plugin suggestions\n /// Whether to open the default audio stream from plugin suggestions\n /// Whether to open the default subtitles stream from plugin suggestions\n /// \n public void OpenAsync(PlaylistItem item, bool defaultVideo = true, bool defaultAudio = true, bool defaultSubtitles = true)\n => OpenAsyncPush(item, defaultVideo, defaultAudio, defaultSubtitles);\n\n /// \n /// Opens an external stream (audio/subtitles/video)\n /// \n /// The external stream to open\n /// Whether to force resync with other streams\n /// Whether to open the default audio stream from plugin suggestions\n /// -2: None, -1: Suggested/Default, X: Specified embedded stream index\n /// \n public ExternalStreamOpenedArgs Open(ExternalStream extStream, bool resync = true, bool defaultAudio = true, int streamIndex = -1)\n {\n /* TODO\n *\n * Decoder.Stop() should not be called on video input switch as it will close the other inputs as well (audio/subs)\n * If the input is from different plugin we don't dispose the current plugin (eg. switching between recent/history plugin with torrents) (?)\n */\n\n ExternalStreamOpenedArgs args = null;\n\n try\n {\n int syncMs = decoder.GetCurTimeMs();\n\n if (LastError != null)\n {\n lastError = null;\n UI(() => LastError = LastError);\n }\n\n if (extStream is ExternalAudioStream)\n {\n if (decoder.VideoStream == null)\n requiresBuffering = true;\n\n isAudioSwitch = true;\n Config.Audio.SetEnabled(true);\n args = decoder.Open(extStream, false, streamIndex);\n\n if (!args.Success)\n {\n isAudioSwitch = false;\n return args;\n }\n\n if (resync)\n ReSync(decoder.AudioStream, syncMs);\n\n if (VideoDemuxer.VideoStream == null)\n {\n isLive = MainDemuxer.IsLive;\n duration = MainDemuxer.Duration;\n }\n\n isAudioSwitch = false;\n }\n else if (extStream is ExternalVideoStream)\n {\n bool shouldPlay = false;\n if (IsPlaying)\n {\n shouldPlay = true;\n Pause();\n }\n\n Initialize(Status.Opening, false, true);\n args = decoder.Open(extStream, defaultAudio, streamIndex);\n\n if (!args.Success || !CanPlay)\n return args;\n\n decoder.Seek(syncMs, false, false);\n decoder.GetVideoFrame(syncMs * (long)10000);\n VideoDemuxer.Start();\n AudioDemuxer.Start();\n //for (int i = 0; i < subNum; i++)\n //{\n // SubtitlesDemuxers[i].Start();\n //}\n DataDemuxer.Start();\n decoder.PauseOnQueueFull();\n\n // Initialize will Reset those and is posible that Codec Changed will not be called (as they are not chaning necessary)\n Decoder_OpenAudioStreamCompleted(null, null);\n Decoder_OpenSubtitlesStreamCompleted(null, null);\n\n if (shouldPlay)\n Play();\n else\n ShowOneFrame();\n }\n else // ExternalSubtitlesStream\n {\n if (!Video.IsOpened)\n {\n args.Error = \"Subtitles require opened video stream\";\n return args;\n }\n\n Config.Subtitles.SetEnabled(true);\n args = decoder.Open(extStream, false, streamIndex);\n }\n\n return args;\n\n } catch (Exception e)\n {\n args.Error = !args.Success ? args.Error + \"\\r\\n\" + e.Message : e.Message;\n return args;\n } finally\n {\n if (extStream is ExternalVideoStream)\n OnOpenExternalVideoStreamCompleted((OpenExternalVideoStreamCompletedArgs)args);\n else if (extStream is ExternalAudioStream)\n OnOpenExternalAudioStreamCompleted((OpenExternalAudioStreamCompletedArgs)args);\n else\n OnOpenExternalSubtitlesStreamCompleted((OpenExternalSubtitlesStreamCompletedArgs)args);\n }\n }\n\n /// \n /// Opens an external stream (audio/subtitles/video) without blocking\n /// You can get the results from , , \n /// \n /// The external stream to open\n /// Whether to force resync with other streams\n /// Whether to open the default audio stream from plugin suggestions\n public void OpenAsync(ExternalStream extStream, bool resync = true, bool defaultAudio = true)\n => OpenAsyncPush(extStream, resync, defaultAudio);\n\n /// \n /// Opens an embedded stream (audio/subtitles/video)\n /// \n /// An existing Player's media stream\n /// Whether to force resync with other streams\n /// Whether to re-suggest audio based on the new video stream (has effect only on VideoStream)\n /// \n public StreamOpenedArgs Open(StreamBase stream, bool resync = true, bool defaultAudio = true)\n {\n StreamOpenedArgs args = new();\n\n try\n {\n long delay = DateTime.UtcNow.Ticks;\n long fromEnd = Duration - CurTime;\n\n if (stream.Demuxer.Type == MediaType.Video)\n {\n isVideoSwitch = true;\n requiresBuffering = true;\n }\n\n if (stream is AudioStream astream)\n {\n Config.Audio.SetEnabled(true);\n args = decoder.OpenAudioStream(astream);\n }\n else if (stream is VideoStream vstream)\n args = decoder.OpenVideoStream(vstream, defaultAudio);\n else if (stream is SubtitlesStream sstream)\n {\n Config.Subtitles.SetEnabled(true);\n args = decoder.OpenSubtitlesStream(sstream);\n }\n else if (stream is DataStream dstream)\n {\n Config.Data.SetEnabled(true);\n args = decoder.OpenDataStream(dstream);\n }\n\n if (resync)\n {\n // Wait for at least on package before seek to update the HLS context first_time\n if (stream.Demuxer.IsHLSLive)\n {\n while (stream.Demuxer.IsRunning && stream.Demuxer.GetPacketsPtr(stream).Count < 3)\n System.Threading.Thread.Sleep(20);\n\n ReSync(stream, (int) ((Duration - fromEnd - (DateTime.UtcNow.Ticks - delay))/ 10000));\n }\n else\n ReSync(stream, (int) (CurTime / 10000), true);\n }\n else\n isVideoSwitch = false;\n\n return args;\n\n } catch (Exception e)\n {\n args.Error = !args.Success ? args.Error + \"\\r\\n\" + e.Message : e.Message;\n return args;\n } finally\n {\n if (stream is VideoStream)\n OnOpenVideoStreamCompleted((OpenVideoStreamCompletedArgs)args);\n else if (stream is AudioStream)\n OnOpenAudioStreamCompleted((OpenAudioStreamCompletedArgs)args);\n else if (stream is SubtitlesStream)\n OnOpenSubtitlesStreamCompleted((OpenSubtitlesStreamCompletedArgs)args);\n else\n OnOpenDataStreamCompleted((OpenDataStreamCompletedArgs)args);\n }\n }\n\n /// \n /// Opens an embedded stream (audio/subtitles/video) without blocking\n /// You can get the results from , , \n /// \n /// An existing Player's media stream\n /// Whether to force resync with other streams\n /// Whether to re-suggest audio based on the new video stream (has effect only on VideoStream)\n public void OpenAsync(StreamBase stream, bool resync = true, bool defaultAudio = true)\n => OpenAsyncPush(stream, resync, defaultAudio);\n\n /// \n /// Gets a session that can be re-opened later on with \n /// \n /// The current selected playlist item if null\n /// \n public Session GetSession(PlaylistItem item = null)\n => Playlist.Selected != null && (item == null || item.Index == Playlist.Selected.Index)\n ? GetCurrentSession()\n : item != null && item.GetTag(playerSessionTag) != null ? (Session)item.GetTag(playerSessionTag) : null;\n string playerSessionTag = \"_session\";\n private Session GetCurrentSession()\n {\n Session session = new();\n var item = Playlist.Selected;\n\n session.Url = Playlist.Url;\n session.PlaylistItem = item.Index;\n\n if (item.ExternalAudioStream != null)\n session.ExternalAudioStream = item.ExternalAudioStream.Index;\n\n if (item.ExternalVideoStream != null)\n session.ExternalVideoStream = item.ExternalVideoStream.Index;\n\n // TODO: L: Support secondary subtitles\n if (item.ExternalSubtitlesStreams[0] != null)\n session.ExternalSubtitlesUrl = item.ExternalSubtitlesStreams[0].Url;\n else if (decoder.SubtitlesStreams[0] != null)\n session.SubtitlesStream = decoder.SubtitlesStreams[0].StreamIndex;\n\n if (decoder.AudioStream != null)\n session.AudioStream = decoder.AudioStream.StreamIndex;\n\n if (decoder.VideoStream != null)\n session.VideoStream = decoder.VideoStream.StreamIndex;\n\n session.CurTime = CurTime;\n session.AudioDelay = Config.Audio.Delay;\n // TODO: L: Support secondary subtitles\n session.SubtitlesDelay = Config.Subtitles[0].Delay;\n\n return session;\n }\n\n internal void ReSync(StreamBase stream, int syncMs = -1, bool accurate = false)\n {\n /* TODO\n *\n * HLS live resync on stream switch should be from the end not from the start (could have different cache/duration)\n */\n\n if (stream == null) return;\n //if (stream == null || (syncMs == 0 || (syncMs == -1 && decoder.GetCurTimeMs() == 0))) return; // Avoid initial open resync?\n\n if (stream.Demuxer.Type == MediaType.Video)\n {\n isVideoSwitch = true;\n isAudioSwitch = true;\n for (int i = 0; i < subNum; i++)\n {\n isSubsSwitches[i] = true;\n }\n isDataSwitch = true;\n requiresBuffering = true;\n\n if (accurate && Video.IsOpened)\n {\n decoder.PauseDecoders();\n decoder.Seek(syncMs, false, false);\n decoder.GetVideoFrame(syncMs * (long)10000); // TBR: syncMs should not be -1 here\n }\n else\n decoder.Seek(syncMs, false, false);\n\n aFrame = null;\n isAudioSwitch = false;\n isVideoSwitch = false;\n for (int i = 0; i < subNum; i++)\n {\n sFrames[i] = sFramesPrev[i] = null;\n isSubsSwitches[i] = false;\n }\n dFrame = null;\n isDataSwitch = false;\n\n if (!IsPlaying)\n {\n decoder.PauseDecoders();\n decoder.GetVideoFrame();\n ShowOneFrame();\n }\n else\n {\n SubtitleClear();\n }\n }\n else\n {\n if (stream.Demuxer.Type == MediaType.Audio)\n {\n isAudioSwitch = true;\n decoder.SeekAudio();\n aFrame = null;\n isAudioSwitch = false;\n }\n else if (stream.Demuxer.Type == MediaType.Subs)\n {\n int i = SubtitlesSelectedHelper.CurIndex;\n\n isSubsSwitches[i] = true;\n\n //decoder.SeekSubtitles(i);\n sFrames[i] = sFramesPrev[i] = null;\n SubtitleClear(i);\n isSubsSwitches[i] = false;\n\n // do not start demuxer and decoder for external subs\n return;\n }\n else if (stream.Demuxer.Type == MediaType.Data)\n {\n isDataSwitch = true;\n decoder.SeekData();\n dFrame = null;\n isDataSwitch = false;\n }\n\n if (IsPlaying)\n {\n stream.Demuxer.Start();\n decoder.GetDecoderPtr(stream).Start();\n }\n }\n }\n #endregion\n\n #region OpenAsync Implementation\n private void OpenAsync()\n {\n lock (lockActions)\n if (taskOpenAsyncRuns)\n return;\n\n taskOpenAsyncRuns = true;\n\n Task.Run(() =>\n {\n if (IsDisposed)\n return;\n\n while (true)\n {\n if (openInputs.TryPop(out var data))\n {\n openInputs.Clear();\n decoder.Interrupt = true;\n OpenInternal(data.url_iostream, data.defaultPlaylistItem, data.defaultVideo, data.defaultAudio, data.defaultSubtitles);\n }\n else if (openSessions.TryPop(out data))\n {\n openSessions.Clear();\n decoder.Interrupt = true;\n Open(data.session);\n }\n else if (openItems.TryPop(out data))\n {\n openItems.Clear();\n decoder.Interrupt = true;\n Open(data.playlistItem, data.defaultVideo, data.defaultAudio, data.defaultSubtitles);\n }\n else if (openVideo.TryPop(out data))\n {\n openVideo.Clear();\n if (data.extStream != null)\n Open(data.extStream, data.resync, data.defaultAudio);\n else\n Open(data.stream, data.resync, data.defaultAudio);\n }\n else if (openAudio.TryPop(out data))\n {\n openAudio.Clear();\n if (data.extStream != null)\n Open(data.extStream, data.resync);\n else\n Open(data.stream, data.resync);\n }\n else if (openSubtitles.TryPop(out data))\n {\n openSubtitles.Clear();\n if (data.url_iostream != null)\n OpenSubtitles(data.url_iostream.ToString());\n else if (data.extStream != null)\n Open(data.extStream, data.resync);\n else if (data.stream != null)\n Open(data.stream, data.resync);\n }\n else\n {\n lock (lockActions)\n {\n if (openInputs.IsEmpty && openSessions.IsEmpty && openItems.IsEmpty && openVideo.IsEmpty && openAudio.IsEmpty && openSubtitles.IsEmpty)\n {\n taskOpenAsyncRuns = false;\n break;\n }\n }\n }\n }\n });\n }\n\n private void OpenAsyncPush(object url_iostream, bool defaultPlaylistItem = true, bool defaultVideo = true, bool defaultAudio = true, bool defaultSubtitles = true)\n {\n lock (lockActions)\n {\n if (url_iostream is string url_iostream_str)\n {\n // convert Windows lnk file to targetPath\n if (Path.GetExtension(url_iostream_str).Equals(\".lnk\", StringComparison.OrdinalIgnoreCase))\n {\n var targetPath = GetLnkTargetPath(url_iostream_str);\n if (targetPath != null)\n url_iostream = targetPath;\n }\n }\n\n if ((url_iostream is string) && ExtensionsSubtitles.Contains(GetUrlExtention(url_iostream.ToString())))\n {\n OnOpening(new() { Url = url_iostream.ToString(), IsSubtitles = true});\n openSubtitles.Push(new OpenAsyncData(url_iostream));\n }\n else\n {\n decoder.Interrupt = true;\n\n if (url_iostream is string)\n OnOpening(new() { Url = url_iostream.ToString() });\n else\n OnOpening(new() { IOStream = (Stream)url_iostream });\n\n openInputs.Push(new OpenAsyncData(url_iostream, defaultPlaylistItem, defaultVideo, defaultAudio, defaultSubtitles));\n }\n\n // Select primary subtitle & original mode when dropped\n SubtitlesSelectedHelper.CurIndex = 0;\n SubtitlesSelectedHelper.PrimaryMethod = SelectSubMethod.Original;\n\n OpenAsync();\n }\n }\n private void OpenAsyncPush(Session session)\n {\n lock (lockActions)\n {\n if (!openInputs.IsEmpty)\n return;\n\n decoder.Interrupt = true;\n openSessions.Clear();\n openSessions.Push(new OpenAsyncData(session));\n\n OpenAsync();\n }\n }\n private void OpenAsyncPush(PlaylistItem playlistItem, bool defaultVideo = true, bool defaultAudio = true, bool defaultSubtitles = true)\n {\n lock (lockActions)\n {\n if (!openInputs.IsEmpty || !openSessions.IsEmpty)\n return;\n\n decoder.Interrupt = true;\n openItems.Push(new OpenAsyncData(playlistItem, defaultVideo, defaultAudio, defaultSubtitles));\n\n OpenAsync();\n }\n }\n private void OpenAsyncPush(ExternalStream extStream, bool resync = true, bool defaultAudio = true, int streamIndex = -1)\n {\n lock (lockActions)\n {\n if (!openInputs.IsEmpty || !openItems.IsEmpty || !openSessions.IsEmpty)\n return;\n\n if (extStream is ExternalAudioStream)\n {\n openAudio.Clear();\n openAudio.Push(new OpenAsyncData(extStream, resync, false, streamIndex));\n }\n else if (extStream is ExternalVideoStream)\n {\n openVideo.Clear();\n openVideo.Push(new OpenAsyncData(extStream, resync, defaultAudio, streamIndex));\n }\n else\n {\n openSubtitles.Clear();\n openSubtitles.Push(new OpenAsyncData(extStream, resync, false, streamIndex));\n }\n\n OpenAsync();\n }\n }\n private void OpenAsyncPush(StreamBase stream, bool resync = true, bool defaultAudio = true)\n {\n lock (lockActions)\n {\n if (!openInputs.IsEmpty || !openItems.IsEmpty || !openSessions.IsEmpty)\n return;\n\n if (stream is AudioStream)\n {\n openAudio.Clear();\n openAudio.Push(new OpenAsyncData(stream, resync));\n }\n else if (stream is VideoStream)\n {\n openVideo.Clear();\n openVideo.Push(new OpenAsyncData(stream, resync, defaultAudio));\n }\n else\n {\n openSubtitles.Clear();\n openSubtitles.Push(new OpenAsyncData(stream, resync));\n }\n\n OpenAsync();\n }\n }\n\n ConcurrentStack openInputs = new();\n ConcurrentStack openSessions = new();\n ConcurrentStack openItems = new();\n ConcurrentStack openVideo = new();\n ConcurrentStack openAudio = new();\n ConcurrentStack openSubtitles= new();\n #endregion\n}\n\npublic class OpeningArgs\n{\n public string Url;\n public Stream IOStream;\n public bool IsSubtitles;\n}\n\npublic class OpenCompletedArgs\n{\n public string Url;\n public Stream IOStream;\n public string Error;\n public bool Success => Error == null;\n public bool IsSubtitles;\n\n public OpenCompletedArgs(string url = null, Stream iostream = null, string error = null, bool isSubtitles = false) { Url = url; IOStream = iostream; Error = error; IsSubtitles = isSubtitles; }\n}\n\nclass OpenAsyncData\n{\n public object url_iostream;\n public Session session;\n public PlaylistItem playlistItem;\n public ExternalStream extStream;\n public int streamIndex;\n public StreamBase stream;\n public bool resync;\n public bool defaultPlaylistItem;\n public bool defaultAudio;\n public bool defaultVideo;\n public bool defaultSubtitles;\n\n public OpenAsyncData(object url_iostream, bool defaultPlaylistItem = true, bool defaultVideo = true, bool defaultAudio = true, bool defaultSubtitles = true)\n { this.url_iostream = url_iostream; this.defaultPlaylistItem = defaultPlaylistItem; this.defaultVideo = defaultVideo; this.defaultAudio = defaultAudio; this.defaultSubtitles = defaultSubtitles; }\n public OpenAsyncData(Session session) => this.session = session;\n public OpenAsyncData(PlaylistItem playlistItem, bool defaultVideo = true, bool defaultAudio = true, bool defaultSubtitles = true)\n { this.playlistItem = playlistItem; this.defaultVideo = defaultVideo; this.defaultAudio = defaultAudio; this.defaultSubtitles = defaultSubtitles; }\n public OpenAsyncData(ExternalStream extStream, bool resync = true, bool defaultAudio = true, int streamIndex = -1)\n { this.extStream = extStream; this.resync = resync; this.defaultAudio = defaultAudio; this.streamIndex = streamIndex; }\n public OpenAsyncData(StreamBase stream, bool resync = true, bool defaultAudio = true)\n { this.stream = stream; this.resync = resync; this.defaultAudio = defaultAudio; }\n}\n"], ["/LLPlayer/FlyleafLib/MediaFramework/MediaRenderer/ShaderCompiler.cs", "using System.Collections.Generic;\nusing System.Text;\nusing System.Threading;\n\nusing Vortice.D3DCompiler;\nusing Vortice.Direct3D;\nusing Vortice.Direct3D11;\n\nusing ID3D11Device = Vortice.Direct3D11.ID3D11Device;\nusing static FlyleafLib.Utils;\n\nnamespace FlyleafLib.MediaFramework.MediaRenderer;\n\ninternal class BlobWrapper\n{\n public Blob blob;\n public BlobWrapper(Blob blob) => this.blob = blob;\n public BlobWrapper() { }\n}\n\ninternal static class ShaderCompiler\n{\n internal static Blob VSBlob = Compile(VS, false); // TODO Embedded?\n\n const int MAXSIZE = 64;\n static Dictionary cache = new();\n\n internal static ID3D11PixelShader CompilePS(ID3D11Device device, string uniqueId, string hlslSample, List defines = null)\n {\n BlobWrapper bw;\n\n lock (cache)\n {\n if (cache.Count > MAXSIZE)\n {\n Engine.Log.Trace($\"[ShaderCompiler] Clears cache\");\n foreach (var bw1 in cache.Values)\n bw1.blob.Dispose();\n\n cache.Clear();\n }\n\n cache.TryGetValue(uniqueId, out var bw2);\n if (bw2 != null)\n {\n Engine.Log.Trace($\"[ShaderCompiler] Found in cache {uniqueId}\");\n lock(bw2)\n return device.CreatePixelShader(bw2.blob);\n }\n\n bw = new();\n Monitor.Enter(bw);\n cache.Add(uniqueId, bw);\n }\n\n var blob = Compile(PS_HEADER + hlslSample + PS_FOOTER, true, defines);\n bw.blob = blob;\n var ps = device.CreatePixelShader(bw.blob);\n Monitor.Exit(bw);\n\n Engine.Log.Trace($\"[ShaderCompiler] Compiled {uniqueId}\");\n return ps;\n }\n internal static Blob Compile(string hlsl, bool isPS = true, List defines = null)\n {\n ShaderMacro[] definesMacro = null;\n\n if (defines != null)\n {\n definesMacro = new ShaderMacro[defines.Count + 1];\n for(int i=0; i GetUrlExtention(x) == \"hlsl\").ToArray();\n\n // foreach (string shader in shaders)\n // using (Stream stream = assembly.GetManifestResourceStream(shader))\n // {\n // string shaderName = shader.Substring(0, shader.Length - 5);\n // shaderName = shaderName.Substring(shaderName.LastIndexOf('.') + 1);\n\n // byte[] bytes = new byte[stream.Length];\n // stream.Read(bytes, 0, bytes.Length);\n\n // CompileShader(bytes, shaderName);\n // }\n //}\n\n //private unsafe static void CompileFileShaders()\n //{\n // List shaders = Directory.EnumerateFiles(EmbeddedShadersFolder, \"*.hlsl\").ToList();\n // foreach (string shader in shaders)\n // {\n // string shaderName = shader.Substring(0, shader.Length - 5);\n // shaderName = shaderName.Substring(shaderName.LastIndexOf('\\\\') + 1);\n\n // CompileShader(File.ReadAllBytes(shader), shaderName);\n // }\n //}\n\n // Loads compiled blob shaders\n //private static void LoadShaders()\n //{\n // Assembly assembly = Assembly.GetExecutingAssembly();\n // string[] shaders = assembly.GetManifestResourceNames().Where(x => GetUrlExtention(x) == \"blob\").ToArray();\n // string tempFile = Path.GetTempFileName();\n\n // foreach (string shader in shaders)\n // {\n // using (Stream stream = assembly.GetManifestResourceStream(shader))\n // {\n // var shaderName = shader.Substring(0, shader.Length - 5);\n // shaderName = shaderName.Substring(shaderName.LastIndexOf('.') + 1);\n\n // byte[] bytes = new byte[stream.Length];\n // stream.Read(bytes, 0, bytes.Length);\n\n // Dictionary curShaders = shaderName.Substring(0, 2).ToLower() == \"vs\" ? VSShaderBlobs : PSShaderBlobs;\n\n // File.WriteAllBytes(tempFile, bytes);\n // curShaders.Add(shaderName, Compiler.ReadFileToBlob(tempFile));\n // }\n // }\n //}\n\n // Should work at least from main Samples => FlyleafPlayer (WPF Control) (WPF)\n //static string EmbeddedShadersFolder = @\"..\\..\\..\\..\\..\\..\\FlyleafLib\\MediaFramework\\MediaRenderer\\Shaders\";\n //static Assembly ASSEMBLY = Assembly.GetExecutingAssembly();\n //static string SHADERS_NS = typeof(Renderer).Namespace + \".Shaders.\";\n\n //static byte[] GetEmbeddedShaderResource(string shaderName)\n //{\n // using (Stream stream = ASSEMBLY.GetManifestResourceStream(SHADERS_NS + shaderName + \".hlsl\"))\n // {\n // byte[] bytes = new byte[stream.Length];\n // stream.Read(bytes, 0, bytes.Length);\n\n // return bytes;\n // }\n //}\n\n const string PS_HEADER = @\"\n#pragma warning( disable: 3571 )\nTexture2D\t\tTexture1\t\t: register(t0);\nTexture2D\t\tTexture2\t\t: register(t1);\nTexture2D\t\tTexture3\t\t: register(t2);\nTexture2D\t\tTexture4\t\t: register(t3);\n\ncbuffer Config : register(b0)\n{\n int coefsIndex;\n int hdrmethod;\n\n float brightness;\n float contrast;\n\n float g_luminance;\n float g_toneP1;\n float g_toneP2;\n\n float texWidth;\n};\n\nSamplerState Sampler : IMMUTABLE\n{\n Filter = MIN_MAG_MIP_LINEAR;\n AddressU = CLAMP;\n AddressV = CLAMP;\n AddressW = CLAMP;\n ComparisonFunc = NEVER;\n MinLOD = 0;\n};\n\n#if defined(YUV)\n// YUV to RGB matrix coefficients\nstatic const float4x4 coefs[] =\n{\n // Limited -> Full\n {\n // BT2020 (srcBits = 10)\n { 1.16438353, 1.16438353, 1.16438353, 0 },\n { 0, -0.187326103, 2.14177227, 0 },\n { 1.67867422, -0.650424361, 0, 0 },\n { -0.915688038, 0.347458541, -1.14814520, 1 }\n },\n\n // BT709\n {\n { 1.16438341, 1.16438341, 1.16438341, 0 },\n { 0, -0.213248596, 2.11240149, 0 },\n { 1.79274082, -0.532909214, 0, 0 },\n { -0.972944975, 0.301482648, -1.13340211, 1 }\n },\n // BT601\n {\n { 1.16438341, 1.16438341, 1.16438341, 0 },\n { 0, -0.391762286, 2.01723194, 0 },\n { 1.59602666, -0.812967658, 0, 0 },\n { -0.874202192, 0.531667829, -1.08563077, 1 },\n }\n};\n#endif\n\n#if defined(HDR)\n// hdrmethod enum\nstatic const int Aces = 1;\nstatic const int Hable = 2;\nstatic const int Reinhard = 3;\n\n// HDR to SDR color convert (Thanks to KODI community https://github.com/thexai/xbmc)\nstatic const float ST2084_m1 = 2610.0f / (4096.0f * 4.0f);\nstatic const float ST2084_m2 = (2523.0f / 4096.0f) * 128.0f;\nstatic const float ST2084_c1 = 3424.0f / 4096.0f;\nstatic const float ST2084_c2 = (2413.0f / 4096.0f) * 32.0f;\nstatic const float ST2084_c3 = (2392.0f / 4096.0f) * 32.0f;\n\nstatic const float4x4 bt2020tobt709color =\n{\n { 1.6604f, -0.1245f, -0.0181f, 0 },\n { -0.5876f, 1.1329f, -0.10057f, 0 },\n { -0.07284f, -0.0083f, 1.1187f, 0 },\n { 0, 0, 0, 0 }\n};\n\nfloat3 inversePQ(float3 x)\n{\n x = pow(max(x, 0.0f), 1.0f / ST2084_m2);\n x = max(x - ST2084_c1, 0.0f) / (ST2084_c2 - ST2084_c3 * x);\n x = pow(x, 1.0f / ST2084_m1);\n return x;\n}\n\n#if defined(HLG)\nfloat3 inverseHLG(float3 x)\n{\n const float B67_a = 0.17883277f;\n const float B67_b = 0.28466892f;\n const float B67_c = 0.55991073f;\n const float B67_inv_r2 = 4.0f;\n x = (x <= 0.5f) ? x * x * B67_inv_r2 : exp((x - B67_c) / B67_a) + B67_b;\n return x;\n}\n\nfloat3 tranferPQ(float3 x)\n{\n x = pow(x / 1000.0f, ST2084_m1);\n x = (ST2084_c1 + ST2084_c2 * x) / (1.0f + ST2084_c3 * x);\n x = pow(x, ST2084_m2);\n return x;\n}\n\n#endif\nfloat3 aces(float3 x)\n{\n const float A = 2.51f;\n const float B = 0.03f;\n const float C = 2.43f;\n const float D = 0.59f;\n const float E = 0.14f;\n return (x * (A * x + B)) / (x * (C * x + D) + E);\n}\n\nfloat3 hable(float3 x)\n{\n const float A = 0.15f;\n const float B = 0.5f;\n const float C = 0.1f;\n const float D = 0.2f;\n const float E = 0.02f;\n const float F = 0.3f;\n return ((x * (A * x + C * B) + D * E) / (x * (A * x + B) + D * F)) - E / F;\n}\n\nstatic const float3 bt709coefs = { 0.2126f, 1.0f - 0.2126f - 0.0722f, 0.0722f };\nfloat reinhard(float x)\n{\n return x * (1.0f + x / (g_toneP1 * g_toneP1)) / (1.0f + x);\n}\n#endif\n\nstruct PSInput\n{\n float4 Position : SV_POSITION;\n float2 Texture : TEXCOORD;\n};\n\nfloat4 main(PSInput input) : SV_TARGET\n{\n float4 color;\n\n // Dynamic Sampling\n\n\";\n\n const string PS_FOOTER = @\"\n\n // YUV to RGB\n#if defined(YUV)\n color = mul(color, coefs[coefsIndex]);\n#endif\n\n\n // HDR\n#if defined(HDR)\n // BT2020 -> BT709\n color.rgb = pow(max(0.0, color.rgb), 2.4f);\n color.rgb = max(0.0, mul(color, bt2020tobt709color).rgb);\n color.rgb = pow(color.rgb, 1.0f / 2.2f);\n\n if (hdrmethod == Aces)\n {\n color.rgb = inversePQ(color.rgb);\n color.rgb *= (10000.0f / g_luminance) * (2.0f / g_toneP1);\n color.rgb = aces(color.rgb);\n color.rgb *= (1.24f / g_toneP1);\n color.rgb = pow(color.rgb, 0.27f);\n }\n else if (hdrmethod == Hable)\n {\n color.rgb = inversePQ(color.rgb);\n color.rgb *= g_toneP1;\n color.rgb = hable(color.rgb * g_toneP2) / hable(g_toneP2);\n color.rgb = pow(color.rgb, 1.0f / 2.2f);\n }\n else if (hdrmethod == Reinhard)\n {\n float luma = dot(color.rgb, bt709coefs);\n color.rgb *= reinhard(luma) / luma;\n }\n #if defined(HLG)\n // HLG\n color.rgb = inverseHLG(color.rgb);\n float3 ootf_2020 = float3(0.2627f, 0.6780f, 0.0593f);\n float ootf_ys = 2000.0f * dot(ootf_2020, color.rgb);\n color.rgb *= pow(ootf_ys, 0.2f);\n color.rgb = tranferPQ(color.rgb);\n #endif\n#endif\n\n // Contrast / Brightness / Saturate / Hue\n color *= contrast * 2.0f;\n color += brightness - 0.5f;\n\n return color;\n}\n\";\n\n const string VS = @\"\ncbuffer cBuf : register(b0)\n{\n matrix mat;\n}\n\nstruct VSInput\n{\n float4 Position : POSITION;\n float2 Texture : TEXCOORD;\n};\n\nstruct PSInput\n{\n float4 Position : SV_POSITION;\n float2 Texture : TEXCOORD;\n};\n\nPSInput main(VSInput vsi)\n{\n PSInput psi;\n\n psi.Position = mul(vsi.Position, mat);\n psi.Texture = vsi.Texture;\n\n return psi;\n}\n\";\n}\n"], ["/LLPlayer/LLPlayer/Services/OpenSubtitlesProvider.cs", "using System.IO;\nusing System.IO.Compression;\nusing System.Net.Http;\nusing System.Text;\nusing System.Xml.Serialization;\nusing FlyleafLib;\nusing LLPlayer.Extensions;\n\nnamespace LLPlayer.Services;\n\npublic class OpenSubtitlesProvider\n{\n private readonly FlyleafManager FL;\n private readonly HttpClient _client;\n private string? _token;\n private bool _initialized = false;\n\n public OpenSubtitlesProvider(FlyleafManager fl)\n {\n FL = fl;\n HttpClient client = new();\n client.BaseAddress = new Uri(\"http://api.opensubtitles.org/xml-rpc\");\n client.Timeout = TimeSpan.FromSeconds(15);\n\n _client = client;\n }\n\n private readonly SemaphoreSlim _loginSemaphore = new(1);\n\n private async Task Initialize()\n {\n if (!_initialized)\n {\n try\n {\n await _loginSemaphore.WaitAsync();\n await Login();\n _initialized = true;\n }\n finally\n {\n _loginSemaphore.Release();\n }\n }\n }\n\n /// \n /// Login\n /// \n /// \n /// \n /// \n private async Task Login()\n {\n string loginReqXml =\n\"\"\"\n\n\n LogIn\n \n \n \n \n \n \n \n \n \n \n \n \n en\n \n \n VLsub 0.10.2\n \n \n\n\"\"\";\n\n var result = await _client.PostAsync(string.Empty, new StringContent(loginReqXml));\n var content = await result.Content.ReadAsStringAsync();\n\n var serializer = new XmlSerializer(typeof(MethodResponse));\n LoginResponse loginResponse = new();\n using (var reader = new StringReader(content))\n {\n MethodResponse? response = null;\n try\n {\n result.EnsureSuccessStatusCode();\n response = serializer.Deserialize(reader) as MethodResponse;\n if (response == null)\n {\n throw new InvalidOperationException(\"response is not MethodResponse\");\n }\n }\n catch (Exception ex)\n {\n throw new InvalidOperationException($\"Can't parse the login content: {ex.Message}\", ex)\n {\n Data =\n {\n [\"status_code\"] = ((int)result.StatusCode).ToString(),\n [\"login_content\"] = content\n }\n };\n }\n\n foreach (var member in response.Params.Param.Value.Struct.Member)\n {\n var propertyName = member.Name.ToUpperFirstChar();\n switch (propertyName)\n {\n case nameof(loginResponse.Token):\n loginResponse.Token = member.Value.String;\n break;\n case nameof(loginResponse.Status):\n loginResponse.Status = member.Value.String;\n break;\n }\n }\n }\n\n if (loginResponse.StatusCode != \"200\")\n throw new InvalidOperationException($\"Can't login because status is '{loginResponse.StatusCode}'\");\n\n if (string.IsNullOrWhiteSpace(loginResponse.Token))\n throw new InvalidOperationException(\"Can't login because token is empty\");\n\n _token = loginResponse.Token;\n }\n\n\n /// \n /// Search\n /// \n /// \n /// \n /// \n /// \n public async Task> Search(string query)\n {\n await Initialize();\n\n if (_token == null)\n throw new InvalidOperationException(\"token is not initialized\");\n\n var subLanguageId = \"all\";\n var limit = 500;\n\n string searchReqXml =\n$\"\"\"\n\n\n SearchSubtitles\n \n \n {_token}\n \n \n \n \n \n \n \n \n query\n {query}\n \n \n sublanguageid\n {subLanguageId}\n \n \n \n \n \n \n \n \n \n \n \n limit\n \n {limit}\n \n \n \n \n \n \n\n\"\"\";\n\n var result = await _client.PostAsync(string.Empty, new StringContent(searchReqXml));\n var content = await result.Content.ReadAsStringAsync();\n\n var serializer = new XmlSerializer(typeof(MethodResponse));\n\n List searchResponses = new();\n\n using (StringReader reader = new(content))\n {\n MethodResponse? response = null;\n try\n {\n result.EnsureSuccessStatusCode();\n response = serializer.Deserialize(reader) as MethodResponse;\n if (response == null)\n {\n throw new InvalidOperationException(\"response is not MethodResponse\");\n }\n }\n catch (Exception ex)\n {\n throw new InvalidOperationException($\"Can't parse the search content: {ex.Message}\", ex)\n {\n Data =\n {\n [\"status_code\"] = ((int)result.StatusCode).ToString(),\n [\"search_content\"] = content\n }\n };\n }\n\n if (!response.Params.Param.Value.Struct.Member.Any(m => m.Name == \"status\" && m.Value.String == \"200 OK\"))\n throw new InvalidOperationException(\"Can't get the search result, status is not 200.\");\n\n var resultMembers = response.Params.Param.Value.Struct.Member.FirstOrDefault(m => m.Name == \"data\");\n if (resultMembers == null)\n throw new InvalidOperationException(\"Can't get the search result, data is not found.\");\n\n foreach (var record in resultMembers.Value.Array.Data.Value)\n {\n SearchResponse searchResponse = new();\n foreach (var member in record.Struct.Member)\n {\n var propertyName = member.Name.ToUpperFirstChar();\n\n var property = typeof(SearchResponse).GetProperty(propertyName);\n if (property != null && property.CanWrite)\n {\n switch (Type.GetTypeCode(property.PropertyType))\n {\n case TypeCode.Int32:\n if (member.Value.String != null &&\n int.TryParse(member.Value.String, out var n))\n {\n property.SetValue(searchResponse, n);\n }\n else\n {\n property.SetValue(searchResponse, member.Value.Int);\n }\n break;\n\n case TypeCode.Double:\n if (member.Value.String != null &&\n double.TryParse(member.Value.String, out var d))\n {\n property.SetValue(searchResponse, d);\n }\n else\n {\n property.SetValue(searchResponse, member.Value.Double);\n }\n break;\n\n case TypeCode.String:\n property.SetValue(searchResponse, member.Value.String);\n break;\n }\n }\n }\n\n searchResponses.Add(searchResponse);\n }\n }\n\n return searchResponses;\n }\n\n /// \n /// Download\n /// \n /// \n /// \n /// \n /// \n public async Task<(byte[] data, bool isBitmap)> Download(SearchResponse sub)\n {\n await Initialize();\n\n if (_token == null)\n throw new InvalidOperationException(\"token is not initialized\");\n\n var idSubtitleFile = sub.IDSubtitleFile;\n var isBitmap = sub.SubFormat.ToLower() == \"sub\";\n\n string downloadReqXml =\n$\"\"\"\n \n \n DownloadSubtitles\n \n \n {_token}\n \n \n \n \n \n {idSubtitleFile}\n \n \n \n \n \n \n \"\"\";\n\n var result = await _client.PostAsync(string.Empty, new StringContent(downloadReqXml));\n var content = await result.Content.ReadAsStringAsync();\n\n XmlSerializer serializer = new(typeof(MethodResponse));\n\n DownloadResponse downloadResponse = new();\n\n using (StringReader reader = new(content))\n {\n MethodResponse? response = null;\n try\n {\n result.EnsureSuccessStatusCode();\n response = serializer.Deserialize(reader) as MethodResponse;\n if (response == null)\n {\n throw new InvalidOperationException(\"response is not MethodResponse\");\n }\n }\n catch (Exception ex)\n {\n throw new InvalidOperationException($\"Can't parse the download content: {ex.Message}\", ex)\n {\n Data =\n {\n [\"status_code\"] = ((int)result.StatusCode).ToString(),\n [\"download_content\"] = content\n }\n };\n }\n\n if (!response.Params.Param.Value.Struct.Member.Any(m => m.Name == \"status\" && m.Value.String == \"200 OK\"))\n throw new InvalidOperationException(\"Can't get the download result, status is not 200.\");\n\n var resultMembers = response.Params.Param.Value.Struct.Member.FirstOrDefault(m => m.Name == \"data\");\n if (resultMembers == null)\n throw new InvalidOperationException(\"Can't get the download result, data is not found.\");\n\n var data = resultMembers.Value.Array.Data.Value.First();\n\n foreach (var member in data.Struct.Member)\n {\n var propertyName = member.Name.ToUpperFirstChar();\n switch (propertyName)\n {\n case nameof(downloadResponse.Data):\n downloadResponse.Data = member.Value.String;\n break;\n case nameof(downloadResponse.Idsubtitlefile):\n downloadResponse.Idsubtitlefile = member.Value.String;\n break;\n }\n }\n }\n\n if (string.IsNullOrEmpty(downloadResponse.Data))\n throw new InvalidOperationException(\"Can't get the download result, base64 data is not found.\");\n\n var gzipSub = Convert.FromBase64String(downloadResponse.Data);\n byte[]? subData;\n\n using MemoryStream compressedStream = new(gzipSub);\n using (GZipStream gzipStream = new(compressedStream, CompressionMode.Decompress))\n using (MemoryStream resultStream = new())\n {\n gzipStream.CopyTo(resultStream);\n subData = resultStream.ToArray();\n }\n\n if (subData == null)\n throw new InvalidOperationException(\"Can't get the download result, decompressed data is not found.\");\n\n if (isBitmap)\n {\n return (subData, true);\n }\n\n Encoding? encoding = TextEncodings.DetectEncoding(subData);\n encoding ??= Encoding.UTF8;\n\n // If there is originally a BOM, it will remain even if it is converted to a string, so delete it.\n string subString = encoding.GetString(subData).TrimStart('\\uFEFF');\n\n // Convert to UTF-8 and return\n byte[] subText = Encoding.UTF8.GetBytes(subString);\n\n if (FL.Config.Subs.SubsExportUTF8WithBom)\n {\n // append BOM\n subText = Encoding.UTF8.GetPreamble().Concat(subText).ToArray();\n }\n\n return (subText, false);\n }\n}\n\n\npublic class LoginResponse\n{\n public string? Token { get; set; }\n public string? Status { get; set; }\n public string? StatusCode => Status?.Split(' ')[0];\n}\n\npublic class SearchResponse\n{\n public string IDSubtitleFile { get; set; } = \"\";\n public string SubFileName { get; set; } = \"\";\n public int SubSize { get; set; } // from string\n public string SubLastTS { get; set; } = \"\";\n public string IDSubtitle { get; set; } = \"\";\n public string SubLanguageID { get; set; } = \"\";\n public string SubFormat { get; set; } = \"\";\n public string SubAddDate { get; set; } = \"\";\n public double SubRating { get; set; } // from string\n public string SubSumVotes { get; set; } = \"\";\n public int SubDownloadsCnt { get; set; } // from string\n public string MovieName { get; set; } = \"\";\n public string MovieYear { get; set; } = \"\";\n public string MovieKind { get; set; } = \"\";\n public string ISO639 { get; set; } = \"\";\n public string LanguageName { get; set; } = \"\";\n public string SeriesSeason { get; set; } = \"\";\n public string SeriesEpisode { get; set; } = \"\";\n public string SubEncoding { get; set; } = \"\";\n public string SubDownloadLink { get; set; } = \"\";\n public string SubtitlesLink { get; set; } = \"\";\n public double Score { get; set; }\n}\n\npublic class DownloadResponse\n{\n public string? Data { get; set; }\n public string? Idsubtitlefile { get; set; }\n}\n\n[XmlRoot(\"value\")]\npublic class Value\n{\n [XmlElement(\"string\")]\n public string? String { get; set; }\n\n [XmlElement(\"struct\")]\n public Struct Struct { get; set; } = null!;\n\n [XmlElement(\"int\")]\n public int Int { get; set; }\n\n [XmlElement(\"double\")]\n public double Double { get; set; }\n\n [XmlElement(\"array\")]\n public Array Array { get; set; } = null!;\n}\n\n[XmlRoot(\"member\")]\npublic class Member\n{\n [XmlElement(\"name\")]\n public string Name { get; set; } = null!;\n\n [XmlElement(\"value\")]\n public Value Value { get; set; } = null!;\n}\n\n[XmlRoot(\"struct\")]\npublic class Struct\n{\n [XmlElement(\"member\")]\n public List Member { get; set; } = null!;\n}\n\n[XmlRoot(\"data\")]\npublic class Data\n{\n [XmlElement(\"value\")]\n public List Value { get; set; } = null!;\n}\n\n[XmlRoot(\"array\")]\npublic class Array\n{\n [XmlElement(\"data\")]\n public Data Data { get; set; } = null!;\n}\n\n[XmlRoot(\"param\")]\npublic class Param\n{\n [XmlElement(\"value\")]\n public Value Value { get; set; } = null!;\n}\n\n[XmlRoot(\"params\")]\npublic class Params\n{\n [XmlElement(\"param\")]\n public Param Param { get; set; } = null!;\n}\n\n[XmlRoot(\"methodResponse\")]\npublic class MethodResponse\n{\n [XmlElement(\"params\")]\n public Params Params { get; set; } = null!;\n}\n"], ["/LLPlayer/FlyleafLib/MediaFramework/MediaContext/DecoderContext.cs", "using FlyleafLib.MediaFramework.MediaDecoder;\nusing FlyleafLib.MediaFramework.MediaDemuxer;\nusing FlyleafLib.MediaFramework.MediaRemuxer;\nusing FlyleafLib.MediaFramework.MediaStream;\nusing FlyleafLib.MediaPlayer;\nusing FlyleafLib.Plugins;\n\nusing static FlyleafLib.Logger;\nusing static FlyleafLib.Utils;\n\nnamespace FlyleafLib.MediaFramework.MediaContext;\n\npublic unsafe partial class DecoderContext : PluginHandler\n{\n /* TODO\n *\n * 1) Lock delay on demuxers' Format Context (for network streams)\n * Ensure we interrupt if we are planning to seek\n * Merge Seek witih GetVideoFrame (To seek accurate or to ensure keyframe)\n * Long delay on Enable/Disable demuxer's streams (lock might not required)\n *\n * 2) Resync implementation / CurTime\n * Transfer player's resync implementation here\n * Ensure we can trust CurTime on lower level (eg. on decoders - demuxers using dts)\n *\n * 3) Timestamps / Memory leak\n * If we have embedded audio/video and the audio decoder will stop/fail for some reason the demuxer will keep filling audio packets\n * Should also check at lower level (demuxer) to prevent wrong packet timestamps (too early or too late)\n * This is normal if it happens on live HLS (probably an ffmpeg bug)\n */\n\n #region Properties\n public object Tag { get; set; } // Upper Layer Object (eg. Player, Downloader) - mainly for plugins to access it\n public bool EnableDecoding { get; set; }\n public new bool Interrupt\n {\n get => base.Interrupt;\n set\n {\n base.Interrupt = value;\n\n if (value)\n {\n VideoDemuxer.Interrupter.ForceInterrupt = 1;\n AudioDemuxer.Interrupter.ForceInterrupt = 1;\n\n for (int i = 0; i < subNum; i++)\n {\n SubtitlesDemuxers[i].Interrupter.ForceInterrupt = 1;\n }\n DataDemuxer.Interrupter.ForceInterrupt = 1;\n }\n else\n {\n VideoDemuxer.Interrupter.ForceInterrupt = 0;\n AudioDemuxer.Interrupter.ForceInterrupt = 0;\n\n for (int i = 0; i < subNum; i++)\n {\n SubtitlesDemuxers[i].Interrupter.ForceInterrupt = 0;\n }\n DataDemuxer.Interrupter.ForceInterrupt = 0;\n }\n }\n }\n\n /// \n /// It will not resync by itself. Requires manual call to ReSync()\n /// \n public bool RequiresResync { get; set; }\n\n public string Extension => VideoDemuxer.Disposed ? AudioDemuxer.Extension : VideoDemuxer.Extension;\n\n // Demuxers\n public Demuxer MainDemuxer { get; private set; }\n public Demuxer AudioDemuxer { get; private set; }\n public Demuxer VideoDemuxer { get; private set; }\n // Demuxer for external subtitles, currently not used for subtitles, just used for stream info\n // Subtitles are displayed using SubtitlesManager\n public Demuxer[] SubtitlesDemuxers { get; private set; }\n public SubtitlesManager SubtitlesManager { get; private set; }\n\n public SubtitlesOCR SubtitlesOCR { get; private set; }\n public SubtitlesASR SubtitlesASR { get; private set; }\n\n public Demuxer DataDemuxer { get; private set; }\n\n // Decoders\n public AudioDecoder AudioDecoder { get; private set; }\n public VideoDecoder VideoDecoder { get; internal set;}\n public SubtitlesDecoder[] SubtitlesDecoders { get; private set; }\n public DataDecoder DataDecoder { get; private set; }\n public DecoderBase GetDecoderPtr(StreamBase stream)\n {\n switch (stream.Type)\n {\n case MediaType.Audio:\n return AudioDecoder;\n case MediaType.Video:\n return VideoDecoder;\n case MediaType.Data:\n return DataDecoder;\n case MediaType.Subs:\n return SubtitlesDecoders[SubtitlesSelectedHelper.CurIndex];\n default:\n throw new InvalidOperationException();\n }\n }\n // Streams\n public AudioStream AudioStream => (VideoDemuxer?.AudioStream) ?? AudioDemuxer.AudioStream;\n public VideoStream VideoStream => VideoDemuxer?.VideoStream;\n public SubtitlesStream[] SubtitlesStreams\n {\n get\n {\n SubtitlesStream[] streams = new SubtitlesStream[subNum];\n\n for (int i = 0; i < subNum; i++)\n {\n if (VideoDemuxer?.SubtitlesStreams?[i] != null)\n {\n streams[i] = VideoDemuxer.SubtitlesStreams[i];\n }\n else if (SubtitlesDemuxers[i]?.SubtitlesStreams?[i] != null)\n {\n streams[i] = SubtitlesDemuxers[i].SubtitlesStreams[i];\n }\n }\n\n return streams;\n }\n }\n public DataStream DataStream => (VideoDemuxer?.DataStream) ?? DataDemuxer.DataStream;\n\n public Tuple ClosedAudioStream { get; private set; }\n public Tuple ClosedVideoStream { get; private set; }\n #endregion\n\n #region Initialize\n LogHandler Log;\n bool shouldDispose;\n int subNum => Config.Subtitles.Max;\n\n public DecoderContext(Config config = null, int uniqueId = -1, bool enableDecoding = true) : base(config, uniqueId)\n {\n Log = new LogHandler((\"[#\" + UniqueId + \"]\").PadRight(8, ' ') + \" [DecoderContext] \");\n Playlist.decoder = this;\n\n EnableDecoding = enableDecoding;\n\n AudioDemuxer = new Demuxer(Config.Demuxer, MediaType.Audio, UniqueId, EnableDecoding);\n VideoDemuxer = new Demuxer(Config.Demuxer, MediaType.Video, UniqueId, EnableDecoding);\n SubtitlesDemuxers = new Demuxer[subNum];\n for (int i = 0; i < subNum; i++)\n {\n SubtitlesDemuxers[i] = new Demuxer(Config.Demuxer, MediaType.Subs, UniqueId, EnableDecoding);\n }\n DataDemuxer = new Demuxer(Config.Demuxer, MediaType.Data, UniqueId, EnableDecoding);\n\n SubtitlesManager = new SubtitlesManager(Config, subNum);\n SubtitlesOCR = new SubtitlesOCR(Config.Subtitles, subNum);\n SubtitlesASR = new SubtitlesASR(SubtitlesManager, Config);\n\n Recorder = new Remuxer(UniqueId);\n\n VideoDecoder = new VideoDecoder(Config, UniqueId);\n AudioDecoder = new AudioDecoder(Config, UniqueId, VideoDecoder);\n SubtitlesDecoders = new SubtitlesDecoder[subNum];\n for (int i = 0; i < subNum; i++)\n {\n SubtitlesDecoders[i] = new SubtitlesDecoder(Config, UniqueId, i);\n }\n DataDecoder = new DataDecoder(Config, UniqueId);\n\n if (EnableDecoding && config.Player.Usage != MediaPlayer.Usage.Audio)\n VideoDecoder.CreateRenderer();\n\n VideoDecoder.recCompleted = RecordCompleted;\n AudioDecoder.recCompleted = RecordCompleted;\n }\n\n public void Initialize()\n {\n VideoDecoder.Renderer?.ClearScreen();\n RequiresResync = false;\n\n OnInitializing();\n Stop();\n OnInitialized();\n }\n public void InitializeSwitch()\n {\n VideoDecoder.Renderer?.ClearScreen();\n RequiresResync = false;\n ClosedAudioStream = null;\n ClosedVideoStream = null;\n\n OnInitializingSwitch();\n Stop();\n OnInitializedSwitch();\n }\n #endregion\n\n #region Seek\n public int Seek(long ms = -1, bool forward = false, bool seekInQueue = true)\n {\n int ret = 0;\n\n if (ms == -1) ms = GetCurTimeMs();\n\n // Review decoder locks (lockAction should be added to avoid dead locks with flush mainly before lockCodecCtx)\n AudioDecoder.resyncWithVideoRequired = false; // Temporary to avoid dead lock on AudioDecoder.lockCodecCtx\n lock (VideoDecoder.lockCodecCtx)\n lock (AudioDecoder.lockCodecCtx)\n lock (SubtitlesDecoders[0].lockCodecCtx)\n lock (SubtitlesDecoders[1].lockCodecCtx)\n lock (DataDecoder.lockCodecCtx)\n {\n long seekTimestamp = CalcSeekTimestamp(VideoDemuxer, ms, ref forward);\n\n // Should exclude seek in queue for all \"local/fast\" files\n lock (VideoDemuxer.lockActions)\n if (Playlist.InputType == InputType.Torrent || ms == 0 || !seekInQueue || VideoDemuxer.SeekInQueue(seekTimestamp, forward) != 0)\n {\n VideoDemuxer.Interrupter.ForceInterrupt = 1;\n OpenedPlugin.OnBuffering();\n lock (VideoDemuxer.lockFmtCtx)\n {\n if (VideoDemuxer.Disposed) { VideoDemuxer.Interrupter.ForceInterrupt = 0; return -1; }\n ret = VideoDemuxer.Seek(seekTimestamp, forward);\n }\n }\n\n VideoDecoder.Flush();\n if (ms == 0)\n VideoDecoder.keyPacketRequired = false; // TBR\n\n if (AudioStream != null && AudioDecoder.OnVideoDemuxer)\n {\n AudioDecoder.Flush();\n if (ms == 0)\n AudioDecoder.nextPts = AudioDecoder.Stream.StartTimePts;\n }\n\n for (int i = 0; i < subNum; i++)\n {\n if (SubtitlesStreams[i] != null && SubtitlesDecoders[i].OnVideoDemuxer)\n {\n SubtitlesDecoders[i].Flush();\n }\n }\n\n if (DataStream != null && DataDecoder.OnVideoDemuxer)\n DataDecoder.Flush();\n }\n\n if (AudioStream != null && !AudioDecoder.OnVideoDemuxer)\n {\n AudioDecoder.Pause();\n AudioDecoder.Flush();\n AudioDemuxer.PauseOnQueueFull = true;\n RequiresResync = true;\n }\n\n //for (int i = 0; i < subNum; i++)\n //{\n // if (SubtitlesStreams[i] != null && !SubtitlesDecoders[i].OnVideoDemuxer)\n // {\n // SubtitlesDecoders[i].Pause();\n // SubtitlesDecoders[i].Flush();\n // SubtitlesDemuxers[i].PauseOnQueueFull = true;\n // RequiresResync = true;\n // }\n //}\n\n if (DataStream != null && !DataDecoder.OnVideoDemuxer)\n {\n DataDecoder.Pause();\n DataDecoder.Flush();\n DataDemuxer.PauseOnQueueFull = true;\n RequiresResync = true;\n }\n\n return ret;\n }\n public int SeekAudio(long ms = -1, bool forward = false)\n {\n int ret = 0;\n\n if (AudioDemuxer.Disposed || AudioDecoder.OnVideoDemuxer || !Config.Audio.Enabled) return -1;\n\n if (ms == -1) ms = GetCurTimeMs();\n\n long seekTimestamp = CalcSeekTimestamp(AudioDemuxer, ms, ref forward);\n\n AudioDecoder.resyncWithVideoRequired = false; // Temporary to avoid dead lock on AudioDecoder.lockCodecCtx\n lock (AudioDecoder.lockActions)\n lock (AudioDecoder.lockCodecCtx)\n {\n lock (AudioDemuxer.lockActions)\n if (AudioDemuxer.SeekInQueue(seekTimestamp, forward) != 0)\n ret = AudioDemuxer.Seek(seekTimestamp, forward);\n\n AudioDecoder.Flush();\n if (VideoDecoder.IsRunning)\n {\n AudioDemuxer.Start();\n AudioDecoder.Start();\n }\n }\n\n return ret;\n }\n\n //public int SeekSubtitles(int subIndex = -1, long ms = -1, bool forward = false)\n //{\n // int ret = -1;\n\n // if (!Config.Subtitles.Enabled)\n // return ret;\n\n // // all sub streams\n // int startIndex = 0;\n // int endIndex = subNum - 1;\n // if (subIndex != -1)\n // {\n // // specific sub stream\n // startIndex = subIndex;\n // endIndex = subIndex;\n // }\n\n // for (int i = startIndex; i <= endIndex; i++)\n // {\n // // Perform seek only for external subtitles\n // if (SubtitlesDemuxers[i].Disposed || SubtitlesDecoders[i].OnVideoDemuxer)\n // {\n // continue;\n // }\n\n // long localMs = ms;\n // if (localMs == -1)\n // {\n // localMs = GetCurTimeMs();\n // }\n\n // long seekTimestamp = CalcSeekTimestamp(SubtitlesDemuxers[i], localMs, ref forward);\n\n // lock (SubtitlesDecoders[i].lockActions)\n // lock (SubtitlesDecoders[i].lockCodecCtx)\n // {\n // // Currently disabled as it will fail to seek within the queue the most of the times\n // //lock (SubtitlesDemuxer.lockActions)\n // //if (SubtitlesDemuxer.SeekInQueue(seekTimestamp, forward) != 0)\n // ret = SubtitlesDemuxers[i].Seek(seekTimestamp, forward);\n\n // SubtitlesDecoders[i].Flush();\n // if (VideoDecoder.IsRunning)\n // {\n // SubtitlesDemuxers[i].Start();\n // SubtitlesDecoders[i].Start();\n // }\n // }\n // }\n // return ret;\n //}\n\n public int SeekData(long ms = -1, bool forward = false)\n {\n int ret = 0;\n\n if (DataDemuxer.Disposed || DataDecoder.OnVideoDemuxer)\n return -1;\n\n if (ms == -1)\n ms = GetCurTimeMs();\n\n long seekTimestamp = CalcSeekTimestamp(DataDemuxer, ms, ref forward);\n\n lock (DataDecoder.lockActions)\n lock (DataDecoder.lockCodecCtx)\n {\n ret = DataDemuxer.Seek(seekTimestamp, forward);\n\n DataDecoder.Flush();\n if (VideoDecoder.IsRunning)\n {\n DataDemuxer.Start();\n DataDecoder.Start();\n }\n }\n\n return ret;\n }\n\n public long GetCurTime() => !VideoDemuxer.Disposed ? VideoDemuxer.CurTime : !AudioDemuxer.Disposed ? AudioDemuxer.CurTime : 0;\n public int GetCurTimeMs() => !VideoDemuxer.Disposed ? (int)(VideoDemuxer.CurTime / 10000) : (!AudioDemuxer.Disposed ? (int)(AudioDemuxer.CurTime / 10000) : 0);\n\n private long CalcSeekTimestamp(Demuxer demuxer, long ms, ref bool forward)\n {\n long startTime = demuxer.hlsCtx == null ? demuxer.StartTime : demuxer.hlsCtx->first_timestamp * 10;\n long ticks = (ms * 10000) + startTime;\n\n if (demuxer.Type == MediaType.Audio) ticks -= Config.Audio.Delay;\n //if (demuxer.Type == MediaType.Subs)\n //{\n // int i = SubtitlesDemuxers[0] == demuxer ? 0 : 1;\n // ticks -= Config.Subtitles[i].Delay + (2 * 1000 * 10000); // We even want the previous subtitles\n //}\n\n if (ticks < startTime)\n {\n ticks = startTime;\n forward = true;\n }\n else if (ticks > startTime + (!VideoDemuxer.Disposed ? VideoDemuxer.Duration : AudioDemuxer.Duration) - (50 * 10000))\n {\n ticks = Math.Max(startTime, startTime + demuxer.Duration - (50 * 10000));\n forward = false;\n }\n\n return ticks;\n }\n #endregion\n\n #region Start/Pause/Stop\n public void Pause()\n {\n VideoDecoder.Pause();\n AudioDecoder.Pause();\n for (int i = 0; i < subNum; i++)\n {\n SubtitlesDecoders[i].Pause();\n }\n DataDecoder.Pause();\n\n VideoDemuxer.Pause();\n AudioDemuxer.Pause();\n for (int i = 0; i < subNum; i++)\n {\n SubtitlesDemuxers[i].Pause();\n }\n DataDemuxer.Pause();\n }\n public void PauseDecoders()\n {\n VideoDecoder.Pause();\n AudioDecoder.Pause();\n for (int i = 0; i < subNum; i++)\n {\n SubtitlesDecoders[i].Pause();\n }\n DataDecoder.Pause();\n }\n public void PauseOnQueueFull()\n {\n VideoDemuxer.PauseOnQueueFull = true;\n AudioDemuxer.PauseOnQueueFull = true;\n for (int i = 0; i < subNum; i++)\n {\n SubtitlesDemuxers[i].PauseOnQueueFull = true;\n }\n DataDecoder.PauseOnQueueFull = true;\n }\n public void Start()\n {\n //if (RequiresResync) Resync();\n\n if (Config.Audio.Enabled)\n {\n AudioDemuxer.Start();\n AudioDecoder.Start();\n }\n\n if (Config.Video.Enabled)\n {\n VideoDemuxer.Start();\n VideoDecoder.Start();\n }\n\n if (Config.Subtitles.Enabled)\n {\n for (int i = 0; i < subNum; i++)\n {\n //if (SubtitlesStreams[i] != null && !SubtitlesDecoders[i].OnVideoDemuxer)\n // SubtitlesDemuxers[i].Start();\n\n //if (SubtitlesStreams[i] != null)\n if (SubtitlesStreams[i] != null && SubtitlesDecoders[i].OnVideoDemuxer)\n SubtitlesDecoders[i].Start();\n }\n }\n\n if (Config.Data.Enabled)\n {\n DataDemuxer.Start();\n DataDecoder.Start();\n }\n }\n public void Stop()\n {\n Interrupt = true;\n\n VideoDecoder.Dispose();\n AudioDecoder.Dispose();\n for (int i = 0; i < subNum; i++)\n {\n SubtitlesDecoders[i].Dispose();\n }\n\n DataDecoder.Dispose();\n AudioDemuxer.Dispose();\n for (int i = 0; i < subNum; i++)\n {\n SubtitlesDemuxers[i].Dispose();\n }\n\n DataDemuxer.Dispose();\n VideoDemuxer.Dispose();\n\n Interrupt = false;\n }\n public void StopThreads()\n {\n Interrupt = true;\n\n VideoDecoder.Stop();\n AudioDecoder.Stop();\n for (int i = 0; i < subNum; i++)\n {\n SubtitlesDecoders[i].Stop();\n }\n\n DataDecoder.Stop();\n AudioDemuxer.Stop();\n for (int i = 0; i < subNum; i++)\n {\n SubtitlesDemuxers[i].Stop();\n }\n DataDemuxer.Stop();\n VideoDemuxer.Stop();\n\n Interrupt = false;\n }\n #endregion\n\n public void Resync(long timestamp = -1)\n {\n bool isRunning = VideoDemuxer.IsRunning;\n\n if (AudioStream != null && AudioStream.Demuxer.Type != MediaType.Video && Config.Audio.Enabled)\n {\n if (timestamp == -1) timestamp = VideoDemuxer.CurTime;\n if (CanInfo) Log.Info($\"Resync audio to {TicksToTime(timestamp)}\");\n\n SeekAudio(timestamp / 10000);\n if (isRunning)\n {\n AudioDemuxer.Start();\n AudioDecoder.Start();\n }\n }\n\n //for (int i = 0; i < subNum; i++)\n //{\n // if (SubtitlesStreams[i] != null && SubtitlesStreams[i].Demuxer.Type != MediaType.Video && Config.Subtitles.Enabled)\n // {\n // if (timestamp == -1)\n // timestamp = VideoDemuxer.CurTime;\n // if (CanInfo)\n // Log.Info($\"Resync subs:{i} to {TicksToTime(timestamp)}\");\n\n // SeekSubtitles(i, timestamp / 10000, false);\n // if (isRunning)\n // {\n // SubtitlesDemuxers[i].Start();\n // SubtitlesDecoders[i].Start();\n // }\n // }\n //}\n\n if (DataStream != null && Config.Data.Enabled) // Should check if it actually an external (not embedded) stream DataStream.Demuxer.Type != MediaType.Video ?\n {\n if (timestamp == -1)\n timestamp = VideoDemuxer.CurTime;\n if (CanInfo)\n Log.Info($\"Resync data to {TicksToTime(timestamp)}\");\n\n SeekData(timestamp / 10000);\n if (isRunning)\n {\n DataDemuxer.Start();\n DataDecoder.Start();\n }\n }\n\n RequiresResync = false;\n }\n\n //public void ResyncSubtitles(long timestamp = -1)\n //{\n // if (SubtitlesStream != null && Config.Subtitles.Enabled)\n // {\n // if (timestamp == -1) timestamp = VideoDemuxer.CurTime;\n // if (CanInfo) Log.Info($\"Resync subs to {TicksToTime(timestamp)}\");\n\n // if (SubtitlesStream.Demuxer.Type != MediaType.Video)\n // SeekSubtitles(timestamp / 10000);\n // else\n\n // if (VideoDemuxer.IsRunning)\n // {\n // SubtitlesDemuxer.Start();\n // SubtitlesDecoder.Start();\n // }\n // }\n //}\n public void Flush()\n {\n VideoDemuxer.DisposePackets();\n AudioDemuxer.DisposePackets();\n for (int i = 0; i < subNum; i++)\n {\n SubtitlesDemuxers[i].DisposePackets();\n }\n DataDemuxer.DisposePackets();\n\n VideoDecoder.Flush();\n AudioDecoder.Flush();\n for (int i = 0; i < subNum; i++)\n {\n SubtitlesDecoders[i].Flush();\n }\n DataDecoder.Flush();\n }\n\n // !!! NEEDS RECODING\n public long GetVideoFrame(long timestamp = -1)\n {\n // TBR: Between seek and GetVideoFrame lockCodecCtx is lost and if VideoDecoder is running will already have decoded some frames (Currently ensure you pause VideDecoder before seek)\n\n int ret;\n int allowedErrors = Config.Decoder.MaxErrors;\n AVPacket* packet;\n\n lock (VideoDemuxer.lockFmtCtx)\n lock (VideoDecoder.lockCodecCtx)\n while (VideoDemuxer.VideoStream != null && !Interrupt)\n {\n if (VideoDemuxer.VideoPackets.IsEmpty)\n {\n packet = av_packet_alloc();\n VideoDemuxer.Interrupter.ReadRequest();\n ret = av_read_frame(VideoDemuxer.FormatContext, packet);\n if (ret != 0)\n {\n av_packet_free(&packet);\n return -1;\n }\n }\n else\n packet = VideoDemuxer.VideoPackets.Dequeue();\n\n if (!VideoDemuxer.EnabledStreams.Contains(packet->stream_index)) { av_packet_free(&packet); continue; }\n\n if (CanTrace)\n {\n var stream = VideoDemuxer.AVStreamToStream[packet->stream_index];\n long dts = packet->dts == AV_NOPTS_VALUE ? -1 : (long)(packet->dts * stream.Timebase);\n long pts = packet->pts == AV_NOPTS_VALUE ? -1 : (long)(packet->pts * stream.Timebase);\n Log.Trace($\"[{stream.Type}] DTS: {(dts == -1 ? \"-\" : TicksToTime(dts))} PTS: {(pts == -1 ? \"-\" : TicksToTime(pts))} | FLPTS: {(pts == -1 ? \"-\" : TicksToTime(pts - VideoDemuxer.StartTime))} | CurTime: {TicksToTime(VideoDemuxer.CurTime)} | Buffered: {TicksToTime(VideoDemuxer.BufferedDuration)}\");\n }\n\n var codecType = VideoDemuxer.FormatContext->streams[packet->stream_index]->codecpar->codec_type;\n\n if (codecType == AVMediaType.Video && VideoDecoder.keyPacketRequired)\n {\n if (packet->flags.HasFlag(PktFlags.Key))\n VideoDecoder.keyPacketRequired = false;\n else\n {\n if (CanWarn) Log.Warn(\"Ignoring non-key packet\");\n av_packet_free(&packet);\n continue;\n }\n }\n\n if (VideoDemuxer.IsHLSLive)\n VideoDemuxer.UpdateHLSTime();\n\n switch (codecType)\n {\n case AVMediaType.Audio:\n if (timestamp == -1 || (long)(packet->pts * AudioStream.Timebase) - VideoDemuxer.StartTime + (VideoStream.FrameDuration / 2) > timestamp)\n VideoDemuxer.AudioPackets.Enqueue(packet);\n else\n av_packet_free(&packet);\n\n continue;\n\n case AVMediaType.Subtitle:\n for (int i = 0; i < subNum; i++)\n {\n if (SubtitlesStreams[i]?.StreamIndex != packet->stream_index)\n {\n continue;\n }\n\n if (timestamp == -1 ||\n (long)(packet->pts * SubtitlesStreams[i].Timebase) - VideoDemuxer.StartTime +\n (VideoStream.FrameDuration / 2) > timestamp)\n {\n // Clone packets to support simultaneous display of the same subtitle\n VideoDemuxer.SubtitlesPackets[i].Enqueue(av_packet_clone(packet));\n }\n }\n\n // cloned, so free packet\n av_packet_free(&packet);\n\n continue;\n\n case AVMediaType.Data: // this should catch the data stream packets until we have a valid vidoe keyframe (it should fill the pts if NOPTS with lastVideoPacketPts similarly to the demuxer)\n if ((timestamp == -1 && VideoDecoder.StartTime != NoTs) || (long)(packet->pts * DataStream.Timebase) - VideoDemuxer.StartTime + (VideoStream.FrameDuration / 2) > timestamp)\n VideoDemuxer.DataPackets.Enqueue(packet);\n\n packet = av_packet_alloc();\n\n continue;\n\n case AVMediaType.Video:\n ret = avcodec_send_packet(VideoDecoder.CodecCtx, packet);\n\n if (VideoDecoder.swFallback)\n {\n VideoDecoder.SWFallback();\n ret = avcodec_send_packet(VideoDecoder.CodecCtx, packet);\n }\n\n av_packet_free(&packet);\n\n if (ret != 0)\n {\n allowedErrors--;\n if (CanWarn) Log.Warn($\"{FFmpegEngine.ErrorCodeToMsg(ret)} ({ret})\");\n\n if (allowedErrors == 0) { Log.Error(\"Too many errors!\"); return -1; }\n\n continue;\n }\n\n //VideoDemuxer.UpdateCurTime();\n\n var frame = av_frame_alloc();\n while (VideoDemuxer.VideoStream != null && !Interrupt)\n {\n ret = avcodec_receive_frame(VideoDecoder.CodecCtx, frame);\n if (ret != 0) { av_frame_unref(frame); break; }\n\n if (frame->best_effort_timestamp != AV_NOPTS_VALUE)\n frame->pts = frame->best_effort_timestamp;\n else if (frame->pts == AV_NOPTS_VALUE)\n {\n if (!VideoStream.FixTimestamps)\n {\n av_frame_unref(frame);\n continue;\n }\n\n frame->pts = VideoDecoder.lastFixedPts + VideoStream.StartTimePts;\n VideoDecoder.lastFixedPts += av_rescale_q(VideoStream.FrameDuration / 10, Engine.FFmpeg.AV_TIMEBASE_Q, VideoStream.AVStream->time_base);\n }\n\n if (!VideoDecoder.filledFromCodec)\n {\n ret = VideoDecoder.FillFromCodec(frame);\n\n if (ret == -1234)\n {\n av_frame_free(&frame);\n return -1;\n }\n }\n\n // Accurate seek with +- half frame distance\n if (timestamp != -1 && (long)(frame->pts * VideoStream.Timebase) - VideoDemuxer.StartTime + (VideoStream.FrameDuration / 2) < timestamp)\n {\n av_frame_unref(frame);\n continue;\n }\n\n //if (CanInfo) Info($\"Asked for {Utils.TicksToTime(timestamp)} and got {Utils.TicksToTime((long)(frame->pts * VideoStream.Timebase) - VideoDemuxer.StartTime)} | Diff {Utils.TicksToTime(timestamp - ((long)(frame->pts * VideoStream.Timebase) - VideoDemuxer.StartTime))}\");\n VideoDecoder.StartTime = (long)(frame->pts * VideoStream.Timebase) - VideoDemuxer.StartTime;\n\n var mFrame = VideoDecoder.Renderer.FillPlanes(frame);\n if (mFrame != null) VideoDecoder.Frames.Enqueue(mFrame);\n\n do\n {\n ret = avcodec_receive_frame(VideoDecoder.CodecCtx, frame);\n if (ret != 0) break;\n mFrame = VideoDecoder.Renderer.FillPlanes(frame);\n if (mFrame != null) VideoDecoder.Frames.Enqueue(mFrame);\n } while (!VideoDemuxer.Disposed && !Interrupt);\n\n av_frame_free(&frame);\n return mFrame.timestamp;\n }\n\n av_frame_free(&frame);\n\n break; // Switch break\n\n default:\n av_packet_free(&packet);\n continue;\n\n } // Switch\n\n } // While\n\n return -1;\n }\n public new void Dispose()\n {\n shouldDispose = true;\n Stop();\n Interrupt = true;\n VideoDecoder.DestroyRenderer();\n base.Dispose();\n }\n\n public void PrintStats()\n {\n string dump = \"\\r\\n-===== Streams / Packets / Frames =====-\\r\\n\";\n dump += $\"\\r\\n AudioPackets ({VideoDemuxer.AudioStreams.Count}): {VideoDemuxer.AudioPackets.Count}\";\n dump += $\"\\r\\n VideoPackets ({VideoDemuxer.VideoStreams.Count}): {VideoDemuxer.VideoPackets.Count}\";\n for (int i = 0; i < subNum; i++)\n {\n dump += $\"\\r\\n SubtitlesPackets{i+1} ({VideoDemuxer.SubtitlesStreamsAll.Count}): {VideoDemuxer.SubtitlesPackets[i].Count}\";\n }\n\n dump += $\"\\r\\n AudioPackets ({AudioDemuxer.AudioStreams.Count}): {AudioDemuxer.AudioPackets.Count} (AudioDemuxer)\";\n\n for (int i = 0; i < subNum; i++)\n {\n dump += $\"\\r\\n SubtitlesPackets{i+1} ({SubtitlesDemuxers[i].SubtitlesStreamsAll.Count}): {SubtitlesDemuxers[i].SubtitlesPackets[0].Count} (SubtitlesDemuxer)\";\n }\n\n dump += $\"\\r\\n Video Frames : {VideoDecoder.Frames.Count}\";\n dump += $\"\\r\\n Audio Frames : {AudioDecoder.Frames.Count}\";\n for (int i = 0; i < subNum; i++)\n {\n dump += $\"\\r\\n Subtitles Frames{i+1} : {SubtitlesDecoders[i].Frames.Count}\";\n }\n\n if (CanInfo) Log.Info(dump);\n }\n\n #region Recorder\n Remuxer Recorder;\n public event EventHandler RecordingCompleted;\n public bool IsRecording => VideoDecoder.isRecording || AudioDecoder.isRecording;\n int oldMaxAudioFrames;\n bool recHasVideo;\n public void StartRecording(ref string filename, bool useRecommendedExtension = true)\n {\n if (IsRecording) StopRecording();\n\n oldMaxAudioFrames = -1;\n recHasVideo = false;\n\n if (CanInfo) Log.Info(\"Record Start\");\n\n recHasVideo = !VideoDecoder.Disposed && VideoDecoder.Stream != null;\n\n if (useRecommendedExtension)\n filename = $\"{filename}.{(recHasVideo ? VideoDecoder.Stream.Demuxer.Extension : AudioDecoder.Stream.Demuxer.Extension)}\";\n\n Recorder.Open(filename);\n\n bool failed;\n\n if (recHasVideo)\n {\n failed = Recorder.AddStream(VideoDecoder.Stream.AVStream) != 0;\n if (CanInfo) Log.Info(failed ? \"Failed to add video stream\" : \"Video stream added to the recorder\");\n }\n\n if (!AudioDecoder.Disposed && AudioDecoder.Stream != null)\n {\n failed = Recorder.AddStream(AudioDecoder.Stream.AVStream, !AudioDecoder.OnVideoDemuxer) != 0;\n if (CanInfo) Log.Info(failed ? \"Failed to add audio stream\" : \"Audio stream added to the recorder\");\n }\n\n if (!Recorder.HasStreams || Recorder.WriteHeader() != 0) return; //throw new Exception(\"Invalid remuxer configuration\");\n\n // Check also buffering and possible Diff of first audio/video timestamp to remuxer to ensure sync between each other (shouldn't be more than 30-50ms)\n oldMaxAudioFrames = Config.Decoder.MaxAudioFrames;\n //long timestamp = Math.Max(VideoDemuxer.CurTime + VideoDemuxer.BufferedDuration, AudioDemuxer.CurTime + AudioDemuxer.BufferedDuration) + 1500 * 10000;\n Config.Decoder.MaxAudioFrames = Config.Decoder.MaxVideoFrames;\n\n VideoDecoder.StartRecording(Recorder);\n AudioDecoder.StartRecording(Recorder);\n }\n public void StopRecording()\n {\n if (oldMaxAudioFrames != -1) Config.Decoder.MaxAudioFrames = oldMaxAudioFrames;\n\n VideoDecoder.StopRecording();\n AudioDecoder.StopRecording();\n Recorder.Dispose();\n oldMaxAudioFrames = -1;\n if (CanInfo) Log.Info(\"Record Completed\");\n }\n internal void RecordCompleted(MediaType type)\n {\n if (!recHasVideo || (recHasVideo && type == MediaType.Video))\n {\n StopRecording();\n RecordingCompleted?.Invoke(this, new EventArgs());\n }\n }\n #endregion\n}\n"], ["/LLPlayer/FlyleafLib/MediaPlayer/Player.Extra.cs", "using System;\nusing System.Drawing.Imaging;\nusing System.IO;\nusing System.Windows;\n\nusing FlyleafLib.MediaFramework.MediaDecoder;\nusing FlyleafLib.MediaFramework.MediaDemuxer;\nusing FlyleafLib.MediaFramework.MediaFrame;\nusing FlyleafLib.MediaFramework.MediaRenderer;\n\nusing static FlyleafLib.Utils;\nusing static FlyleafLib.Logger;\n\nnamespace FlyleafLib.MediaPlayer;\n\nunsafe partial class Player\n{\n public bool IsOpenFileDialogOpen { get; private set; }\n\n\n public void SeekBackward() => SeekBackward_(Config.Player.SeekOffset, Config.Player.SeekOffsetAccurate);\n public void SeekBackward2() => SeekBackward_(Config.Player.SeekOffset2, Config.Player.SeekOffsetAccurate2);\n public void SeekBackward3() => SeekBackward_(Config.Player.SeekOffset3, Config.Player.SeekOffsetAccurate3);\n public void SeekBackward4() => SeekBackward_(Config.Player.SeekOffset4, Config.Player.SeekOffsetAccurate4);\n public void SeekBackward_(long offset, bool accurate)\n {\n if (!CanPlay)\n return;\n\n long seekTs = CurTime - (CurTime % offset) - offset;\n\n if (Config.Player.SeekAccurate || accurate)\n SeekAccurate(Math.Max((int) (seekTs / 10000), 0));\n else\n Seek(Math.Max((int) (seekTs / 10000), 0), false);\n }\n\n public void SeekForward() => SeekForward_(Config.Player.SeekOffset, Config.Player.SeekOffsetAccurate);\n public void SeekForward2() => SeekForward_(Config.Player.SeekOffset2, Config.Player.SeekOffsetAccurate2);\n public void SeekForward3() => SeekForward_(Config.Player.SeekOffset3, Config.Player.SeekOffsetAccurate3);\n public void SeekForward4() => SeekForward_(Config.Player.SeekOffset4, Config.Player.SeekOffsetAccurate4);\n public void SeekForward_(long offset, bool accurate)\n {\n if (!CanPlay)\n return;\n\n long seekTs = CurTime - (CurTime % offset) + offset;\n\n if (seekTs > Duration && !isLive)\n return;\n\n if (Config.Player.SeekAccurate || accurate)\n SeekAccurate((int)(seekTs / 10000));\n else\n Seek((int)(seekTs / 10000), true);\n }\n\n public void SeekToChapter(Demuxer.Chapter chapter) =>\n /* TODO\n* Accurate pts required (backward/forward check)\n* Get current chapter implementation + next/prev\n*/\n Seek((int)(chapter.StartTime / 10000.0), true);\n\n public void CopyToClipboard()\n {\n var url = decoder.Playlist.Url;\n if (url == null)\n return;\n\n Clipboard.SetText(url);\n OSDMessage = $\"Copy {url}\";\n }\n public void CopyItemToClipboard()\n {\n if (decoder.Playlist.Selected == null || decoder.Playlist.Selected.DirectUrl == null)\n return;\n\n string url = decoder.Playlist.Selected.DirectUrl;\n\n Clipboard.SetText(url);\n OSDMessage = $\"Copy {url}\";\n }\n public void OpenFromClipboard()\n {\n string text = Clipboard.GetText();\n if (!string.IsNullOrWhiteSpace(text))\n {\n OpenAsync(text);\n }\n }\n\n public void OpenFromClipboardSafe()\n {\n if (decoder.Playlist.Selected != null)\n {\n return;\n }\n\n OpenFromClipboard();\n }\n\n public void OpenFromFileDialog()\n {\n int prevTimeout = Activity.Timeout;\n Activity.IsEnabled = false;\n Activity.Timeout = 0;\n IsOpenFileDialogOpen = true;\n\n System.Windows.Forms.OpenFileDialog openFileDialog = new();\n\n // If there is currently an open file, set that folder as the base folder\n if (decoder.Playlist.Url != null && File.Exists(decoder.Playlist.Url))\n {\n var folder = Path.GetDirectoryName(decoder.Playlist.Url);\n if (folder != null)\n openFileDialog.InitialDirectory = folder;\n }\n\n var res = openFileDialog.ShowDialog();\n\n if (res == System.Windows.Forms.DialogResult.OK)\n OpenAsync(openFileDialog.FileName);\n\n Activity.Timeout = prevTimeout;\n Activity.IsEnabled = true;\n IsOpenFileDialogOpen = false;\n }\n\n public void ShowFrame(int frameIndex)\n {\n if (!Video.IsOpened || !CanPlay || VideoDemuxer.IsHLSLive) return;\n\n lock (lockActions)\n {\n Pause();\n dFrame = null;\n for (int i = 0; i < subNum; i++)\n {\n sFrames[i] = null;\n SubtitleClear(i);\n }\n\n decoder.Flush();\n decoder.RequiresResync = true;\n\n vFrame = VideoDecoder.GetFrame(frameIndex);\n if (vFrame == null) return;\n\n if (CanDebug) Log.Debug($\"SFI: {VideoDecoder.GetFrameNumber(vFrame.timestamp)}\");\n\n curTime = vFrame.timestamp;\n renderer.Present(vFrame);\n reversePlaybackResync = true;\n vFrame = null;\n\n UI(() => UpdateCurTime());\n }\n }\n\n // Whether video queue should be flushed as it could have opposite direction frames\n bool shouldFlushNext;\n bool shouldFlushPrev;\n public void ShowFrameNext()\n {\n if (!Video.IsOpened || !CanPlay || VideoDemuxer.IsHLSLive)\n return;\n\n lock (lockActions)\n {\n Pause();\n\n if (Status == Status.Ended)\n {\n status = Status.Paused;\n UI(() => Status = Status);\n }\n\n shouldFlushPrev = true;\n decoder.RequiresResync = true;\n\n if (shouldFlushNext)\n {\n decoder.StopThreads();\n decoder.Flush();\n shouldFlushNext = false;\n\n var vFrame = VideoDecoder.GetFrame(VideoDecoder.GetFrameNumber(CurTime));\n VideoDecoder.DisposeFrame(vFrame);\n }\n\n for (int i = 0; i < subNum; i++)\n {\n sFrames[i] = null;\n SubtitleClear(i);\n }\n\n if (VideoDecoder.Frames.IsEmpty)\n vFrame = VideoDecoder.GetFrameNext();\n else\n VideoDecoder.Frames.TryDequeue(out vFrame);\n\n if (vFrame == null)\n return;\n\n if (CanDebug) Log.Debug($\"SFN: {VideoDecoder.GetFrameNumber(vFrame.timestamp)}\");\n\n curTime = curTime = vFrame.timestamp;\n renderer.Present(vFrame);\n reversePlaybackResync = true;\n vFrame = null;\n\n UI(() => UpdateCurTime());\n }\n }\n public void ShowFramePrev()\n {\n if (!Video.IsOpened || !CanPlay || VideoDemuxer.IsHLSLive)\n return;\n\n lock (lockActions)\n {\n Pause();\n\n if (Status == Status.Ended)\n {\n status = Status.Paused;\n UI(() => Status = Status);\n }\n\n shouldFlushNext = true;\n decoder.RequiresResync = true;\n\n if (shouldFlushPrev)\n {\n decoder.StopThreads();\n decoder.Flush();\n shouldFlushPrev = false;\n }\n\n for (int i = 0; i < subNum; i++)\n {\n sFrames[i] = null;\n SubtitleClear(i);\n }\n\n if (VideoDecoder.Frames.IsEmpty)\n {\n // Temp fix for previous timestamps until we seperate GetFrame for Extractor and the Player\n reversePlaybackResync = true;\n int askedFrame = VideoDecoder.GetFrameNumber(CurTime) - 1;\n //Log.Debug($\"CurTime1: {TicksToTime(CurTime)}, Asked: {askedFrame}\");\n vFrame = VideoDecoder.GetFrame(askedFrame);\n if (vFrame == null) return;\n\n int recvFrame = VideoDecoder.GetFrameNumber(vFrame.timestamp);\n //Log.Debug($\"CurTime2: {TicksToTime(vFrame.timestamp)}, Got: {recvFrame}\");\n if (askedFrame != recvFrame)\n {\n VideoDecoder.DisposeFrame(vFrame);\n vFrame = null;\n vFrame = askedFrame > recvFrame\n ? VideoDecoder.GetFrame(VideoDecoder.GetFrameNumber(CurTime))\n : VideoDecoder.GetFrame(VideoDecoder.GetFrameNumber(CurTime) - 2);\n }\n }\n else\n VideoDecoder.Frames.TryDequeue(out vFrame);\n\n if (vFrame == null)\n return;\n\n if (CanDebug) Log.Debug($\"SFB: {VideoDecoder.GetFrameNumber(vFrame.timestamp)}\");\n\n curTime = vFrame.timestamp;\n renderer.Present(vFrame);\n vFrame = null;\n UI(() => UpdateCurTime()); // For some strange reason this will not be updated on KeyDown (only on KeyUp) which doesn't happen on ShowFrameNext (GPU overload? / Thread.Sleep underlying in UI thread?)\n }\n }\n\n public void SpeedUp() => Speed += Config.Player.SpeedOffset;\n public void SpeedUp2() => Speed += Config.Player.SpeedOffset2;\n public void SpeedDown() => Speed -= Config.Player.SpeedOffset;\n public void SpeedDown2() => Speed -= Config.Player.SpeedOffset2;\n\n public void RotateRight() => renderer.Rotation = (renderer.Rotation + 90) % 360;\n public void RotateLeft() => renderer.Rotation = renderer.Rotation < 90 ? 360 + renderer.Rotation - 90 : renderer.Rotation - 90;\n\n public void FullScreen() => Host?.Player_SetFullScreen(true);\n public void NormalScreen() => Host?.Player_SetFullScreen(false);\n public void ToggleFullScreen()\n {\n if (Host == null)\n return;\n\n if (Host.Player_GetFullScreen())\n Host.Player_SetFullScreen(false);\n else\n Host.Player_SetFullScreen(true);\n }\n\n /// \n /// Starts recording (uses Config.Player.FolderRecordings and default filename title_curTime)\n /// \n public void StartRecording()\n {\n if (!CanPlay)\n return;\n try\n {\n if (!Directory.Exists(Config.Player.FolderRecordings))\n Directory.CreateDirectory(Config.Player.FolderRecordings);\n\n string filename = GetValidFileName(string.IsNullOrEmpty(Playlist.Selected.Title) ? \"Record\" : Playlist.Selected.Title) + $\"_{new TimeSpan(CurTime):hhmmss}.\" + decoder.Extension;\n filename = FindNextAvailableFile(Path.Combine(Config.Player.FolderRecordings, filename));\n StartRecording(ref filename, false);\n } catch { }\n }\n\n /// \n /// Starts recording\n /// \n /// Path of the new recording file\n /// You can force the output container's format or use the recommended one to avoid incompatibility\n public void StartRecording(ref string filename, bool useRecommendedExtension = true)\n {\n if (!CanPlay)\n return;\n\n OSDMessage = $\"Start recording to {Path.GetFileName(filename)}\";\n decoder.StartRecording(ref filename, useRecommendedExtension);\n IsRecording = decoder.IsRecording;\n }\n\n /// \n /// Stops recording\n /// \n public void StopRecording()\n {\n decoder.StopRecording();\n IsRecording = decoder.IsRecording;\n OSDMessage = \"Stop recording\";\n }\n public void ToggleRecording()\n {\n if (!CanPlay) return;\n\n if (IsRecording)\n StopRecording();\n else\n StartRecording();\n }\n\n /// \n /// Saves the current video frame (encoding based on file extention .bmp, .png, .jpg)\n /// If filename not specified will use Config.Player.FolderSnapshots and with default filename title_frameNumber.ext (ext from Config.Player.SnapshotFormat)\n /// If width/height not specified will use the original size. If one of them will be set, the other one will be set based on original ratio\n /// If frame not specified will use the current/last frame\n /// \n /// Specify the filename (null: will use Config.Player.FolderSnapshots and with default filename title_frameNumber.ext (ext from Config.Player.SnapshotFormat)\n /// Specify the width (-1: will keep the ratio based on height)\n /// Specify the height (-1: will keep the ratio based on width)\n /// Specify the frame (null: will use the current/last frame)\n /// \n public void TakeSnapshotToFile(string filename = null, int width = -1, int height = -1, VideoFrame frame = null)\n {\n if (!CanPlay)\n return;\n\n if (filename == null)\n {\n try\n {\n if (!Directory.Exists(Config.Player.FolderSnapshots))\n Directory.CreateDirectory(Config.Player.FolderSnapshots);\n\n // TBR: if frame is specified we don't know the frame's number\n filename = GetValidFileName(string.IsNullOrEmpty(Playlist.Selected.Title) ? \"Snapshot\" : Playlist.Selected.Title) + $\"_{(frame == null ? VideoDecoder.GetFrameNumber(CurTime).ToString() : \"X\")}.{Config.Player.SnapshotFormat}\";\n filename = FindNextAvailableFile(Path.Combine(Config.Player.FolderSnapshots, filename));\n } catch { return; }\n }\n\n string ext = GetUrlExtention(filename);\n\n ImageFormat imageFormat;\n\n switch (ext)\n {\n case \"bmp\":\n imageFormat = ImageFormat.Bmp;\n break;\n\n case \"png\":\n imageFormat = ImageFormat.Png;\n break;\n\n case \"jpg\":\n case \"jpeg\":\n imageFormat = ImageFormat.Jpeg;\n break;\n\n default:\n throw new Exception($\"Invalid snapshot extention '{ext}' (valid .bmp, .png, .jpeg, .jpg\");\n }\n\n if (renderer == null)\n return;\n\n var snapshotBitmap = renderer.GetBitmap(width, height, frame);\n if (snapshotBitmap == null)\n return;\n\n Exception e = null;\n try\n {\n snapshotBitmap.Save(filename, imageFormat);\n\n UI(() =>\n {\n OSDMessage = $\"Save snapshot to {Path.GetFileName(filename)}\";\n });\n }\n catch (Exception e2)\n {\n e = e2;\n }\n snapshotBitmap.Dispose();\n\n if (e != null)\n throw e;\n }\n\n /// \n /// Returns a bitmap of the current or specified video frame\n /// If width/height not specified will use the original size. If one of them will be set, the other one will be set based on original ratio\n /// If frame not specified will use the current/last frame\n /// \n /// Specify the width (-1: will keep the ratio based on height)\n /// Specify the height (-1: will keep the ratio based on width)\n /// Specify the frame (null: will use the current/last frame)\n /// \n public System.Drawing.Bitmap TakeSnapshotToBitmap(int width = -1, int height = -1, VideoFrame frame = null) => renderer?.GetBitmap(width, height, frame);\n\n public void ZoomIn() => Zoom += Config.Player.ZoomOffset;\n public void ZoomOut() { if (Zoom - Config.Player.ZoomOffset < 1) return; Zoom -= Config.Player.ZoomOffset; }\n\n /// \n /// Pan zoom in with center point\n /// \n /// \n public void ZoomIn(Point p) { renderer.ZoomWithCenterPoint(p, renderer.Zoom + Config.Player.ZoomOffset / 100.0); RaiseUI(nameof(Zoom)); }\n\n /// \n /// Pan zoom out with center point\n /// \n /// \n public void ZoomOut(Point p){ double zoom = renderer.Zoom - Config.Player.ZoomOffset / 100.0; if (zoom < 0.001) return; renderer.ZoomWithCenterPoint(p, zoom); RaiseUI(nameof(Zoom)); }\n\n /// \n /// Pan zoom (no raise)\n /// \n /// \n public void SetZoom(double zoom) => renderer.SetZoom(zoom);\n /// \n /// Pan zoom's center point (no raise, no center point change)\n /// \n /// \n public void SetZoomCenter(Point p) => renderer.SetZoomCenter(p);\n /// \n /// Pan zoom and center point (no raise)\n /// \n /// \n /// \n public void SetZoomAndCenter(double zoom, Point p) => renderer.SetZoomAndCenter(zoom, p);\n\n public void ResetAll()\n {\n ResetSpeed();\n ResetRotation();\n ResetZoom();\n }\n\n public void ResetSpeed()\n {\n Speed = 1;\n }\n\n public void ResetRotation()\n {\n Rotation = 0;\n }\n\n public void ResetZoom()\n {\n bool npx = renderer.PanXOffset != 0;\n bool npy = renderer.PanYOffset != 0;\n bool npz = renderer.Zoom != 1;\n renderer.SetPanAll(0, 0, Rotation, 1, Renderer.ZoomCenterPoint, true); // Pan X/Y, Rotation, Zoom, Zoomcenter, Refresh\n\n UI(() =>\n {\n if (npx) Raise(nameof(PanXOffset));\n if (npy) Raise(nameof(PanYOffset));\n if (npz) Raise(nameof(Zoom));\n });\n }\n}\n"], ["/LLPlayer/FlyleafLib/MediaFramework/MediaDecoder/AudioDecoder.Filters.cs", "using System.Runtime.InteropServices;\nusing System.Threading;\n\nusing FlyleafLib.MediaFramework.MediaStream;\nusing FlyleafLib.MediaFramework.MediaFrame;\n\nusing static FlyleafLib.Logger;\n\nnamespace FlyleafLib.MediaFramework.MediaDecoder;\n\npublic unsafe partial class AudioDecoder\n{\n AVFilterContext* abufferCtx;\n AVFilterContext* abufferSinkCtx;\n AVFilterGraph* filterGraph;\n bool abufferDrained;\n long curSamples;\n double missedSamples;\n long filterFirstPts;\n bool setFirstPts;\n object lockSpeed = new();\n AVRational sinkTimebase;\n AVFrame* filtframe;\n\n private AVFilterContext* CreateFilter(string name, string args, AVFilterContext* prevCtx = null, string id = null)\n {\n int ret;\n AVFilterContext* filterCtx;\n AVFilter* filter;\n\n id ??= name;\n\n filter = avfilter_get_by_name(name);\n if (filter == null)\n throw new Exception($\"[Filter {name}] not found\");\n\n ret = avfilter_graph_create_filter(&filterCtx, filter, id, args, null, filterGraph);\n if (ret < 0)\n throw new Exception($\"[Filter {name}] avfilter_graph_create_filter failed ({FFmpegEngine.ErrorCodeToMsg(ret)})\");\n\n if (prevCtx == null)\n return filterCtx;\n\n ret = avfilter_link(prevCtx, 0, filterCtx, 0);\n\n return ret != 0\n ? throw new Exception($\"[Filter {name}] avfilter_link failed ({FFmpegEngine.ErrorCodeToMsg(ret)})\")\n : filterCtx;\n }\n private int SetupFilters()\n {\n int ret = -1;\n\n try\n {\n DisposeFilters();\n\n AVFilterContext* linkCtx;\n\n sinkTimebase = new() { Num = 1, Den = codecCtx->sample_rate};\n filtframe = av_frame_alloc();\n filterGraph = avfilter_graph_alloc();\n setFirstPts = true;\n abufferDrained = false;\n\n // IN (abuffersrc)\n linkCtx = abufferCtx = CreateFilter(\"abuffer\",\n $\"channel_layout={AudioStream.ChannelLayoutStr}:sample_fmt={AudioStream.SampleFormatStr}:sample_rate={codecCtx->sample_rate}:time_base={sinkTimebase.Num}/{sinkTimebase.Den}\");\n\n // USER DEFINED\n if (Config.Audio.Filters != null)\n foreach (var filter in Config.Audio.Filters)\n try\n {\n linkCtx = CreateFilter(filter.Name, filter.Args, linkCtx, filter.Id);\n }\n catch (Exception e) { Log.Error($\"{e.Message}\"); }\n\n // SPEED (atempo up to 3) | [0.125 - 0.25](3), [0.25 - 0.5](2), [0.5 - 2.0](1), [2.0 - 4.0](2), [4.0 - X](3)\n if (speed != 1)\n {\n if (speed >= 0.5 && speed <= 2)\n linkCtx = CreateFilter(\"atempo\", $\"tempo={speed.ToString(\"0.0000000000\", System.Globalization.CultureInfo.InvariantCulture)}\", linkCtx);\n else if ((speed > 2 & speed <= 4) || (speed >= 0.25 && speed < 0.5))\n {\n var singleAtempoSpeed = Math.Sqrt(speed);\n linkCtx = CreateFilter(\"atempo\", $\"tempo={singleAtempoSpeed.ToString(\"0.0000000000\", System.Globalization.CultureInfo.InvariantCulture)}\", linkCtx);\n linkCtx = CreateFilter(\"atempo\", $\"tempo={singleAtempoSpeed.ToString(\"0.0000000000\", System.Globalization.CultureInfo.InvariantCulture)}\", linkCtx);\n }\n else if (speed > 4 || speed >= 0.125 && speed < 0.25)\n {\n var singleAtempoSpeed = Math.Pow(speed, 1.0 / 3);\n linkCtx = CreateFilter(\"atempo\", $\"tempo={singleAtempoSpeed.ToString(\"0.0000000000\", System.Globalization.CultureInfo.InvariantCulture)}\", linkCtx);\n linkCtx = CreateFilter(\"atempo\", $\"tempo={singleAtempoSpeed.ToString(\"0.0000000000\", System.Globalization.CultureInfo.InvariantCulture)}\", linkCtx);\n linkCtx = CreateFilter(\"atempo\", $\"tempo={singleAtempoSpeed.ToString(\"0.0000000000\", System.Globalization.CultureInfo.InvariantCulture)}\", linkCtx);\n }\n }\n\n // OUT (abuffersink)\n abufferSinkCtx = CreateFilter(\"abuffersink\", null, null);\n\n int tmpSampleRate = AudioStream.SampleRate;\n fixed (AVSampleFormat* ptr = &AOutSampleFormat)\n ret = av_opt_set_bin(abufferSinkCtx , \"sample_fmts\" , (byte*)ptr, sizeof(AVSampleFormat) , OptSearchFlags.Children);\n ret = av_opt_set_bin(abufferSinkCtx , \"sample_rates\" , (byte*)&tmpSampleRate, sizeof(int) , OptSearchFlags.Children);\n ret = av_opt_set_int(abufferSinkCtx , \"all_channel_counts\" , 0 , OptSearchFlags.Children);\n ret = av_opt_set(abufferSinkCtx , \"ch_layouts\" , \"stereo\" , OptSearchFlags.Children);\n avfilter_link(linkCtx, 0, abufferSinkCtx, 0);\n\n // GRAPH CONFIG\n ret = avfilter_graph_config(filterGraph, null);\n\n // CRIT TBR:!!!\n var tb = 1000 * 10000.0 / sinkTimebase.Den; // Ensures we have at least 20-70ms samples to avoid audio crackling and av sync issues\n ((FilterLink*)abufferSinkCtx->inputs[0])->min_samples = (int) (20 * 10000 / tb);\n ((FilterLink*)abufferSinkCtx->inputs[0])->max_samples = (int) (70 * 10000 / tb);\n\n return ret < 0\n ? throw new Exception($\"[FilterGraph] {FFmpegEngine.ErrorCodeToMsg(ret)} ({ret})\")\n : 0;\n }\n catch (Exception e)\n {\n fixed(AVFilterGraph** filterGraphPtr = &filterGraph)\n avfilter_graph_free(filterGraphPtr);\n\n Log.Error($\"{e.Message}\");\n\n return ret;\n }\n }\n\n private void DisposeFilters()\n {\n if (filterGraph == null)\n return;\n\n fixed(AVFilterGraph** filterGraphPtr = &filterGraph)\n avfilter_graph_free(filterGraphPtr);\n\n if (filtframe != null)\n fixed (AVFrame** ptr = &filtframe)\n av_frame_free(ptr);\n\n abufferCtx = null;\n abufferSinkCtx = null;\n filterGraph = null;\n filtframe = null;\n }\n protected override void OnSpeedChanged(double value)\n {\n // Possible Task to avoid locking UI thread as lockAtempo can wait for the Frames queue to be freed (will cause other issues and couldnt reproduce the possible dead lock)\n cBufTimesCur = cBufTimesSize;\n lock (lockSpeed)\n {\n if (filterGraph != null)\n DrainFilters();\n\n cBufTimesCur= 1;\n oldSpeed = speed;\n speed = value;\n\n var frames = Frames.ToArray();\n for (int i = 0; i < frames.Length; i++)\n FixSample(frames[i], oldSpeed, speed);\n\n if (filterGraph != null)\n SetupFilters();\n }\n }\n internal void FixSample(AudioFrame frame, double oldSpeed, double speed)\n {\n var oldDataLen = frame.dataLen;\n frame.dataLen = Utils.Align((int) (oldDataLen * oldSpeed / speed), ASampleBytes);\n fixed (byte* cBufStartPosPtr = &cBuf[0])\n {\n var curOffset = (long)frame.dataPtr - (long)cBufStartPosPtr;\n\n if (speed < oldSpeed)\n {\n if (curOffset + frame.dataLen >= cBuf.Length)\n {\n frame.dataPtr = (IntPtr)cBufStartPosPtr;\n curOffset = 0;\n oldDataLen = 0;\n }\n\n // fill silence\n for (int p = oldDataLen; p < frame.dataLen; p++)\n cBuf[curOffset + p] = 0;\n }\n }\n }\n private int UpdateFilterInternal(string filterId, string key, string value)\n {\n int ret = avfilter_graph_send_command(filterGraph, filterId, key, value, null, 0, 0);\n Log.Info($\"[{filterId}] {key}={value} {(ret >=0 ? \"success\" : \"failed\")}\");\n\n return ret;\n }\n internal int SetupFiltersOrSwr()\n {\n lock (lockSpeed)\n {\n int ret = -1;\n\n if (Disposed)\n return ret;\n\n if (Config.Audio.FiltersEnabled)\n {\n ret = SetupFilters();\n\n if (ret != 0)\n {\n Log.Error($\"Setup filters failed. Fallback to Swr.\");\n ret = SetupSwr();\n }\n else\n DisposeSwr();\n }\n else\n {\n DisposeFilters();\n ret = SetupSwr();\n }\n\n return ret;\n }\n }\n\n public int UpdateFilter(string filterId, string key, string value)\n {\n lock (lockCodecCtx)\n return filterGraph != null ? UpdateFilterInternal(filterId, key, value) : -1;\n }\n public int ReloadFilters()\n {\n if (!Config.Audio.FiltersEnabled)\n return -1;\n\n lock (lockActions)\n lock (lockCodecCtx)\n return SetupFilters();\n }\n\n private void ProcessFilters()\n {\n if (setFirstPts)\n {\n setFirstPts = false;\n filterFirstPts = frame->pts;\n curSamples = 0;\n missedSamples = 0;\n }\n else if (Math.Abs(frame->pts - nextPts) > 10 * 10000) // 10ms distance should resync filters (TBR: it should be 0ms however we might get 0 pkt_duration for unknown?)\n {\n DrainFilters();\n Log.Warn($\"Resync filters! ({Utils.TicksToTime((long)((frame->pts - nextPts) * AudioStream.Timebase))} distance)\");\n //resyncWithVideoRequired = !VideoDecoder.Disposed;\n DisposeFrames();\n avcodec_flush_buffers(codecCtx);\n if (filterGraph != null)\n SetupFilters();\n return;\n }\n\n nextPts = frame->pts + frame->duration;\n\n int ret;\n\n if ((ret = av_buffersrc_add_frame_flags(abufferCtx, frame, AVBuffersrcFlag.KeepRef | AVBuffersrcFlag.NoCheckFormat)) < 0) // AV_BUFFERSRC_FLAG_KEEP_REF = 8, AV_BUFFERSRC_FLAG_NO_CHECK_FORMAT = 1 (we check format change manually before here)\n {\n Log.Warn($\"[buffersrc] {FFmpegEngine.ErrorCodeToMsg(ret)} ({ret})\");\n Status = Status.Stopping;\n return;\n }\n\n while (true)\n {\n if ((ret = av_buffersink_get_frame_flags(abufferSinkCtx, filtframe, 0)) < 0) // Sometimes we get AccessViolationException while we UpdateFilter (possible related with .NET7 debug only bug)\n return; // EAGAIN (Some filters will send EAGAIN even if EOF currently we handled cause our Status will be Draining)\n\n if (filtframe->pts == AV_NOPTS_VALUE) // we might desync here (we dont count frames->nb_samples) ?\n {\n av_frame_unref(filtframe);\n continue;\n }\n\n ProcessFilter();\n\n // Wait until Queue not Full or Stopped\n if (Frames.Count >= Config.Decoder.MaxAudioFrames * cBufTimesCur)\n {\n Monitor.Exit(lockCodecCtx);\n lock (lockStatus)\n if (Status == Status.Running)\n Status = Status.QueueFull;\n\n while (Frames.Count >= Config.Decoder.MaxAudioFrames * cBufTimesCur && (Status == Status.QueueFull || Status == Status.Draining))\n Thread.Sleep(20);\n\n Monitor.Enter(lockCodecCtx);\n\n lock (lockStatus)\n {\n if (Status == Status.QueueFull)\n Status = Status.Running;\n else if (Status != Status.Draining)\n return;\n }\n }\n }\n }\n private void DrainFilters()\n {\n if (abufferDrained)\n return;\n\n abufferDrained = true;\n\n int ret;\n\n if ((ret = av_buffersrc_add_frame(abufferCtx, null)) < 0)\n {\n Log.Warn($\"[buffersrc] {FFmpegEngine.ErrorCodeToMsg(ret)} ({ret})\");\n return;\n }\n\n while (true)\n {\n if ((ret = av_buffersink_get_frame_flags(abufferSinkCtx, filtframe, 0)) < 0)\n return;\n\n if (filtframe->pts == AV_NOPTS_VALUE)\n {\n av_frame_unref(filtframe);\n return;\n }\n\n ProcessFilter();\n }\n }\n private void ProcessFilter()\n {\n var curLen = filtframe->nb_samples * ASampleBytes;\n\n if (filtframe->nb_samples > cBufSamples) // (min 10000)\n AllocateCircularBuffer(filtframe->nb_samples);\n else if (cBufPos + curLen >= cBuf.Length)\n cBufPos = 0;\n\n long newPts = filterFirstPts + av_rescale_q((long)(curSamples + missedSamples), sinkTimebase, AudioStream.AVStream->time_base);\n var samplesSpeed1 = filtframe->nb_samples * speed;\n missedSamples += samplesSpeed1 - (int)samplesSpeed1;\n curSamples += (int)samplesSpeed1;\n\n AudioFrame mFrame = new()\n {\n dataLen = curLen,\n timestamp = (long)((newPts * AudioStream.Timebase) - demuxer.StartTime + Config.Audio.Delay)\n };\n\n if (CanTrace) Log.Trace($\"Processes {Utils.TicksToTime(mFrame.timestamp)}\");\n\n fixed (byte* circularBufferPosPtr = &cBuf[cBufPos])\n mFrame.dataPtr = (IntPtr)circularBufferPosPtr;\n\n Marshal.Copy((IntPtr) filtframe->data[0], cBuf, cBufPos, mFrame.dataLen);\n cBufPos += curLen;\n\n Frames.Enqueue(mFrame);\n av_frame_unref(filtframe);\n }\n}\n\n/// \n/// FFmpeg Filter\n/// \npublic class Filter\n{\n /// \n /// \n /// FFmpeg valid filter id\n /// (Required only to send commands)\n /// \n /// \n public string Id { get; set; }\n\n /// \n /// FFmpeg valid filter name\n /// \n public string Name { get; set; }\n\n /// \n /// FFmpeg valid filter args\n /// \n public string Args { get; set; }\n}\n"], ["/LLPlayer/FlyleafLib/MediaPlayer/SubtitlesOCR.cs", "using System.Collections.Generic;\nusing System.Drawing;\nusing System.Drawing.Drawing2D;\nusing System.Drawing.Imaging;\nusing System.IO;\nusing System.Linq;\nusing System.Runtime.InteropServices;\nusing System.Threading;\nusing System.Threading.Tasks;\nusing Windows.Graphics.Imaging;\nusing Windows.Media.Ocr;\nusing Windows.Storage.Streams;\nusing Color = System.Drawing.Color;\nusing ImageFormat = System.Drawing.Imaging.ImageFormat;\nusing PixelFormat = System.Drawing.Imaging.PixelFormat;\n\nnamespace FlyleafLib.MediaPlayer;\n\n#nullable enable\n\npublic unsafe class SubtitlesOCR\n{\n private readonly Config.SubtitlesConfig _config;\n private int _subNum;\n\n private readonly CancellationTokenSource?[] _ctss;\n private readonly object[] _lockers;\n private IOCRService? _ocrService;\n\n public SubtitlesOCR(Config.SubtitlesConfig config, int subNum)\n {\n _config = config;\n _subNum = subNum;\n\n _lockers = new object[subNum];\n _ctss = new CancellationTokenSource[subNum];\n for (int i = 0; i < subNum; i++)\n {\n _lockers[i] = new object();\n _ctss[i] = new CancellationTokenSource();\n }\n }\n\n /// \n /// Try to initialize OCR Engine\n /// \n /// OCR Language\n /// expected initialize error\n /// whether to success to initialize\n public bool TryInitialize(int subIndex, Language lang, out string err)\n {\n lang = GetLanguageWithFallback(subIndex, lang);\n\n // Retaining engines will increase memory usage, so they are created and discarded on the fly.\n IOCRService ocrService = _config[subIndex].OCREngine switch\n {\n SubOCREngineType.Tesseract => new TesseractOCRService(_config),\n SubOCREngineType.MicrosoftOCR => new MicrosoftOCRService(_config),\n _ => throw new InvalidOperationException(),\n };\n\n if (!ocrService.TryInitialize(lang, out err))\n {\n return false;\n }\n\n _ocrService = ocrService;\n\n err = \"\";\n return true;\n }\n\n /// \n /// Do OCR\n /// \n /// 0: Primary, 1: Secondary\n /// List of subtitle data for OCR\n /// Timestamp to start OCR\n public void Do(int subIndex, List subs, TimeSpan? startTime = null)\n {\n if (_ocrService == null)\n throw new InvalidOperationException(\"ocrService is not initialized. you must call TryInitialize() first\");\n\n if (subs.Count == 0 || !subs[0].IsBitmap)\n return;\n\n // Cancel preceding OCR\n TryCancelWait(subIndex);\n\n lock (_lockers[subIndex])\n {\n // NOTE: important to dispose inside lock\n using IOCRService ocrService = _ocrService;\n\n _ctss[subIndex] = new CancellationTokenSource();\n\n int startIndex = 0;\n // Start OCR from the current playback point\n if (startTime.HasValue)\n {\n int match = subs.FindIndex(s => s.StartTime >= startTime);\n if (match != -1)\n {\n // Do from 5 previous subtitles\n startIndex = Math.Max(0, match - 5);\n }\n }\n\n for (int i = 0; i < subs.Count; i++)\n {\n if (_ctss[subIndex]!.Token.IsCancellationRequested)\n {\n foreach (var sub in subs)\n {\n sub.Dispose();\n }\n\n break;\n }\n\n int index = (startIndex + i) % subs.Count;\n\n SubtitleBitmapData? bitmap = subs[index].Bitmap;\n if (bitmap == null)\n continue;\n\n // TODO: L: If it's disposed, do I need to cancel it later?\n subs[index].Text = Process(ocrService, subIndex, bitmap);\n if (!string.IsNullOrEmpty(subs[index].Text))\n {\n // If OCR succeeds, dispose of it (if it fails, leave it so that it can be displayed in the sidebar).\n subs[index].Dispose();\n }\n }\n\n if (!_ctss[subIndex]!.Token.IsCancellationRequested)\n {\n // TODO: L: Notify, express completion in some way\n Utils.PlayCompletionSound();\n }\n }\n }\n\n private Language GetLanguageWithFallback(int subIndex, Language lang)\n {\n if (lang == Language.Unknown)\n {\n // fallback to user set language\n lang = subIndex == 0 ? _config.LanguageFallbackPrimary : _config.LanguageFallbackSecondary;\n }\n\n return lang;\n }\n\n public void TryCancelWait(int subIndex)\n {\n if (_ctss[subIndex] != null)\n {\n // Cancel if preceding OCR is running\n _ctss[subIndex]!.Cancel();\n\n // Wait until it is canceled by taking a lock\n lock (_lockers[subIndex])\n {\n _ctss[subIndex]?.Dispose();\n _ctss[subIndex] = null;\n }\n }\n }\n\n public static string Process(IOCRService ocrService, int subIndex, SubtitleBitmapData sub)\n {\n (byte[] data, AVSubtitleRect rect) = sub.SubToBitmap(true);\n\n int width = rect.w;\n int height = rect.h;\n\n fixed (byte* ptr = data)\n {\n // TODO: L: Make it possible to set true here in config (should the bitmap itself have an invert function automatically?)\n Binarize(width, height, ptr, 4, true);\n }\n\n using Bitmap bitmap = new(width, height, PixelFormat.Format32bppArgb);\n BitmapData bitmapData = bitmap.LockBits(\n new Rectangle(0, 0, width, height),\n ImageLockMode.WriteOnly, bitmap.PixelFormat);\n Marshal.Copy(data, 0, bitmapData.Scan0, data.Length);\n bitmap.UnlockBits(bitmapData);\n\n // Perform preprocessing to improve accuracy before OCR (common processing independent of OCR method)\n using Bitmap ocrBitmap = Preprocess(bitmap);\n\n string ocrText = ocrService.RecognizeTextAsync(ocrBitmap).GetAwaiter().GetResult();\n string processedText = ocrService.PostProcess(ocrText);\n\n return processedText;\n }\n\n private static Bitmap Preprocess(Bitmap bitmap)\n {\n using Bitmap blackText = ImageProcessor.BlackText(bitmap);\n Bitmap padded = ImageProcessor.AddPadding(blackText, 20);\n\n return padded;\n }\n\n /// \n /// Perform binarization on bitmaps\n /// \n /// \n /// \n /// \n /// \n /// \n private static void Binarize(int width, int height, byte* buffer, int pixelByte, bool srcTextWhite)\n {\n // Black text on white background\n byte white = 255;\n byte black = 0;\n if (srcTextWhite)\n {\n // The text is white on a black background, so invert it to black text.\n white = 0;\n black = 255;\n }\n\n for (int y = 0; y < height; y++)\n {\n for (int x = 0; x < width; x++)\n {\n byte* pixel = buffer + (y * width + x) * pixelByte;\n // Take out the first R bits since they are already in grayscale\n int grayscale = pixel[0];\n byte binaryValue = grayscale < 128 ? black : white;\n pixel[0] = pixel[1] = pixel[2] = binaryValue;\n }\n }\n }\n\n public void Reset(int subIndex)\n {\n TryCancelWait(subIndex);\n }\n}\n\npublic interface IOCRService : IDisposable\n{\n bool TryInitialize(Language lang, out string err);\n Task RecognizeTextAsync(Bitmap bitmap);\n string PostProcess(string text);\n}\n\npublic class TesseractOCRService : IOCRService\n{\n private readonly Config.SubtitlesConfig _config;\n private TesseractOCR.Engine? _ocrEngine;\n private bool _disposed;\n private Language? _lang;\n\n public TesseractOCRService(Config.SubtitlesConfig config)\n {\n _config = config;\n }\n\n public bool TryInitialize(Language lang, out string err)\n {\n _lang = lang;\n\n string iso6391 = lang.ISO6391;\n\n if (iso6391 == \"nb\")\n {\n // Norwegian Bokmål to Norwegian\n iso6391 = \"no\";\n }\n\n Dictionary> tesseractModels = TesseractModelLoader.GetAvailableModels();\n\n if (!tesseractModels.TryGetValue(iso6391, out List? models))\n {\n err = $\"Language:{lang.TopEnglishName} ({iso6391}) is not available in Tesseract OCR, Please download a model in settings if available language.\";\n\n return false;\n }\n\n TesseractModel model = models.First();\n if (_config.TesseractOcrRegions != null && models.Count >= 2)\n {\n // choose zh-CN or zh-TW (for Chinese)\n if (_config.TesseractOcrRegions.TryGetValue(iso6391, out string? langCode))\n {\n TesseractModel? m = models.FirstOrDefault(m => m.LangCode == langCode);\n if (m != null)\n {\n model = m;\n }\n }\n }\n\n _ocrEngine = new TesseractOCR.Engine(\n TesseractModel.ModelsDirectory,\n model.Lang);\n\n bool isCJK = model.Lang is\n TesseractOCR.Enums.Language.Japanese or\n TesseractOCR.Enums.Language.Korean or\n TesseractOCR.Enums.Language.ChineseSimplified or\n TesseractOCR.Enums.Language.ChineseTraditional;\n\n if (isCJK)\n {\n // remove whitespace around word if CJK\n _ocrEngine.SetVariable(\"preserve_interword_spaces\", 1);\n }\n\n err = string.Empty;\n return true;\n }\n\n public Task RecognizeTextAsync(Bitmap bitmap)\n {\n if (_ocrEngine == null)\n throw new InvalidOperationException(\"ocrEngine is not initialized\");\n\n using MemoryStream stream = new();\n\n // 32bit -> 24bit conversion\n Bitmap converted = new Bitmap(bitmap.Width, bitmap.Height, PixelFormat.Format24bppRgb);\n using (Graphics g = Graphics.FromImage(converted))\n {\n g.DrawImage(bitmap, 0, 0);\n }\n\n converted.Save(stream, ImageFormat.Bmp);\n\n stream.Position = 0;\n\n using var img = TesseractOCR.Pix.Image.LoadFromMemory(stream);\n\n using var page = _ocrEngine.Process(img);\n return Task.FromResult(page.Text);\n }\n\n public string PostProcess(string text)\n {\n var processedText = text;\n\n if (_lang == Language.English)\n {\n processedText = processedText\n .Replace(\"|\", \"I\")\n .Replace(\"I1t's\", \"It's\")\n .Replace(\"’'\", \"'\");\n }\n\n // common\n processedText = processedText\n .Trim();\n\n return processedText;\n }\n\n public void Dispose()\n {\n if (_disposed)\n return;\n\n _ocrEngine?.Dispose();\n _disposed = true;\n }\n}\n\npublic class MicrosoftOCRService : IOCRService\n{\n private readonly Config.SubtitlesConfig _config;\n private OcrEngine? _ocrEngine;\n private bool _isCJK;\n private bool _disposed;\n\n public MicrosoftOCRService(Config.SubtitlesConfig config)\n {\n _config = config;\n }\n\n public bool TryInitialize(Language lang, out string err)\n {\n string iso6391 = lang.ISO6391;\n\n string? langTag = null;\n\n if (_config.MsOcrRegions.TryGetValue(iso6391, out string? tag))\n {\n // If there is a preferred language region in the settings, it is given priority.\n langTag = tag;\n }\n else\n {\n var availableLangs = OcrEngine.AvailableRecognizerLanguages.ToList();\n\n // full match\n var match = availableLangs.FirstOrDefault(l => l.LanguageTag == iso6391);\n\n if (match == null)\n {\n // left match\n match = availableLangs.FirstOrDefault(l => l.LanguageTag.StartsWith($\"{iso6391}-\"));\n }\n\n if (match != null)\n {\n langTag = match.LanguageTag;\n }\n }\n\n if (langTag == null)\n {\n err = $\"Language:{lang.TopEnglishName} ({iso6391}) is not available in Microsoft OCR, Please install an OCR engine if available language.\";\n return false;\n }\n\n var language = new Windows.Globalization.Language(langTag);\n\n OcrEngine ocrEngine = OcrEngine.TryCreateFromLanguage(language);\n if (ocrEngine == null)\n {\n err = $\"Language:{lang.TopEnglishName} ({iso6391}) is not available in Microsoft OCR (TryCreateFromLanguage), Please install an OCR engine if available language.\";\n return false;\n }\n\n _ocrEngine = ocrEngine;\n _isCJK = langTag.StartsWith(\"zh\", StringComparison.OrdinalIgnoreCase) || // Chinese\n langTag.StartsWith(\"ja\", StringComparison.OrdinalIgnoreCase); // Japanese\n\n err = string.Empty;\n return true;\n }\n\n public async Task RecognizeTextAsync(Bitmap bitmap)\n {\n if (_ocrEngine == null)\n throw new InvalidOperationException(\"ocrEngine is not initialized\");\n\n using MemoryStream ms = new();\n\n bitmap.Save(ms, ImageFormat.Bmp);\n ms.Position = 0;\n\n using IRandomAccessStream randomAccessStream = ms.AsRandomAccessStream();\n BitmapDecoder decoder = await BitmapDecoder.CreateAsync(randomAccessStream);\n using SoftwareBitmap softwareBitmap = await decoder.GetSoftwareBitmapAsync();\n\n OcrResult ocrResult = await _ocrEngine.RecognizeAsync(softwareBitmap);\n\n if (_isCJK)\n {\n // remove whitespace around word if CJK\n return string.Join(Environment.NewLine,\n ocrResult.Lines.Select(line => string.Concat(line.Words.Select(word => word.Text))));\n }\n\n return string.Join(Environment.NewLine, ocrResult.Lines.Select(l => l.Text));\n }\n\n public string PostProcess(string text)\n {\n return text;\n }\n\n public void Dispose()\n {\n if (_disposed)\n return;\n\n // do nothing\n _disposed = true;\n }\n}\n\npublic static class ImageProcessor\n{\n /// \n /// Converts to black text on a white background\n /// \n /// original bitmap\n /// processed bitmap\n public static Bitmap BlackText(Bitmap original)\n {\n Bitmap converted = new(original.Width, original.Height, original.PixelFormat);\n\n using (Graphics g = Graphics.FromImage(converted))\n {\n // Convert to black text on a white background\n g.Clear(Color.White);\n\n // Drawing images with alpha blending enabled\n g.CompositingMode = System.Drawing.Drawing2D.CompositingMode.SourceOver;\n\n g.DrawImage(original, 0, 0);\n }\n\n return converted;\n }\n\n /// \n /// Add white padding around the bitmap\n /// \n /// original bitmap\n /// Size of padding to be added (in pixels)\n /// padded bitmap\n public static Bitmap AddPadding(Bitmap original, int padding)\n {\n int newWidth = original.Width + padding * 2;\n int newHeight = original.Height + padding * 2;\n\n Bitmap paddedBitmap = new(newWidth, newHeight, original.PixelFormat);\n\n using (Graphics graphics = Graphics.FromImage(paddedBitmap))\n {\n // White background\n graphics.Clear(Color.White);\n\n graphics.InterpolationMode = InterpolationMode.HighQualityBicubic;\n graphics.CompositingQuality = CompositingQuality.HighQuality;\n graphics.SmoothingMode = SmoothingMode.HighQuality;\n graphics.PixelOffsetMode = PixelOffsetMode.HighQuality;\n\n // Draw the original image in the center\n graphics.DrawImage(original, padding, padding, original.Width, original.Height);\n }\n\n return paddedBitmap;\n }\n\n /// \n /// Enlarge the size of the bitmap while maintaining the aspect ratio.\n /// \n /// source bitmap\n /// processed bitmap\n private static Bitmap ResizeBitmap(Bitmap original, double scaleFactor)\n {\n // Calculate new size\n int newWidth = (int)(original.Width * scaleFactor);\n int newHeight = (int)(original.Height * scaleFactor);\n\n Bitmap resizedBitmap = new(newWidth, newHeight);\n\n using (Graphics graphics = Graphics.FromImage(resizedBitmap))\n {\n graphics.InterpolationMode = InterpolationMode.HighQualityBicubic;\n graphics.CompositingQuality = CompositingQuality.HighQuality;\n graphics.SmoothingMode = SmoothingMode.HighQuality;\n graphics.PixelOffsetMode = PixelOffsetMode.HighQuality;\n\n // resize\n graphics.DrawImage(original, 0, 0, newWidth, newHeight);\n }\n\n return resizedBitmap;\n }\n}\n"], ["/LLPlayer/FlyleafLib/MediaPlayer/Subtitles.cs", "using System.Collections.ObjectModel;\nusing FlyleafLib.MediaFramework.MediaContext;\nusing FlyleafLib.MediaFramework.MediaStream;\nusing System.ComponentModel;\nusing System.Diagnostics;\nusing System.Linq;\nusing System.Threading.Tasks;\nusing System.Windows;\nusing System.Windows.Media.Imaging;\nusing static FlyleafLib.Utils;\n\nnamespace FlyleafLib.MediaPlayer;\n\npublic class SubsBitmap\n{\n public WriteableBitmap Source { get; set; }\n public int X { get; set; }\n public int Y { get; set; }\n public int Width { get; set; }\n public int Height { get; set; }\n}\n\npublic class SubsBitmapPosition : NotifyPropertyChanged\n{\n private readonly Player _player;\n private readonly int _subIndex;\n\n public SubsBitmapPosition(Player player, int subIndex)\n {\n _player = player;\n _subIndex = subIndex;\n\n Calculate();\n }\n\n #region Config\n\n public double ConfScale\n {\n get;\n set\n {\n if (value <= 0)\n {\n return;\n }\n\n if (Set(ref field, Math.Round(value, 2)))\n {\n Calculate();\n }\n }\n } = 1.0; // x 1.0\n\n public double ConfPos\n {\n get;\n set\n {\n if (value < 0 || value > 150)\n {\n return;\n }\n\n if (Set(ref field, Math.Round(value)))\n {\n Calculate();\n }\n }\n } = 100; // 0 - 150\n\n #endregion\n\n #region WPF Property\n\n public Thickness? Margin { get; private set => Set(ref field, value); }\n\n public double ScaleX { get; private set => Set(ref field, value); } = 1.0;\n\n public double ScaleY { get; private set => Set(ref field, value); } = 1.0;\n\n /// \n /// True for horizontal subtitles\n /// Bitmap subtitles may be displayed vertically\n /// \n public bool IsHorizontal { get; private set; }\n\n #endregion\n\n public void Reset()\n {\n ConfScale = 1.0;\n ConfPos = 100;\n\n Margin = null;\n ScaleX = 1.0;\n ScaleY = 1.0;\n IsHorizontal = false;\n }\n\n public void Calculate()\n {\n if (_player.Subtitles == null ||\n _player.Subtitles[_subIndex].Data.Bitmap == null ||\n _player.SubtitlesDecoders[_subIndex].SubtitlesStream == null ||\n (_player.SubtitlesDecoders[_subIndex].Width == 0 && _player.SubtitlesManager[_subIndex].Width == 0) ||\n (_player.SubtitlesDecoders[_subIndex].Height == 0 && _player.SubtitlesManager[_subIndex].Height == 0))\n {\n return;\n }\n\n SubsBitmap bitmap = _player.Subtitles[_subIndex].Data.Bitmap;\n\n // Calculate the ratio of the current width of the window to the width of the video\n double renderWidth = _player.VideoDecoder.Renderer.GetViewport.Width;\n double videoWidth = _player.SubtitlesDecoders[_subIndex].Width;\n if (videoWidth == 0)\n {\n // Restore from cache because Width/Height may not be taken if the subtitle is not decoded enough.\n videoWidth = _player.SubtitlesManager[_subIndex].Width;\n }\n\n // double videoHeight_ = (int)(videoWidth / Player.VideoDemuxer.VideoStream.AspectRatio.Value);\n double renderHeight = _player.VideoDecoder.Renderer.GetViewport.Height;\n double videoHeight = _player.SubtitlesDecoders[_subIndex].Height;\n if (videoHeight == 0)\n {\n videoHeight = _player.SubtitlesManager[_subIndex].Height;\n }\n\n // In aspect ratio like a movie, a black background may be added to the top and bottom.\n // In this case, the subtitles should be placed based on the video display area, so the offset from the image rendering area excluding the black background should be taken into consideration.\n double yOffset = _player.renderer.GetViewport.Y;\n double xOffset = _player.renderer.GetViewport.X;\n\n double scaleFactorX = renderWidth / videoWidth;\n // double scaleFactorY = renderHeight / videoHeight;\n\n // Adjust subtitle size by the calculated ratio\n double scaleX = scaleFactorX;\n // double scaleY = scaleFactorY;\n\n // Note that if you are cropping videos with mkv in Handbrake, the subtitles will be crushed vertically if you don't use this one. vlc will crush them, but mpv will not have a problem.\n // It may be nice to be able to choose between the two.\n double scaleY = scaleX;\n\n double x = bitmap.X * scaleFactorX + xOffset;\n\n double yPosition = bitmap.Y / videoHeight;\n double y = renderHeight * yPosition + yOffset;\n\n // Adjust subtitle position(y - axis) by config.\n // However, if it detects that the subtitle is not a normal subtitle such as vertical subtitle, it will not be adjusted.\n // (Adjust only when it is below the center of the screen)\n // mpv: https://github.com/mpv-player/mpv/blob/df166c1333694cbfe70980dbded1984d48b0685a/sub/sd_lavc.c#L491-L494\n IsHorizontal = (bitmap.Y >= videoHeight / 2);\n if (IsHorizontal)\n {\n // mpv: https://github.com/mpv-player/mpv/blob/df166c1333694cbfe70980dbded1984d48b0685a/sub/sd_lavc.c#L486\n double offset = (100.0 - ConfPos) / 100.0 * videoHeight;\n y -= offset * scaleY;\n }\n\n // Adjust x and y axes when changing subtitle size(centering)\n if (ConfScale != 1.0)\n {\n // mpv: https://github.com/mpv-player/mpv/blob/df166c1333694cbfe70980dbded1984d48b0685a/sub/sd_lavc.c#L508-L515\n double ratio = (ConfScale - 1.0) / 2;\n\n double dw = bitmap.Width * scaleX;\n double dy = bitmap.Height * scaleY;\n\n x -= dw * ratio;\n y -= dy * ratio;\n\n scaleX *= ConfScale;\n scaleY *= ConfScale;\n }\n\n Margin = new Thickness(x, y, 0, 0);\n ScaleX = scaleX;\n ScaleY = scaleY;\n }\n}\n\npublic class SubsData : NotifyPropertyChanged\n{\n#nullable enable\n private readonly Player _player;\n private readonly int _subIndex;\n private Subtitles Subs => _player.Subtitles;\n private Config Config => _player.Config;\n\n public SubsData(Player player, int subIndex)\n {\n _player = player;\n _subIndex = subIndex;\n\n BitmapPosition = new SubsBitmapPosition(_player, _subIndex);\n\n Config.Subtitles[_subIndex].PropertyChanged += SubConfigOnPropertyChanged;\n }\n\n private void SubConfigOnPropertyChanged(object? sender, PropertyChangedEventArgs e)\n {\n if (e.PropertyName == nameof(Config.SubConfig.Visible))\n {\n Raise(nameof(IsVisible));\n Raise(nameof(IsAbsoluteVisible));\n Raise(nameof(IsDisplaying));\n }\n }\n\n /// \n /// Subtitles Position (Position & Scale)\n /// \n public SubsBitmapPosition BitmapPosition { get; }\n\n /// \n /// Subtitles Bitmap\n /// \n public SubsBitmap? Bitmap\n {\n get;\n internal set\n {\n if (!Set(ref field, value))\n {\n return;\n }\n\n BitmapPosition.Calculate();\n\n if (Bitmap != null)\n {\n // TODO: L: When vertical and horizontal subtitles are displayed at the same time, the subtitles are displayed incorrectly\n // Absolute display of Primary sub\n // 1. If Primary is true and Secondary is false\n // 2. When a vertical subtitle is detected\n\n // Absolute display of Secondary sub\n // 1. When a vertical subtitle is detected\n bool isAbsolute = Subs[0].Enabled && !Subs[1].Enabled;\n if (!BitmapPosition.IsHorizontal)\n {\n isAbsolute = true;\n }\n\n IsAbsolute = isAbsolute;\n }\n\n Raise(nameof(IsDisplaying));\n }\n }\n\n /// \n /// Whether subtitles are currently displayed or not\n /// (unless bitmap subtitles are displayed absolutely)\n /// \n public bool IsDisplaying => IsVisible && (Bitmap != null && !IsAbsolute // Bitmap subtitles, not absolute display\n ||\n !string.IsNullOrEmpty(Text)); // When text subtitles are available\n\n /// \n /// When vertical subtitle is detected in the case of bitmap sub, it becomes True and is displayed as absolute.\n /// \n public bool IsAbsolute\n {\n get;\n private set\n {\n if (Set(ref field, value))\n {\n Raise(nameof(IsAbsoluteVisible));\n Raise(nameof(IsDisplaying));\n }\n }\n } = false;\n\n /// \n /// Bind target Used for switching Visibility\n /// \n public bool IsAbsoluteVisible => IsAbsolute && IsVisible;\n\n /// \n /// Bind target Used for switching Visibility\n /// \n public bool IsVisible => Config.Subtitles[_subIndex].Visible;\n\n /// \n /// Subtitles Text (updates dynamically while playing based on the duration that it should be displayed)\n /// \n public string Text\n {\n get;\n internal set\n {\n if (Set(ref field, value))\n {\n Raise(nameof(IsDisplaying));\n }\n }\n } = \"\";\n\n public bool IsTranslated { get; set => Set(ref field, value); }\n\n public Language? Language { get; set => Set(ref field, value); }\n\n public void Reset()\n {\n Clear();\n UI(() =>\n {\n // Clear does not reset because there is a config in SubsBitmapPosition\n BitmapPosition.Reset();\n });\n }\n\n public void Clear()\n {\n if (Text != \"\" || Bitmap != null)\n {\n UI(() =>\n {\n Text = \"\";\n Bitmap = null;\n });\n }\n }\n#nullable restore\n}\n\n/// \n/// Preserve the state of streamIndex, URL, etc. of the currently selected subtitle in a global variable.\n/// TODO: L: Cannot use multiple Players in one app, required to change this?\n/// \npublic static class SubtitlesSelectedHelper\n{\n#nullable enable\n public static ValueTuple? Primary { get; set; }\n public static ValueTuple? Secondary { get; set; }\n\n public static SelectSubMethod PrimaryMethod { get; set; } = SelectSubMethod.Original;\n public static SelectSubMethod SecondaryMethod { get; set; } = SelectSubMethod.Original;\n\n /// \n /// Holds the index to switch (0: Primary, 1: Secondary)\n /// \n public static int CurIndex { get; set; } = 0;\n\n public static void Reset(int subIndex)\n {\n Debug.Assert(subIndex is 0 or 1);\n\n if (subIndex == 1)\n {\n Secondary = null;\n SecondaryMethod = SelectSubMethod.Original;\n }\n else\n {\n Primary = null;\n PrimaryMethod = SelectSubMethod.Original;\n }\n }\n\n public static SelectSubMethod GetMethod(int subIndex)\n {\n Debug.Assert(subIndex is 0 or 1);\n\n return subIndex == 1 ? SecondaryMethod : PrimaryMethod;\n }\n\n public static void SetMethod(int subIndex, SelectSubMethod method)\n {\n Debug.Assert(subIndex is 0 or 1);\n\n if (subIndex == 1)\n {\n SecondaryMethod = method;\n }\n else\n {\n PrimaryMethod = method;\n }\n }\n\n public static ValueTuple? Get(int subIndex)\n {\n Debug.Assert(subIndex is 0 or 1);\n return subIndex == 1 ? Secondary : Primary;\n }\n\n public static void Set(int subIndex, ValueTuple? tuple)\n {\n Debug.Assert(subIndex is 0 or 1);\n if (subIndex == 1)\n {\n Secondary = tuple;\n }\n else\n {\n Primary = tuple;\n }\n }\n\n public static bool GetSubEnabled(this StreamBase stream, int subIndex)\n {\n Debug.Assert(subIndex is 0 or 1);\n var tuple = subIndex == 1 ? Secondary : Primary;\n\n if (!tuple.HasValue)\n {\n return false;\n }\n\n if (tuple.Value.Item1.HasValue)\n {\n // internal sub\n return tuple.Value.Item1 == stream.StreamIndex;\n }\n\n if (tuple.Value.Item2 is not null && stream.ExternalStream is not null)\n {\n // external sub\n return GetSubEnabled(stream.ExternalStream, subIndex);\n }\n\n return false;\n }\n\n public static bool GetSubEnabled(this ExternalStream stream, int subIndex)\n {\n ArgumentNullException.ThrowIfNull(stream);\n\n return GetSubEnabled(stream.Url, subIndex);\n }\n\n public static bool GetSubEnabled(this string url, int subIndex)\n {\n Debug.Assert(subIndex is 0 or 1);\n var tuple = subIndex == 1 ? Secondary : Primary;\n\n if (!tuple.HasValue || tuple.Value.Item2 is null)\n {\n return false;\n }\n\n return tuple.Value.Item2.Url == url;\n }\n#nullable restore\n}\n\npublic class Subtitle : NotifyPropertyChanged\n{\n private readonly Player _player;\n private readonly int _subIndex;\n\n private Config Config => _player.Config;\n private DecoderContext Decoder => _player?.decoder;\n\n public Subtitle(int subIndex, Player player)\n {\n _player = player;\n _subIndex = subIndex;\n\n Data = new SubsData(_player, _subIndex);\n }\n\n #pragma warning disable CS9266\n public bool EnabledASR { get => _enabledASR; private set => Set(ref field, value); }\n private bool _enabledASR;\n\n /// \n /// Whether the input has subtitles and it is configured\n /// \n public bool IsOpened { get => _isOpened; private set => Set(ref field, value); }\n private bool _isOpened;\n\n public string Codec { get => _codec; private set => Set(ref field, value); }\n private string _codec;\n\n public bool IsBitmap { get => _isBitmap; private set => Set(ref field, value); }\n private bool _isBitmap;\n #pragma warning restore CS9266\n\n public bool Enabled => IsOpened || EnabledASR;\n\n public SubsData Data { get; }\n\n private void UpdateUI()\n {\n UI(() =>\n {\n IsOpened = IsOpened;\n Codec = Codec;\n IsBitmap = IsBitmap;\n EnabledASR = EnabledASR;\n });\n }\n\n internal void Reset()\n {\n _codec = null;\n _isOpened = false;\n _isBitmap = false;\n _player.sFramesPrev[_subIndex] = null;\n // TODO: L: Here it may be null when switching subs while displaying.\n _player.sFrames[_subIndex] = null;\n _enabledASR = false;\n\n _player.SubtitlesASR.Reset(_subIndex);\n _player.SubtitlesOCR.Reset(_subIndex);\n _player.SubtitlesManager[_subIndex].Reset();\n\n _player.SubtitleClear(_subIndex);\n //_player.renderer?.ClearOverlayTexture();\n\n SubtitlesSelectedHelper.Reset(_subIndex);\n\n Data.Reset();\n UpdateUI();\n }\n\n internal void Refresh()\n {\n var subStream = Decoder.SubtitlesStreams[_subIndex];\n\n if (subStream == null)\n {\n Reset();\n return;\n }\n\n _codec = subStream.Codec;\n _isOpened = !Decoder.SubtitlesDecoders[_subIndex].Disposed;\n _isBitmap = subStream is { IsBitmap: true };\n\n // Update the selection state of automatically opened subtitles\n // (also manually updated but no problem as it is no change, necessary for primary subtitles)\n if (subStream.ExternalStream is ExternalSubtitlesStream extStream)\n {\n // external sub\n SubtitlesSelectedHelper.Set(_subIndex, (null, extStream));\n }\n else if (subStream.StreamIndex != -1)\n {\n // internal sub\n SubtitlesSelectedHelper.Set(_subIndex, (subStream.StreamIndex, null));\n }\n\n Data.Reset();\n _player.sFramesPrev[_subIndex] = null;\n _player.sFrames[_subIndex] = null;\n _player.SubtitleClear(_subIndex);\n //player.renderer?.ClearOverlayTexture();\n\n _enabledASR = false;\n _player.SubtitlesASR.Reset(_subIndex);\n _player.SubtitlesOCR.Reset(_subIndex);\n _player.SubtitlesManager[_subIndex].Reset();\n\n if (_player.renderer != null)\n {\n // Adjust bitmap subtitle size when resizing screen\n _player.renderer.ViewportChanged -= RendererOnViewportChanged;\n _player.renderer.ViewportChanged += RendererOnViewportChanged;\n }\n\n UpdateUI();\n\n // Create cache of the all subtitles in a separate thread\n Task.Run(Load)\n .ContinueWith(t =>\n {\n // TODO: L: error handling - restore state gracefully?\n if (t.IsFaulted)\n {\n var ex = t.Exception.Flatten().InnerException;\n\n _player.RaiseUnknownErrorOccurred($\"Cannot load all subtitles on worker thread: {ex?.Message}\", UnknownErrorType.Subtitles, ex);\n }\n }, TaskContinuationOptions.OnlyOnFaulted);\n }\n\n internal void Load()\n {\n SubtitlesStream stream = Decoder.SubtitlesStreams[_subIndex];\n ExternalSubtitlesStream extStream = stream.ExternalStream as ExternalSubtitlesStream;\n\n if (extStream != null)\n {\n // external sub\n // always load all bitmaps on memory with external subtitles\n _player.SubtitlesManager.Open(_subIndex, stream.Demuxer.Url, stream.StreamIndex, stream.Demuxer.Type, true, extStream.Language);\n }\n else\n {\n // internal sub\n // load all bitmaps on memory when cache enabled or OCR used\n bool useBitmap = Config.Subtitles.EnabledCached || SubtitlesSelectedHelper.GetMethod(_subIndex) == SelectSubMethod.OCR;\n _player.SubtitlesManager.Open(_subIndex, stream.Demuxer.Url, stream.StreamIndex, stream.Demuxer.Type, useBitmap, stream.Language);\n }\n\n TimeSpan curTime = new(_player.CurTime);\n\n _player.SubtitlesManager[_subIndex].SetCurrentTime(curTime);\n\n // Do OCR\n // TODO: L: When OCR is performed while bitmap stream is loaded, the stream is reset and the bitmap is loaded again.\n // Is it better to reuse loaded bitmap?\n if (SubtitlesSelectedHelper.GetMethod(_subIndex) == SelectSubMethod.OCR)\n {\n using (_player.SubtitlesManager[_subIndex].StartLoading())\n {\n _player.SubtitlesOCR.Do(_subIndex, _player.SubtitlesManager[_subIndex].Subs.ToList(), curTime);\n }\n }\n }\n\n internal void Enable()\n {\n if (!_player.CanPlay)\n return;\n\n // TODO: L: For some reason, there is a problem with subtitles temporarily not being\n // displayed, waiting for about 10 seconds will fix it.\n Decoder.OpenSuggestedSubtitles(_subIndex);\n\n _player.ReSync(Decoder.SubtitlesStreams[_subIndex], (int)(_player.CurTime / 10000), true);\n\n Refresh();\n UpdateUI();\n }\n internal void Disable()\n {\n if (!Enabled)\n return;\n\n Decoder.CloseSubtitles(_subIndex);\n Reset();\n UpdateUI();\n\n SubtitlesSelectedHelper.Reset(_subIndex);\n }\n\n private void RendererOnViewportChanged(object sender, EventArgs e)\n {\n Data.BitmapPosition.Calculate();\n }\n\n public void EnableASR()\n {\n _enabledASR = true;\n\n var url = _player.AudioDecoder.Demuxer.Url;\n var type = _player.AudioDecoder.Demuxer.Type;\n var streamIndex = _player.AudioDecoder.AudioStream.StreamIndex;\n\n TimeSpan curTime = new(_player.CurTime);\n\n Task.Run(() =>\n {\n bool isDone;\n\n using (_player.SubtitlesManager[_subIndex].StartLoading())\n {\n isDone = _player.SubtitlesASR.Execute(_subIndex, url, streamIndex, type, curTime);\n }\n\n if (!isDone)\n {\n // re-enable spinner because it is running\n _player.SubtitlesManager[_subIndex].StartLoading();\n }\n })\n .ContinueWith(t =>\n {\n if (t.IsFaulted)\n {\n if (_player.SubtitlesManager[_subIndex].Subs.Count == 0)\n {\n // reset if not single subtitles generated\n Disable();\n }\n\n var ex = t.Exception.Flatten().InnerException;\n\n _player.RaiseUnknownErrorOccurred($\"Cannot execute ASR: {ex?.Message}\", UnknownErrorType.ASR, t.Exception);\n }\n }, TaskContinuationOptions.OnlyOnFaulted);\n\n UpdateUI();\n }\n}\n\npublic class Subtitles\n{\n /// \n /// Embedded Streams\n /// \n public ObservableCollection\n Streams => _player.decoder?.VideoDemuxer.SubtitlesStreamsAll;\n\n private readonly Subtitle[] _subs;\n\n // indexer\n public Subtitle this[int i] => _subs[i];\n\n public Player Player => _player;\n\n private readonly Player _player;\n\n private Config Config => _player.Config;\n\n private int subNum => Config.Subtitles.Max;\n\n public Subtitles(Player player)\n {\n _player = player;\n _subs = new Subtitle[subNum];\n\n for (int i = 0; i < subNum; i++)\n {\n _subs[i] = new Subtitle(i, _player);\n }\n }\n\n internal void Enable()\n {\n for (int i = 0; i < subNum; i++)\n {\n this[i].Enable();\n }\n }\n\n internal void Disable()\n {\n for (int i = 0; i < subNum; i++)\n {\n this[i].Disable();\n }\n }\n\n internal void Reset()\n {\n for (int i = 0; i < subNum; i++)\n {\n this[i].Reset();\n }\n }\n\n internal void Refresh()\n {\n for (int i = 0; i < subNum; i++)\n {\n this[i].Refresh();\n }\n }\n\n // TODO: L: refactor\n public void DelayRemovePrimary() => Config.Subtitles[0].Delay -= Config.Player.SubtitlesDelayOffset;\n public void DelayAddPrimary() => Config.Subtitles[0].Delay += Config.Player.SubtitlesDelayOffset;\n public void DelayRemove2Primary() => Config.Subtitles[0].Delay -= Config.Player.SubtitlesDelayOffset2;\n public void DelayAdd2Primary() => Config.Subtitles[0].Delay += Config.Player.SubtitlesDelayOffset2;\n\n public void DelayRemoveSecondary() => Config.Subtitles[1].Delay -= Config.Player.SubtitlesDelayOffset;\n public void DelayAddSecondary() => Config.Subtitles[1].Delay += Config.Player.SubtitlesDelayOffset;\n public void DelayRemove2Secondary() => Config.Subtitles[1].Delay -= Config.Player.SubtitlesDelayOffset2;\n public void DelayAdd2Secondary() => Config.Subtitles[1].Delay += Config.Player.SubtitlesDelayOffset2;\n\n public void ToggleEnabled() => Config.Subtitles.Enabled = !Config.Subtitles.Enabled;\n\n public void ToggleVisibility()\n {\n Config.Subtitles[0].Visible = !Config.Subtitles[0].Visible;\n Config.Subtitles[1].Visible = Config.Subtitles[0].Visible;\n }\n public void ToggleVisibilityPrimary()\n {\n Config.Subtitles[0].Visible = !Config.Subtitles[0].Visible;\n }\n\n public void ToggleVisibilitySecondary()\n {\n Config.Subtitles[1].Visible = !Config.Subtitles[1].Visible;\n }\n\n private bool _prevSeek(int subIndex)\n {\n var prev = _player.SubtitlesManager[subIndex].GetPrev();\n if (prev is not null)\n {\n _player.SeekAccurate(prev.StartTime, subIndex);\n return true;\n }\n\n return false;\n }\n\n public void PrevSeek() => _prevSeek(0);\n public void PrevSeek2() => _prevSeek(1);\n\n public void PrevSeekFallback()\n {\n if (!_prevSeek(0))\n {\n _player.SeekBackward2();\n }\n }\n public void PrevSeekFallback2()\n {\n if (!_prevSeek(1))\n {\n _player.SeekBackward2();\n }\n }\n\n private void _curSeek(int subIndex)\n {\n var cur = _player.SubtitlesManager[subIndex].GetCurrent();\n if (cur is not null)\n {\n _player.SeekAccurate(cur.StartTime, subIndex);\n }\n else\n {\n // fallback to prevSeek (same as mpv)\n _prevSeek(subIndex);\n }\n }\n\n public void CurSeek() => _curSeek(0);\n public void CurSeek2() => _curSeek(1);\n\n private bool _nextSeek(int subIndex)\n {\n var next = _player.SubtitlesManager[subIndex].GetNext();\n if (next is not null)\n {\n _player.SeekAccurate(next.StartTime, subIndex);\n return true;\n }\n return false;\n }\n\n public void NextSeek() => _nextSeek(0);\n public void NextSeek2() => _nextSeek(1);\n\n public void NextSeekFallback()\n {\n if (!_nextSeek(0))\n {\n _player.SeekForward2();\n }\n }\n public void NextSeekFallback2()\n {\n if (!_nextSeek(1))\n {\n _player.SeekForward2();\n }\n }\n}\n"], ["/LLPlayer/FlyleafLib/MediaFramework/MediaContext/Downloader.cs", "using System.IO;\nusing System.Threading;\nusing System.Threading.Tasks;\n\nusing FlyleafLib.MediaFramework.MediaDemuxer;\nusing FlyleafLib.MediaFramework.MediaRemuxer;\n\nusing static FlyleafLib.Logger;\n\n/* TODO\n * Don't let audio go further than video (because of large duration without video)?\n *\n */\n\nnamespace FlyleafLib.MediaFramework.MediaContext;\n\n/// \n/// Downloads or remuxes to different format any ffmpeg valid input url\n/// \npublic unsafe class Downloader : RunThreadBase\n{\n /// \n /// The backend demuxer. Access this to enable the required streams for downloading\n /// \n //public Demuxer Demuxer { get; private set; }\n\n public DecoderContext DecCtx { get; private set; }\n internal Demuxer AudioDemuxer => DecCtx.AudioDemuxer;\n\n /// \n /// The backend remuxer. Normally you shouldn't access this\n /// \n public Remuxer Remuxer { get; private set; }\n\n /// \n /// The current timestamp of the frame starting from 0 (Ticks)\n /// \n public long CurTime { get => _CurTime; private set => Set(ref _CurTime, value); }\n long _CurTime;\n\n /// \n /// The total duration of the input (Ticks)\n /// \n public long Duration { get => _Duration; private set => Set(ref _Duration, value); }\n long _Duration;\n\n /// \n /// The percentage of the current download process (0 for live streams)\n /// \n public double DownloadPercentage { get => _DownloadPercentage; set => Set(ref _DownloadPercentage, value); }\n double _DownloadPercentage;\n double downPercentageFactor;\n\n public Downloader(Config config, int uniqueId = -1) : base(uniqueId)\n {\n DecCtx = new DecoderContext(config, UniqueId, false);\n DecCtx.AudioDemuxer.Config = config.Demuxer.Clone(); // We change buffer duration and we need to avoid changing video demuxer's config\n\n //DecCtx.VideoInputOpened += (o, e) => { if (!e.Success) OnDownloadCompleted(false); };\n Remuxer = new Remuxer(UniqueId);\n threadName = \"Downloader\";\n }\n\n /// \n /// Fires on download completed or failed\n /// \n public event EventHandler DownloadCompleted;\n protected virtual void OnDownloadCompleted(bool success)\n => Task.Run(() => { Dispose(); DownloadCompleted?.Invoke(this, success); });\n\n /// \n /// Opens a new media file (audio/video) and prepares it for download (blocking)\n /// \n /// Media file's url\n /// Whether to open the default input (in case of multiple inputs eg. from bitswarm/youtube-dl, you might want to choose yours)\n /// Whether to open the default video stream from plugin suggestions\n /// Whether to open the default audio stream from plugin suggestions\n /// \n public string Open(string url, bool defaultPlaylistItem = true, bool defaultVideo = true, bool defaultAudio = true) => Open((object) url, defaultPlaylistItem, defaultVideo, defaultAudio);\n\n /// \n /// Opens a new media file (audio/video) and prepares it for download (blocking)\n /// \n /// Media Stream\n /// Whether to open the default input (in case of multiple inputs eg. from bitswarm/youtube-dl, you might want to choose yours)\n /// Whether to open the default video stream from plugin suggestions\n /// Whether to open the default audio stream from plugin suggestions\n /// \n public string Open(Stream stream, bool defaultPlaylistItem = true, bool defaultVideo = true, bool defaultAudio = true) => Open((object) stream, defaultPlaylistItem, defaultVideo, defaultAudio);\n\n internal string Open(object url, bool defaultPlaylistItem = true, bool defaultVideo = true, bool defaultAudio = true)\n {\n lock (lockActions)\n {\n Dispose();\n\n Disposed= false;\n Status = Status.Opening;\n var ret = DecCtx.Open(url, defaultPlaylistItem, defaultVideo, defaultAudio, false);\n if (ret != null && ret.Error != null) return ret.Error;\n\n CurTime = 0;\n DownloadPercentage = 0;\n\n var Demuxer = !DecCtx.VideoDemuxer.Disposed ? DecCtx.VideoDemuxer : DecCtx.AudioDemuxer;\n Duration = Demuxer.IsLive ? 0 : Demuxer.Duration;\n downPercentageFactor = Duration / 100.0;\n\n return null;\n }\n }\n\n /// \n /// Downloads the currently configured AVS streams\n /// \n /// The filename for the downloaded video. The file extension will let the demuxer to choose the output format (eg. mp4). If you useRecommendedExtension will be updated with the extension.\n /// Will try to match the output container with the input container\n public void Download(ref string filename, bool useRecommendedExtension = true)\n {\n lock (lockActions)\n {\n if (Status != Status.Opening || Disposed)\n { OnDownloadCompleted(false); return; }\n\n if (useRecommendedExtension)\n filename = $\"{filename}.{(!DecCtx.VideoDemuxer.Disposed ? DecCtx.VideoDemuxer.Extension : DecCtx.AudioDemuxer.Extension)}\";\n\n int ret = Remuxer.Open(filename);\n if (ret != 0)\n { OnDownloadCompleted(false); return; }\n\n AddStreams(DecCtx.VideoDemuxer);\n AddStreams(DecCtx.AudioDemuxer);\n\n if (!Remuxer.HasStreams || Remuxer.WriteHeader() != 0)\n { OnDownloadCompleted(false); return; }\n\n Start();\n }\n }\n\n private void AddStreams(Demuxer demuxer)\n {\n for(int i=0; i\n /// Stops and disposes the downloader\n /// \n public void Dispose()\n {\n if (Disposed) return;\n\n lock (lockActions)\n {\n if (Disposed) return;\n\n Stop();\n\n DecCtx.Dispose();\n Remuxer.Dispose();\n\n Status = Status.Stopped;\n Disposed = true;\n }\n }\n\n protected override void RunInternal()\n {\n if (!Remuxer.HasStreams) { OnDownloadCompleted(false); return; }\n\n // Don't allow audio to change our duration without video (TBR: requires timestamp of videodemuxer to wait)\n long resetBufferDuration = -1;\n bool hasAVDemuxers = !DecCtx.VideoDemuxer.Disposed && !DecCtx.AudioDemuxer.Disposed;\n if (hasAVDemuxers)\n {\n resetBufferDuration = DecCtx.AudioDemuxer.Config.BufferDuration;\n DecCtx.AudioDemuxer.Config.BufferDuration = 100 * 10000;\n }\n\n DecCtx.Start();\n\n var Demuxer = !DecCtx.VideoDemuxer.Disposed ? DecCtx.VideoDemuxer : DecCtx.AudioDemuxer;\n long startTime = Demuxer.hlsCtx == null ? Demuxer.StartTime : Demuxer.hlsCtx->first_timestamp * 10;\n Duration = Demuxer.IsLive ? 0 : Demuxer.Duration;\n downPercentageFactor = Duration / 100.0;\n\n long startedAt = DateTime.UtcNow.Ticks;\n long secondTicks = startedAt;\n bool isAudioDemuxer = DecCtx.VideoDemuxer.Disposed && !DecCtx.AudioDemuxer.Disposed;\n IntPtr pktPtr = IntPtr.Zero;\n AVPacket* packet = null;\n AVPacket* packet2 = null;\n\n do\n {\n if ((Demuxer.Packets.Count == 0 && AudioDemuxer.Packets.Count == 0) || (hasAVDemuxers && (Demuxer.Packets.Count == 0 || AudioDemuxer.Packets.Count == 0)))\n {\n lock (lockStatus)\n if (Status == Status.Running) Status = Status.QueueEmpty;\n\n while (Demuxer.Packets.Count == 0 && Status == Status.QueueEmpty)\n {\n if (Demuxer.Status == Status.Ended)\n {\n Status = Status.Ended;\n if (Demuxer.Interrupter.Interrupted == 0)\n {\n CurTime = _Duration;\n DownloadPercentage = 100;\n }\n break;\n }\n else if (!Demuxer.IsRunning)\n {\n if (CanDebug) Log.Debug($\"Demuxer is not running [Demuxer Status: {Demuxer.Status}]\");\n\n lock (Demuxer.lockStatus)\n lock (lockStatus)\n {\n if (Demuxer.Status == Status.Pausing || Demuxer.Status == Status.Paused)\n Status = Status.Pausing;\n else if (Demuxer.Status != Status.Ended)\n Status = Status.Stopping;\n else\n continue;\n }\n\n break;\n }\n\n Thread.Sleep(20);\n }\n\n if (hasAVDemuxers && Status == Status.QueueEmpty && AudioDemuxer.Packets.Count == 0)\n {\n while (AudioDemuxer.Packets.Count == 0 && Status == Status.QueueEmpty && AudioDemuxer.IsRunning)\n Thread.Sleep(20);\n }\n\n lock (lockStatus)\n {\n if (Status != Status.QueueEmpty) break;\n Status = Status.Running;\n }\n }\n\n if (hasAVDemuxers)\n {\n if (AudioDemuxer.Packets.Count == 0)\n {\n packet = Demuxer.Packets.Dequeue();\n isAudioDemuxer = false;\n }\n else if (Demuxer.Packets.Count == 0)\n {\n packet = AudioDemuxer.Packets.Dequeue();\n isAudioDemuxer = true;\n }\n else\n {\n packet = Demuxer.Packets.Peek();\n packet2 = AudioDemuxer.Packets.Peek();\n\n long ts1 = (long) ((packet->dts * Demuxer.AVStreamToStream[packet->stream_index].Timebase) - Demuxer.StartTime);\n long ts2 = (long) ((packet2->dts * AudioDemuxer.AVStreamToStream[packet2->stream_index].Timebase) - AudioDemuxer.StartTime);\n\n if (ts2 <= ts1)\n {\n AudioDemuxer.Packets.Dequeue();\n isAudioDemuxer = true;\n packet = packet2;\n }\n else\n {\n Demuxer.Packets.Dequeue();\n isAudioDemuxer = false;\n }\n\n //Log($\"[{isAudioDemuxer}] {Utils.TicksToTime(ts1)} | {Utils.TicksToTime(ts2)}\");\n }\n }\n else\n {\n packet = Demuxer.Packets.Dequeue();\n }\n\n long curDT = DateTime.UtcNow.Ticks;\n if (curDT - secondTicks > 1000 * 10000 && (!isAudioDemuxer || DecCtx.VideoDemuxer.Disposed))\n {\n secondTicks = curDT;\n\n CurTime = Demuxer.hlsCtx != null\n ? (long) ((packet->dts * Demuxer.AVStreamToStream[packet->stream_index].Timebase) - startTime)\n : Demuxer.CurTime + Demuxer.BufferedDuration;\n\n if (_Duration > 0) DownloadPercentage = CurTime / downPercentageFactor;\n }\n\n Remuxer.Write(packet, isAudioDemuxer);\n\n } while (Status == Status.Running);\n\n if (resetBufferDuration != -1) DecCtx.AudioDemuxer.Config.BufferDuration = resetBufferDuration;\n\n if (Status != Status.Pausing && Status != Status.Paused)\n OnDownloadCompleted(Remuxer.WriteTrailer() == 0);\n else\n Demuxer.Pause();\n }\n}\n"], ["/LLPlayer/LLPlayer/Services/FlyleafLoader.cs", "using System.IO;\nusing System.Windows;\nusing FlyleafLib;\nusing FlyleafLib.MediaPlayer;\nusing FlyleafLib.MediaPlayer.Translation;\n\nnamespace LLPlayer.Services;\n\npublic static class FlyleafLoader\n{\n public static void StartEngine()\n {\n EngineConfig engineConfig = DefaultEngineConfig();\n\n // Load Player's Config\n if (File.Exists(App.EngineConfigPath))\n {\n try\n {\n var opts = AppConfig.GetJsonSerializerOptions();\n engineConfig = EngineConfig.Load(App.EngineConfigPath, opts);\n if (engineConfig.Version != App.Version)\n {\n engineConfig.Version = App.Version;\n engineConfig.Save(App.EngineConfigPath, opts);\n }\n }\n catch (Exception ex)\n {\n MessageBox.Show($\"Cannot load EngineConfig from {Path.GetFileName(App.EngineConfigPath)}, Please review the settings or delete the config file. Error details are recorded in {Path.GetFileName(App.CrashLogPath)}.\");\n try\n {\n File.WriteAllText(App.CrashLogPath, \"EngineConfig Loading Error: \" + ex);\n }\n catch\n {\n // ignored\n }\n\n Application.Current.Shutdown();\n }\n }\n\n Engine.Start(engineConfig);\n }\n\n public static Player CreateFlyleafPlayer()\n {\n Config? config = null;\n bool useConfig = false;\n\n // Load Player's Config\n if (File.Exists(App.PlayerConfigPath))\n {\n try\n {\n var opts = AppConfig.GetJsonSerializerOptions();\n config = Config.Load(App.PlayerConfigPath, opts);\n\n if (config.Version != App.Version)\n {\n config.Version = App.Version;\n config.Save(App.PlayerConfigPath, opts);\n }\n useConfig = true;\n }\n catch (Exception ex)\n {\n MessageBox.Show($\"Cannot load PlayerConfig from {Path.GetFileName(App.PlayerConfigPath)}, Please review the settings or delete the config file. Error details are recorded in {Path.GetFileName(App.CrashLogPath)}.\");\n try\n {\n File.WriteAllText(App.CrashLogPath, \"PlayerConfig Loading Error: \" + ex);\n }\n catch\n {\n // ignored\n }\n\n Application.Current.Shutdown();\n }\n }\n\n config ??= DefaultConfig();\n Player player = new(config);\n\n if (!useConfig)\n {\n // Initialize default key bindings for custom keys for new config.\n foreach (var binding in AppActions.DefaultCustomActionsMap())\n {\n config.Player.KeyBindings.Keys.Add(binding);\n }\n }\n\n return player;\n }\n\n public static EngineConfig DefaultEngineConfig()\n {\n EngineConfig engineConfig = new()\n {\n#if DEBUG\n PluginsPath = @\":Plugins\\bin\\Plugins.NET9\",\n#else\n PluginsPath = \":Plugins\",\n#endif\n FFmpegPath = \":FFmpeg\",\n FFmpegHLSLiveSeek = true,\n UIRefresh = true,\n FFmpegLoadProfile = Flyleaf.FFmpeg.LoadProfile.Filters,\n#if DEBUG\n LogOutput = \":debug\",\n LogLevel = LogLevel.Debug,\n FFmpegLogLevel = Flyleaf.FFmpeg.LogLevel.Warn,\n#endif\n };\n\n return engineConfig;\n }\n\n private static Config DefaultConfig()\n {\n Config config = new();\n config.Demuxer.FormatOptToUnderlying =\n true; // Mainly for HLS to pass the original query which might includes session keys\n config.Audio.FiltersEnabled = true; // To allow embedded atempo filter for speed\n config.Video.GPUAdapter = \"\"; // Set it empty so it will include it when we save it\n config.Subtitles.SearchLocal = true;\n config.Subtitles.TranslateTargetLanguage = Language.Get(Utils.OriginalCulture).ToTargetLanguage() ?? TargetLanguage.EnglishAmerican; // try to set native language\n\n return config;\n }\n}\n"], ["/LLPlayer/FlyleafLib/MediaFramework/MediaRenderer/Renderer.SwapChain.cs", "using System.Windows;\n\nusing Vortice;\nusing Vortice.Direct3D;\nusing Vortice.Direct3D11;\nusing Vortice.DirectComposition;\nusing Vortice.DXGI;\n\nusing static FlyleafLib.Utils.NativeMethods;\nusing ID3D11Texture2D = Vortice.Direct3D11.ID3D11Texture2D;\n\nnamespace FlyleafLib.MediaFramework.MediaRenderer;\n\npublic partial class Renderer\n{\n ID3D11Texture2D backBuffer;\n ID3D11RenderTargetView backBufferRtv;\n IDXGISwapChain1 swapChain;\n IDCompositionDevice dCompDevice;\n IDCompositionVisual dCompVisual;\n IDCompositionTarget dCompTarget;\n\n const Int32 WM_NCDESTROY= 0x0082;\n const Int32 WM_SIZE = 0x0005;\n const Int32 WS_EX_NOREDIRECTIONBITMAP\n = 0x00200000;\n SubclassWndProc wndProcDelegate;\n IntPtr wndProcDelegatePtr;\n\n // Support Windows 8+\n private SwapChainDescription1 GetSwapChainDesc(int width, int height, bool isComp = false, bool alpha = false)\n {\n if (Device.FeatureLevel < FeatureLevel.Level_10_0 || (!string.IsNullOrWhiteSpace(Config.Video.GPUAdapter) && Config.Video.GPUAdapter.ToUpper() == \"WARP\"))\n {\n return new()\n {\n BufferUsage = Usage.RenderTargetOutput,\n Format = Config.Video.Swap10Bit ? Format.R10G10B10A2_UNorm : Format.B8G8R8A8_UNorm,\n Width = (uint)width,\n Height = (uint)height,\n AlphaMode = AlphaMode.Ignore,\n SwapEffect = isComp ? SwapEffect.FlipSequential : SwapEffect.Discard, // will this work for warp?\n Scaling = Scaling.Stretch,\n BufferCount = 1,\n SampleDescription = new SampleDescription(1, 0)\n };\n }\n else\n {\n SwapEffect swapEffect = isComp ? SwapEffect.FlipSequential : Environment.OSVersion.Version.Major >= 10 ? SwapEffect.FlipDiscard : SwapEffect.FlipSequential;\n\n return new()\n {\n BufferUsage = Usage.RenderTargetOutput,\n Format = Config.Video.Swap10Bit ? Format.R10G10B10A2_UNorm : (Config.Video.SwapForceR8G8B8A8 ? Format.R8G8B8A8_UNorm : Format.B8G8R8A8_UNorm),\n Width = (uint)width,\n Height = (uint)height,\n AlphaMode = alpha ? AlphaMode.Premultiplied : AlphaMode.Ignore,\n SwapEffect = swapEffect,\n Scaling = isComp ? Scaling.Stretch : Scaling.None,\n BufferCount = swapEffect == SwapEffect.FlipDiscard ? Math.Min(Config.Video.SwapBuffers, 2) : Config.Video.SwapBuffers,\n SampleDescription = new SampleDescription(1, 0),\n };\n }\n }\n\n internal void InitializeSwapChain(IntPtr handle)\n {\n lock (lockDevice)\n {\n if (!SCDisposed)\n DisposeSwapChain();\n\n if (Disposed && parent == null)\n Initialize(false);\n\n ControlHandle = handle;\n RECT rect = new();\n GetWindowRect(ControlHandle,ref rect);\n ControlWidth = rect.Right - rect.Left;\n ControlHeight = rect.Bottom - rect.Top;\n\n try\n {\n if (cornerRadius == zeroCornerRadius)\n {\n Log.Info($\"Initializing {(Config.Video.Swap10Bit ? \"10-bit\" : \"8-bit\")} swap chain with {Config.Video.SwapBuffers} buffers [Handle: {handle}]\");\n swapChain = Engine.Video.Factory.CreateSwapChainForHwnd(Device, handle, GetSwapChainDesc(ControlWidth, ControlHeight));\n }\n else\n {\n Log.Info($\"Initializing {(Config.Video.Swap10Bit ? \"10-bit\" : \"8-bit\")} composition swap chain with {Config.Video.SwapBuffers} buffers [Handle: {handle}]\");\n swapChain = Engine.Video.Factory.CreateSwapChainForComposition(Device, GetSwapChainDesc(ControlWidth, ControlHeight, true, true));\n using (var dxgiDevice = Device.QueryInterface())\n dCompDevice = DComp.DCompositionCreateDevice(dxgiDevice);\n dCompDevice.CreateTargetForHwnd(handle, false, out dCompTarget).CheckError();\n dCompDevice.CreateVisual(out dCompVisual).CheckError();\n dCompVisual.SetContent(swapChain).CheckError();\n dCompTarget.SetRoot(dCompVisual).CheckError();\n dCompDevice.Commit().CheckError();\n\n int styleEx = GetWindowLong(handle, (int)WindowLongFlags.GWL_EXSTYLE).ToInt32() | WS_EX_NOREDIRECTIONBITMAP;\n SetWindowLong(handle, (int)WindowLongFlags.GWL_EXSTYLE, new IntPtr(styleEx));\n }\n }\n catch (Exception e)\n {\n if (string.IsNullOrWhiteSpace(Config.Video.GPUAdapter) || Config.Video.GPUAdapter.ToUpper() != \"WARP\")\n {\n try { if (Device != null) Log.Warn($\"Device Remove Reason = {Device.DeviceRemovedReason.Description}\"); } catch { } // For troubleshooting\n\n Log.Warn($\"[SwapChain] Initialization failed ({e.Message}). Failling back to WARP device.\");\n Config.Video.GPUAdapter = \"WARP\";\n Flush();\n }\n else\n {\n ControlHandle = IntPtr.Zero;\n Log.Error($\"[SwapChain] Initialization failed ({e.Message})\");\n }\n\n return;\n }\n\n backBuffer = swapChain.GetBuffer(0);\n backBufferRtv = Device.CreateRenderTargetView(backBuffer);\n SCDisposed = false;\n\n if (!isFlushing) // avoid calling UI thread during Player.Stop\n {\n // SetWindowSubclass seems to require UI thread when RemoveWindowSubclass does not (docs are not mentioning this?)\n if (System.Threading.Thread.CurrentThread.ManagedThreadId == System.Windows.Application.Current.Dispatcher.Thread.ManagedThreadId)\n SetWindowSubclass(ControlHandle, wndProcDelegatePtr, UIntPtr.Zero, UIntPtr.Zero);\n else\n Utils.UI(() => SetWindowSubclass(ControlHandle, wndProcDelegatePtr, UIntPtr.Zero, UIntPtr.Zero));\n }\n\n Engine.Video.Factory.MakeWindowAssociation(ControlHandle, WindowAssociationFlags.IgnoreAll);\n\n ResizeBuffers(ControlWidth, ControlHeight); // maybe not required (only for vp)?\n }\n }\n internal void InitializeWinUISwapChain() // TODO: width/height directly here\n {\n lock (lockDevice)\n {\n if (!SCDisposed)\n DisposeSwapChain();\n\n if (Disposed)\n Initialize(false);\n\n Log.Info($\"Initializing {(Config.Video.Swap10Bit ? \"10-bit\" : \"8-bit\")} swap chain with {Config.Video.SwapBuffers} buffers\");\n\n try\n {\n swapChain = Engine.Video.Factory.CreateSwapChainForComposition(Device, GetSwapChainDesc(1, 1, true));\n }\n catch (Exception e)\n {\n Log.Error($\"Initialization failed [{e.Message}]\");\n\n // TODO fallback to WARP?\n\n SwapChainWinUIClbk?.Invoke(null);\n return;\n }\n\n backBuffer = swapChain.GetBuffer(0);\n backBufferRtv = Device.CreateRenderTargetView(backBuffer);\n SCDisposed = false;\n ResizeBuffers(1, 1);\n\n SwapChainWinUIClbk?.Invoke(swapChain.QueryInterface());\n }\n }\n\n public void DisposeSwapChain()\n {\n lock (lockDevice)\n {\n if (SCDisposed)\n return;\n\n SCDisposed = true;\n\n // Clear Screan\n if (!Disposed && swapChain != null)\n {\n try\n {\n context.ClearRenderTargetView(backBufferRtv, Config.Video._BackgroundColor);\n swapChain.Present(Config.Video.VSync, PresentFlags.None);\n }\n catch { }\n }\n\n Log.Info($\"Destroying swap chain [Handle: {ControlHandle}]\");\n\n // Unassign renderer's WndProc if still there and re-assign the old one\n if (ControlHandle != IntPtr.Zero)\n {\n if (!isFlushing) // SetWindowSubclass requires UI thread so avoid calling it on flush (Player.Stop)\n RemoveWindowSubclass(ControlHandle, wndProcDelegatePtr, UIntPtr.Zero);\n ControlHandle = IntPtr.Zero;\n }\n\n if (SwapChainWinUIClbk != null)\n {\n SwapChainWinUIClbk.Invoke(null);\n SwapChainWinUIClbk = null;\n swapChain?.Release(); // TBR: SwapChainPanel (SCP) should be disposed and create new instance instead (currently used from Template)\n }\n\n dCompVisual?.Dispose();\n dCompTarget?.Dispose();\n dCompDevice?.Dispose();\n dCompVisual = null;\n dCompTarget = null;\n dCompDevice = null;\n\n vpov?.Dispose();\n backBufferRtv?.Dispose();\n backBuffer?.Dispose();\n swapChain?.Dispose();\n\n if (Device != null)\n context?.Flush();\n }\n }\n\n public void RemoveViewportOffsets(ref Point p)\n {\n p.X -= (SideXPixels / 2 + PanXOffset);\n p.Y -= (SideYPixels / 2 + PanYOffset);\n }\n public bool IsPointWithInViewPort(Point p)\n => p.X >= GetViewport.X && p.X < GetViewport.X + GetViewport.Width && p.Y >= GetViewport.Y && p.Y < GetViewport.Y + GetViewport.Height;\n\n public static double GetCenterPoint(double zoom, double offset)\n => zoom == 1 ? offset : offset / (zoom - 1); // possible bug when zoom = 1 (noticed in out of bounds zoom out)\n\n /// \n /// Zooms in a way that the specified point before zoom will be at the same position after zoom\n /// \n /// \n /// \n public void ZoomWithCenterPoint(Point p, double zoom)\n {\n /* Notes\n *\n * Zoomed Point (ZP) // the current point in a -possible- zoomed viewport\n * Zoom (Z)\n * Unzoomed Point (UP) // the actual pixel of the current point\n * Viewport Point (VP)\n * Center Point (CP)\n *\n * UP = (VP + ZP) / Z =>\n * ZP = (UP * Z) - VP\n * CP = VP / (ZP - 1) (when UP = ZP)\n */\n\n if (!IsPointWithInViewPort(p))\n {\n SetZoom(zoom);\n return;\n }\n\n Point viewport = new(GetViewport.X, GetViewport.Y);\n RemoveViewportOffsets(ref viewport);\n RemoveViewportOffsets(ref p);\n\n // Finds the required center point so that p will have the same pixel after zoom\n Point zoomCenter = new(\n GetCenterPoint(zoom, ((p.X - viewport.X) / (this.zoom / zoom)) - p.X) / (GetViewport.Width / this.zoom),\n GetCenterPoint(zoom, ((p.Y - viewport.Y) / (this.zoom / zoom)) - p.Y) / (GetViewport.Height / this.zoom));\n\n SetZoomAndCenter(zoom, zoomCenter);\n }\n\n public void SetViewport(bool refresh = true)\n {\n float ratio;\n int x, y, newWidth, newHeight, xZoomPixels, yZoomPixels;\n\n if (Config.Video.AspectRatio == AspectRatio.Keep)\n ratio = curRatio;\n else ratio = Config.Video.AspectRatio == AspectRatio.Fill\n ? ControlWidth / (float)ControlHeight\n : Config.Video.AspectRatio == AspectRatio.Custom ? Config.Video.CustomAspectRatio.Value : Config.Video.AspectRatio.Value;\n\n if (ratio <= 0)\n ratio = 1;\n\n if (actualRotation == 90 || actualRotation == 270)\n ratio = 1 / ratio;\n\n if (ratio < ControlWidth / (float) ControlHeight)\n {\n newHeight = (int)(ControlHeight * zoom);\n newWidth = (int)(newHeight * ratio);\n\n SideXPixels = newWidth > ControlWidth && false ? 0 : (int) (ControlWidth - (ControlHeight * ratio)); // TBR\n SideYPixels = 0;\n\n y = PanYOffset;\n x = PanXOffset + SideXPixels / 2;\n\n yZoomPixels = newHeight - ControlHeight;\n xZoomPixels = newWidth - (ControlWidth - SideXPixels);\n }\n else\n {\n newWidth = (int)(ControlWidth * zoom);\n newHeight = (int)(newWidth / ratio);\n\n SideYPixels = newHeight > ControlHeight && false ? 0 : (int) (ControlHeight - (ControlWidth / ratio));\n SideXPixels = 0;\n\n x = PanXOffset;\n y = PanYOffset + SideYPixels / 2;\n\n xZoomPixels = newWidth - ControlWidth;\n yZoomPixels = newHeight - (ControlHeight - SideYPixels);\n }\n\n GetViewport = new(x - xZoomPixels * (float)zoomCenter.X, y - yZoomPixels * (float)zoomCenter.Y, newWidth, newHeight);\n ViewportChanged?.Invoke(this, new());\n\n if (videoProcessor == VideoProcessors.D3D11)\n {\n RawRect src, dst;\n\n if (GetViewport.Width < 1 || GetViewport.X + GetViewport.Width <= 0 || GetViewport.X >= ControlWidth || GetViewport.Y + GetViewport.Height <= 0 || GetViewport.Y >= ControlHeight)\n { // Out of screen\n src = new RawRect();\n dst = new RawRect();\n }\n else\n {\n int cropLeft = GetViewport.X < 0 ? (int) GetViewport.X * -1 : 0;\n int cropRight = GetViewport.X + GetViewport.Width > ControlWidth ? (int) (GetViewport.X + GetViewport.Width - ControlWidth) : 0;\n int cropTop = GetViewport.Y < 0 ? (int) GetViewport.Y * -1 : 0;\n int cropBottom = GetViewport.Y + GetViewport.Height > ControlHeight ? (int) (GetViewport.Y + GetViewport.Height - ControlHeight) : 0;\n\n dst = new RawRect(Math.Max((int)GetViewport.X, 0), Math.Max((int)GetViewport.Y, 0), Math.Min((int)GetViewport.Width + (int)GetViewport.X, ControlWidth), Math.Min((int)GetViewport.Height + (int)GetViewport.Y, ControlHeight));\n\n if (_RotationAngle == 90)\n {\n src = new RawRect(\n (int) (cropTop * (VideoRect.Right / GetViewport.Height)),\n (int) (cropRight * (VideoRect.Bottom / GetViewport.Width)),\n VideoRect.Right - (int) (cropBottom * VideoRect.Right / GetViewport.Height),\n VideoRect.Bottom - (int) (cropLeft * VideoRect.Bottom / GetViewport.Width));\n }\n else if (_RotationAngle == 270)\n {\n src = new RawRect(\n (int) (cropBottom * VideoRect.Right / GetViewport.Height),\n (int) (cropLeft * VideoRect.Bottom / GetViewport.Width),\n VideoRect.Right - (int) (cropTop * VideoRect.Right / GetViewport.Height),\n VideoRect.Bottom - (int) (cropRight * VideoRect.Bottom / GetViewport.Width));\n }\n else if (_RotationAngle == 180)\n {\n src = new RawRect(\n (int) (cropRight * VideoRect.Right / GetViewport.Width),\n (int) (cropBottom * VideoRect.Bottom /GetViewport.Height),\n VideoRect.Right - (int) (cropLeft * VideoRect.Right / GetViewport.Width),\n VideoRect.Bottom - (int) (cropTop * VideoRect.Bottom / GetViewport.Height));\n }\n else\n {\n src = new RawRect(\n (int) (cropLeft * VideoRect.Right / GetViewport.Width),\n (int) (cropTop * VideoRect.Bottom / GetViewport.Height),\n VideoRect.Right - (int) (cropRight * VideoRect.Right / GetViewport.Width),\n VideoRect.Bottom - (int) (cropBottom * VideoRect.Bottom / GetViewport.Height));\n }\n }\n\n vc.VideoProcessorSetStreamSourceRect(vp, 0, true, src);\n vc.VideoProcessorSetStreamDestRect (vp, 0, true, dst);\n vc.VideoProcessorSetOutputTargetRect(vp, true, new RawRect(0, 0, ControlWidth, ControlHeight));\n }\n\n if (refresh)\n Present();\n }\n public void ResizeBuffers(int width, int height)\n {\n lock (lockDevice)\n {\n if (SCDisposed)\n return;\n\n ControlWidth = width;\n ControlHeight = height;\n\n backBufferRtv.Dispose();\n vpov?.Dispose();\n backBuffer.Dispose();\n swapChain.ResizeBuffers(0, (uint)ControlWidth, (uint)ControlHeight, Format.Unknown, SwapChainFlags.None);\n UpdateCornerRadius();\n backBuffer = swapChain.GetBuffer(0);\n backBufferRtv = Device.CreateRenderTargetView(backBuffer);\n if (videoProcessor == VideoProcessors.D3D11)\n vd1.CreateVideoProcessorOutputView(backBuffer, vpe, vpovd, out vpov);\n\n SetViewport();\n }\n }\n\n internal void UpdateCornerRadius()\n {\n if (dCompDevice == null)\n return;\n\n dCompDevice.CreateRectangleClip(out var clip).CheckError();\n clip.SetLeft(0);\n clip.SetRight(ControlWidth);\n clip.SetTop(0);\n clip.SetBottom(ControlHeight);\n clip.SetTopLeftRadiusX((float)cornerRadius.TopLeft);\n clip.SetTopLeftRadiusY((float)cornerRadius.TopLeft);\n clip.SetTopRightRadiusX((float)cornerRadius.TopRight);\n clip.SetTopRightRadiusY((float)cornerRadius.TopRight);\n clip.SetBottomLeftRadiusX((float)cornerRadius.BottomLeft);\n clip.SetBottomLeftRadiusY((float)cornerRadius.BottomLeft);\n clip.SetBottomRightRadiusX((float)cornerRadius.BottomRight);\n clip.SetBottomRightRadiusY((float)cornerRadius.BottomRight);\n dCompVisual.SetClip(clip).CheckError();\n clip.Dispose();\n dCompDevice.Commit().CheckError();\n }\n\n private IntPtr WndProc(IntPtr hWnd, uint msg, IntPtr wParam, IntPtr lParam, IntPtr uIdSubclass, IntPtr dwRefData)\n {\n switch (msg)\n {\n case WM_NCDESTROY:\n if (SCDisposed)\n RemoveWindowSubclass(ControlHandle, wndProcDelegatePtr, UIntPtr.Zero);\n else\n DisposeSwapChain();\n break;\n\n case WM_SIZE:\n ResizeBuffers(SignedLOWORD(lParam), SignedHIWORD(lParam));\n break;\n }\n\n return DefSubclassProc(hWnd, msg, wParam, lParam);\n }\n}\n"], ["/LLPlayer/FlyleafLib/MediaPlayer/Translation/Services/OpenAIBaseTranslateService.cs", "using System.Collections.Concurrent;\nusing System.Collections.Generic;\nusing System.Diagnostics;\nusing System.Linq;\nusing System.Net.Http;\nusing System.Text;\nusing System.Text.Encodings.Web;\nusing System.Text.Json;\nusing System.Text.Json.Nodes;\nusing System.Text.Json.Serialization;\nusing System.Threading;\nusing System.Threading.Tasks;\n\nnamespace FlyleafLib.MediaPlayer.Translation.Services;\n\n#nullable enable\n\n// All LLM translation use this class\n// Currently only supports OpenAI compatible API\npublic class OpenAIBaseTranslateService : ITranslateService\n{\n private readonly HttpClient _httpClient;\n private readonly OpenAIBaseTranslateSettings _settings;\n private readonly TranslateChatConfig _chatConfig;\n private readonly bool _wordMode;\n\n private ChatTranslateMethod TranslateMethod => _chatConfig.TranslateMethod;\n\n public OpenAIBaseTranslateService(OpenAIBaseTranslateSettings settings, TranslateChatConfig chatConfig, bool wordMode)\n {\n _httpClient = settings.GetHttpClient();\n _settings = settings;\n _chatConfig = chatConfig;\n _wordMode = wordMode;\n }\n\n private string? _basePrompt;\n private readonly ConcurrentQueue _messageQueue = new();\n\n private static readonly JsonSerializerOptions JsonOptions = new()\n {\n DefaultIgnoreCondition = JsonIgnoreCondition.WhenWritingNull,\n Encoder = JavaScriptEncoder.UnsafeRelaxedJsonEscaping\n };\n\n public TranslateServiceType ServiceType => _settings.ServiceType;\n\n public void Dispose()\n {\n _httpClient.Dispose();\n }\n\n public void Initialize(Language src, TargetLanguage target)\n {\n (TranslateLanguage srcLang, TranslateLanguage targetLang) = this.TryGetLanguage(src, target);\n\n // setup prompt\n string prompt = !_wordMode && TranslateMethod == ChatTranslateMethod.KeepContext\n ? _chatConfig.PromptKeepContext\n : _chatConfig.PromptOneByOne;\n\n string targetLangName = _chatConfig.IncludeTargetLangRegion\n ? target.DisplayName() : targetLang.Name;\n\n _basePrompt = prompt\n .Replace(\"{source_lang}\", srcLang.Name)\n .Replace(\"{target_lang}\", targetLangName);\n }\n\n public async Task TranslateAsync(string text, CancellationToken token)\n {\n if (!_wordMode && TranslateMethod == ChatTranslateMethod.KeepContext)\n {\n return await DoKeepContext(text, token);\n }\n\n return await DoOneByOne(text, token);\n }\n\n private async Task DoKeepContext(string text, CancellationToken token)\n {\n if (_basePrompt == null)\n throw new InvalidOperationException(\"must be initialized\");\n\n // Trim message history if required\n while (_messageQueue.Count / 2 > _chatConfig.SubtitleContextCount)\n {\n if (_chatConfig.ContextRetainPolicy == ChatContextRetainPolicy.KeepSize)\n {\n Debug.Assert(_messageQueue.Count >= 2);\n\n // user\n _messageQueue.TryDequeue(out _);\n // assistant\n _messageQueue.TryDequeue(out _);\n }\n else if (_chatConfig.ContextRetainPolicy == ChatContextRetainPolicy.Reset)\n {\n // clear\n _messageQueue.Clear();\n }\n }\n\n List messages = new(_messageQueue.Count + 2)\n {\n new OpenAIMessage { role = \"system\", content = _basePrompt },\n };\n\n // add history\n messages.AddRange(_messageQueue);\n\n // add new message\n OpenAIMessage newMessage = new() { role = \"user\", content = text };\n messages.Add(newMessage);\n\n string reply = await SendChatRequest(\n _httpClient, _settings, messages.ToArray(), token);\n\n // add to message history if success\n _messageQueue.Enqueue(newMessage);\n _messageQueue.Enqueue(new OpenAIMessage { role = \"assistant\", content = reply });\n\n return reply;\n }\n\n private async Task DoOneByOne(string text, CancellationToken token)\n {\n if (_basePrompt == null)\n throw new InvalidOperationException(\"must be initialized\");\n\n string prompt = _basePrompt.Replace(\"{source_text}\", text);\n\n OpenAIMessage[] messages =\n [\n new() { role = \"user\", content = prompt }\n ];\n\n return await SendChatRequest(_httpClient, _settings, messages, token);\n }\n\n public static async Task Hello(OpenAIBaseTranslateSettings settings)\n {\n using HttpClient client = settings.GetHttpClient();\n\n OpenAIMessage[] messages =\n [\n new() { role = \"user\", content = \"Hello\" }\n ];\n\n return await SendChatRequest(client, settings, messages, CancellationToken.None);\n }\n\n private static async Task SendChatRequest(\n HttpClient client,\n OpenAIBaseTranslateSettings settings,\n OpenAIMessage[] messages,\n CancellationToken token)\n {\n string jsonResultString = string.Empty;\n int statusCode = -1;\n\n // Create the request payload\n OpenAIRequest request = new()\n {\n model = settings.Model,\n stream = false,\n messages = messages,\n\n temperature = settings.TemperatureManual ? settings.Temperature : null,\n top_p = settings.TopPManual ? settings.TopP : null,\n max_completion_tokens = settings.MaxCompletionTokens,\n max_tokens = settings.MaxTokens,\n };\n\n if (!settings.ModelRequired && string.IsNullOrWhiteSpace(settings.Model))\n {\n request.model = null;\n }\n\n try\n {\n // Convert to JSON\n string jsonContent = JsonSerializer.Serialize(request, JsonOptions);\n using var content = new StringContent(jsonContent, Encoding.UTF8, \"application/json\");\n using var result = await client.PostAsync(settings.ChatPath, content, token);\n\n jsonResultString = await result.Content.ReadAsStringAsync(token);\n\n statusCode = (int)result.StatusCode;\n result.EnsureSuccessStatusCode();\n\n OpenAIResponse? chatResponse = JsonSerializer.Deserialize(jsonResultString);\n string reply = chatResponse!.choices[0].message.content;\n if (settings.ReasonStripRequired)\n {\n var stripped = ChatReplyParser.StripReasoning(reply);\n return stripped.Trim().ToString();\n }\n\n return reply.Trim();\n }\n // Distinguish between timeout and cancel errors\n catch (OperationCanceledException ex)\n when (!ex.Message.StartsWith(\"The request was canceled due to the configured HttpClient.Timeout\"))\n {\n // cancel\n throw;\n }\n catch (Exception ex)\n {\n // timeout and other error\n throw new TranslationException($\"Cannot request to {settings.ServiceType}: {ex.Message}\", ex)\n {\n Data =\n {\n [\"status_code\"] = statusCode.ToString(),\n [\"response\"] = jsonResultString\n }\n };\n }\n }\n\n public static async Task> GetLoadedModels(OpenAIBaseTranslateSettings settings)\n {\n using HttpClient client = settings.GetHttpClient(true);\n\n string jsonResultString = string.Empty;\n int statusCode = -1;\n\n // getting models\n try\n {\n using var result = await client.GetAsync(\"/v1/models\");\n\n jsonResultString = await result.Content.ReadAsStringAsync();\n\n statusCode = (int)result.StatusCode;\n result.EnsureSuccessStatusCode();\n\n JsonNode? node = JsonNode.Parse(jsonResultString);\n List models = node![\"data\"]!.AsArray()\n .Select(model => model![\"id\"]!.GetValue())\n .Order()\n .ToList();\n\n return models;\n }\n catch (Exception ex)\n {\n throw new InvalidOperationException($\"get models error: {ex.Message}\", ex)\n {\n Data =\n {\n [\"status_code\"] = statusCode.ToString(),\n [\"response\"] = jsonResultString\n }\n };\n }\n }\n}\n\npublic class OpenAIMessage\n{\n public required string role { get; init; }\n public required string content { get; init; }\n}\n\npublic class OpenAIRequest\n{\n public string? model { get; set; }\n public required OpenAIMessage[] messages { get; init; }\n public required bool stream { get; init; }\n public double? temperature { get; set; }\n public double? top_p { get; set; }\n public int? max_completion_tokens { get; set; }\n public int? max_tokens { get; set; }\n}\n\npublic class OpenAIResponse\n{\n public required OpenAIChoice[] choices { get; init; }\n}\n\npublic class OpenAIChoice\n{\n public required OpenAIMessage message { get; init; }\n}\n\npublic static class ChatReplyParser\n{\n // Target tag names to remove (lowercase)\n private static readonly string[] Tags = [\"think\", \"reason\", \"reasoning\", \"thought\"];\n\n // open/close tag strings from tag names\n private static readonly string[] OpenTags;\n private static readonly string[] CloseTags;\n\n static ChatReplyParser()\n {\n OpenTags = new string[Tags.Length];\n CloseTags = new string[Tags.Length];\n for (int i = 0; i < Tags.Length; i++)\n {\n OpenTags[i] = $\"<{Tags[i]}>\"; // e.g. \"\"\n CloseTags[i] = $\"\"; // e.g. \"\"\n }\n }\n\n /// \n /// Removes a leading reasoning tag if present and returns only the generated message portion.\n /// \n public static ReadOnlySpan StripReasoning(ReadOnlySpan input)\n {\n // Return immediately if it doesn't start with a tag\n if (input.Length == 0 || input[0] != '<')\n {\n return input;\n }\n\n for (int i = 0; i < OpenTags.Length; i++)\n {\n if (input.StartsWith(OpenTags[i], StringComparison.OrdinalIgnoreCase))\n {\n int endIdx = input.IndexOf(CloseTags[i], StringComparison.OrdinalIgnoreCase);\n if (endIdx >= 0)\n {\n int next = endIdx + CloseTags[i].Length;\n // Skip over any consecutive line breaks and whitespace\n while (next < input.Length && char.IsWhiteSpace(input[next]))\n {\n next++;\n }\n return input.Slice(next);\n }\n }\n }\n\n // Return original string if no tag matched\n return input;\n }\n}\n"], ["/LLPlayer/FlyleafLib/MediaFramework/MediaDecoder/DecoderBase.cs", "using FlyleafLib.MediaFramework.MediaDemuxer;\nusing FlyleafLib.MediaFramework.MediaStream;\n\nnamespace FlyleafLib.MediaFramework.MediaDecoder;\n\npublic abstract unsafe class DecoderBase : RunThreadBase\n{\n public MediaType Type { get; protected set; }\n\n public bool OnVideoDemuxer => demuxer?.Type == MediaType.Video;\n public Demuxer Demuxer => demuxer;\n public StreamBase Stream { get; protected set; }\n public AVCodecContext* CodecCtx => codecCtx;\n public int Width => codecCtx != null ? codecCtx->width : 0; // for subtitle\n public int Height => codecCtx != null ? codecCtx->height : 0; // for subtitle\n\n public Action CodecChanged { get; set; }\n public Config Config { get; protected set; }\n public double Speed { get => speed; set { if (Disposed) { speed = value; return; } if (speed != value) OnSpeedChanged(value); } }\n protected double speed = 1, oldSpeed = 1;\n protected virtual void OnSpeedChanged(double value) { }\n\n internal bool filledFromCodec;\n protected AVFrame* frame;\n protected AVCodecContext* codecCtx;\n internal object lockCodecCtx = new();\n\n protected Demuxer demuxer;\n\n public DecoderBase(Config config, int uniqueId = -1) : base(uniqueId)\n {\n Config = config;\n\n if (this is VideoDecoder)\n Type = MediaType.Video;\n else if (this is AudioDecoder)\n Type = MediaType.Audio;\n else if (this is SubtitlesDecoder)\n Type = MediaType.Subs;\n else if (this is DataDecoder)\n Type = MediaType.Data;\n\n threadName = $\"Decoder: {Type,5}\";\n }\n\n public string Open(StreamBase stream)\n {\n lock (lockActions)\n {\n var prevStream = Stream;\n Dispose();\n Status = Status.Opening;\n string error = Open2(stream, prevStream);\n if (!Disposed)\n frame = av_frame_alloc();\n\n return error;\n }\n }\n protected string Open2(StreamBase stream, StreamBase prevStream, bool openStream = true)\n {\n string error = null;\n\n try\n {\n lock (stream.Demuxer.lockActions)\n {\n if (stream == null || stream.Demuxer.Interrupter.ForceInterrupt == 1 || stream.Demuxer.Disposed)\n return \"Cancelled\";\n\n int ret = -1;\n Disposed= false;\n Stream = stream;\n demuxer = stream.Demuxer;\n\n if (stream is not DataStream) // if we don't open/use a data codec context why not just push the Data Frames directly from the Demuxer? no need to have DataDecoder*\n {\n // avcodec_find_decoder will use libdav1d which does not support hardware decoding (software fallback with openStream = false from av1 to default:libdav1d) [#340]\n var codec = stream.CodecID == AVCodecID.Av1 && openStream && Config.Video.VideoAcceleration ? avcodec_find_decoder_by_name(\"av1\") : avcodec_find_decoder(stream.CodecID);\n if (codec == null)\n return error = $\"[{Type} avcodec_find_decoder] No suitable codec found\";\n\n codecCtx = avcodec_alloc_context3(codec); // Pass codec to use default settings\n if (codecCtx == null)\n return error = $\"[{Type} avcodec_alloc_context3] Failed to allocate context3\";\n\n ret = avcodec_parameters_to_context(codecCtx, stream.AVStream->codecpar);\n if (ret < 0)\n return error = $\"[{Type} avcodec_parameters_to_context] {FFmpegEngine.ErrorCodeToMsg(ret)} ({ret})\";\n\n codecCtx->pkt_timebase = stream.AVStream->time_base;\n codecCtx->codec_id = codec->id; // avcodec_parameters_to_context will change this we need to set Stream's Codec Id (eg we change mp2 to mp3)\n\n if (Config.Decoder.ShowCorrupted)\n codecCtx->flags |= CodecFlags.OutputCorrupt;\n\n if (Config.Decoder.LowDelay)\n codecCtx->flags |= CodecFlags.LowDelay;\n\n try { ret = Setup(codec); } catch(Exception e) { return error = $\"[{Type} Setup] {e.Message}\"; }\n if (ret < 0)\n return error = $\"[{Type} Setup] {ret}\";\n\n var codecOpts = Config.Decoder.GetCodecOptPtr(stream.Type);\n AVDictionary* avopt = null;\n foreach(var optKV in codecOpts)\n av_dict_set(&avopt, optKV.Key, optKV.Value, 0);\n\n ret = avcodec_open2(codecCtx, null, avopt == null ? null : &avopt);\n\n if (avopt != null)\n {\n if (ret >= 0)\n {\n AVDictionaryEntry *t = null;\n\n while ((t = av_dict_get(avopt, \"\", t, DictReadFlags.IgnoreSuffix)) != null)\n Log.Debug($\"Ignoring codec option {Utils.BytePtrToStringUTF8(t->key)}\");\n }\n\n av_dict_free(&avopt);\n }\n\n if (ret < 0)\n return error = $\"[{Type} avcodec_open2] {FFmpegEngine.ErrorCodeToMsg(ret)} ({ret})\";\n }\n\n if (openStream)\n {\n if (prevStream != null)\n {\n if (prevStream.Demuxer.Type == stream.Demuxer.Type)\n stream.Demuxer.SwitchStream(stream);\n else if (!prevStream.Demuxer.Disposed)\n {\n if (prevStream.Demuxer.Type == MediaType.Video)\n prevStream.Demuxer.DisableStream(prevStream);\n else if (prevStream.Demuxer.Type == MediaType.Audio || prevStream.Demuxer.Type == MediaType.Subs)\n prevStream.Demuxer.Dispose();\n\n stream.Demuxer.EnableStream(stream);\n }\n }\n else\n stream.Demuxer.EnableStream(stream);\n\n Status = Status.Stopped;\n CodecChanged?.Invoke(this);\n }\n\n return null;\n }\n }\n finally\n {\n if (error != null)\n Dispose(true);\n }\n }\n protected abstract int Setup(AVCodec* codec);\n\n public void Dispose(bool closeStream = false)\n {\n if (Disposed)\n return;\n\n lock (lockActions)\n {\n if (Disposed)\n return;\n\n Stop();\n DisposeInternal();\n\n if (closeStream && Stream != null && !Stream.Demuxer.Disposed)\n {\n if (Stream.Demuxer.Type == MediaType.Video)\n Stream.Demuxer.DisableStream(Stream);\n else\n Stream.Demuxer.Dispose();\n }\n\n if (frame != null)\n fixed (AVFrame** ptr = &frame)\n av_frame_free(ptr);\n\n if (codecCtx != null)\n fixed (AVCodecContext** ptr = &codecCtx)\n avcodec_free_context(ptr);\n\n codecCtx = null;\n demuxer = null;\n Stream = null;\n Status = Status.Stopped;\n Disposed = true;\n Log.Info(\"Disposed\");\n }\n }\n protected abstract void DisposeInternal();\n}\n"], ["/LLPlayer/LLPlayer/ViewModels/SubtitlesDownloaderDialogVM.cs", "using System.Collections.ObjectModel;\nusing System.ComponentModel;\nusing System.IO;\nusing FlyleafLib;\nusing FlyleafLib.MediaFramework.MediaPlaylist;\nusing FlyleafLib.MediaPlayer;\nusing LLPlayer.Extensions;\nusing LLPlayer.Services;\nusing Microsoft.Win32;\nusing static FlyleafLib.MediaFramework.MediaContext.DecoderContext;\n\nnamespace LLPlayer.ViewModels;\n\npublic class SubtitlesDownloaderDialogVM : Bindable, IDialogAware\n{\n public FlyleafManager FL { get; }\n private readonly OpenSubtitlesProvider _subProvider;\n\n public SubtitlesDownloaderDialogVM(\n FlyleafManager fl,\n OpenSubtitlesProvider subProvider\n )\n {\n FL = fl;\n _subProvider = subProvider;\n }\n\n public ObservableCollection Subs { get; } = new();\n\n public SearchResponse? SelectedSub\n {\n get;\n set\n {\n if (Set(ref field, value))\n {\n OnPropertyChanged(nameof(CanAction));\n }\n }\n } = null;\n\n public string Query\n {\n get;\n set\n {\n if (Set(ref field, value))\n {\n OnPropertyChanged(nameof(CanSearch));\n }\n }\n } = string.Empty;\n\n public bool CanSearch => !string.IsNullOrWhiteSpace(Query);\n public bool CanAction => SelectedSub != null;\n\n public AsyncDelegateCommand? CmdSearch => field ??= new AsyncDelegateCommand(async () =>\n {\n Subs.Clear();\n\n IList result;\n\n try\n {\n result = await _subProvider.Search(Query);\n }\n catch (Exception ex)\n {\n ErrorDialogHelper.ShowUnknownErrorPopup($\"Cannot search subtitles from opensubtitles.org: {ex.Message}\", UnknownErrorType.Network, ex);\n return;\n }\n\n var query = result\n .OrderByDescending(r =>\n {\n // prefer user-configured languages\n return FL.PlayerConfig.Subtitles.Languages.Any(l =>\n l.Equals(Language.Get(r.ISO639)));\n })\n .ThenBy(r => r.LanguageName)\n .ThenByDescending(r => r.SubDownloadsCnt)\n .ThenBy(r => r.SubFileName);\n\n foreach (var record in query)\n {\n Subs.Add(record);\n }\n }).ObservesCanExecute(() => CanSearch);\n\n public AsyncDelegateCommand? CmdLoad => field ??= new AsyncDelegateCommand(async () =>\n {\n var sub = SelectedSub;\n if (sub == null)\n {\n return;\n }\n\n byte[] subData;\n\n try\n {\n (subData, _) = await _subProvider.Download(sub);\n }\n catch (Exception ex)\n {\n ErrorDialogHelper.ShowUnknownErrorPopup($\"Cannot load the subtitle from opensubtitles.org: {ex.Message}\", UnknownErrorType.Network, ex);\n return;\n }\n\n string subDir = Path.Combine(Path.GetTempPath(), App.Name, \"Subs\");\n string subPath = Path.Combine(subDir, sub.SubFileName);\n if (!Directory.Exists(subDir))\n {\n Directory.CreateDirectory(subDir);\n }\n\n var ext = Path.GetExtension(subPath).ToLower();\n if (ext.StartsWith(\".\"))\n {\n ext = ext.Substring(1);\n }\n\n if (!Utils.ExtensionsSubtitles.Contains(ext))\n {\n throw new InvalidOperationException($\"'{ext}' extension is not supported\");\n }\n\n await File.WriteAllBytesAsync(subPath, subData);\n\n // TODO: L: Refactor to pass language directly at Open\n // TODO: L: Allow to load as a secondary subtitle\n FL.Player.decoder.OpenExternalSubtitlesStreamCompleted += DecoderOnOpenExternalSubtitlesStreamCompleted;\n\n void DecoderOnOpenExternalSubtitlesStreamCompleted(object? sender, OpenExternalSubtitlesStreamCompletedArgs e)\n {\n FL.Player.decoder.OpenExternalSubtitlesStreamCompleted -= DecoderOnOpenExternalSubtitlesStreamCompleted;\n\n if (e.Success)\n {\n var stream = e.ExtStream;\n if (stream != null && stream.Url == subPath)\n {\n // Override if different from auto-detected language\n stream.ManualDownloaded = true;\n\n if (stream.Language.ISO6391 != sub.ISO639)\n {\n var lang = Language.Get(sub.ISO639);\n if (!string.IsNullOrEmpty(lang.IdSubLanguage) && lang.IdSubLanguage != \"und\")\n {\n stream.Language = lang;\n FL.Player.SubtitlesManager[0].LanguageSource = stream.Language;\n }\n }\n }\n }\n }\n\n FL.Player.OpenAsync(subPath);\n\n }).ObservesCanExecute(() => CanAction);\n\n public AsyncDelegateCommand? CmdDownload => field ??= new AsyncDelegateCommand(async () =>\n {\n var sub = SelectedSub;\n if (sub == null)\n {\n return;\n }\n\n string fileName = sub.SubFileName;\n\n string? initDir = null;\n if (FL.Player.Playlist.Selected != null)\n {\n var url = FL.Player.Playlist.Selected.DirectUrl;\n if (File.Exists(url))\n {\n initDir = Path.GetDirectoryName(url);\n }\n }\n\n SaveFileDialog dialog = new()\n {\n Title = \"Save subtitles to file\",\n InitialDirectory = initDir,\n FileName = fileName,\n Filter = \"All Files (*.*)|*.*\",\n };\n\n if (dialog.ShowDialog() == true)\n {\n byte[] subData;\n\n try\n {\n (subData, _) = await _subProvider.Download(sub);\n }\n catch (Exception ex)\n {\n ErrorDialogHelper.ShowUnknownErrorPopup($\"Cannot download the subtitle from opensubtitles.org: {ex.Message}\", UnknownErrorType.Network, ex);\n return;\n }\n\n await File.WriteAllBytesAsync(dialog.FileName, subData);\n }\n }).ObservesCanExecute(() => CanAction);\n\n private void Playlist_OnPropertyChanged(object? sender, PropertyChangedEventArgs e)\n {\n if (e.PropertyName == nameof(FL.Player.Playlist.Selected) &&\n FL.Player.Playlist.Selected != null)\n {\n // Update query when video changes\n UpdateQuery(FL.Player.Playlist.Selected);\n }\n }\n\n private void UpdateQuery(PlaylistItem selected)\n {\n string title = selected.Title;\n if (title == selected.OriginalTitle && File.Exists(selected.Url))\n {\n FileInfo fi = new(selected.Url);\n if (!string.IsNullOrEmpty(fi.Extension) && title.EndsWith(fi.Extension))\n {\n // remove extension part\n title = title[..^fi.Extension.Length];\n }\n }\n\n Query = title;\n }\n\n #region IDialogAware\n public string Title { get; set => Set(ref field, value); }\n = $\"Subtitles Downloader - {App.Name}\";\n public double WindowWidth { get; set => Set(ref field, value); } = 900;\n public double WindowHeight { get; set => Set(ref field, value); } = 600;\n\n public DialogCloseListener RequestClose { get; }\n\n public bool CanCloseDialog()\n {\n return true;\n }\n public void OnDialogClosed()\n {\n FL.Player.Playlist.PropertyChanged -= Playlist_OnPropertyChanged;\n }\n public void OnDialogOpened(IDialogParameters parameters)\n {\n // Set query from current video\n var selected = FL.Player.Playlist.Selected;\n if (selected != null)\n {\n UpdateQuery(selected);\n }\n\n // Register update playlist event\n FL.Player.Playlist.PropertyChanged += Playlist_OnPropertyChanged;\n }\n #endregion\n}\n"], ["/LLPlayer/FlyleafLib/MediaFramework/MediaRenderer/Renderer.VideoProcessor.cs", "using System.Collections.Generic;\nusing System.Numerics;\nusing System.Text.Json.Serialization;\nusing Vortice.DXGI;\nusing Vortice.Direct3D11;\n\nusing ID3D11VideoContext = Vortice.Direct3D11.ID3D11VideoContext;\n\nusing FlyleafLib.Controls.WPF;\nusing FlyleafLib.MediaPlayer;\n\nusing static FlyleafLib.Logger;\nusing static FlyleafLib.Utils;\n\nnamespace FlyleafLib.MediaFramework.MediaRenderer;\n\nunsafe public partial class Renderer\n{\n /* TODO\n * 1) Try to sync filters between Flyleaf and D3D11 video processors so we will not have to reset on change\n * 2) Filter default values will change when the device/adapter is changed\n */\n\n public static Dictionary VideoProcessorsCapsCache = new();\n\n internal static VideoProcessorFilter ConvertFromVideoProcessorFilterCaps(VideoProcessorFilterCaps filter)\n {\n switch (filter)\n {\n case VideoProcessorFilterCaps.Brightness:\n return VideoProcessorFilter.Brightness;\n case VideoProcessorFilterCaps.Contrast:\n return VideoProcessorFilter.Contrast;\n case VideoProcessorFilterCaps.Hue:\n return VideoProcessorFilter.Hue;\n case VideoProcessorFilterCaps.Saturation:\n return VideoProcessorFilter.Saturation;\n case VideoProcessorFilterCaps.EdgeEnhancement:\n return VideoProcessorFilter.EdgeEnhancement;\n case VideoProcessorFilterCaps.NoiseReduction:\n return VideoProcessorFilter.NoiseReduction;\n case VideoProcessorFilterCaps.AnamorphicScaling:\n return VideoProcessorFilter.AnamorphicScaling;\n case VideoProcessorFilterCaps.StereoAdjustment:\n return VideoProcessorFilter.StereoAdjustment;\n\n default:\n return VideoProcessorFilter.StereoAdjustment;\n }\n }\n internal static VideoProcessorFilterCaps ConvertFromVideoProcessorFilter(VideoProcessorFilter filter)\n {\n switch (filter)\n {\n case VideoProcessorFilter.Brightness:\n return VideoProcessorFilterCaps.Brightness;\n case VideoProcessorFilter.Contrast:\n return VideoProcessorFilterCaps.Contrast;\n case VideoProcessorFilter.Hue:\n return VideoProcessorFilterCaps.Hue;\n case VideoProcessorFilter.Saturation:\n return VideoProcessorFilterCaps.Saturation;\n case VideoProcessorFilter.EdgeEnhancement:\n return VideoProcessorFilterCaps.EdgeEnhancement;\n case VideoProcessorFilter.NoiseReduction:\n return VideoProcessorFilterCaps.NoiseReduction;\n case VideoProcessorFilter.AnamorphicScaling:\n return VideoProcessorFilterCaps.AnamorphicScaling;\n case VideoProcessorFilter.StereoAdjustment:\n return VideoProcessorFilterCaps.StereoAdjustment;\n\n default:\n return VideoProcessorFilterCaps.StereoAdjustment;\n }\n }\n internal static VideoFilter ConvertFromVideoProcessorFilterRange(VideoProcessorFilterRange filter) => new()\n {\n Minimum = filter.Minimum,\n Maximum = filter.Maximum,\n Value = filter.Default,\n Step = filter.Multiplier\n };\n\n VideoColor D3D11VPBackgroundColor;\n ID3D11VideoDevice1 vd1;\n ID3D11VideoProcessor vp;\n ID3D11VideoContext vc;\n ID3D11VideoProcessorEnumerator vpe;\n ID3D11VideoProcessorInputView vpiv;\n ID3D11VideoProcessorOutputView vpov;\n\n VideoProcessorStream[] vpsa = new VideoProcessorStream[] { new VideoProcessorStream() { Enable = true } };\n VideoProcessorContentDescription vpcd = new()\n {\n Usage = VideoUsage.PlaybackNormal,\n InputFrameFormat = VideoFrameFormat.InterlacedTopFieldFirst,\n\n InputFrameRate = new Rational(1, 1),\n OutputFrameRate = new Rational(1, 1),\n };\n VideoProcessorOutputViewDescription vpovd = new() { ViewDimension = VideoProcessorOutputViewDimension.Texture2D };\n VideoProcessorInputViewDescription vpivd = new()\n {\n FourCC = 0,\n ViewDimension = VideoProcessorInputViewDimension.Texture2D,\n Texture2D = new Texture2DVideoProcessorInputView() { MipSlice = 0, ArraySlice = 0 }\n };\n VideoProcessorColorSpace inputColorSpace;\n VideoProcessorColorSpace outputColorSpace;\n\n AVDynamicHDRPlus* hdrPlusData = null;\n AVContentLightMetadata lightData = new();\n AVMasteringDisplayMetadata displayData = new();\n\n uint actualRotation;\n bool actualHFlip, actualVFlip;\n bool configLoadedChecked;\n\n void InitializeVideoProcessor()\n {\n lock (VideoProcessorsCapsCache)\n try\n {\n vpcd.InputWidth = 1;\n vpcd.InputHeight= 1;\n vpcd.OutputWidth = vpcd.InputWidth;\n vpcd.OutputHeight= vpcd.InputHeight;\n\n outputColorSpace = new VideoProcessorColorSpace()\n {\n Usage = 0,\n RGB_Range = 0,\n YCbCr_Matrix = 1,\n YCbCr_xvYCC = 0,\n Nominal_Range = 2\n };\n\n if (VideoProcessorsCapsCache.ContainsKey(Device.Tag.ToString()))\n {\n if (VideoProcessorsCapsCache[Device.Tag.ToString()].Failed)\n {\n InitializeFilters();\n return;\n }\n\n vd1 = Device.QueryInterface();\n vc = context.QueryInterface();\n\n vd1.CreateVideoProcessorEnumerator(ref vpcd, out vpe);\n\n if (vpe == null)\n {\n VPFailed();\n return;\n }\n\n // if (!VideoProcessorsCapsCache[Device.Tag.ToString()].TypeIndex != -1)\n vd1.CreateVideoProcessor(vpe, (uint)VideoProcessorsCapsCache[Device.Tag.ToString()].TypeIndex, out vp);\n InitializeFilters();\n\n return;\n }\n\n VideoProcessorCapsCache cache = new();\n VideoProcessorsCapsCache.Add(Device.Tag.ToString(), cache);\n\n vd1 = Device.QueryInterface();\n vc = context.QueryInterface();\n\n vd1.CreateVideoProcessorEnumerator(ref vpcd, out vpe);\n\n if (vpe == null || Device.FeatureLevel < Vortice.Direct3D.FeatureLevel.Level_10_0)\n {\n VPFailed();\n return;\n }\n\n var vpe1 = vpe.QueryInterface();\n bool supportHLG = vpe1.CheckVideoProcessorFormatConversion(Format.P010, ColorSpaceType.YcbcrStudioGhlgTopLeftP2020, Format.B8G8R8A8_UNorm, ColorSpaceType.RgbFullG22NoneP709);\n bool supportHDR10Limited = vpe1.CheckVideoProcessorFormatConversion(Format.P010, ColorSpaceType.YcbcrStudioG2084TopLeftP2020, Format.B8G8R8A8_UNorm, ColorSpaceType.RgbStudioG2084NoneP2020);\n\n var vpCaps = vpe.VideoProcessorCaps;\n string dump = \"\";\n\n if (CanDebug)\n {\n dump += $\"=====================================================\\r\\n\";\n dump += $\"MaxInputStreams {vpCaps.MaxInputStreams}\\r\\n\";\n dump += $\"MaxStreamStates {vpCaps.MaxStreamStates}\\r\\n\";\n dump += $\"HDR10 Limited {(supportHDR10Limited ? \"yes\" : \"no\")}\\r\\n\";\n dump += $\"HLG {(supportHLG ? \"yes\" : \"no\")}\\r\\n\";\n\n dump += $\"\\n[Video Processor Device Caps]\\r\\n\";\n foreach (VideoProcessorDeviceCaps cap in Enum.GetValues(typeof(VideoProcessorDeviceCaps)))\n dump += $\"{cap,-25} {((vpCaps.DeviceCaps & cap) != 0 ? \"yes\" : \"no\")}\\r\\n\";\n\n dump += $\"\\n[Video Processor Feature Caps]\\r\\n\";\n foreach (VideoProcessorFeatureCaps cap in Enum.GetValues(typeof(VideoProcessorFeatureCaps)))\n dump += $\"{cap,-25} {((vpCaps.FeatureCaps & cap) != 0 ? \"yes\" : \"no\")}\\r\\n\";\n\n dump += $\"\\n[Video Processor Stereo Caps]\\r\\n\";\n foreach (VideoProcessorStereoCaps cap in Enum.GetValues(typeof(VideoProcessorStereoCaps)))\n dump += $\"{cap,-25} {((vpCaps.StereoCaps & cap) != 0 ? \"yes\" : \"no\")}\\r\\n\";\n\n dump += $\"\\n[Video Processor Input Format Caps]\\r\\n\";\n foreach (VideoProcessorFormatCaps cap in Enum.GetValues(typeof(VideoProcessorFormatCaps)))\n dump += $\"{cap,-25} {((vpCaps.InputFormatCaps & cap) != 0 ? \"yes\" : \"no\")}\\r\\n\";\n\n dump += $\"\\n[Video Processor Filter Caps]\\r\\n\";\n }\n\n foreach (VideoProcessorFilterCaps filter in Enum.GetValues(typeof(VideoProcessorFilterCaps)))\n if ((vpCaps.FilterCaps & filter) != 0)\n {\n vpe1.GetVideoProcessorFilterRange(ConvertFromVideoProcessorFilterCaps(filter), out var range);\n if (CanDebug) dump += $\"{filter,-25} [{range.Minimum,6} - {range.Maximum,4}] | x{range.Multiplier,4} | *{range.Default}\\r\\n\";\n var vf = ConvertFromVideoProcessorFilterRange(range);\n vf.Filter = (VideoFilters)filter;\n cache.Filters.Add((VideoFilters)filter, vf);\n }\n else if (CanDebug)\n dump += $\"{filter,-25} no\\r\\n\";\n\n if (CanDebug)\n {\n dump += $\"\\n[Video Processor Input Format Caps]\\r\\n\";\n foreach (VideoProcessorAutoStreamCaps cap in Enum.GetValues(typeof(VideoProcessorAutoStreamCaps)))\n dump += $\"{cap,-25} {((vpCaps.AutoStreamCaps & cap) != 0 ? \"yes\" : \"no\")}\\r\\n\";\n }\n\n uint typeIndex = 0;\n VideoProcessorRateConversionCaps rcCap = new();\n for (uint i = 0; i < vpCaps.RateConversionCapsCount; i++)\n {\n vpe.GetVideoProcessorRateConversionCaps(i, out rcCap);\n VideoProcessorProcessorCaps pCaps = (VideoProcessorProcessorCaps) rcCap.ProcessorCaps;\n\n if (CanDebug)\n {\n dump += $\"\\n[Video Processor Rate Conversion Caps #{i}]\\r\\n\";\n\n dump += $\"\\n\\t[Video Processor Rate Conversion Caps]\\r\\n\";\n var fields = typeof(VideoProcessorRateConversionCaps).GetFields();\n foreach (var field in fields)\n dump += $\"\\t{field.Name,-35} {field.GetValue(rcCap)}\\r\\n\";\n\n dump += $\"\\n\\t[Video Processor Processor Caps]\\r\\n\";\n foreach (VideoProcessorProcessorCaps cap in Enum.GetValues(typeof(VideoProcessorProcessorCaps)))\n dump += $\"\\t{cap,-35} {(((VideoProcessorProcessorCaps)rcCap.ProcessorCaps & cap) != 0 ? \"yes\" : \"no\")}\\r\\n\";\n }\n\n typeIndex = i;\n\n if (((VideoProcessorProcessorCaps)rcCap.ProcessorCaps & VideoProcessorProcessorCaps.DeinterlaceBob) != 0)\n break; // TBR: When we add past/future frames support\n }\n vpe1.Dispose();\n\n if (CanDebug) Log.Debug($\"D3D11 Video Processor\\r\\n{dump}\");\n\n cache.TypeIndex = (int)typeIndex;\n cache.HLG = supportHLG;\n cache.HDR10Limited = supportHDR10Limited;\n cache.VideoProcessorCaps = vpCaps;\n cache.VideoProcessorRateConversionCaps = rcCap;\n\n //if (typeIndex != -1)\n vd1.CreateVideoProcessor(vpe, (uint)typeIndex, out vp);\n if (vp == null)\n {\n VPFailed();\n return;\n }\n\n cache.Failed = false;\n Log.Info($\"D3D11 Video Processor Initialized (Rate Caps #{typeIndex})\");\n\n } catch { DisposeVideoProcessor(); Log.Error($\"D3D11 Video Processor Initialization Failed\"); }\n\n InitializeFilters();\n }\n void VPFailed()\n {\n Log.Error($\"D3D11 Video Processor Initialization Failed\");\n\n if (!VideoProcessorsCapsCache.ContainsKey(Device.Tag.ToString()))\n VideoProcessorsCapsCache.Add(Device.Tag.ToString(), new VideoProcessorCapsCache());\n VideoProcessorsCapsCache[Device.Tag.ToString()].Failed = true;\n\n VideoProcessorsCapsCache[Device.Tag.ToString()].Filters.Add(VideoFilters.Brightness, new VideoFilter() { Filter = VideoFilters.Brightness });\n VideoProcessorsCapsCache[Device.Tag.ToString()].Filters.Add(VideoFilters.Contrast, new VideoFilter() { Filter = VideoFilters.Contrast });\n\n DisposeVideoProcessor();\n InitializeFilters();\n }\n void DisposeVideoProcessor()\n {\n vpiv?.Dispose();\n vpov?.Dispose();\n vp?. Dispose();\n vpe?. Dispose();\n vc?. Dispose();\n vd1?. Dispose();\n\n vc = null;\n }\n void InitializeFilters()\n {\n Filters = VideoProcessorsCapsCache[Device.Tag.ToString()].Filters;\n\n // Add FLVP filters if D3D11VP does not support them\n if (!Filters.ContainsKey(VideoFilters.Brightness))\n Filters.Add(VideoFilters.Brightness, new VideoFilter(VideoFilters.Brightness));\n\n if (!Filters.ContainsKey(VideoFilters.Contrast))\n Filters.Add(VideoFilters.Contrast, new VideoFilter(VideoFilters.Contrast));\n\n foreach(var filter in Filters.Values)\n {\n if (!Config.Video.Filters.ContainsKey(filter.Filter))\n continue;\n\n var cfgFilter = Config.Video.Filters[filter.Filter];\n cfgFilter.Available = true;\n cfgFilter.renderer = this;\n\n if (!configLoadedChecked && !Config.Loaded)\n {\n cfgFilter.Minimum = filter.Minimum;\n cfgFilter.Maximum = filter.Maximum;\n cfgFilter.DefaultValue = filter.Value;\n cfgFilter.Value = filter.Value;\n cfgFilter.Step = filter.Step;\n }\n\n UpdateFilterValue(cfgFilter);\n }\n\n configLoadedChecked = true;\n UpdateBackgroundColor();\n\n if (vc != null)\n {\n vc.VideoProcessorSetStreamAutoProcessingMode(vp, 0, false);\n vc.VideoProcessorSetStreamFrameFormat(vp, 0, !Config.Video.Deinterlace ? VideoFrameFormat.Progressive : (Config.Video.DeinterlaceBottomFirst ? VideoFrameFormat.InterlacedBottomFieldFirst : VideoFrameFormat.InterlacedTopFieldFirst));\n }\n\n // Reset FLVP filters to defaults (can be different from D3D11VP filters scaling)\n if (videoProcessor == VideoProcessors.Flyleaf)\n {\n Config.Video.Filters[VideoFilters.Brightness].Value = Config.Video.Filters[VideoFilters.Brightness].Minimum + ((Config.Video.Filters[VideoFilters.Brightness].Maximum - Config.Video.Filters[VideoFilters.Brightness].Minimum) / 2);\n Config.Video.Filters[VideoFilters.Contrast].Value = Config.Video.Filters[VideoFilters.Contrast].Minimum + ((Config.Video.Filters[VideoFilters.Contrast].Maximum - Config.Video.Filters[VideoFilters.Contrast].Minimum) / 2);\n }\n }\n\n internal void UpdateBackgroundColor()\n {\n D3D11VPBackgroundColor.Rgba.R = Scale(Config.Video.BackgroundColor.R, 0, 255, 0, 100) / 100.0f;\n D3D11VPBackgroundColor.Rgba.G = Scale(Config.Video.BackgroundColor.G, 0, 255, 0, 100) / 100.0f;\n D3D11VPBackgroundColor.Rgba.B = Scale(Config.Video.BackgroundColor.B, 0, 255, 0, 100) / 100.0f;\n\n vc?.VideoProcessorSetOutputBackgroundColor(vp, false, D3D11VPBackgroundColor);\n\n Present();\n }\n internal void UpdateDeinterlace()\n {\n lock (lockDevice)\n {\n if (Disposed)\n return;\n\n vc?.VideoProcessorSetStreamFrameFormat(vp, 0, !Config.Video.Deinterlace ? VideoFrameFormat.Progressive : (Config.Video.DeinterlaceBottomFirst ? VideoFrameFormat.InterlacedBottomFieldFirst : VideoFrameFormat.InterlacedTopFieldFirst));\n\n if (Config.Video.VideoProcessor != VideoProcessors.Auto)\n return;\n\n if (parent != null)\n return;\n\n ConfigPlanes();\n Present();\n }\n }\n internal void UpdateFilterValue(VideoFilter filter)\n {\n // D3D11VP\n if (Filters.ContainsKey(filter.Filter) && vc != null)\n {\n int scaledValue = (int) Scale(filter.Value, filter.Minimum, filter.Maximum, Filters[filter.Filter].Minimum, Filters[filter.Filter].Maximum);\n vc.VideoProcessorSetStreamFilter(vp, 0, ConvertFromVideoProcessorFilterCaps((VideoProcessorFilterCaps)filter.Filter), true, scaledValue);\n }\n\n if (parent != null)\n return;\n\n // FLVP\n switch (filter.Filter)\n {\n case VideoFilters.Brightness:\n int scaledValue = (int) Scale(filter.Value, filter.Minimum, filter.Maximum, 0, 100);\n psBufferData.brightness = scaledValue / 100.0f;\n context.UpdateSubresource(psBufferData, psBuffer);\n\n break;\n\n case VideoFilters.Contrast:\n scaledValue = (int) Scale(filter.Value, filter.Minimum, filter.Maximum, 0, 100);\n psBufferData.contrast = scaledValue / 100.0f;\n context.UpdateSubresource(psBufferData, psBuffer);\n\n break;\n\n default:\n break;\n }\n\n Present();\n }\n internal void UpdateHDRtoSDR(bool updateResource = true)\n {\n if(parent != null)\n return;\n\n float lum1 = 400;\n\n if (hdrPlusData != null)\n {\n lum1 = (float) (av_q2d(hdrPlusData->@params[0].average_maxrgb) * 100000.0);\n\n // this is not accurate more research required\n if (lum1 < 100)\n lum1 *= 10;\n lum1 = Math.Max(lum1, 400);\n }\n else if (Config.Video.HDRtoSDRMethod != HDRtoSDRMethod.Reinhard)\n {\n float lum2 = lum1;\n float lum3 = lum1;\n\n double lum = displayData.has_luminance != 0 ? av_q2d(displayData.max_luminance) : 400;\n\n if (lightData.MaxCLL > 0)\n {\n if (lightData.MaxCLL >= lum)\n {\n lum1 = (float)lum;\n lum2 = lightData.MaxCLL;\n }\n else\n {\n lum1 = lightData.MaxCLL;\n lum2 = (float)lum;\n }\n lum3 = lightData.MaxFALL;\n lum1 = (lum1 * 0.5f) + (lum2 * 0.2f) + (lum3 * 0.3f);\n }\n else\n {\n lum1 = (float)lum;\n }\n }\n else\n {\n if (lightData.MaxCLL > 0)\n lum1 = lightData.MaxCLL;\n else if (displayData.has_luminance != 0)\n lum1 = (float)av_q2d(displayData.max_luminance);\n }\n\n psBufferData.hdrmethod = Config.Video.HDRtoSDRMethod;\n\n if (psBufferData.hdrmethod == HDRtoSDRMethod.Hable)\n {\n psBufferData.g_luminance = lum1 > 1 ? lum1 : 400.0f;\n psBufferData.g_toneP1 = 10000.0f / psBufferData.g_luminance * (2.0f / Config.Video.HDRtoSDRTone);\n psBufferData.g_toneP2 = psBufferData.g_luminance / (100.0f * Config.Video.HDRtoSDRTone);\n }\n else if (psBufferData.hdrmethod == HDRtoSDRMethod.Reinhard)\n {\n psBufferData.g_toneP1 = lum1 > 0 ? (float)(Math.Log10(100) / Math.Log10(lum1)) : 0.72f;\n if (psBufferData.g_toneP1 < 0.1f || psBufferData.g_toneP1 > 5.0f)\n psBufferData.g_toneP1 = 0.72f;\n\n psBufferData.g_toneP1 *= Config.Video.HDRtoSDRTone;\n }\n else if (psBufferData.hdrmethod == HDRtoSDRMethod.Aces)\n {\n psBufferData.g_luminance = lum1 > 1 ? lum1 : 400.0f;\n psBufferData.g_toneP1 = Config.Video.HDRtoSDRTone;\n }\n\n if (updateResource)\n {\n context.UpdateSubresource(psBufferData, psBuffer);\n if (!VideoDecoder.IsRunning)\n Present();\n }\n }\n void UpdateRotation(uint angle, bool refresh = true)\n {\n _RotationAngle = angle;\n\n uint newRotation = _RotationAngle;\n\n if (VideoStream != null)\n newRotation += (uint)VideoStream.Rotation;\n\n if (rotationLinesize)\n newRotation += 180;\n\n newRotation %= 360;\n\n if (Disposed || (actualRotation == newRotation && actualHFlip == _HFlip && actualVFlip == _VFlip))\n return;\n\n bool hvFlipChanged = (actualHFlip || actualVFlip) != (_HFlip || _VFlip);\n\n actualRotation = newRotation;\n actualHFlip = _HFlip;\n actualVFlip = _VFlip;\n\n if (actualRotation < 45 || actualRotation == 360)\n _d3d11vpRotation = VideoProcessorRotation.Identity;\n else if (actualRotation < 135)\n _d3d11vpRotation = VideoProcessorRotation.Rotation90;\n else if (actualRotation < 225)\n _d3d11vpRotation = VideoProcessorRotation.Rotation180;\n else if (actualRotation < 360)\n _d3d11vpRotation = VideoProcessorRotation.Rotation270;\n\n vsBufferData.mat = Matrix4x4.CreateFromYawPitchRoll(0.0f, 0.0f, (float) (Math.PI / 180 * actualRotation));\n\n if (_HFlip || _VFlip)\n {\n vsBufferData.mat *= Matrix4x4.CreateScale(_HFlip ? -1 : 1, _VFlip ? -1 : 1, 1);\n if (hvFlipChanged)\n {\n // Renders both sides required for H-V Flip - TBR: consider for performance changing the vertex buffer / input layout instead?\n rasterizerState?.Dispose();\n rasterizerState = Device.CreateRasterizerState(new(CullMode.None, FillMode.Solid));\n context.RSSetState(rasterizerState);\n }\n }\n else if (hvFlipChanged)\n {\n // Removes back rendering for better performance\n rasterizerState?.Dispose();\n rasterizerState = Device.CreateRasterizerState(new(CullMode.Back, FillMode.Solid));\n context.RSSetState(rasterizerState);\n }\n\n if (parent == null)\n context.UpdateSubresource(vsBufferData, vsBuffer);\n\n if (child != null)\n {\n child.actualRotation = actualRotation;\n child._d3d11vpRotation = _d3d11vpRotation;\n child._RotationAngle = _RotationAngle;\n child.rotationLinesize = rotationLinesize;\n child.SetViewport();\n }\n\n vc?.VideoProcessorSetStreamRotation(vp, 0, true, _d3d11vpRotation);\n\n if (refresh)\n SetViewport();\n }\n internal void UpdateVideoProcessor()\n {\n if(parent != null)\n return;\n\n if (Config.Video.VideoProcessor == videoProcessor || (Config.Video.VideoProcessor == VideoProcessors.D3D11 && D3D11VPFailed))\n return;\n\n ConfigPlanes();\n Present();\n }\n}\n\npublic class VideoFilter : NotifyPropertyChanged\n{\n internal Renderer renderer;\n\n [JsonIgnore]\n public bool Available { get => _Available; set => SetUI(ref _Available, value); }\n bool _Available;\n\n public VideoFilters Filter { get => _Filter; set => SetUI(ref _Filter, value); }\n VideoFilters _Filter = VideoFilters.Brightness;\n\n public int Minimum { get => _Minimum; set => SetUI(ref _Minimum, value); }\n int _Minimum = 0;\n\n public int Maximum { get => _Maximum; set => SetUI(ref _Maximum, value); }\n int _Maximum = 100;\n\n public float Step { get => _Step; set => SetUI(ref _Step, value); }\n float _Step = 1;\n\n public int DefaultValue\n {\n get;\n set\n {\n if (SetUI(ref field, value))\n {\n SetDefaultValue.OnCanExecuteChanged();\n }\n }\n } = 50;\n\n public int Value\n {\n get;\n set\n {\n int v = value;\n v = Math.Min(v, Maximum);\n v = Math.Max(v, Minimum);\n\n if (Set(ref field, v))\n {\n renderer?.UpdateFilterValue(this);\n SetDefaultValue.OnCanExecuteChanged();\n }\n }\n } = 50;\n\n public RelayCommand SetDefaultValue => field ??= new(_ =>\n {\n Value = DefaultValue;\n }, _ => Value != DefaultValue);\n\n //internal void SetValue(int value) => SetUI(ref _Value, value, true, nameof(Value));\n\n public VideoFilter() { }\n public VideoFilter(VideoFilters filter, Player player = null)\n => Filter = filter;\n}\n\npublic class VideoProcessorCapsCache\n{\n public bool Failed = true;\n public int TypeIndex = -1;\n public bool HLG;\n public bool HDR10Limited;\n public VideoProcessorCaps VideoProcessorCaps;\n public VideoProcessorRateConversionCaps VideoProcessorRateConversionCaps;\n\n public Dictionary Filters { get; set; } = new();\n}\n"], ["/LLPlayer/FlyleafLib/MediaPlayer/Player.Screamers.cs", "using System.Diagnostics;\nusing System.Threading;\n\nusing FlyleafLib.MediaFramework.MediaDecoder;\nusing FlyleafLib.MediaFramework.MediaFrame;\nusing FlyleafLib.MediaFramework.MediaStream;\nusing static FlyleafLib.Utils;\nusing static FlyleafLib.Logger;\n\nnamespace FlyleafLib.MediaPlayer;\n\nunsafe partial class Player\n{\n /// \n /// Fires on Data frame when it's supposed to be shown according to the stream\n /// Warning: Uses Invoke and it comes from playback thread so you can't pause/stop etc. You need to use another thread if you have to.\n /// \n public event EventHandler OnDataFrame;\n\n /// \n /// Fires on buffering started\n /// Warning: Uses Invoke and it comes from playback thread so you can't pause/stop etc. You need to use another thread if you have to.\n /// \n public event EventHandler BufferingStarted;\n protected virtual void OnBufferingStarted()\n {\n if (onBufferingStarted != onBufferingCompleted) return;\n BufferingStarted?.Invoke(this, new EventArgs());\n onBufferingStarted++;\n\n if (CanDebug) Log.Debug($\"OnBufferingStarted\");\n }\n\n /// \n /// Fires on buffering completed (will fire also on failed buffering completed)\n /// (BufferDration > Config.Player.MinBufferDuration)\n /// Warning: Uses Invoke and it comes from playback thread so you can't pause/stop etc. You need to use another thread if you have to.\n /// \n public event EventHandler BufferingCompleted;\n protected virtual void OnBufferingCompleted(string error = null)\n {\n if (onBufferingStarted - 1 != onBufferingCompleted) return;\n\n if (error != null && LastError == null)\n {\n lastError = error;\n UI(() => LastError = LastError);\n }\n\n BufferingCompleted?.Invoke(this, new BufferingCompletedArgs(error));\n onBufferingCompleted++;\n if (CanDebug) Log.Debug($\"OnBufferingCompleted{(error != null ? $\" (Error: {error})\" : \"\")}\");\n }\n\n long onBufferingStarted;\n long onBufferingCompleted;\n\n int vDistanceMs;\n int aDistanceMs;\n int[] sDistanceMss;\n int dDistanceMs;\n int sleepMs;\n\n long elapsedTicks;\n long elapsedSec;\n long startTicks;\n long showOneFrameTicks;\n\n int allowedLateAudioDrops;\n long lastSpeedChangeTicks;\n long curLatency;\n internal long curAudioDeviceDelay;\n\n public int subNum => Config.Subtitles.Max;\n\n Stopwatch sw = new();\n\n private void ShowOneFrame()\n {\n for (int i = 0; i < subNum; i++)\n {\n sFrames[i] = null;\n }\n if (VideoDecoder.Frames.IsEmpty || !VideoDecoder.Frames.TryDequeue(out vFrame))\n return;\n\n renderer.Present(vFrame);\n\n if (!seeks.IsEmpty)\n return;\n\n if (!VideoDemuxer.IsHLSLive)\n curTime = vFrame.timestamp;\n\n UI(() => UpdateCurTime());\n\n for (int i = 0; i < subNum; i++)\n {\n // Prevents blinking after seek\n if (sFramesPrev[i] != null)\n {\n var cur = SubtitlesManager[i].GetCurrent();\n if (cur != null)\n {\n if (!string.IsNullOrEmpty(cur.DisplayText) || (cur.IsBitmap && cur.Bitmap != null))\n {\n continue;\n }\n }\n }\n\n // Clear last subtitles text if video timestamp is not within subs timestamp + duration (to prevent clearing current subs on pause/play)\n if (sFramesPrev[i] == null || sFramesPrev[i].timestamp > vFrame.timestamp || (sFramesPrev[i].timestamp + (sFramesPrev[i].duration * (long)10000)) < vFrame.timestamp)\n {\n sFramesPrev[i] = null;\n SubtitleClear(i);\n }\n }\n\n // Required for buffering on paused\n if (decoder.RequiresResync && !IsPlaying && seeks.IsEmpty)\n decoder.Resync(vFrame.timestamp);\n\n vFrame = null;\n }\n\n // !!! NEEDS RECODING (We show one frame, we dispose it, we get another one and we show it also after buffering which can be in 'no time' which can leave us without any more decoded frames so we rebuffer)\n private bool MediaBuffer()\n {\n if (CanTrace) Log.Trace(\"Buffering\");\n\n while (isVideoSwitch && IsPlaying) Thread.Sleep(10);\n\n Audio.ClearBuffer();\n\n VideoDemuxer.Start();\n VideoDecoder.Start();\n\n if (Audio.isOpened && Config.Audio.Enabled)\n {\n curAudioDeviceDelay = Audio.GetDeviceDelay();\n\n if (AudioDecoder.OnVideoDemuxer)\n AudioDecoder.Start();\n else if (!decoder.RequiresResync)\n {\n AudioDemuxer.Start();\n AudioDecoder.Start();\n }\n }\n\n if (Config.Subtitles.Enabled)\n {\n for (int i = 0; i < subNum; i++)\n {\n if (!Subtitles[i].IsOpened)\n {\n continue;\n }\n\n lock (lockSubtitles)\n {\n if (SubtitlesDecoders[i].OnVideoDemuxer)\n {\n SubtitlesDecoders[i].Start();\n }\n //else if (!decoder.RequiresResync)\n //{\n // SubtitlesDemuxers[i].Start();\n // SubtitlesDecoders[i].Start();\n //}\n }\n }\n }\n\n if (Data.isOpened && Config.Data.Enabled)\n {\n if (DataDecoder.OnVideoDemuxer)\n DataDecoder.Start();\n else if (!decoder.RequiresResync)\n {\n DataDemuxer.Start();\n DataDecoder.Start();\n }\n }\n\n VideoDecoder.DisposeFrame(vFrame);\n vFrame = null;\n aFrame = null;\n for (int i = 0; i < subNum; i++)\n {\n sFrames[i] = null;\n }\n dFrame = null;\n\n bool gotAudio = !Audio.IsOpened || Config.Player.MaxLatency != 0;\n bool gotVideo = false;\n bool shouldStop = false;\n bool showOneFrame = true;\n int audioRetries = 4;\n int loops = 0;\n\n if (Config.Player.MaxLatency != 0)\n {\n lastSpeedChangeTicks = DateTime.UtcNow.Ticks;\n showOneFrame = false;\n Speed = 1;\n }\n\n do\n {\n loops++;\n\n if (showOneFrame && !VideoDecoder.Frames.IsEmpty)\n {\n ShowOneFrame();\n showOneFrameTicks = DateTime.UtcNow.Ticks;\n showOneFrame = false;\n }\n\n // We allo few ms to show a frame before cancelling\n if ((!showOneFrame || loops > 8) && !seeks.IsEmpty)\n return false;\n\n if (!gotVideo && !showOneFrame && !VideoDecoder.Frames.IsEmpty)\n {\n VideoDecoder.Frames.TryDequeue(out vFrame);\n if (vFrame != null) gotVideo = true;\n }\n\n if (!gotAudio && aFrame == null && !AudioDecoder.Frames.IsEmpty)\n AudioDecoder.Frames.TryDequeue(out aFrame);\n\n if (gotVideo)\n {\n if (decoder.RequiresResync)\n decoder.Resync(vFrame.timestamp);\n\n if (!gotAudio && aFrame != null)\n {\n for (int i=0; i vFrame.timestamp\n || vFrame.timestamp > Duration)\n {\n gotAudio = true;\n break;\n }\n\n if (CanTrace) Log.Trace($\"Drop aFrame {TicksToTime(aFrame.timestamp)}\");\n AudioDecoder.Frames.TryDequeue(out aFrame);\n }\n\n // Avoid infinite loop in case of all audio timestamps wrong\n if (!gotAudio)\n {\n audioRetries--;\n\n if (audioRetries < 1)\n {\n gotAudio = true;\n aFrame = null;\n Log.Warn($\"Audio Exhausted 1\");\n }\n }\n }\n }\n\n if (!IsPlaying || decoderHasEnded)\n shouldStop = true;\n else\n {\n if (!VideoDecoder.IsRunning && !isVideoSwitch)\n {\n Log.Warn(\"Video Exhausted\");\n shouldStop= true;\n }\n\n if (gotVideo && !gotAudio && audioRetries > 0 && (!AudioDecoder.IsRunning || AudioDecoder.Demuxer.Status == MediaFramework.Status.QueueFull))\n {\n if (CanWarn) Log.Warn($\"Audio Exhausted 2 | {audioRetries}\");\n\n audioRetries--;\n\n if (audioRetries < 1)\n gotAudio = true;\n }\n }\n\n Thread.Sleep(10);\n\n } while (!shouldStop && (!gotVideo || !gotAudio));\n\n if (shouldStop && !(decoderHasEnded && IsPlaying && vFrame != null))\n {\n Log.Info(\"Stopped\");\n return false;\n }\n\n if (vFrame == null)\n {\n Log.Error(\"No Frames!\");\n return false;\n }\n\n // Negative Buffer Duration during codec change (we don't dipose the cached frames or we receive them later) *skip waiting for now\n var bufDuration = GetBufferedDuration();\n if (bufDuration >= 0)\n while(seeks.IsEmpty && bufDuration < Config.Player.MinBufferDuration && IsPlaying && VideoDemuxer.IsRunning && VideoDemuxer.Status != MediaFramework.Status.QueueFull)\n {\n Thread.Sleep(20);\n bufDuration = GetBufferedDuration();\n if (bufDuration < 0)\n break;\n }\n\n if (!seeks.IsEmpty)\n return false;\n\n if (CanInfo) Log.Info($\"Started [V: {TicksToTime(vFrame.timestamp)}]\" + (aFrame == null ? \"\" : $\" [A: {TicksToTime(aFrame.timestamp)}]\"));\n\n decoder.OpenedPlugin.OnBufferingCompleted();\n\n return true;\n }\n private void Screamer()\n {\n long audioBufferedDuration = 0; // We force audio resync with = 0\n\n while (Status == Status.Playing)\n {\n if (seeks.TryPop(out var seekData))\n {\n seeks.Clear();\n requiresBuffering = true;\n\n for (int i = 0; i < subNum; i++)\n {\n // Display subtitles from cache when seeking while playing\n bool display = false;\n var cur = SubtitlesManager[i].GetCurrent();\n if (cur != null)\n {\n if (!string.IsNullOrEmpty(cur.DisplayText))\n {\n SubtitleDisplay(cur.DisplayText, i, cur.UseTranslated);\n display = true;\n }\n else if (cur.IsBitmap && cur.Bitmap != null)\n {\n SubtitleDisplay(cur.Bitmap, i);\n display = true;\n }\n\n if (display)\n {\n sFramesPrev[i] = new SubtitlesFrame\n {\n timestamp = cur.StartTime.Ticks + Config.Subtitles[i].Delay,\n duration = (uint)cur.Duration.TotalMilliseconds,\n isTranslated = cur.UseTranslated\n };\n }\n }\n\n // clear subtitles\n // but do not clear when cache hit\n if (!display && sFramesPrev[i] != null)\n {\n sFramesPrev[i] = null;\n SubtitleClear(i);\n }\n }\n\n decoder.PauseDecoders(); // TBR: Required to avoid gettings packets between Seek and ShowFrame which causes resync issues\n\n if (decoder.Seek(seekData.accurate ? Math.Max(0, seekData.ms - (int)new TimeSpan(Config.Player.SeekAccurateFixMargin).TotalMilliseconds) : seekData.ms, seekData.forward, !seekData.accurate) < 0) // Consider using GetVideoFrame with no timestamp (any) to ensure keyframe packet for faster seek in HEVC\n Log.Warn(\"Seek failed\");\n else if (seekData.accurate)\n decoder.GetVideoFrame(seekData.ms * (long)10000);\n }\n\n if (requiresBuffering)\n {\n if (VideoDemuxer.Interrupter.Timedout)\n break;\n\n OnBufferingStarted();\n MediaBuffer();\n requiresBuffering = false;\n if (!seeks.IsEmpty)\n continue;\n\n if (vFrame == null)\n {\n if (decoderHasEnded)\n OnBufferingCompleted();\n\n Log.Warn(\"[MediaBuffer] No video frame\");\n break;\n }\n\n // Temp fix to ensure we had enough time to decode one more frame\n int retries = 5;\n while (IsPlaying && VideoDecoder.Frames.Count == 0 && retries-- > 0)\n Thread.Sleep(10);\n\n // Give enough time for the 1st frame to be presented\n while (IsPlaying && DateTime.UtcNow.Ticks - showOneFrameTicks < VideoDecoder.VideoStream.FrameDuration)\n Thread.Sleep(4);\n\n OnBufferingCompleted();\n\n audioBufferedDuration = 0;\n allowedLateAudioDrops = 7;\n elapsedSec = 0;\n startTicks = vFrame.timestamp;\n sw.Restart();\n }\n\n if (Status != Status.Playing)\n break;\n\n if (vFrame == null)\n {\n if (VideoDecoder.Status == MediaFramework.Status.Ended)\n {\n if (!MainDemuxer.IsHLSLive)\n {\n if (Math.Abs(MainDemuxer.Duration - curTime) < 2 * VideoDemuxer.VideoStream.FrameDuration)\n curTime = MainDemuxer.Duration;\n else\n curTime += VideoDemuxer.VideoStream.FrameDuration;\n\n UI(() => Set(ref _CurTime, curTime, true, nameof(CurTime)));\n }\n\n break;\n }\n\n Log.Warn(\"No video frames\");\n requiresBuffering = true;\n continue;\n }\n\n if (aFrame == null && !isAudioSwitch)\n AudioDecoder.Frames.TryDequeue(out aFrame);\n\n for (int i = 0; i < subNum; i++)\n {\n if (sFrames[i] == null && !isSubsSwitches[i])\n SubtitlesDecoders[i].Frames.TryPeek(out sFrames[i]);\n }\n\n if (dFrame == null && !isDataSwitch)\n DataDecoder.Frames.TryPeek(out dFrame);\n\n elapsedTicks = (long) (sw.ElapsedTicks * SWFREQ_TO_TICKS); // Do we really need ticks precision?\n\n vDistanceMs =\n (int) ((((vFrame.timestamp - startTicks) / speed) - elapsedTicks) / 10000);\n\n if (aFrame != null)\n {\n curAudioDeviceDelay = Audio.GetDeviceDelay();\n audioBufferedDuration = Audio.GetBufferedDuration();\n aDistanceMs = (int) ((((aFrame.timestamp - startTicks) / speed) - (elapsedTicks - curAudioDeviceDelay)) / 10000);\n\n // Try to keep the audio buffer full enough to avoid audio crackling (up to 50ms)\n while (audioBufferedDuration > 0 && audioBufferedDuration < 50 * 10000 && aDistanceMs > -5 && aDistanceMs < 50)\n {\n Audio.AddSamples(aFrame);\n\n if (isAudioSwitch)\n {\n audioBufferedDuration = 0;\n aDistanceMs = int.MaxValue;\n aFrame = null;\n }\n else\n {\n audioBufferedDuration = Audio.GetBufferedDuration();\n AudioDecoder.Frames.TryDequeue(out aFrame);\n if (aFrame != null)\n aDistanceMs = (int) ((((aFrame.timestamp - startTicks) / speed) - (elapsedTicks - curAudioDeviceDelay)) / 10000);\n else\n aDistanceMs = int.MaxValue;\n }\n }\n }\n else\n aDistanceMs = int.MaxValue;\n\n for (int i = 0; i < subNum; i++)\n {\n sDistanceMss[i] = sFrames[i] != null\n ? (int)((((sFrames[i].timestamp - startTicks) / speed) - elapsedTicks) / 10000)\n : int.MaxValue;\n }\n\n dDistanceMs = dFrame != null\n ? (int)((((dFrame.timestamp - startTicks) / speed) - elapsedTicks) / 10000)\n : int.MaxValue;\n\n sleepMs = Math.Min(vDistanceMs, aDistanceMs) - 1;\n if (sleepMs < 0 || sleepMs == int.MaxValue)\n sleepMs = 0;\n\n if (sleepMs > 2)\n {\n if (vDistanceMs > 2000)\n {\n Log.Warn($\"vDistanceMs = {vDistanceMs} (restarting)\");\n requiresBuffering = true;\n continue;\n }\n\n if (Engine.Config.UICurTimePerSecond && (\n (!MainDemuxer.IsHLSLive && curTime / 10000000 != _CurTime / 10000000) ||\n (MainDemuxer.IsHLSLive && Math.Abs(elapsedTicks - elapsedSec) > 10000000)))\n {\n elapsedSec = elapsedTicks;\n UI(() => UpdateCurTime());\n }\n\n Thread.Sleep(sleepMs);\n }\n\n if (aFrame != null) // Should use different thread for better accurancy (renderer might delay it on high fps) | also on high offset we will have silence between samples\n {\n if (Math.Abs(aDistanceMs - sleepMs) <= 5)\n {\n Audio.AddSamples(aFrame);\n\n // Audio Desync - Large Buffer | ASampleBytes (S16 * 2 Channels = 4) * TimeBase * 2 -frames duration-\n if (Audio.GetBufferedDuration() > Math.Max(50 * 10000, (aFrame.dataLen / 4) * Audio.Timebase * 2))\n {\n if (CanDebug)\n Log.Debug($\"Audio desynced by {(int)(audioBufferedDuration / 10000)}ms, clearing buffers\");\n\n Audio.ClearBuffer();\n audioBufferedDuration = 0;\n }\n\n aFrame = null;\n }\n else if (aDistanceMs > 4000) // Drops few audio frames in case of wrong timestamps (Note this should be lower, until swr has min/max samples for about 20-70ms)\n {\n if (allowedLateAudioDrops > 0)\n {\n Audio.framesDropped++;\n allowedLateAudioDrops--;\n if (CanDebug) Log.Debug($\"aDistanceMs 3 = {aDistanceMs}\");\n aFrame = null;\n audioBufferedDuration = 0;\n }\n }\n else if (aDistanceMs < -5) // Will be transfered back to decoder to drop invalid timestamps\n {\n if (CanTrace) Log.Trace($\"aDistanceMs = {aDistanceMs} | AudioFrames: {AudioDecoder.Frames.Count} AudioPackets: {AudioDecoder.Demuxer.AudioPackets.Count}\");\n\n if (GetBufferedDuration() < Config.Player.MinBufferDuration / 2)\n {\n if (CanInfo)\n Log.Warn($\"Not enough buffer (restarting)\");\n\n requiresBuffering = true;\n continue;\n }\n\n audioBufferedDuration = 0;\n\n if (aDistanceMs < -600)\n {\n if (CanTrace) Log.Trace($\"All audio frames disposed\");\n Audio.framesDropped += AudioDecoder.Frames.Count;\n AudioDecoder.DisposeFrames();\n aFrame = null;\n }\n else\n {\n int maxdrop = Math.Max(Math.Min(vDistanceMs - sleepMs - 1, 20), 3);\n for (int i=0; i 0)\n break;\n\n aFrame = null;\n }\n }\n }\n }\n\n if (Math.Abs(vDistanceMs - sleepMs) <= 2)\n {\n if (CanTrace) Log.Trace($\"[V] Presenting {TicksToTime(vFrame.timestamp)}\");\n\n if (decoder.VideoDecoder.Renderer.Present(vFrame, false))\n Video.framesDisplayed++;\n else\n Video.framesDropped++;\n\n lock (seeks)\n if (seeks.IsEmpty)\n {\n curTime = !MainDemuxer.IsHLSLive ? vFrame.timestamp : VideoDemuxer.CurTime;\n\n if (Config.Player.UICurTimePerFrame)\n UI(() => UpdateCurTime());\n }\n\n VideoDecoder.Frames.TryDequeue(out vFrame);\n if (vFrame != null && Config.Player.MaxLatency != 0)\n CheckLatency();\n }\n else if (vDistanceMs < -2)\n {\n if (vDistanceMs < -10 || GetBufferedDuration() < Config.Player.MinBufferDuration / 2)\n {\n if (CanDebug)\n Log.Debug($\"vDistanceMs = {vDistanceMs} (restarting)\");\n\n requiresBuffering = true;\n continue;\n }\n\n if (CanDebug)\n Log.Debug($\"vDistanceMs = {vDistanceMs}\");\n\n Video.framesDropped++;\n VideoDecoder.DisposeFrame(vFrame);\n VideoDecoder.Frames.TryDequeue(out vFrame);\n }\n\n // Set the current time to SubtitleManager in a loop\n if (Config.Subtitles.Enabled)\n {\n for (int i = 0; i < subNum; i++)\n {\n if (Subtitles[i].Enabled)\n {\n SubtitlesManager[i].SetCurrentTime(new TimeSpan(curTime));\n }\n }\n }\n // Internal subtitles (Text or Bitmap or OCR)\n for (int i = 0; i < subNum; i++)\n {\n if (sFramesPrev[i] != null && ((sFramesPrev[i].timestamp - startTicks + (sFramesPrev[i].duration * (long)10000)) / speed) - (long) (sw.ElapsedTicks * SWFREQ_TO_TICKS) < 0)\n {\n SubtitleClear(i);\n\n sFramesPrev[i] = null;\n }\n\n if (sFrames[i] != null)\n {\n if (Math.Abs(sDistanceMss[i] - sleepMs) < 30 || (sDistanceMss[i] < -30 && sFrames[i].duration + sDistanceMss[i] > 0))\n {\n if (sFrames[i].isBitmap && sFrames[i].sub.num_rects > 0)\n {\n if (SubtitlesSelectedHelper.GetMethod(i) == SelectSubMethod.OCR)\n {\n // Prevent the problem of OCR subtitles not being used in priority by setting\n // the timestamp of the subtitles as they are displayed a little earlier\n SubtitlesManager[i].SetCurrentTime(new TimeSpan(sFrames[i].timestamp));\n }\n\n var cur = SubtitlesManager[i].GetCurrent();\n\n if (cur != null && !string.IsNullOrEmpty(cur.Text))\n {\n // Use OCR text subtitles if available\n SubtitleDisplay(cur.DisplayText, i, cur.UseTranslated);\n }\n else\n {\n // renderer.CreateOverlayTexture(sFrame, SubtitlesDecoder.CodecCtx->width, SubtitlesDecoder.CodecCtx->height);\n SubtitleDisplay(sFrames[i].bitmap, i);\n }\n\n SubtitlesDecoder.DisposeFrame(sFrames[i]); // only rects\n }\n else if (sFrames[i].isBitmap && sFrames[i].sub.num_rects == 0)\n {\n // For Blu-ray subtitles (PGS), clear the previous subtitle\n SubtitleClear(i);\n sFramesPrev[i] = sFrames[i] = null;\n }\n else\n {\n // internal text sub (does not support translate)\n SubtitleDisplay(sFrames[i].text, i, false);\n }\n sFramesPrev[i] = sFrames[i];\n sFrames[i] = null;\n SubtitlesDecoders[i].Frames.TryDequeue(out _);\n }\n else if (sDistanceMss[i] < -30)\n {\n if (CanDebug)\n Log.Debug($\"sDistanceMss[i] = {sDistanceMss[i]}\");\n\n //SubtitleClear(i);\n\n // TODO: L: Here sFrames can be null, occurs when switching subtitles?\n SubtitlesDecoder.DisposeFrame(sFrames[i]);\n sFrames[i] = null;\n SubtitlesDecoders[i].Frames.TryDequeue(out _);\n }\n }\n }\n\n // External or ASR subtitles\n for (int i = 0; i < subNum; i++)\n {\n if (!Config.Subtitles.Enabled || !Subtitles[i].Enabled)\n {\n continue;\n }\n\n SubtitleData cur = SubtitlesManager[i].GetCurrent();\n\n if (cur == null)\n {\n continue;\n }\n\n if (sFramesPrev[i] == null ||\n sFramesPrev[i].timestamp != cur.StartTime.Ticks + Config.Subtitles[i].Delay)\n {\n bool display = false;\n if (!string.IsNullOrEmpty(cur.DisplayText))\n {\n SubtitleDisplay(cur.DisplayText, i, cur.UseTranslated);\n display = true;\n }\n else if (cur.IsBitmap && cur.Bitmap != null)\n {\n SubtitleDisplay(cur.Bitmap, i);\n display = true;\n }\n\n if (display)\n {\n sFramesPrev[i] = new SubtitlesFrame\n {\n timestamp = cur.StartTime.Ticks + Config.Subtitles[i].Delay,\n duration = (uint)cur.Duration.TotalMilliseconds,\n isTranslated = cur.UseTranslated\n };\n }\n }\n else\n {\n // Apply translation to current sub\n if (Config.Subtitles[i].EnabledTranslated) {\n\n // If the subtitle currently playing is not translated, change to the translated for display\n if (sFramesPrev[i] != null &&\n sFramesPrev[i].timestamp == cur.StartTime.Ticks + Config.Subtitles[i].Delay &&\n sFramesPrev[i].isTranslated != cur.UseTranslated)\n {\n SubtitleDisplay(cur.DisplayText, i, cur.UseTranslated);\n sFramesPrev[i].isTranslated = cur.UseTranslated;\n }\n }\n }\n }\n\n if (dFrame != null)\n {\n if (Math.Abs(dDistanceMs - sleepMs) < 30 || (dDistanceMs < -30))\n {\n OnDataFrame?.Invoke(this, dFrame);\n\n dFrame = null;\n DataDecoder.Frames.TryDequeue(out var devnull);\n }\n else if (dDistanceMs < -30)\n {\n if (CanDebug)\n Log.Debug($\"dDistanceMs = {dDistanceMs}\");\n\n dFrame = null;\n DataDecoder.Frames.TryDequeue(out var devnull);\n }\n }\n }\n\n if (CanInfo) Log.Info($\"Finished -> {TicksToTime(CurTime)}\");\n }\n\n private void CheckLatency()\n {\n curLatency = GetBufferedDuration();\n\n if (CanDebug)\n Log.Debug($\"[Latency {curLatency/10000}ms] Frames: {VideoDecoder.Frames.Count} Packets: {VideoDemuxer.VideoPackets.Count} Speed: {speed}\");\n\n if (curLatency <= Config.Player.MinLatency) // We've reached the down limit (back to speed x1)\n {\n ChangeSpeedWithoutBuffering(1);\n return;\n }\n else if (curLatency < Config.Player.MaxLatency)\n return;\n\n var newSpeed = Math.Max(Math.Round((double)curLatency / Config.Player.MaxLatency, 1, MidpointRounding.ToPositiveInfinity), 1.1);\n\n if (newSpeed > 4) // TBR: dispose only as much as required to avoid rebuffering\n {\n decoder.Flush();\n requiresBuffering = true;\n Log.Debug($\"[Latency {curLatency/10000}ms] Clearing queue\");\n return;\n }\n\n ChangeSpeedWithoutBuffering(newSpeed);\n }\n private void ChangeSpeedWithoutBuffering(double newSpeed)\n {\n if (speed == newSpeed)\n return;\n\n long curTicks = DateTime.UtcNow.Ticks;\n\n if (newSpeed != 1 && curTicks - lastSpeedChangeTicks < Config.Player.LatencySpeedChangeInterval)\n return;\n\n lastSpeedChangeTicks = curTicks;\n\n if (CanDebug)\n Log.Debug($\"[Latency {curLatency/10000}ms] Speed changed x{speed} -> x{newSpeed}\");\n\n if (aFrame != null)\n AudioDecoder.FixSample(aFrame, speed, newSpeed);\n\n Speed = newSpeed;\n requiresBuffering\n = false;\n startTicks = curTime;\n elapsedSec = 0;\n sw.Restart();\n }\n private long GetBufferedDuration()\n {\n var decoder = VideoDecoder.Frames.IsEmpty ? 0 : VideoDecoder.Frames.ToArray()[^1].timestamp - vFrame.timestamp;\n var demuxer = VideoDemuxer.VideoPackets.IsEmpty || VideoDemuxer.VideoPackets.LastTimestamp == NoTs\n ? 0 :\n (VideoDemuxer.VideoPackets.LastTimestamp - VideoDemuxer.StartTime) - vFrame.timestamp;\n\n return Math.Max(decoder, demuxer);\n }\n\n private void AudioBuffer()\n {\n if (CanTrace) Log.Trace(\"Buffering\");\n\n while ((isVideoSwitch || isAudioSwitch) && IsPlaying)\n Thread.Sleep(10);\n\n if (!IsPlaying)\n return;\n\n aFrame = null;\n Audio.ClearBuffer();\n decoder.AudioStream.Demuxer.Start();\n AudioDecoder.Start();\n\n while(AudioDecoder.Frames.IsEmpty && IsPlaying && AudioDecoder.IsRunning)\n Thread.Sleep(10);\n\n AudioDecoder.Frames.TryPeek(out aFrame);\n\n if (aFrame == null)\n return;\n\n lock (seeks)\n if (seeks.IsEmpty)\n {\n curTime = !MainDemuxer.IsHLSLive ? aFrame.timestamp : MainDemuxer.CurTime;\n UI(() =>\n {\n Set(ref _CurTime, curTime, true, nameof(CurTime));\n UpdateBufferedDuration();\n });\n }\n\n while(seeks.IsEmpty && decoder.AudioStream.Demuxer.BufferedDuration < Config.Player.MinBufferDuration && AudioDecoder.Frames.Count < Config.Decoder.MaxAudioFrames / 2 && IsPlaying && decoder.AudioStream.Demuxer.IsRunning && decoder.AudioStream.Demuxer.Status != MediaFramework.Status.QueueFull)\n Thread.Sleep(20);\n }\n private void ScreamerAudioOnly()\n {\n long bufferedDuration = 0;\n\n while (IsPlaying)\n {\n if (seeks.TryPop(out var seekData))\n {\n seeks.Clear();\n requiresBuffering = true;\n\n if (AudioDecoder.OnVideoDemuxer)\n {\n if (decoder.Seek(seekData.ms, seekData.forward) < 0)\n Log.Warn(\"Seek failed 1\");\n }\n else\n {\n if (decoder.SeekAudio(seekData.ms, seekData.forward) < 0)\n Log.Warn(\"Seek failed 2\");\n }\n }\n\n if (requiresBuffering)\n {\n OnBufferingStarted();\n AudioBuffer();\n requiresBuffering = false;\n\n if (!seeks.IsEmpty)\n continue;\n\n if (!IsPlaying || AudioDecoder.Frames.IsEmpty)\n break;\n\n OnBufferingCompleted();\n }\n\n if (AudioDecoder.Frames.IsEmpty)\n {\n if (bufferedDuration == 0)\n {\n if (!IsPlaying || AudioDecoder.Status == MediaFramework.Status.Ended)\n break;\n\n Log.Warn(\"No audio frames\");\n requiresBuffering = true;\n }\n else\n {\n Thread.Sleep(50); // waiting for audio buffer to be played before end\n bufferedDuration = Audio.GetBufferedDuration();\n }\n\n continue;\n }\n\n // Support only ASR subtitle for audio\n foreach (int i in SubtitlesASR.SubIndexSet)\n {\n SubtitlesManager[i].SetCurrentTime(new TimeSpan(curTime));\n\n var cur = SubtitlesManager[i].GetCurrent();\n if (cur != null && !string.IsNullOrEmpty(cur.DisplayText))\n {\n SubtitleDisplay(cur.DisplayText, i, cur.UseTranslated);\n }\n else\n {\n SubtitleClear(i);\n }\n }\n\n bufferedDuration = Audio.GetBufferedDuration();\n\n if (bufferedDuration < 300 * 10000)\n {\n do\n {\n AudioDecoder.Frames.TryDequeue(out aFrame);\n if (aFrame == null || !IsPlaying)\n break;\n\n Audio.AddSamples(aFrame);\n bufferedDuration += (long) ((aFrame.dataLen / 4) * Audio.Timebase);\n curTime = !MainDemuxer.IsHLSLive ? aFrame.timestamp : MainDemuxer.CurTime;\n } while (bufferedDuration < 100 * 10000);\n\n lock (seeks)\n if (seeks.IsEmpty)\n {\n if (!Engine.Config.UICurTimePerSecond || curTime / 10000000 != _CurTime / 10000000)\n {\n UI(() =>\n {\n Set(ref _CurTime, curTime, true, nameof(CurTime));\n UpdateBufferedDuration();\n });\n }\n }\n\n Thread.Sleep(20);\n }\n else\n Thread.Sleep(50);\n }\n }\n\n private void ScreamerReverse()\n {\n while (Status == Status.Playing)\n {\n if (seeks.TryPop(out var seekData))\n {\n seeks.Clear();\n if (decoder.Seek(seekData.ms, seekData.forward) < 0)\n Log.Warn(\"Seek failed\");\n }\n\n if (vFrame == null)\n {\n if (VideoDecoder.Status == MediaFramework.Status.Ended)\n break;\n\n OnBufferingStarted();\n if (reversePlaybackResync)\n {\n decoder.Flush();\n VideoDemuxer.EnableReversePlayback(CurTime);\n reversePlaybackResync = false;\n }\n VideoDemuxer.Start();\n VideoDecoder.Start();\n\n while (VideoDecoder.Frames.IsEmpty && Status == Status.Playing && VideoDecoder.IsRunning) Thread.Sleep(15);\n OnBufferingCompleted();\n VideoDecoder.Frames.TryDequeue(out vFrame);\n if (vFrame == null) { Log.Warn(\"No video frame\"); break; }\n vFrame.timestamp = (long) (vFrame.timestamp / Speed);\n\n startTicks = vFrame.timestamp;\n sw.Restart();\n elapsedSec = 0;\n\n if (!MainDemuxer.IsHLSLive && seeks.IsEmpty)\n curTime = (long) (vFrame.timestamp * Speed);\n UI(() => UpdateCurTime());\n }\n\n elapsedTicks = startTicks - (long) (sw.ElapsedTicks * SWFREQ_TO_TICKS);\n vDistanceMs = (int) ((elapsedTicks - vFrame.timestamp) / 10000);\n sleepMs = vDistanceMs - 1;\n\n if (sleepMs < 0) sleepMs = 0;\n\n if (Math.Abs(vDistanceMs - sleepMs) > 5)\n {\n //Log($\"vDistanceMs |-> {vDistanceMs}\");\n VideoDecoder.DisposeFrame(vFrame);\n vFrame = null;\n Thread.Sleep(5);\n continue; // rebuffer\n }\n\n if (sleepMs > 2)\n {\n if (sleepMs > 1000)\n {\n //Log($\"sleepMs -> {sleepMs} , vDistanceMs |-> {vDistanceMs}\");\n VideoDecoder.DisposeFrame(vFrame);\n vFrame = null;\n Thread.Sleep(5);\n continue; // rebuffer\n }\n\n // Every seconds informs the application with CurTime / Bitrates (invokes UI thread to ensure the updates will actually happen)\n if (Engine.Config.UICurTimePerSecond && (\n (!MainDemuxer.IsHLSLive && curTime / 10000000 != _CurTime / 10000000) ||\n (MainDemuxer.IsHLSLive && Math.Abs(elapsedTicks - elapsedSec) > 10000000)))\n {\n elapsedSec = elapsedTicks;\n UI(() => UpdateCurTime());\n }\n\n Thread.Sleep(sleepMs);\n }\n\n decoder.VideoDecoder.Renderer.Present(vFrame, false);\n if (!MainDemuxer.IsHLSLive && seeks.IsEmpty)\n {\n curTime = (long) (vFrame.timestamp * Speed);\n\n if (Config.Player.UICurTimePerFrame)\n UI(() => UpdateCurTime());\n }\n\n VideoDecoder.Frames.TryDequeue(out vFrame);\n if (vFrame != null)\n vFrame.timestamp = (long) (vFrame.timestamp / Speed);\n }\n }\n}\n\npublic class BufferingCompletedArgs : EventArgs\n{\n public string Error { get; }\n public bool Success { get; }\n\n public BufferingCompletedArgs(string error)\n {\n Error = error;\n Success = Error == null;\n }\n}\n"], ["/LLPlayer/LLPlayer/App.xaml.cs", "using System.Diagnostics;\nusing System.Globalization;\nusing System.IO;\nusing System.Runtime.InteropServices;\nusing System.Windows;\nusing System.Windows.Threading;\nusing FlyleafLib;\nusing FlyleafLib.MediaPlayer;\nusing LLPlayer.Extensions;\nusing LLPlayer.Services;\nusing LLPlayer.Views;\n\nnamespace LLPlayer;\n\npublic partial class App : PrismApplication\n{\n public static string Name => \"LLPlayer\";\n public static string? CmdUrl { get; private set; } = null;\n public static string PlayerConfigPath { get; } = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, \"LLPlayer.PlayerConfig.json\");\n public static string EngineConfigPath { get; } = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, \"LLPlayer.Engine.json\");\n public static string AppConfigPath { get; } = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, \"LLPlayer.Config.json\");\n public static string CrashLogPath { get; } = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, \"crash.log\");\n\n private readonly LogHandler Log;\n\n public App()\n {\n Log = new LogHandler(\"[App] [MainApp ] \");\n }\n\n static App()\n {\n // Set thread culture to English and error messages to English\n Utils.SaveOriginalCulture();\n\n CultureInfo.DefaultThreadCurrentCulture = new CultureInfo(\"en-US\");\n CultureInfo.DefaultThreadCurrentUICulture = new CultureInfo(\"en-US\");\n }\n\n protected override void RegisterTypes(IContainerRegistry containerRegistry)\n {\n containerRegistry\n .Register(FlyleafLoader.CreateFlyleafPlayer)\n .RegisterSingleton()\n .RegisterSingleton();\n\n containerRegistry.RegisterDialogWindow();\n\n containerRegistry.RegisterDialog();\n containerRegistry.RegisterDialog();\n containerRegistry.RegisterDialog();\n containerRegistry.RegisterDialog();\n containerRegistry.RegisterDialog();\n containerRegistry.RegisterDialog();\n containerRegistry.RegisterDialog();\n containerRegistry.RegisterDialog();\n containerRegistry.RegisterDialog();\n }\n\n protected override Window CreateShell()\n {\n return Container.Resolve();\n }\n\n protected override void OnStartup(StartupEventArgs e)\n {\n if (e.Args.Length == 1)\n {\n CmdUrl = e.Args[0];\n }\n\n // TODO: L: customizable?\n // Ensures that we have enough worker threads to avoid the UI from freezing or not updating on time\n ThreadPool.GetMinThreads(out int workers, out int ports);\n ThreadPool.SetMinThreads(workers + 6, ports + 6);\n\n // Start flyleaf engine\n FlyleafLoader.StartEngine();\n\n base.OnStartup(e);\n }\n\n private void App_OnDispatcherUnhandledException(object sender, DispatcherUnhandledExceptionEventArgs e)\n {\n // Ignore WPF Clipboard exception\n if (e.Exception is COMException { ErrorCode: -2147221040 })\n {\n e.Handled = true;\n }\n\n if (!e.Handled)\n {\n Log.Error($\"Unknown error occurred in App: {e.Exception}\");\n Logger.ForceFlush();\n\n ErrorDialogHelper.ShowUnknownErrorPopup($\"Unhandled Exception: {e.Exception.Message}\", \"Global\", e.Exception);\n e.Handled = true;\n }\n }\n\n #region App Version\n public static string OSArchitecture => RuntimeInformation.OSArchitecture.ToString().ToLowerFirstChar();\n public static string ProcessArchitecture => RuntimeInformation.ProcessArchitecture.ToString().ToLowerFirstChar();\n\n private static string? _version;\n public static string Version\n {\n get\n {\n if (_version == null)\n {\n (_version, _commitHash) = GetVersion();\n }\n\n return _version;\n }\n }\n\n private static string? _commitHash;\n public static string CommitHash\n {\n get\n {\n if (_commitHash == null)\n {\n (_version, _commitHash) = GetVersion();\n }\n\n return _commitHash;\n }\n }\n\n private static (string version, string commitHash) GetVersion()\n {\n string exeLocation = Process.GetCurrentProcess().MainModule!.FileName;\n FileVersionInfo fvi = FileVersionInfo.GetVersionInfo(exeLocation);\n\n Guards.ThrowIfNull(fvi.ProductVersion);\n\n var version = fvi.ProductVersion.Split(\"+\");\n if (version.Length != 2)\n {\n throw new InvalidOperationException($\"ProductVersion is invalid: {fvi.ProductVersion}\");\n }\n\n return (version[0], version[1]);\n }\n #endregion\n}\n"], ["/LLPlayer/LLPlayer/Extensions/JsonInterfaceConcreteConverter.cs", "using System.Text.Json;\nusing System.Text.Json.Serialization;\n\nnamespace LLPlayer.Extensions;\n\n/// \n/// JsonConverter to serialize and deserialize interfaces with concrete types using a mapping between interfaces and concrete types\n/// \n/// \npublic class JsonInterfaceConcreteConverter : JsonConverter\n{\n private const string TypeKey = \"TypeName\";\n private readonly Dictionary _typeMapping;\n\n public JsonInterfaceConcreteConverter(Dictionary typeMapping)\n {\n _typeMapping = typeMapping;\n }\n\n public override T Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options)\n {\n using JsonDocument jsonDoc = JsonDocument.ParseValue(ref reader);\n\n if (!jsonDoc.RootElement.TryGetProperty(TypeKey, out JsonElement typeProperty))\n {\n throw new JsonException(\"Type discriminator not found.\");\n }\n\n string? typeDiscriminator = typeProperty.GetString();\n if (typeDiscriminator == null || !_typeMapping.TryGetValue(typeDiscriminator, out Type? targetType))\n {\n throw new JsonException($\"Unknown type discriminator: {typeDiscriminator}\");\n }\n\n // If a specific type is specified as the second argument, it is deserialized with that type\n return (T)JsonSerializer.Deserialize(jsonDoc.RootElement, targetType, options)!;\n }\n\n public override void Write(Utf8JsonWriter writer, T value, JsonSerializerOptions options)\n {\n Type type = value!.GetType();\n string typeDiscriminator = type.Name; // Use type name as discriminator\n\n // Serialize with concrete types, not interfaces\n string json = JsonSerializer.Serialize(value, type, options);\n using JsonDocument jsonDoc = JsonDocument.Parse(json);\n\n writer.WriteStartObject();\n // Save concrete type name\n writer.WriteString(TypeKey, typeDiscriminator);\n\n // Does this work even if it's nested?\n foreach (JsonProperty property in jsonDoc.RootElement.EnumerateObject())\n {\n property.WriteTo(writer);\n }\n\n writer.WriteEndObject();\n }\n}\n"], ["/LLPlayer/LLPlayer/ViewModels/WhisperEngineDownloadDialogVM.cs", "using System.Diagnostics;\nusing System.IO;\nusing System.Net.Http;\nusing FlyleafLib;\nusing LLPlayer.Extensions;\nusing LLPlayer.Services;\nusing SevenZip;\nusing File = System.IO.File;\n\nnamespace LLPlayer.ViewModels;\n\npublic class WhisperEngineDownloadDialogVM : Bindable, IDialogAware\n{\n // currently not reusable at all\n public static string EngineURL => \"https://github.com/Purfview/whisper-standalone-win/releases/tag/Faster-Whisper-XXL\";\n public static string EngineFile => \"Faster-Whisper-XXL_r245.4_windows.7z\";\n private static string EngineDownloadURL =\n \"https://github.com/umlx5h/LLPlayer/releases/download/v0.0.1/Faster-Whisper-XXL_r245.4_windows.7z\";\n private static string EngineName = \"Faster-Whisper-XXL\";\n private static string EnginePath = Path.Combine(WhisperConfig.EnginesDirectory, EngineName);\n\n public FlyleafManager FL { get; }\n\n public WhisperEngineDownloadDialogVM(FlyleafManager fl)\n {\n FL = fl;\n\n CmdDownloadEngine!.PropertyChanged += (sender, args) =>\n {\n if (args.PropertyName == nameof(CmdDownloadEngine.IsExecuting))\n {\n OnPropertyChanged(nameof(CanDownload));\n OnPropertyChanged(nameof(CanDelete));\n }\n };\n }\n\n public string StatusText { get; set => Set(ref field, value); } = \"\";\n\n public long DownloadedSize { get; set => Set(ref field, value); }\n\n public bool Downloaded => Directory.Exists(EnginePath);\n\n public bool CanDownload => !Downloaded && !CmdDownloadEngine!.IsExecuting;\n\n public bool CanDelete => Downloaded && !CmdDownloadEngine!.IsExecuting;\n\n private CancellationTokenSource? _cts;\n\n public AsyncDelegateCommand? CmdDownloadEngine => field ??= new AsyncDelegateCommand(async () =>\n {\n _cts = new CancellationTokenSource();\n CancellationToken token = _cts.Token;\n\n string tempPath = Path.GetTempPath();\n string tempDownloadFile = Path.Combine(tempPath, EngineFile);\n\n try\n {\n StatusText = $\"Engine '{EngineName}' downloading..\";\n\n await DownloadEngineWithProgressAsync(EngineDownloadURL, tempDownloadFile, token);\n\n StatusText = $\"Engine '{EngineName}' unzipping..\";\n await UnzipEngine(tempDownloadFile);\n\n StatusText = $\"Engine '{EngineName}' is downloaded successfully\";\n OnDownloadStatusChanged();\n }\n catch (OperationCanceledException)\n {\n StatusText = \"Download canceled\";\n }\n catch (Exception ex)\n {\n StatusText = $\"Failed to download: {ex.Message}\";\n }\n finally\n {\n _cts = null;\n DeleteTempEngine();\n }\n\n return;\n\n bool DeleteTempEngine()\n {\n // Delete temporary files if they exist\n if (File.Exists(tempDownloadFile))\n {\n try\n {\n File.Delete(tempDownloadFile);\n }\n catch (Exception)\n {\n // ignore\n\n return false;\n }\n }\n\n return true;\n }\n }).ObservesCanExecute(() => CanDownload);\n\n public DelegateCommand? CmdCancelDownloadEngine => field ??= new(() =>\n {\n _cts?.Cancel();\n });\n\n public AsyncDelegateCommand? CmdDeleteEngine => field ??= new AsyncDelegateCommand(async () =>\n {\n try\n {\n StatusText = $\"Engine '{EngineName}' deleting...\";\n\n // Delete engine if exists\n if (Directory.Exists(EnginePath))\n {\n await Task.Run(() =>\n {\n Directory.Delete(EnginePath, true);\n });\n }\n\n OnDownloadStatusChanged();\n\n StatusText = $\"Engine '{EngineName}' is deleted successfully\";\n }\n catch (Exception ex)\n {\n StatusText = $\"Failed to delete engine: {ex.Message}\";\n }\n }).ObservesCanExecute(() => CanDelete);\n\n public DelegateCommand? CmdOpenFolder => field ??= new(() =>\n {\n if (!Directory.Exists(WhisperConfig.EnginesDirectory))\n return;\n\n Process.Start(new ProcessStartInfo\n {\n FileName = WhisperConfig.EnginesDirectory,\n UseShellExecute = true,\n CreateNoWindow = true\n });\n });\n\n private void OnDownloadStatusChanged()\n {\n OnPropertyChanged(nameof(CanDownload));\n OnPropertyChanged(nameof(CanDelete));\n }\n\n private async Task UnzipEngine(string zipPath)\n {\n WhisperConfig.EnsureEnginesDirectory();\n\n SevenZipBase.SetLibraryPath(\"lib/7z.dll\");\n\n using (SevenZipExtractor extractor = new(zipPath))\n {\n await extractor.ExtractArchiveAsync(WhisperConfig.EnginesDirectory);\n }\n\n string licencePath = Path.Combine(WhisperConfig.EnginesDirectory, \"license.txt\");\n\n if (File.Exists(licencePath) && Directory.Exists(WhisperConfig.EnginesDirectory))\n {\n // move license.txt to engine directory\n File.Move(licencePath, Path.Combine(EnginePath, \"license.txt\"));\n }\n }\n\n private async Task DownloadEngineWithProgressAsync(string url, string destinationPath, CancellationToken token)\n {\n DownloadedSize = 0;\n\n using HttpClient httpClient = new();\n httpClient.Timeout = TimeSpan.FromSeconds(10);\n\n using var response = await httpClient.GetAsync(url, HttpCompletionOption.ResponseHeadersRead, token);\n\n response.EnsureSuccessStatusCode();\n\n await using Stream engineStream = await response.Content.ReadAsStreamAsync(token);\n await using FileStream fileWriter = File.Open(destinationPath, FileMode.Create);\n\n byte[] buffer = new byte[1024 * 128];\n int bytesRead;\n long totalBytesRead = 0;\n\n Stopwatch sw = new();\n sw.Start();\n\n while ((bytesRead = await engineStream.ReadAsync(buffer, 0, buffer.Length, token)) > 0)\n {\n await fileWriter.WriteAsync(buffer, 0, bytesRead, token);\n totalBytesRead += bytesRead;\n\n if (sw.Elapsed > TimeSpan.FromMilliseconds(50))\n {\n DownloadedSize = totalBytesRead;\n sw.Restart();\n }\n\n token.ThrowIfCancellationRequested();\n }\n\n return totalBytesRead;\n }\n\n #region IDialogAware\n public string Title { get; set => Set(ref field, value); } = $\"Whisper Engine Downloader - {App.Name}\";\n public double WindowWidth { get; set => Set(ref field, value); } = 400;\n public double WindowHeight { get; set => Set(ref field, value); } = 210;\n\n public bool CanCloseDialog() => !CmdDownloadEngine!.IsExecuting;\n public void OnDialogClosed() { }\n public void OnDialogOpened(IDialogParameters parameters) { }\n public DialogCloseListener RequestClose { get; }\n #endregion IDialogAware\n}\n"], ["/LLPlayer/FlyleafLib/MediaFramework/MediaDecoder/AudioDecoder.cs", "using System.Collections.Concurrent;\nusing System.Threading;\n\nusing FlyleafLib.MediaFramework.MediaStream;\nusing FlyleafLib.MediaFramework.MediaFrame;\nusing FlyleafLib.MediaFramework.MediaRemuxer;\n\nusing static FlyleafLib.Logger;\n\nnamespace FlyleafLib.MediaFramework.MediaDecoder;\n\n/* TODO\n *\n * Circular Buffer\n * - Safe re-allocation and check also actual frames in queue (as now during draining we can overwrite them)\n * - Locking with Audio.AddSamples during re-allocation and re-write old data to the new buffer and update the pointers in queue\n *\n * Filters\n * - Note: Performance issue (for seek/speed change). We can't drain the buffersrc and re-use the filtergraph without re-initializing it, is not supported\n * - Check if av_buffersrc_get_nb_failed_requests required\n * - Add Config for filter threads?\n * - Review Access Violation issue with dynaudnorm/loudnorm filters in combination with atempo (when changing speed to fast?)\n * - Use multiple atempo for better quality (for < 0.5 and > 2, use eg. 2 of sqrt(X) * sqrt(X) to achive this)\n * - Review locks / recode RunInternal to be able to continue from where it stopped (eg. ProcessFilter)\n *\n * Custom Frames Queue to notify when the queue is not full anymore (to avoid thread sleep which can cause delays)\n * Support more output formats/channels/sampleRates (and currently output to 32-bit, sample rate to 48Khz and not the same as input? - should calculate possible delays)\n */\n\npublic unsafe partial class AudioDecoder : DecoderBase\n{\n public AudioStream AudioStream => (AudioStream) Stream;\n public readonly\n VideoDecoder VideoDecoder;\n public ConcurrentQueue\n Frames { get; protected set; } = new();\n\n static AVSampleFormat AOutSampleFormat = AVSampleFormat.S16;\n static string AOutSampleFormatStr = av_get_sample_fmt_name(AOutSampleFormat);\n static AVChannelLayout AOutChannelLayout = AV_CHANNEL_LAYOUT_STEREO;// new() { order = AVChannelOrder.Native, nb_channels = 2, u = new AVChannelLayout_u() { mask = AVChannel.for AV_CH_FRONT_LEFT | AV_CH_FRONT_RIGHT} };\n static int AOutChannels = AOutChannelLayout.nb_channels;\n static int ASampleBytes = av_get_bytes_per_sample(AOutSampleFormat) * AOutChannels;\n\n public readonly object CircularBufferLocker= new();\n internal Action CBufAlloc; // Informs Audio player to clear buffer pointers to avoid access violation\n static int cBufTimesSize = 4;\n int cBufTimesCur = 1;\n byte[] cBuf;\n int cBufPos;\n int cBufSamples;\n internal bool resyncWithVideoRequired;\n SwrContext* swrCtx;\n\n internal long nextPts;\n double sampleRateTimebase;\n\n public AudioDecoder(Config config, int uniqueId = -1, VideoDecoder syncDecoder = null) : base(config, uniqueId)\n => VideoDecoder = syncDecoder;\n\n protected override int Setup(AVCodec* codec) => 0;\n private int SetupSwr()\n {\n int ret;\n\n DisposeSwr();\n swrCtx = swr_alloc();\n\n av_opt_set_chlayout(swrCtx, \"in_chlayout\", &codecCtx->ch_layout, 0);\n av_opt_set_int(swrCtx, \"in_sample_rate\", codecCtx->sample_rate, 0);\n av_opt_set_sample_fmt(swrCtx, \"in_sample_fmt\", codecCtx->sample_fmt, 0);\n\n fixed(AVChannelLayout* ptr = &AOutChannelLayout)\n av_opt_set_chlayout(swrCtx, \"out_chlayout\", ptr, 0);\n av_opt_set_int(swrCtx, \"out_sample_rate\", codecCtx->sample_rate, 0);\n av_opt_set_sample_fmt(swrCtx, \"out_sample_fmt\", AOutSampleFormat, 0);\n\n ret = swr_init(swrCtx);\n if (ret < 0)\n Log.Error($\"Swr setup failed {FFmpegEngine.ErrorCodeToMsg(ret)} ({ret})\");\n\n return ret;\n }\n private void DisposeSwr()\n {\n if (swrCtx == null)\n return;\n\n swr_close(swrCtx);\n\n fixed(SwrContext** ptr = &swrCtx)\n swr_free(ptr);\n\n swrCtx = null;\n }\n\n protected override void DisposeInternal()\n {\n DisposeFrames();\n DisposeSwr();\n DisposeFilters();\n\n lock (CircularBufferLocker)\n cBuf = null;\n cBufSamples = 0;\n filledFromCodec = false;\n nextPts = AV_NOPTS_VALUE;\n }\n public void DisposeFrames() => Frames = new();\n public void Flush()\n {\n lock (lockActions)\n lock (lockCodecCtx)\n {\n if (Disposed)\n return;\n\n if (Status == Status.Ended)\n Status = Status.Stopped;\n else if (Status == Status.Draining)\n Status = Status.Stopping;\n\n resyncWithVideoRequired = !VideoDecoder.Disposed;\n nextPts = AV_NOPTS_VALUE;\n DisposeFrames();\n avcodec_flush_buffers(codecCtx);\n if (filterGraph != null)\n SetupFilters();\n }\n }\n\n protected override void RunInternal()\n {\n int ret = 0;\n int allowedErrors = Config.Decoder.MaxErrors;\n int sleepMs = Config.Decoder.MaxAudioFrames > 5 && Config.Player.MaxLatency == 0 ? 10 : 4;\n AVPacket *packet;\n\n do\n {\n // Wait until Queue not Full or Stopped\n if (Frames.Count >= Config.Decoder.MaxAudioFrames)\n {\n lock (lockStatus)\n if (Status == Status.Running)\n Status = Status.QueueFull;\n\n while (Frames.Count >= Config.Decoder.MaxAudioFrames && Status == Status.QueueFull)\n Thread.Sleep(sleepMs);\n\n lock (lockStatus)\n {\n if (Status != Status.QueueFull)\n break;\n\n Status = Status.Running;\n }\n }\n\n // While Packets Queue Empty (Ended | Quit if Demuxer stopped | Wait until we get packets)\n if (demuxer.AudioPackets.Count == 0)\n {\n CriticalArea = true;\n\n lock (lockStatus)\n if (Status == Status.Running) Status = Status.QueueEmpty;\n\n while (demuxer.AudioPackets.Count == 0 && Status == Status.QueueEmpty)\n {\n if (demuxer.Status == Status.Ended)\n {\n lock (lockStatus)\n {\n // TODO: let the demuxer push the draining packet\n Log.Debug(\"Draining\");\n Status = Status.Draining;\n var drainPacket = av_packet_alloc();\n drainPacket->data = null;\n drainPacket->size = 0;\n demuxer.AudioPackets.Enqueue(drainPacket);\n }\n\n break;\n }\n else if (!demuxer.IsRunning)\n {\n if (CanDebug) Log.Debug($\"Demuxer is not running [Demuxer Status: {demuxer.Status}]\");\n\n int retries = 5;\n\n while (retries > 0)\n {\n retries--;\n Thread.Sleep(10);\n if (demuxer.IsRunning) break;\n }\n\n lock (demuxer.lockStatus)\n lock (lockStatus)\n {\n if (demuxer.Status == Status.Pausing || demuxer.Status == Status.Paused)\n Status = Status.Pausing;\n else if (demuxer.Status != Status.Ended)\n Status = Status.Stopping;\n else\n continue;\n }\n\n break;\n }\n\n Thread.Sleep(sleepMs);\n }\n\n lock (lockStatus)\n {\n CriticalArea = false;\n if (Status != Status.QueueEmpty && Status != Status.Draining) break;\n if (Status != Status.Draining) Status = Status.Running;\n }\n }\n\n Monitor.Enter(lockCodecCtx); // restore the old lock / add interrupters similar to the demuxer\n try\n {\n if (Status == Status.Stopped)\n { Monitor.Exit(lockCodecCtx); continue; }\n\n packet = demuxer.AudioPackets.Dequeue();\n\n if (packet == null)\n { Monitor.Exit(lockCodecCtx); continue; }\n\n if (isRecording)\n {\n if (!recGotKeyframe && VideoDecoder.StartRecordTime != AV_NOPTS_VALUE && (long)(packet->pts * AudioStream.Timebase) - demuxer.StartTime > VideoDecoder.StartRecordTime)\n recGotKeyframe = true;\n\n if (recGotKeyframe)\n curRecorder.Write(av_packet_clone(packet), !OnVideoDemuxer);\n }\n\n ret = avcodec_send_packet(codecCtx, packet);\n av_packet_free(&packet);\n\n if (ret != 0 && ret != AVERROR(EAGAIN))\n {\n if (ret == AVERROR_EOF)\n {\n Status = Status.Ended;\n break;\n }\n else\n {\n allowedErrors--;\n if (CanWarn) Log.Warn($\"{FFmpegEngine.ErrorCodeToMsg(ret)} ({ret})\");\n\n if (allowedErrors == 0) { Log.Error(\"Too many errors!\"); Status = Status.Stopping; break; }\n\n Monitor.Exit(lockCodecCtx); continue;\n }\n }\n\n while (true)\n {\n ret = avcodec_receive_frame(codecCtx, frame);\n if (ret != 0)\n {\n av_frame_unref(frame);\n\n if (ret == AVERROR_EOF && filterGraph != null)\n {\n lock (lockSpeed)\n {\n DrainFilters();\n Status = Status.Ended;\n }\n }\n\n break;\n }\n\n if (frame->best_effort_timestamp != AV_NOPTS_VALUE)\n frame->pts = frame->best_effort_timestamp;\n else if (frame->pts == AV_NOPTS_VALUE)\n {\n if (nextPts == AV_NOPTS_VALUE && filledFromCodec) // Possible after seek (maybe set based on pkt_pos?)\n {\n av_frame_unref(frame);\n continue;\n }\n\n frame->pts = nextPts;\n }\n\n // We could fix it down to the demuxer based on size?\n if (frame->duration <= 0)\n frame->duration = av_rescale_q((long)(frame->nb_samples * sampleRateTimebase), Engine.FFmpeg.AV_TIMEBASE_Q, Stream.AVStream->time_base);\n\n bool codecChanged = AudioStream.SampleFormat != codecCtx->sample_fmt || AudioStream.SampleRate != codecCtx->sample_rate || AudioStream.ChannelLayout != codecCtx->ch_layout.u.mask;\n\n if (!filledFromCodec || codecChanged)\n {\n if (codecChanged && filledFromCodec)\n {\n byte[] buf = new byte[50];\n fixed (byte* bufPtr = buf)\n {\n av_channel_layout_describe(&codecCtx->ch_layout, bufPtr, (nuint)buf.Length);\n Log.Warn($\"Codec changed {AudioStream.CodecIDOrig} {AudioStream.SampleFormat} {AudioStream.SampleRate} {AudioStream.ChannelLayoutStr} => {codecCtx->codec_id} {codecCtx->sample_fmt} {codecCtx->sample_rate} {Utils.BytePtrToStringUTF8(bufPtr)}\");\n }\n }\n\n DisposeInternal();\n filledFromCodec = true;\n\n avcodec_parameters_from_context(Stream.AVStream->codecpar, codecCtx);\n AudioStream.AVStream->time_base = codecCtx->pkt_timebase;\n AudioStream.Refresh();\n resyncWithVideoRequired = !VideoDecoder.Disposed;\n sampleRateTimebase = 1000 * 1000.0 / codecCtx->sample_rate;\n nextPts = AudioStream.StartTimePts;\n\n if (frame->pts == AV_NOPTS_VALUE)\n frame->pts = nextPts;\n\n ret = SetupFiltersOrSwr();\n\n CodecChanged?.Invoke(this);\n\n if (ret != 0)\n {\n Status = Status.Stopping;\n av_frame_unref(frame);\n break;\n }\n\n if (nextPts == AV_NOPTS_VALUE)\n {\n av_frame_unref(frame);\n continue;\n }\n }\n\n if (resyncWithVideoRequired)\n {\n // TODO: in case of long distance will spin (CPU issue), possible reseek?\n while (VideoDecoder.StartTime == AV_NOPTS_VALUE && VideoDecoder.IsRunning && resyncWithVideoRequired)\n Thread.Sleep(10);\n\n long ts = (long)((frame->pts + frame->duration) * AudioStream.Timebase) - demuxer.StartTime + Config.Audio.Delay;\n\n if (ts < VideoDecoder.StartTime)\n {\n if (CanTrace) Log.Trace($\"Drops {Utils.TicksToTime(ts)} (< V: {Utils.TicksToTime(VideoDecoder.StartTime)})\");\n av_frame_unref(frame);\n continue;\n }\n else\n resyncWithVideoRequired = false;\n }\n\n lock (lockSpeed)\n {\n if (filterGraph != null)\n ProcessFilters();\n else\n Process();\n\n av_frame_unref(frame);\n }\n }\n } catch { }\n\n Monitor.Exit(lockCodecCtx);\n\n } while (Status == Status.Running);\n\n if (isRecording) { StopRecording(); recCompleted(MediaType.Audio); }\n\n if (Status == Status.Draining) Status = Status.Ended;\n }\n private void Process()\n {\n try\n {\n nextPts = frame->pts + frame->duration;\n\n var dataLen = frame->nb_samples * ASampleBytes;\n var speedDataLen= Utils.Align((int)(dataLen / speed), ASampleBytes);\n\n AudioFrame mFrame = new()\n {\n timestamp = (long)(frame->pts * AudioStream.Timebase) - demuxer.StartTime + Config.Audio.Delay,\n dataLen = speedDataLen\n };\n if (CanTrace) Log.Trace($\"Processes {Utils.TicksToTime(mFrame.timestamp)}\");\n\n if (frame->nb_samples > cBufSamples)\n AllocateCircularBuffer(frame->nb_samples);\n else if (cBufPos + Math.Max(dataLen, speedDataLen) >= cBuf.Length)\n cBufPos = 0;\n\n fixed (byte *circularBufferPosPtr = &cBuf[cBufPos])\n {\n int ret = swr_convert(swrCtx, &circularBufferPosPtr, frame->nb_samples, (byte**)&frame->data, frame->nb_samples);\n if (ret < 0)\n return;\n\n mFrame.dataPtr = (IntPtr)circularBufferPosPtr;\n }\n\n // Fill silence\n if (speed < 1)\n for (int p = dataLen; p < speedDataLen; p++)\n cBuf[cBufPos + p] = 0;\n\n cBufPos += Math.Max(dataLen, speedDataLen);\n Frames.Enqueue(mFrame);\n\n // Wait until Queue not Full or Stopped\n if (Frames.Count >= Config.Decoder.MaxAudioFrames * cBufTimesCur)\n {\n Monitor.Exit(lockCodecCtx);\n lock (lockStatus)\n if (Status == Status.Running) Status = Status.QueueFull;\n\n while (Frames.Count >= Config.Decoder.MaxAudioFrames * cBufTimesCur && Status == Status.QueueFull)\n Thread.Sleep(20);\n\n Monitor.Enter(lockCodecCtx);\n\n lock (lockStatus)\n {\n if (Status != Status.QueueFull)\n return;\n\n Status = Status.Running;\n }\n }\n }\n catch (Exception e)\n {\n Log.Error($\"Failed to process frame ({e.Message})\");\n }\n }\n\n private void AllocateCircularBuffer(int samples)\n {\n /* TBR\n * 1. If we change to different in/out sample rates we need to calculate delay\n * 2. By destorying the cBuf can create critical issues while the audio decoder reads the data? (add lock) | we need to copy the lost data and change the pointers\n * 3. Recalculate on Config.Decoder.MaxAudioFrames change (greater)\n * 4. cBufTimesSize cause filters can pass the limit when we need to use lockSpeed\n */\n\n samples = Math.Max(10000, samples); // 10K samples to ensure that currently we will not re-allocate?\n int size = Config.Decoder.MaxAudioFrames * samples * ASampleBytes * cBufTimesSize;\n Log.Debug($\"Re-allocating circular buffer ({samples} > {cBufSamples}) with {size}bytes\");\n\n lock (CircularBufferLocker)\n {\n DisposeFrames(); // TODO: copy data\n CBufAlloc?.Invoke();\n cBuf = new byte[size];\n cBufPos = 0;\n cBufSamples = samples;\n }\n\n }\n\n #region Recording\n internal Action\n recCompleted;\n Remuxer curRecorder;\n bool recGotKeyframe;\n internal bool isRecording;\n internal void StartRecording(Remuxer remuxer)\n {\n if (Disposed || isRecording) return;\n\n curRecorder = remuxer;\n isRecording = true;\n recGotKeyframe = VideoDecoder.Disposed || VideoDecoder.Stream == null;\n }\n internal void StopRecording() => isRecording = false;\n #endregion\n}\n"], ["/LLPlayer/FlyleafLib/MediaFramework/MediaRenderer/Renderer.Device.cs", "using System.Numerics;\nusing System.Text.RegularExpressions;\n\nusing Vortice;\nusing Vortice.Direct3D;\nusing Vortice.Direct3D11;\nusing Vortice.DXGI;\nusing Vortice.DXGI.Debug;\n\nusing FlyleafLib.MediaFramework.MediaDecoder;\n\nusing static FlyleafLib.Logger;\nusing System.Runtime.InteropServices;\n\nusing ID3D11Device = Vortice.Direct3D11.ID3D11Device;\nusing ID3D11DeviceContext = Vortice.Direct3D11.ID3D11DeviceContext;\n\nnamespace FlyleafLib.MediaFramework.MediaRenderer;\n\npublic unsafe partial class Renderer\n{\n static InputElementDescription[] inputElements =\n {\n new(\"POSITION\", 0, Format.R32G32B32_Float, 0),\n new(\"TEXCOORD\", 0, Format.R32G32_Float, 0),\n };\n\n static BufferDescription vertexBufferDesc = new()\n {\n BindFlags = BindFlags.VertexBuffer\n };\n\n static float[] vertexBufferData = new[]\n {\n -1.0f, -1.0f, 0, 0.0f, 1.0f,\n -1.0f, 1.0f, 0, 0.0f, 0.0f,\n 1.0f, -1.0f, 0, 1.0f, 1.0f,\n\n 1.0f, -1.0f, 0, 1.0f, 1.0f,\n -1.0f, 1.0f, 0, 0.0f, 0.0f,\n 1.0f, 1.0f, 0, 1.0f, 0.0f\n };\n\n static FeatureLevel[] featureLevelsAll = new[]\n {\n FeatureLevel.Level_12_1,\n FeatureLevel.Level_12_0,\n FeatureLevel.Level_11_1,\n FeatureLevel.Level_11_0,\n FeatureLevel.Level_10_1,\n FeatureLevel.Level_10_0,\n FeatureLevel.Level_9_3,\n FeatureLevel.Level_9_2,\n FeatureLevel.Level_9_1\n };\n\n static FeatureLevel[] featureLevels = new[]\n {\n FeatureLevel.Level_11_0,\n FeatureLevel.Level_10_1,\n FeatureLevel.Level_10_0,\n FeatureLevel.Level_9_3,\n FeatureLevel.Level_9_2,\n FeatureLevel.Level_9_1\n };\n\n static BlendDescription blendDesc = new();\n\n static Renderer()\n {\n blendDesc.RenderTarget[0].BlendEnable = true;\n blendDesc.RenderTarget[0].SourceBlend = Blend.SourceAlpha;\n blendDesc.RenderTarget[0].DestinationBlend = Blend.InverseSourceAlpha;\n blendDesc.RenderTarget[0].BlendOperation = BlendOperation.Add;\n blendDesc.RenderTarget[0].SourceBlendAlpha = Blend.Zero;\n blendDesc.RenderTarget[0].DestinationBlendAlpha = Blend.Zero;\n blendDesc.RenderTarget[0].BlendOperationAlpha = BlendOperation.Add;\n blendDesc.RenderTarget[0].RenderTargetWriteMask = ColorWriteEnable.All;\n }\n\n\n ID3D11DeviceContext context;\n\n ID3D11Buffer vertexBuffer;\n ID3D11InputLayout inputLayout;\n ID3D11RasterizerState\n rasterizerState;\n ID3D11BlendState blendStateAlpha;\n\n ID3D11VertexShader ShaderVS;\n ID3D11PixelShader ShaderPS;\n ID3D11PixelShader ShaderBGRA;\n\n ID3D11Buffer psBuffer;\n PSBufferType psBufferData;\n\n ID3D11Buffer vsBuffer;\n VSBufferType vsBufferData;\n\n internal object lockDevice = new();\n bool isFlushing;\n\n public void Initialize(bool swapChain = true)\n {\n lock (lockDevice)\n {\n try\n {\n if (CanDebug) Log.Debug(\"Initializing\");\n\n if (!Disposed)\n Dispose();\n\n Disposed = false;\n\n ID3D11Device tempDevice;\n IDXGIAdapter1 adapter = null;\n var creationFlags = DeviceCreationFlags.BgraSupport /*| DeviceCreationFlags.VideoSupport*/; // Let FFmpeg failed for VA if does not support it\n var creationFlagsWarp = DeviceCreationFlags.None;\n\n #if DEBUG\n if (D3D11.SdkLayersAvailable())\n {\n creationFlags |= DeviceCreationFlags.Debug;\n creationFlagsWarp |= DeviceCreationFlags.Debug;\n }\n #endif\n\n // Finding User Definied adapter\n if (!string.IsNullOrWhiteSpace(Config.Video.GPUAdapter) && Config.Video.GPUAdapter.ToUpper() != \"WARP\")\n {\n for (uint i=0; Engine.Video.Factory.EnumAdapters1(i, out adapter).Success; i++)\n {\n if (adapter.Description1.Description == Config.Video.GPUAdapter)\n break;\n\n if (Regex.IsMatch(adapter.Description1.Description + \" luid=\" + adapter.Description1.Luid, Config.Video.GPUAdapter, RegexOptions.IgnoreCase))\n break;\n\n adapter.Dispose();\n }\n\n if (adapter == null)\n {\n Log.Error($\"GPU Adapter with {Config.Video.GPUAdapter} has not been found. Falling back to default.\");\n Config.Video.GPUAdapter = null;\n }\n }\n\n // Creating WARP (force by user or us after late failure)\n if (!string.IsNullOrWhiteSpace(Config.Video.GPUAdapter) && Config.Video.GPUAdapter.ToUpper() == \"WARP\")\n D3D11.D3D11CreateDevice(null, DriverType.Warp, creationFlagsWarp, featureLevels, out tempDevice).CheckError();\n\n // Creating User Defined or Default\n else\n {\n // Creates the D3D11 Device based on selected adapter or default hardware (highest to lowest features and fall back to the WARP device. see http://go.microsoft.com/fwlink/?LinkId=286690)\n if (D3D11.D3D11CreateDevice(adapter, adapter == null ? DriverType.Hardware : DriverType.Unknown, creationFlags, featureLevelsAll, out tempDevice).Failure)\n if (D3D11.D3D11CreateDevice(adapter, adapter == null ? DriverType.Hardware : DriverType.Unknown, creationFlags, featureLevels, out tempDevice).Failure)\n {\n Config.Video.GPUAdapter = \"WARP\";\n D3D11.D3D11CreateDevice(null, DriverType.Warp, creationFlagsWarp, featureLevels, out tempDevice).CheckError();\n }\n }\n\n Device = tempDevice.QueryInterface();\n context= Device.ImmediateContext;\n\n // Gets the default adapter from the D3D11 Device\n if (adapter == null)\n {\n Device.Tag = new Luid().ToString();\n using var deviceTmp = Device.QueryInterface();\n using var adapterTmp = deviceTmp.GetAdapter();\n adapter = adapterTmp.QueryInterface();\n }\n else\n Device.Tag = adapter.Description.Luid.ToString();\n\n if (Engine.Video.GPUAdapters.ContainsKey(adapter.Description1.Luid))\n {\n GPUAdapter = Engine.Video.GPUAdapters[adapter.Description1.Luid];\n Config.Video.MaxVerticalResolutionAuto = GPUAdapter.MaxHeight;\n\n if (CanDebug)\n {\n string dump = $\"GPU Adapter\\r\\n{GPUAdapter}\\r\\n\";\n\n for (int i=0; i()) mthread.SetMultithreadProtected(true);\n using (var dxgidevice = Device.QueryInterface()) dxgidevice.MaximumFrameLatency = Config.Video.MaxFrameLatency;\n\n // Input Layout\n inputLayout = Device.CreateInputLayout(inputElements, ShaderCompiler.VSBlob);\n context.IASetInputLayout(inputLayout);\n context.IASetPrimitiveTopology(PrimitiveTopology.TriangleList);\n\n // Vertex Shader\n vertexBuffer = Device.CreateBuffer(vertexBufferData, vertexBufferDesc);\n context.IASetVertexBuffer(0, vertexBuffer, sizeof(float) * 5);\n\n ShaderVS = Device.CreateVertexShader(ShaderCompiler.VSBlob);\n context.VSSetShader(ShaderVS);\n\n vsBuffer = Device.CreateBuffer(new()\n {\n Usage = ResourceUsage.Default,\n BindFlags = BindFlags.ConstantBuffer,\n CPUAccessFlags = CpuAccessFlags.None,\n ByteWidth = (uint)(sizeof(VSBufferType) + (16 - (sizeof(VSBufferType) % 16)))\n });\n context.VSSetConstantBuffer(0, vsBuffer);\n\n vsBufferData.mat = Matrix4x4.Identity;\n context.UpdateSubresource(vsBufferData, vsBuffer);\n\n // Pixel Shader\n InitPS();\n psBuffer = Device.CreateBuffer(new()\n {\n Usage = ResourceUsage.Default,\n BindFlags = BindFlags.ConstantBuffer,\n CPUAccessFlags = CpuAccessFlags.None,\n ByteWidth = (uint)(sizeof(PSBufferType) + (16 - (sizeof(PSBufferType) % 16)))\n });\n context.PSSetConstantBuffer(0, psBuffer);\n psBufferData.hdrmethod = HDRtoSDRMethod.None;\n context.UpdateSubresource(psBufferData, psBuffer);\n\n // subs\n ShaderBGRA = ShaderCompiler.CompilePS(Device, \"bgra\", @\"color = float4(Texture1.Sample(Sampler, input.Texture).rgba);\", null);\n\n // Blend State (currently used -mainly- for RGBA images and OverlayTexture)\n blendStateAlpha = Device.CreateBlendState(blendDesc);\n\n // Rasterizer (Will change CullMode to None for H-V Flip)\n rasterizerState = Device.CreateRasterizerState(new(CullMode.Back, FillMode.Solid));\n context.RSSetState(rasterizerState);\n\n InitializeVideoProcessor();\n\n if (CanInfo) Log.Info($\"Initialized with Feature Level {(int)Device.FeatureLevel >> 12}.{((int)Device.FeatureLevel >> 8) & 0xf}\");\n\n } catch (Exception e)\n {\n if (string.IsNullOrWhiteSpace(Config.Video.GPUAdapter) || Config.Video.GPUAdapter.ToUpper() != \"WARP\")\n {\n try { if (Device != null) Log.Warn($\"Device Remove Reason = {Device.DeviceRemovedReason.Description}\"); } catch { } // For troubleshooting\n\n Log.Warn($\"Initialization failed ({e.Message}). Failling back to WARP device.\");\n Config.Video.GPUAdapter = \"WARP\";\n Flush();\n }\n else\n {\n Log.Error($\"Initialization failed ({e.Message})\");\n Dispose();\n return;\n }\n }\n\n if (swapChain)\n {\n if (ControlHandle != IntPtr.Zero)\n InitializeSwapChain(ControlHandle);\n else if (SwapChainWinUIClbk != null)\n InitializeWinUISwapChain();\n }\n\n InitializeChildSwapChain();\n }\n }\n public void InitializeChildSwapChain(bool swapChain = true)\n {\n if (child == null )\n return;\n\n lock (lockDevice)\n {\n child.lockDevice = lockDevice;\n child.VideoDecoder = VideoDecoder;\n child.Device = Device;\n child.context = context;\n child.curRatio = curRatio;\n child.VideoRect = VideoRect;\n child.videoProcessor= videoProcessor;\n child.InitializeVideoProcessor(); // to use the same VP we need to set it's config in each present (means we don't update VP config as is different)\n\n if (swapChain)\n {\n if (child.ControlHandle != IntPtr.Zero)\n child.InitializeSwapChain(child.ControlHandle);\n else if (child.SwapChainWinUIClbk != null)\n child.InitializeWinUISwapChain();\n }\n\n child.Disposed = false;\n child.SetViewport();\n }\n }\n\n public void Dispose()\n {\n lock (lockDevice)\n {\n if (Disposed)\n return;\n\n if (child != null)\n DisposeChild();\n\n Disposed = true;\n\n if (CanDebug) Log.Debug(\"Disposing\");\n\n VideoDecoder.DisposeFrame(LastFrame);\n RefreshLayout();\n\n DisposeVideoProcessor();\n\n ShaderVS?.Dispose();\n ShaderPS?.Dispose();\n prevPSUniqueId = curPSUniqueId = \"\"; // Ensure we re-create ShaderPS for FlyleafVP on ConfigPlanes\n psBuffer?.Dispose();\n vsBuffer?.Dispose();\n inputLayout?.Dispose();\n vertexBuffer?.Dispose();\n rasterizerState?.Dispose();\n blendStateAlpha?.Dispose();\n DisposeSwapChain();\n\n overlayTexture?.Dispose();\n overlayTextureSrv?.Dispose();\n ShaderBGRA?.Dispose();\n\n singleGpu?.Dispose();\n singleStage?.Dispose();\n singleGpuRtv?.Dispose();\n singleStageDesc.Width = 0; // ensures re-allocation\n\n if (rtv2 != null)\n {\n for(int i = 0; i < rtv2.Length; i++)\n rtv2[i].Dispose();\n\n rtv2 = null;\n }\n\n if (backBuffer2 != null)\n {\n for(int i = 0; i < backBuffer2.Length; i++)\n backBuffer2[i]?.Dispose();\n\n backBuffer2 = null;\n }\n\n if (Device != null)\n {\n context.ClearState();\n context.Flush();\n context.Dispose();\n Device.Dispose();\n Device = null;\n }\n\n #if DEBUG\n ReportLiveObjects();\n #endif\n\n curRatio = 1.0f;\n if (CanInfo) Log.Info(\"Disposed\");\n }\n }\n public void DisposeChild()\n {\n if (child == null)\n return;\n\n lock (lockDevice)\n {\n child.DisposeSwapChain();\n child.DisposeVideoProcessor();\n child.Disposed = true;\n\n if (!isFlushing)\n {\n child.Device = null;\n child.context = null;\n child.VideoDecoder = null;\n child.LastFrame = null;\n child = null;\n }\n }\n }\n\n public void Flush()\n {\n lock (lockDevice)\n {\n isFlushing = true;\n var controlHandle = ControlHandle;\n var swapChainClbk = SwapChainWinUIClbk;\n\n IntPtr controlHandleReplica = IntPtr.Zero;\n Action swapChainClbkReplica = null;;\n if (child != null)\n {\n controlHandleReplica = child.ControlHandle;\n swapChainClbkReplica = child.SwapChainWinUIClbk;\n }\n\n Dispose();\n ControlHandle = controlHandle;\n SwapChainWinUIClbk = swapChainClbk;\n if (child != null)\n {\n child.ControlHandle = controlHandleReplica;\n child.SwapChainWinUIClbk = swapChainClbkReplica;\n }\n Initialize();\n isFlushing = false;\n }\n }\n\n #if DEBUG\n public static void ReportLiveObjects()\n {\n try\n {\n if (DXGI.DXGIGetDebugInterface1(out IDXGIDebug1 dxgiDebug).Success)\n {\n dxgiDebug.ReportLiveObjects(DXGI.DebugAll, ReportLiveObjectFlags.Summary | ReportLiveObjectFlags.IgnoreInternal);\n dxgiDebug.Dispose();\n }\n } catch { }\n }\n #endif\n\n [StructLayout(LayoutKind.Sequential)]\n struct PSBufferType\n {\n public int coefsIndex;\n public HDRtoSDRMethod hdrmethod;\n\n public float brightness;\n public float contrast;\n\n public float g_luminance;\n public float g_toneP1;\n public float g_toneP2;\n\n public float texWidth;\n }\n\n [StructLayout(LayoutKind.Sequential)]\n struct VSBufferType\n {\n public Matrix4x4 mat;\n }\n}\n"], ["/LLPlayer/FlyleafLib/MediaFramework/MediaDevice/VideoDeviceStream.cs", "using System.Collections.Generic;\nusing System.Linq;\nusing System.Reflection;\n\nusing Vortice.MediaFoundation;\n\nnamespace FlyleafLib.MediaFramework.MediaDevice;\n\npublic class VideoDeviceStream : DeviceStreamBase\n{\n public string MajorType { get; }\n public string SubType { get; }\n public int FrameSizeWidth { get; }\n public int FrameSizeHeight { get; }\n public int FrameRate { get; }\n private string FFmpegFormat { get; }\n\n public VideoDeviceStream(string deviceName, Guid majorType, Guid subType, int frameSizeWidth, int frameSizeHeight, int frameRate, int frameRateDenominator) : base(deviceName)\n {\n MajorType = MediaTypeGuids.Video == majorType ? \"Video\" : \"Unknown\";\n SubType = GetPropertyName(subType);\n FrameSizeWidth = frameSizeWidth;\n FrameSizeHeight = frameSizeHeight;\n FrameRate = frameRate / frameRateDenominator;\n FFmpegFormat = GetFFmpegFormat(SubType);\n Url = $\"fmt://dshow?video={DeviceFriendlyName}&video_size={FrameSizeWidth}x{FrameSizeHeight}&framerate={FrameRate}&{FFmpegFormat}\";\n }\n\n private static string GetPropertyName(Guid guid)\n {\n var type = typeof(VideoFormatGuids);\n foreach (var property in type.GetFields(BindingFlags.Public | BindingFlags.Static))\n if (property.FieldType == typeof(Guid))\n {\n object temp = property.GetValue(null);\n if (temp is Guid value)\n if (value == guid)\n return property.Name.ToUpper();\n }\n\n return null;\n }\n private static unsafe string GetFFmpegFormat(string subType)\n {\n switch (subType)\n {\n case \"MJPG\":\n var descriptorPtr = avcodec_descriptor_get(AVCodecID.Mjpeg);\n return $\"vcodec={Utils.BytePtrToStringUTF8(descriptorPtr->name)}\";\n case \"YUY2\":\n return $\"pixel_format={av_get_pix_fmt_name(AVPixelFormat.Yuyv422)}\";\n case \"NV12\":\n return $\"pixel_format={av_get_pix_fmt_name(AVPixelFormat.Nv12)}\";\n default:\n return \"\";\n }\n }\n public override string ToString() => $\"{SubType}, {FrameSizeWidth}x{FrameSizeHeight}, {FrameRate}FPS\";\n\n #region VideoFormatsViaMediaSource\n public static IList GetVideoFormatsForVideoDevice(string friendlyName, string symbolicLink)\n {\n List formatList = new();\n\n using (var mediaSource = GetMediaSourceFromVideoDevice(symbolicLink))\n {\n if (mediaSource == null)\n return null;\n\n using var sourcePresentationDescriptor = mediaSource.CreatePresentationDescriptor();\n int sourceStreamCount = sourcePresentationDescriptor.StreamDescriptorCount;\n\n for (int i = 0; i < sourceStreamCount; i++)\n {\n var guidMajorType = GetMajorMediaTypeFromPresentationDescriptor(sourcePresentationDescriptor, i);\n if (guidMajorType != MediaTypeGuids.Video)\n continue;\n\n sourcePresentationDescriptor.GetStreamDescriptorByIndex(i, out var streamIsSelected, out var videoStreamDescriptor);\n\n using (videoStreamDescriptor)\n {\n if (streamIsSelected == false)\n continue;\n\n using var typeHandler = videoStreamDescriptor.MediaTypeHandler;\n int mediaTypeCount = typeHandler.MediaTypeCount;\n\n for (int mediaTypeId = 0; mediaTypeId < mediaTypeCount; mediaTypeId++)\n using (var workingMediaType = typeHandler.GetMediaTypeByIndex(mediaTypeId))\n {\n var videoFormat = GetVideoFormatFromMediaType(friendlyName, workingMediaType);\n\n if (videoFormat.SubType != \"NV12\") // NV12 is not playable TODO check support for video formats\n formatList.Add(videoFormat);\n }\n }\n }\n }\n\n return formatList.OrderBy(format => format.SubType).ThenBy(format => format.FrameSizeHeight).ThenBy(format => format.FrameRate).ToList();\n }\n\n private static IMFMediaSource GetMediaSourceFromVideoDevice(string symbolicLink)\n {\n using var attributeContainer = MediaFactory.MFCreateAttributes(2);\n attributeContainer.Set(CaptureDeviceAttributeKeys.SourceType, CaptureDeviceAttributeKeys.SourceTypeVidcap);\n attributeContainer.Set(CaptureDeviceAttributeKeys.SourceTypeVidcapSymbolicLink, symbolicLink);\n\n IMFMediaSource ret = null;\n try\n { ret = MediaFactory.MFCreateDeviceSource(attributeContainer); }\n catch (Exception) { }\n\n return ret;\n }\n\n private static Guid GetMajorMediaTypeFromPresentationDescriptor(IMFPresentationDescriptor presentationDescriptor, int streamIndex)\n {\n presentationDescriptor.GetStreamDescriptorByIndex(streamIndex, out _, out var streamDescriptor);\n\n using (streamDescriptor)\n return GetMajorMediaTypeFromStreamDescriptor(streamDescriptor);\n }\n\n private static Guid GetMajorMediaTypeFromStreamDescriptor(IMFStreamDescriptor streamDescriptor)\n {\n using var pHandler = streamDescriptor.MediaTypeHandler;\n var guidMajorType = pHandler.MajorType;\n\n return guidMajorType;\n }\n\n private static VideoDeviceStream GetVideoFormatFromMediaType(string videoDeviceName, IMFMediaType mediaType)\n {\n // MF_MT_MAJOR_TYPE\n // Major type GUID, we return this as human readable text\n var majorType = mediaType.MajorType;\n\n // MF_MT_SUBTYPE\n // Subtype GUID which describes the basic media type, we return this as human readable text\n var subType = mediaType.GetGUID(MediaTypeAttributeKeys.Subtype);\n\n // MF_MT_FRAME_SIZE\n // the Width and height of a video frame, in pixels\n MediaFactory.MFGetAttributeSize(mediaType, MediaTypeAttributeKeys.FrameSize, out uint frameSizeWidth, out uint frameSizeHeight);\n\n // MF_MT_FRAME_RATE\n // The frame rate is expressed as a ratio.The upper 32 bits of the attribute value contain the numerator and the lower 32 bits contain the denominator.\n // For example, if the frame rate is 30 frames per second(fps), the ratio is 30 / 1.If the frame rate is 29.97 fps, the ratio is 30,000 / 1001.\n // we report this back to the user as a decimal\n MediaFactory.MFGetAttributeRatio(mediaType, MediaTypeAttributeKeys.FrameRate, out uint frameRate, out uint frameRateDenominator);\n\n VideoDeviceStream videoFormat = new(videoDeviceName, majorType, subType, (int)frameSizeWidth,\n (int)frameSizeHeight,\n (int)frameRate,\n (int)frameRateDenominator);\n\n return videoFormat;\n }\n #endregion\n}\n"], ["/LLPlayer/LLPlayer/Services/AppActions.cs", "using System.ComponentModel;\nusing System.Diagnostics;\nusing System.IO;\nusing System.Reflection;\nusing System.Windows;\nusing System.Windows.Input;\nusing System.Windows.Media;\nusing FlyleafLib;\nusing FlyleafLib.Controls.WPF;\nusing FlyleafLib.MediaPlayer;\nusing LLPlayer.Extensions;\nusing LLPlayer.Views;\nusing WpfColorFontDialog;\nusing KeyBinding = FlyleafLib.MediaPlayer.KeyBinding;\n\nnamespace LLPlayer.Services;\n\npublic class AppActions\n{\n private readonly Player _player;\n private readonly AppConfig _config;\n private FlyleafHost? _flyleafHost => _player.Host as FlyleafHost;\n private readonly IDialogService _dialogService;\n\n#pragma warning disable CS9264\n public AppActions(Player player, AppConfig config, IDialogService dialogService)\n {\n _player = player;\n _config = config;\n _dialogService = dialogService;\n\n CustomActions = GetCustomActions();\n\n RegisterCustomKeyBindingsAction();\n }\n#pragma warning restore CS9264\n\n private void RegisterCustomKeyBindingsAction()\n {\n // Since the action name is defined in PlayerConfig, get the Action name from there and register delegate.\n foreach (var binding in _player.Config.Player.KeyBindings.Keys)\n {\n if (binding.Action == KeyBindingAction.Custom && !string.IsNullOrEmpty(binding.ActionName))\n {\n if (Enum.TryParse(binding.ActionName, out CustomKeyBindingAction key))\n {\n binding.SetAction(CustomActions[key], binding.IsKeyUp);\n }\n }\n }\n }\n\n public Dictionary CustomActions { get; }\n\n private Dictionary GetCustomActions()\n {\n return new Dictionary\n {\n [CustomKeyBindingAction.OpenNextFile] = CmdOpenNextFile.Execute,\n [CustomKeyBindingAction.OpenPrevFile] = CmdOpenPrevFile.Execute,\n [CustomKeyBindingAction.OpenCurrentPath] = CmdOpenCurrentPath.Execute,\n\n [CustomKeyBindingAction.SubsPositionUp] = CmdSubsPositionUp.Execute,\n [CustomKeyBindingAction.SubsPositionDown] = CmdSubsPositionDown.Execute,\n [CustomKeyBindingAction.SubsSizeIncrease] = CmdSubsSizeIncrease.Execute,\n [CustomKeyBindingAction.SubsSizeDecrease] = CmdSubsSizeDecrease.Execute,\n [CustomKeyBindingAction.SubsPrimarySizeIncrease] = CmdSubsPrimarySizeIncrease.Execute,\n [CustomKeyBindingAction.SubsPrimarySizeDecrease] = CmdSubsPrimarySizeDecrease.Execute,\n [CustomKeyBindingAction.SubsSecondarySizeIncrease] = CmdSubsSecondarySizeIncrease.Execute,\n [CustomKeyBindingAction.SubsSecondarySizeDecrease] = CmdSubsSecondarySizeDecrease.Execute,\n [CustomKeyBindingAction.SubsDistanceIncrease] = CmdSubsDistanceIncrease.Execute,\n [CustomKeyBindingAction.SubsDistanceDecrease] = CmdSubsDistanceDecrease.Execute,\n\n [CustomKeyBindingAction.SubsTextCopy] = () => CmdSubsTextCopy.Execute(false),\n [CustomKeyBindingAction.SubsPrimaryTextCopy] = () => CmdSubsPrimaryTextCopy.Execute(false),\n [CustomKeyBindingAction.SubsSecondaryTextCopy] = () => CmdSubsSecondaryTextCopy.Execute(false),\n [CustomKeyBindingAction.ToggleSubsAutoTextCopy] = CmdToggleSubsAutoTextCopy.Execute,\n [CustomKeyBindingAction.ToggleSidebarShowSecondary] = CmdToggleSidebarShowSecondary.Execute,\n [CustomKeyBindingAction.ToggleSidebarShowOriginalText] = CmdToggleSidebarShowOriginalText.Execute,\n [CustomKeyBindingAction.ActivateSubsSearch] = CmdActivateSubsSearch.Execute,\n\n [CustomKeyBindingAction.ToggleSidebar] = CmdToggleSidebar.Execute,\n [CustomKeyBindingAction.ToggleDebugOverlay] = CmdToggleDebugOverlay.Execute,\n [CustomKeyBindingAction.ToggleAlwaysOnTop] = CmdToggleAlwaysOnTop.Execute,\n\n [CustomKeyBindingAction.OpenWindowSettings] = CmdOpenWindowSettings.Execute,\n [CustomKeyBindingAction.OpenWindowSubsDownloader] = CmdOpenWindowSubsDownloader.Execute,\n [CustomKeyBindingAction.OpenWindowSubsExporter] = CmdOpenWindowSubsExporter.Execute,\n [CustomKeyBindingAction.OpenWindowCheatSheet] = CmdOpenWindowCheatSheet.Execute,\n\n [CustomKeyBindingAction.AppNew] = CmdAppNew.Execute,\n [CustomKeyBindingAction.AppClone] = CmdAppClone.Execute,\n [CustomKeyBindingAction.AppRestart] = CmdAppRestart.Execute,\n [CustomKeyBindingAction.AppExit] = CmdAppExit.Execute,\n };\n }\n\n public static List DefaultCustomActionsMap()\n {\n return\n [\n new() { ActionName = nameof(CustomKeyBindingAction.OpenNextFile), Key = Key.Right, Alt = true, Shift = true, IsKeyUp = true },\n new() { ActionName = nameof(CustomKeyBindingAction.OpenPrevFile), Key = Key.Left, Alt = true, Shift = true, IsKeyUp = true },\n new() { ActionName = nameof(CustomKeyBindingAction.SubsPositionUp), Key = Key.Up, Shift = true },\n new() { ActionName = nameof(CustomKeyBindingAction.SubsPositionDown), Key = Key.Down, Shift = true },\n new() { ActionName = nameof(CustomKeyBindingAction.SubsSizeIncrease), Key = Key.Right, Shift = true },\n new() { ActionName = nameof(CustomKeyBindingAction.SubsSizeDecrease), Key = Key.Left, Shift = true },\n new() { ActionName = nameof(CustomKeyBindingAction.SubsSecondarySizeIncrease), Key = Key.Right, Ctrl = true, Shift = true },\n new() { ActionName = nameof(CustomKeyBindingAction.SubsSecondarySizeDecrease), Key = Key.Left, Ctrl = true, Shift = true },\n new() { ActionName = nameof(CustomKeyBindingAction.SubsDistanceIncrease), Key = Key.Up, Ctrl = true, Shift = true },\n new() { ActionName = nameof(CustomKeyBindingAction.SubsDistanceDecrease), Key = Key.Down, Ctrl = true, Shift = true },\n new() { ActionName = nameof(CustomKeyBindingAction.SubsPrimaryTextCopy), Key = Key.C, Ctrl = true, IsKeyUp = true },\n new() { ActionName = nameof(CustomKeyBindingAction.ToggleSubsAutoTextCopy), Key = Key.A, Ctrl = true, IsKeyUp = true },\n new() { ActionName = nameof(CustomKeyBindingAction.ActivateSubsSearch), Key = Key.F, Ctrl = true, IsKeyUp = true },\n new() { ActionName = nameof(CustomKeyBindingAction.ToggleSidebar), Key = Key.B, Ctrl = true, IsKeyUp = true },\n new() { ActionName = nameof(CustomKeyBindingAction.ToggleDebugOverlay), Key = Key.D, Ctrl = true, Shift = true, IsKeyUp = true },\n new() { ActionName = nameof(CustomKeyBindingAction.ToggleAlwaysOnTop), Key = Key.T, Ctrl = true, IsKeyUp = true },\n new() { ActionName = nameof(CustomKeyBindingAction.OpenWindowSettings), Key = Key.OemComma, Ctrl = true, IsKeyUp = true },\n new() { ActionName = nameof(CustomKeyBindingAction.OpenWindowCheatSheet), Key = Key.F1, IsKeyUp = true },\n new() { ActionName = nameof(CustomKeyBindingAction.AppNew), Key = Key.N, Ctrl = true, IsKeyUp = true },\n ];\n }\n\n // ReSharper disable NullCoalescingConditionIsAlwaysNotNullAccordingToAPIContract\n\n #region Command used in key\n\n public DelegateCommand CmdOpenNextFile => field ??= new(() =>\n {\n OpenNextPrevInternal(isNext: true);\n });\n\n public DelegateCommand CmdOpenPrevFile => field ??= new(() =>\n {\n OpenNextPrevInternal(isNext: false);\n });\n\n private void OpenNextPrevInternal(bool isNext)\n {\n var playlist = _player.Playlist;\n if (playlist.Url == null)\n return;\n\n string url = playlist.Url;\n\n try\n {\n (string? prev, string? next) = FileHelper.GetNextAndPreviousFile(url);\n if (isNext && next != null)\n {\n _player.OpenAsync(next);\n }\n else if (!isNext && prev != null)\n {\n _player.OpenAsync(prev);\n }\n }\n catch (Exception ex)\n {\n MessageBox.Show($\"OpenNextPrevFile is failed: {ex.Message}\");\n }\n }\n\n public DelegateCommand CmdOpenCurrentPath => field ??= new(() =>\n {\n var playlist = _player.Playlist;\n if (playlist.Selected == null)\n return;\n\n string url = playlist.Url;\n\n bool isFile = File.Exists(url);\n bool isUrl = url.StartsWith(\"http:\", StringComparison.OrdinalIgnoreCase) ||\n url.StartsWith(\"https:\", StringComparison.OrdinalIgnoreCase);\n\n if (!isFile && !isUrl)\n {\n return;\n }\n\n if (isUrl)\n {\n // fix url\n url = playlist.Selected.DirectUrl;\n }\n\n // Open folder or URL\n string? fileName = isFile ? Path.GetDirectoryName(url) : url;\n\n Process.Start(new ProcessStartInfo\n {\n FileName = fileName,\n UseShellExecute = true,\n Verb = \"open\"\n });\n });\n\n public DelegateCommand CmdSubsPositionUp => field ??= new(() =>\n {\n SubsPositionUpActionInternal(true);\n });\n\n public DelegateCommand CmdSubsPositionDown => field ??= new(() =>\n {\n SubsPositionUpActionInternal(false);\n });\n\n public DelegateCommand CmdSubsSizeIncrease => field ??= new(() =>\n {\n SubsSizeActionInternal(SubsSizeActionType.All, increase: true);\n });\n\n public DelegateCommand CmdSubsSizeDecrease => field ??= new(() =>\n {\n SubsSizeActionInternal(SubsSizeActionType.All, increase: false);\n });\n\n public DelegateCommand CmdSubsPrimarySizeIncrease => field ??= new(() =>\n {\n SubsSizeActionInternal(SubsSizeActionType.Primary, increase: true);\n });\n\n public DelegateCommand CmdSubsPrimarySizeDecrease => field ??= new(() =>\n {\n SubsSizeActionInternal(SubsSizeActionType.Primary, increase: false);\n });\n\n public DelegateCommand CmdSubsSecondarySizeIncrease => field ??= new(() =>\n {\n SubsSizeActionInternal(SubsSizeActionType.Secondary, increase: true);\n });\n\n public DelegateCommand CmdSubsSecondarySizeDecrease => field ??= new(() =>\n {\n SubsSizeActionInternal(SubsSizeActionType.Secondary, increase: false);\n });\n\n private void SubsSizeActionInternal(SubsSizeActionType type, bool increase)\n {\n var primary = _player.Subtitles[0];\n var secondary = _player.Subtitles[1];\n\n if (type is SubsSizeActionType.All or SubsSizeActionType.Primary)\n {\n // TODO: L: Match scaling ratios in text and bitmap subtitles\n if (primary.Enabled && (!primary.IsBitmap || !string.IsNullOrEmpty(primary.Data.Text)))\n {\n _config.Subs.SubsFontSize += _config.Subs.SubsFontSizeOffset * (increase ? 1 : -1);\n }\n else if (primary.Enabled && primary.IsBitmap)\n {\n _player.Subtitles[0].Data.BitmapPosition.ConfScale += _config.Subs.SubsBitmapScaleOffset / 100.0 * (increase ? 1.0 : -1.0);\n }\n }\n\n if (type is SubsSizeActionType.All or SubsSizeActionType.Secondary)\n {\n if (secondary.Enabled && (!secondary.IsBitmap || !string.IsNullOrEmpty(secondary.Data.Text)))\n {\n _config.Subs.SubsFontSize2 += _config.Subs.SubsFontSizeOffset * (increase ? 1 : -1);\n }\n else if (secondary.Enabled && secondary.IsBitmap)\n {\n _player.Subtitles[1].Data.BitmapPosition.ConfScale += _config.Subs.SubsBitmapScaleOffset / 100.0 * (increase ? 1.0 : -1.0);\n }\n }\n }\n\n public DelegateCommand CmdSubsDistanceIncrease => field ??= new(() =>\n {\n SubsDistanceActionInternal(true);\n });\n\n public DelegateCommand CmdSubsDistanceDecrease => field ??= new(() =>\n {\n SubsDistanceActionInternal(false);\n });\n\n private void SubsDistanceActionInternal(bool increase)\n {\n _config.Subs.SubsDistance += _config.Subs.SubsDistanceOffset * (increase ? 1 : -1);\n }\n\n public DelegateCommand CmdSubsTextCopy => field ??= new((suppressOsd) =>\n {\n if (!_player.Subtitles[0].Enabled && !_player.Subtitles[1].Enabled)\n {\n return;\n }\n\n string text = _player.Subtitles[0].Data.Text;\n if (!string.IsNullOrEmpty(_player.Subtitles[1].Data.Text))\n {\n text += Environment.NewLine + \"( \" + _player.Subtitles[1].Data.Text + \" )\";\n }\n\n if (!string.IsNullOrEmpty(text))\n {\n try\n {\n WindowsClipboard.SetText(text);\n if (!suppressOsd.HasValue || !suppressOsd.Value)\n {\n _player.OSDMessage = \"Copy All Subtitle Text\";\n }\n }\n catch\n {\n // ignored\n }\n }\n });\n\n public DelegateCommand CmdSubsPrimaryTextCopy => field ??= new((suppressOsd) =>\n {\n SubsTextCopyInternal(0, suppressOsd);\n });\n\n public DelegateCommand CmdSubsSecondaryTextCopy => field ??= new((suppressOsd) =>\n {\n SubsTextCopyInternal(1, suppressOsd);\n });\n\n private void SubsTextCopyInternal(int subIndex, bool? suppressOsd)\n {\n if (!_player.Subtitles[subIndex].Enabled)\n {\n return;\n }\n\n string text = _player.Subtitles[subIndex].Data.Text;\n\n if (!string.IsNullOrEmpty(text))\n {\n try\n {\n WindowsClipboard.SetText(text);\n if (!suppressOsd.HasValue || !suppressOsd.Value)\n {\n _player.OSDMessage = $\"Copy {(subIndex == 0 ? \"Primary\" : \"Secondary\")} Subtitle Text\";\n }\n }\n catch\n {\n // ignored\n }\n }\n }\n\n public DelegateCommand CmdToggleSubsAutoTextCopy => field ??= new(() =>\n {\n _config.Subs.SubsAutoTextCopy = !_config.Subs.SubsAutoTextCopy;\n });\n\n public DelegateCommand CmdActivateSubsSearch => field ??= new(() =>\n {\n if (_flyleafHost is { IsFullScreen: true })\n {\n return;\n }\n\n _config.ShowSidebar = true;\n\n // for getting focus to TextBox\n _config.SidebarSearchActive = false;\n _config.SidebarSearchActive = true;\n });\n\n public DelegateCommand CmdToggleSidebarShowSecondary => field ??= new(() =>\n {\n _config.SidebarShowSecondary = !_config.SidebarShowSecondary;\n });\n\n public DelegateCommand CmdToggleSidebarShowOriginalText => field ??= new(() =>\n {\n _config.SidebarShowOriginalText = !_config.SidebarShowOriginalText;\n });\n\n public DelegateCommand CmdToggleSidebar => field ??= new(() =>\n {\n _config.ShowSidebar = !_config.ShowSidebar;\n });\n\n public DelegateCommand CmdToggleDebugOverlay => field ??= new(() =>\n {\n _config.ShowDebug = !_config.ShowDebug;\n });\n\n public DelegateCommand CmdToggleAlwaysOnTop => field ??= new(() =>\n {\n _config.AlwaysOnTop = !_config.AlwaysOnTop;\n });\n\n public DelegateCommand CmdOpenWindowSettings => field ??= new(() =>\n {\n if (_player.IsPlaying)\n {\n _player.Pause();\n }\n\n // Detects configuration changes necessary for restart\n // TODO: L: refactor\n bool requiredRestart = false;\n\n _config.PropertyChanged += ConfigOnPropertyChanged;\n _player.Config.Subtitles.WhisperCppConfig.PropertyChanged += ConfigOnPropertyChanged;\n\n void ConfigOnPropertyChanged(object? sender, PropertyChangedEventArgs e)\n {\n switch (e.PropertyName)\n {\n case nameof(_config.IsDarkTitlebar):\n case nameof(_player.Config.Subtitles.WhisperCppConfig.RuntimeLibraries):\n requiredRestart = true;\n break;\n }\n }\n\n _player.Activity.ForceFullActive();\n _dialogService.ShowSingleton(nameof(SettingsDialog), result =>\n {\n // Activate as it may be minimized for some reason\n if (!Application.Current.MainWindow!.IsActive)\n {\n Application.Current.MainWindow!.Activate();\n }\n\n _config.PropertyChanged -= ConfigOnPropertyChanged;\n _player.Config.Subtitles.WhisperCppConfig.PropertyChanged += ConfigOnPropertyChanged;\n\n if (result.Result == ButtonResult.OK)\n {\n SaveAllConfig();\n\n if (requiredRestart)\n {\n // Show confirmation dialog\n MessageBoxResult confirm = MessageBox.Show(\n \"A restart is required for the settings to take effect. Do you want to restart?\",\n \"Confirm to restart\",\n MessageBoxButton.YesNo,\n MessageBoxImage.Question\n );\n\n if (confirm == MessageBoxResult.Yes)\n {\n CmdAppRestart.Execute();\n }\n }\n }\n }, false);\n });\n\n public DelegateCommand CmdOpenWindowSubsDownloader => field ??= new(() =>\n {\n _player.Activity.ForceFullActive();\n _dialogService.ShowSingleton(nameof(SubtitlesDownloaderDialog), true);\n });\n\n public DelegateCommand CmdOpenWindowSubsExporter => field ??= new(() =>\n {\n _player.Activity.ForceFullActive();\n _dialogService.ShowSingleton(nameof(SubtitlesExportDialog), _ =>\n {\n // Activate as it may be minimized for some reason\n if (!Application.Current.MainWindow!.IsActive)\n {\n Application.Current.MainWindow!.Activate();\n }\n }, false);\n });\n\n public DelegateCommand CmdOpenWindowCheatSheet => field ??= new(() =>\n {\n _player.Activity.ForceFullActive();\n _dialogService.ShowSingleton(nameof(CheatSheetDialog), true);\n });\n\n public DelegateCommand CmdAppNew => field ??= new(() =>\n {\n string exePath = Process.GetCurrentProcess().MainModule!.FileName;\n Process.Start(exePath);\n });\n\n public DelegateCommand CmdAppClone => field ??= new(() =>\n {\n string exePath = Process.GetCurrentProcess().MainModule!.FileName;\n\n ProcessStartInfo startInfo = new()\n {\n FileName = exePath,\n UseShellExecute = false\n };\n\n // Launch New App with current url if opened\n var prevPlaylist = _player.Playlist.Selected;\n if (prevPlaylist != null)\n {\n startInfo.ArgumentList.Add(prevPlaylist.DirectUrl);\n }\n\n Process.Start(startInfo);\n });\n\n public DelegateCommand CmdAppRestart => field ??= new(() =>\n {\n // Clone\n CmdAppClone.Execute();\n\n // Exit\n CmdAppExit.Execute();\n });\n\n public DelegateCommand CmdAppExit => field ??= new(() =>\n {\n Application.Current.Shutdown();\n });\n #endregion\n\n #region Command not used in key\n private static FontWeightConverter _fontWeightConv = new();\n private static FontStyleConverter _fontStyleConv = new();\n private static FontStretchConverter _fontStretchConv = new();\n\n public DelegateCommand CmdSetSubtitlesFont => field ??= new(() =>\n {\n ColorFontDialog dialog = new();\n\n dialog.Topmost = _config.AlwaysOnTop;\n dialog.Font = new FontInfo(new FontFamily(_config.Subs.SubsFontFamily), _config.Subs.SubsFontSize, (FontStyle)_fontStyleConv.ConvertFromString(_config.Subs.SubsFontStyle)!, (FontStretch)_fontStretchConv.ConvertFromString(_config.Subs.SubsFontStretch)!, (FontWeight)_fontWeightConv.ConvertFromString(_config.Subs.SubsFontWeight)!, new SolidColorBrush(Colors.Black));\n\n _player.Activity.ForceFullActive();\n\n double prevFontSize = dialog.Font.Size;\n\n if (dialog.ShowDialog() == true && dialog.Font != null)\n {\n _config.Subs.SubsFontFamily = dialog.Font.Family.ToString();\n _config.Subs.SubsFontWeight = dialog.Font.Weight.ToString();\n _config.Subs.SubsFontStretch = dialog.Font.Stretch.ToString();\n _config.Subs.SubsFontStyle = dialog.Font.Style.ToString();\n\n if (prevFontSize != dialog.Font.Size)\n {\n _config.Subs.SubsFontSize = dialog.Font.Size;\n _config.Subs.SubsFontSize2 = dialog.Font.Size; // change secondary as well\n }\n\n // update display of secondary subtitles\n _config.Subs.UpdateSecondaryFonts();\n }\n });\n\n public DelegateCommand CmdSetSubtitlesFont2 => field ??= new(() =>\n {\n ColorFontDialog dialog = new();\n\n dialog.Topmost = _config.AlwaysOnTop;\n dialog.Font = new FontInfo(new FontFamily(_config.Subs.SubsFontFamily2), _config.Subs.SubsFontSize2, (FontStyle)_fontStyleConv.ConvertFromString(_config.Subs.SubsFontStyle2)!, (FontStretch)_fontStretchConv.ConvertFromString(_config.Subs.SubsFontStretch2)!, (FontWeight)_fontWeightConv.ConvertFromString(_config.Subs.SubsFontWeight2)!, new SolidColorBrush(Colors.Black));\n\n _player.Activity.ForceFullActive();\n\n if (dialog.ShowDialog() == true && dialog.Font != null)\n {\n _config.Subs.SubsFontFamily2 = dialog.Font.Family.ToString();\n _config.Subs.SubsFontWeight2 = dialog.Font.Weight.ToString();\n _config.Subs.SubsFontStretch2 = dialog.Font.Stretch.ToString();\n _config.Subs.SubsFontStyle2 = dialog.Font.Style.ToString();\n\n _config.Subs.SubsFontSize2 = dialog.Font.Size;\n\n // update display of secondary subtitles\n _config.Subs.UpdateSecondaryFonts();\n }\n });\n\n public DelegateCommand CmdSetSubtitlesFontSidebar => field ??= new(() =>\n {\n ColorFontDialog dialog = new();\n\n dialog.Topmost = _config.AlwaysOnTop;\n dialog.Font = new FontInfo(new FontFamily(_config.SidebarFontFamily), _config.SidebarFontSize, FontStyles.Normal, FontStretches.Normal, (FontWeight)_fontWeightConv.ConvertFromString(_config.SidebarFontWeight)!, new SolidColorBrush(Colors.Black));\n\n _player.Activity.ForceFullActive();\n\n if (dialog.ShowDialog() == true && dialog.Font != null)\n {\n _config.SidebarFontFamily = dialog.Font.Family.ToString();\n _config.SidebarFontSize = dialog.Font.Size;\n _config.SidebarFontWeight = dialog.Font.Weight.ToString();\n }\n });\n\n public DelegateCommand CmdResetSubsPosition => field ??= new(() =>\n {\n // TODO: L: Reset bitmap as well\n _config.Subs.ResetSubsPosition();\n });\n\n public DelegateCommand CmdChangeAspectRatio => field ??= new((ratio) =>\n {\n if (!ratio.HasValue)\n return;\n\n _player.Config.Video.AspectRatio = ratio.Value;\n });\n\n public DelegateCommand CmdSetSubPositionAlignment => field ??= new((alignment) =>\n {\n if (!alignment.HasValue)\n return;\n\n _config.Subs.SubsPositionAlignment = alignment.Value;\n });\n\n public DelegateCommand CmdSetSubPositionAlignmentWhenDual => field ??= new((alignment) =>\n {\n if (!alignment.HasValue)\n return;\n\n _config.Subs.SubsPositionAlignmentWhenDual = alignment.Value;\n });\n\n #endregion\n\n // ReSharper restore NullCoalescingConditionIsAlwaysNotNullAccordingToAPIContract\n\n // TODO: L: make it command?\n public void SaveAllConfig()\n {\n _config.Save(App.AppConfigPath);\n\n var opts = AppConfig.GetJsonSerializerOptions();\n _player.Config.Version = App.Version;\n _player.Config.Save(App.PlayerConfigPath, opts);\n\n Engine.Config.Version = App.Version;\n Engine.Config.Save(App.EngineConfigPath, opts);\n }\n\n private enum SubsSizeActionType\n {\n All,\n Primary,\n Secondary\n }\n\n private void SubsPositionUpActionInternal(bool up)\n {\n var primary = _player.Subtitles[0];\n var secondary = _player.Subtitles[1];\n\n bool bothEnabled = primary.Enabled && secondary.Enabled;\n\n if (bothEnabled || // both enabled\n primary.Enabled && !primary.IsBitmap || // When text subtitles are enabled\n secondary.Enabled && !secondary.IsBitmap || !string.IsNullOrEmpty(primary.Data.Text) || // If OCR subtitles are available\n !string.IsNullOrEmpty(secondary.Data.Text))\n {\n _config.Subs.SubsPosition += _config.Subs.SubsPositionOffset * (up ? -1 : 1);\n }\n else if (primary.IsBitmap || secondary.IsBitmap)\n {\n // For bitmap subtitles (absolute position)\n for (int i = 0; i < _player.Config.Subtitles.Max; i++)\n {\n _player.Subtitles[i].Data.BitmapPosition.ConfPos += _config.Subs.SubsPositionOffset * (up ? -1 : 1);\n }\n }\n }\n}\n\n// List of key actions to be added from the app side\npublic enum CustomKeyBindingAction\n{\n [Description(\"Open Next File\")]\n OpenNextFile,\n [Description(\"Open Previous File\")]\n OpenPrevFile,\n [Description(\"Open Folder or URL of the currently opened file\")]\n OpenCurrentPath,\n\n [Description(\"Subtitles Position Up\")]\n SubsPositionUp,\n [Description(\"Subtitles Position Down\")]\n SubsPositionDown,\n [Description(\"Subtitles Size Increase\")]\n SubsSizeIncrease,\n [Description(\"Subtitles Size Decrease\")]\n SubsSizeDecrease,\n [Description(\"Primary Subtitles Size Increase\")]\n SubsPrimarySizeIncrease,\n [Description(\"Primary Subtitles Size Decrease\")]\n SubsPrimarySizeDecrease,\n [Description(\"Secondary Subtitles Size Increase\")]\n SubsSecondarySizeIncrease,\n [Description(\"Secondary Subtitles Size Decrease\")]\n SubsSecondarySizeDecrease,\n [Description(\"Primary/Secondary Subtitles Distance Increase\")]\n SubsDistanceIncrease,\n [Description(\"Primary/Secondary Subtitles Distance Decrease\")]\n SubsDistanceDecrease,\n\n [Description(\"Copy All Subtiltes Text\")]\n SubsTextCopy,\n [Description(\"Copy Primary Subtiltes Text\")]\n SubsPrimaryTextCopy,\n [Description(\"Copy Secondary Subtiltes Text\")]\n SubsSecondaryTextCopy,\n [Description(\"Toggle Auto Subtitles Text Copy\")]\n ToggleSubsAutoTextCopy,\n\n [Description(\"Toggle Primary / Secondary in Subtitles Sidebar\")]\n ToggleSidebarShowSecondary,\n [Description(\"Toggle to show original text in Subtitles Sidebar\")]\n ToggleSidebarShowOriginalText,\n [Description(\"Activate Subtitles Search in Sidebar\")]\n ActivateSubsSearch,\n\n [Description(\"Toggle Subitltes Sidebar\")]\n ToggleSidebar,\n [Description(\"Toggle Debug Overlay\")]\n ToggleDebugOverlay,\n [Description(\"Toggle Always On Top\")]\n ToggleAlwaysOnTop,\n\n [Description(\"Open Settings Window\")]\n OpenWindowSettings,\n [Description(\"Open Subtitles Downloader Window\")]\n OpenWindowSubsDownloader,\n [Description(\"Open Subtitles Exporter Window\")]\n OpenWindowSubsExporter,\n [Description(\"Open Cheat Sheet Window\")]\n OpenWindowCheatSheet,\n\n [Description(\"Launch New Application\")]\n AppNew,\n [Description(\"Launch Clone Application\")]\n AppClone,\n [Description(\"Restart Application\")]\n AppRestart,\n [Description(\"Exit Application\")]\n AppExit,\n}\n\npublic enum KeyBindingActionGroup\n{\n Playback,\n Player,\n Audio,\n Video,\n Subtitles,\n SubtitlesPosition,\n Window,\n Other\n}\n\npublic static class KeyBindingActionExtensions\n{\n public static string ToString(this KeyBindingActionGroup group)\n {\n var str = group.ToString();\n if (group == KeyBindingActionGroup.SubtitlesPosition)\n {\n str = \"Subtitles Position\";\n }\n\n return str;\n }\n\n public static KeyBindingActionGroup ToGroup(this CustomKeyBindingAction action)\n {\n switch (action)\n {\n case CustomKeyBindingAction.OpenNextFile:\n case CustomKeyBindingAction.OpenPrevFile:\n case CustomKeyBindingAction.OpenCurrentPath:\n return KeyBindingActionGroup.Player; // TODO: L: ?\n\n case CustomKeyBindingAction.SubsPositionUp:\n case CustomKeyBindingAction.SubsPositionDown:\n case CustomKeyBindingAction.SubsSizeIncrease:\n case CustomKeyBindingAction.SubsSizeDecrease:\n case CustomKeyBindingAction.SubsPrimarySizeIncrease:\n case CustomKeyBindingAction.SubsPrimarySizeDecrease:\n case CustomKeyBindingAction.SubsSecondarySizeIncrease:\n case CustomKeyBindingAction.SubsSecondarySizeDecrease:\n case CustomKeyBindingAction.SubsDistanceIncrease:\n case CustomKeyBindingAction.SubsDistanceDecrease:\n return KeyBindingActionGroup.SubtitlesPosition;\n\n case CustomKeyBindingAction.SubsTextCopy:\n case CustomKeyBindingAction.SubsPrimaryTextCopy:\n case CustomKeyBindingAction.SubsSecondaryTextCopy:\n case CustomKeyBindingAction.ToggleSubsAutoTextCopy:\n case CustomKeyBindingAction.ToggleSidebarShowSecondary:\n case CustomKeyBindingAction.ToggleSidebarShowOriginalText:\n case CustomKeyBindingAction.ActivateSubsSearch:\n return KeyBindingActionGroup.Subtitles;\n\n case CustomKeyBindingAction.ToggleSidebar:\n case CustomKeyBindingAction.ToggleDebugOverlay:\n case CustomKeyBindingAction.ToggleAlwaysOnTop:\n case CustomKeyBindingAction.OpenWindowSettings:\n case CustomKeyBindingAction.OpenWindowSubsDownloader:\n case CustomKeyBindingAction.OpenWindowSubsExporter:\n case CustomKeyBindingAction.OpenWindowCheatSheet:\n return KeyBindingActionGroup.Window;\n\n // TODO: L: review group\n case CustomKeyBindingAction.AppNew:\n case CustomKeyBindingAction.AppClone:\n case CustomKeyBindingAction.AppRestart:\n case CustomKeyBindingAction.AppExit:\n return KeyBindingActionGroup.Other;\n\n default:\n return KeyBindingActionGroup.Other;\n }\n }\n\n public static KeyBindingActionGroup ToGroup(this KeyBindingAction action)\n {\n switch (action)\n {\n // TODO: L: review order and grouping\n case KeyBindingAction.ForceIdle:\n case KeyBindingAction.ForceActive:\n case KeyBindingAction.ForceFullActive:\n return KeyBindingActionGroup.Player;\n\n case KeyBindingAction.AudioDelayAdd:\n case KeyBindingAction.AudioDelayAdd2:\n case KeyBindingAction.AudioDelayRemove:\n case KeyBindingAction.AudioDelayRemove2:\n case KeyBindingAction.ToggleAudio:\n case KeyBindingAction.ToggleMute:\n case KeyBindingAction.VolumeUp:\n case KeyBindingAction.VolumeDown:\n return KeyBindingActionGroup.Audio;\n\n case KeyBindingAction.SubsDelayAddPrimary:\n case KeyBindingAction.SubsDelayAdd2Primary:\n case KeyBindingAction.SubsDelayRemovePrimary:\n case KeyBindingAction.SubsDelayRemove2Primary:\n case KeyBindingAction.SubsDelayAddSecondary:\n case KeyBindingAction.SubsDelayAdd2Secondary:\n case KeyBindingAction.SubsDelayRemoveSecondary:\n case KeyBindingAction.SubsDelayRemove2Secondary:\n return KeyBindingActionGroup.SubtitlesPosition;\n case KeyBindingAction.ToggleSubtitlesVisibility:\n case KeyBindingAction.ToggleSubtitlesVisibilityPrimary:\n case KeyBindingAction.ToggleSubtitlesVisibilitySecondary:\n return KeyBindingActionGroup.Subtitles;\n\n case KeyBindingAction.CopyToClipboard:\n case KeyBindingAction.CopyItemToClipboard:\n return KeyBindingActionGroup.Other; // TODO: L: ?\n\n case KeyBindingAction.OpenFromClipboard:\n case KeyBindingAction.OpenFromClipboardSafe:\n case KeyBindingAction.OpenFromFileDialog:\n return KeyBindingActionGroup.Player; // TODO: L: ?\n\n case KeyBindingAction.Stop:\n case KeyBindingAction.Pause:\n case KeyBindingAction.Play:\n case KeyBindingAction.TogglePlayPause:\n case KeyBindingAction.ToggleReversePlayback:\n case KeyBindingAction.ToggleLoopPlayback:\n case KeyBindingAction.SeekForward:\n case KeyBindingAction.SeekBackward:\n case KeyBindingAction.SeekForward2:\n case KeyBindingAction.SeekBackward2:\n case KeyBindingAction.SeekForward3:\n case KeyBindingAction.SeekBackward3:\n case KeyBindingAction.SeekForward4:\n case KeyBindingAction.SeekBackward4:\n return KeyBindingActionGroup.Playback;\n\n case KeyBindingAction.Flush:\n case KeyBindingAction.NormalScreen:\n case KeyBindingAction.FullScreen:\n case KeyBindingAction.ToggleFullScreen:\n return KeyBindingActionGroup.Player;\n\n case KeyBindingAction.ToggleVideo:\n case KeyBindingAction.ToggleKeepRatio:\n case KeyBindingAction.ToggleVideoAcceleration:\n case KeyBindingAction.TakeSnapshot:\n case KeyBindingAction.ToggleRecording:\n return KeyBindingActionGroup.Video;\n\n case KeyBindingAction.SubsPrevSeek:\n case KeyBindingAction.SubsCurSeek:\n case KeyBindingAction.SubsNextSeek:\n case KeyBindingAction.SubsPrevSeekFallback:\n case KeyBindingAction.SubsNextSeekFallback:\n case KeyBindingAction.SubsPrevSeek2:\n case KeyBindingAction.SubsCurSeek2:\n case KeyBindingAction.SubsNextSeek2:\n case KeyBindingAction.SubsPrevSeekFallback2:\n case KeyBindingAction.SubsNextSeekFallback2:\n return KeyBindingActionGroup.Subtitles;\n\n case KeyBindingAction.ShowNextFrame:\n case KeyBindingAction.ShowPrevFrame:\n case KeyBindingAction.SpeedAdd:\n case KeyBindingAction.SpeedAdd2:\n case KeyBindingAction.SpeedRemove:\n case KeyBindingAction.SpeedRemove2:\n case KeyBindingAction.ToggleSeekAccurate:\n return KeyBindingActionGroup.Playback;\n\n case KeyBindingAction.ResetAll:\n case KeyBindingAction.ResetSpeed:\n case KeyBindingAction.ResetRotation:\n case KeyBindingAction.ResetZoom:\n case KeyBindingAction.ZoomIn:\n case KeyBindingAction.ZoomOut:\n return KeyBindingActionGroup.Player;\n\n default:\n return KeyBindingActionGroup.Other;\n }\n }\n\n /// \n /// Gets the value of the Description attribute assigned to the Enum member.\n /// \n /// \n /// \n public static string GetDescription(this Enum value)\n {\n ArgumentNullException.ThrowIfNull(value);\n\n Type type = value.GetType();\n\n string name = value.ToString();\n\n MemberInfo[] member = type.GetMember(name);\n\n if (member.Length > 0)\n {\n if (Attribute.GetCustomAttribute(member[0], typeof(DescriptionAttribute)) is DescriptionAttribute attr)\n {\n return attr.Description;\n }\n }\n\n return name;\n }\n}\n"], ["/LLPlayer/FlyleafLib/Engine/Language.cs", "using System.Collections.Generic;\nusing System.Globalization;\nusing System.Linq;\nusing System.Text.Json.Serialization;\n\nnamespace FlyleafLib;\n\npublic class Language : IEquatable\n{\n public string CultureName { get => _CultureName; set\n { // Required for XML load\n Culture = CultureInfo.GetCultureInfo(value);\n Refresh(this);\n }\n }\n string _CultureName;\n\n [JsonIgnore]\n public string TopEnglishName { get; private set; }\n [JsonIgnore]\n public string TopNativeName { get; private set; }\n\n [JsonIgnore]\n public CultureInfo Culture { get; private set; }\n\n [JsonIgnore]\n public CultureInfo TopCulture { get; private set; }\n [JsonIgnore]\n public string DisplayName => $\"{TopEnglishName} ({TopNativeName})\";\n\n [JsonIgnore]\n public string ISO6391 { get; private set; }\n\n [JsonIgnore]\n public string IdSubLanguage { get; private set; } // Can search for online subtitles with this id\n\n [JsonIgnore]\n public string OriginalInput { get; private set; } // Only for Undetermined language (return clone)\n\n [JsonIgnore]\n public bool IsRTL { get; private set; }\n\n public override string ToString() => OriginalInput ?? TopEnglishName;\n\n public override int GetHashCode() => ToString().GetHashCode();\n\n public override bool Equals(object obj) => Equals(obj as Language);\n\n public bool Equals(Language lang)\n {\n if (lang is null)\n return false;\n\n if (ReferenceEquals(this, lang))\n return true;\n\n if (lang.Culture == null && Culture == null)\n {\n if (OriginalInput != null || lang.OriginalInput != null)\n return OriginalInput == lang.OriginalInput;\n\n return true; // und\n }\n\n return lang.IdSubLanguage == IdSubLanguage; // TBR: top level will be equal with lower\n }\n\n public static bool operator ==(Language lang1, Language lang2) => lang1 is null ? lang2 is null ? true : false : lang1.Equals(lang2);\n\n public static bool operator !=(Language lang1, Language lang2) => !(lang1 == lang2);\n\n private static readonly HashSet RTLCodes =\n [\n \"ae\",\n \"ar\",\n \"dv\",\n \"fa\",\n \"ha\",\n \"he\",\n \"ks\",\n \"ku\",\n \"ps\",\n \"sd\",\n \"ug\",\n \"ur\",\n \"yi\"\n ];\n\n public static void Refresh(Language lang)\n {\n lang._CultureName = lang.Culture.Name;\n\n lang.TopCulture = lang.Culture;\n while (lang.TopCulture.Parent.Name != \"\")\n lang.TopCulture = lang.TopCulture.Parent;\n\n lang.TopEnglishName = lang.TopCulture.EnglishName;\n lang.TopNativeName = lang.TopCulture.NativeName;\n lang.IdSubLanguage = lang.Culture.ThreeLetterISOLanguageName;\n lang.ISO6391 = lang.Culture.TwoLetterISOLanguageName;\n lang.IsRTL = RTLCodes.Contains(lang.ISO6391);\n }\n\n public static Language Get(CultureInfo cult)\n {\n Language lang = new() { Culture = cult };\n Refresh(lang);\n\n return lang;\n }\n public static Language Get(string name)\n {\n Language lang = new() { Culture = StringToCulture(name) };\n if (lang.Culture != null)\n Refresh(lang);\n else\n {\n lang.IdSubLanguage = \"und\";\n lang.TopEnglishName = \"Unknown\";\n if (name != \"und\")\n lang.OriginalInput = name;\n }\n\n return lang;\n }\n\n public static CultureInfo StringToCulture(string lang)\n {\n if (string.IsNullOrWhiteSpace(lang) || lang.Length < 2 || lang == \"und\")\n return null;\n\n string langLower = lang.ToLower();\n CultureInfo ret = null;\n\n try\n {\n ret = lang.Length == 3 ? ThreeLetterToCulture(langLower) : CultureInfo.GetCultureInfo(langLower);\n } catch { }\n\n StringComparer cmp = StringComparer.OrdinalIgnoreCase;\n\n // TBR: Check also -Country/region two letters?\n if (ret == null || ret.ThreeLetterISOLanguageName == \"\")\n foreach (var cult in CultureInfo.GetCultures(CultureTypes.AllCultures))\n if (cmp.Equals(cult.Name, langLower) || cmp.Equals(cult.NativeName, langLower) || cmp.Equals(cult.EnglishName, langLower))\n return cult;\n\n return ret;\n }\n\n public static CultureInfo ThreeLetterToCulture(string lang)\n {\n if (lang == \"zht\")\n return CultureInfo.GetCultureInfo(\"zh-Hant\");\n else if (lang == \"pob\")\n return CultureInfo.GetCultureInfo(\"pt-BR\");\n else if (lang == \"nor\")\n return CultureInfo.GetCultureInfo(\"nob\");\n else if (lang == \"scc\")\n return CultureInfo.GetCultureInfo(\"srp\");\n else if (lang == \"tgl\")\n return CultureInfo.GetCultureInfo(\"fil\");\n\n CultureInfo ret = CultureInfo.GetCultureInfo(lang);\n\n if (ret.ThreeLetterISOLanguageName == \"\")\n {\n ISO639_2B_TO_2T.TryGetValue(lang, out string iso639_2t);\n if (iso639_2t != null)\n ret = CultureInfo.GetCultureInfo(iso639_2t);\n }\n\n return ret.ThreeLetterISOLanguageName == \"\" ? null : ret;\n }\n\n public static readonly Dictionary ISO639_2T_TO_2B = new()\n {\n { \"bod\",\"tib\" },\n { \"ces\",\"cze\" },\n { \"cym\",\"wel\" },\n { \"deu\",\"ger\" },\n { \"ell\",\"gre\" },\n { \"eus\",\"baq\" },\n { \"fas\",\"per\" },\n { \"fra\",\"fre\" },\n { \"hye\",\"arm\" },\n { \"isl\",\"ice\" },\n { \"kat\",\"geo\" },\n { \"mkd\",\"mac\" },\n { \"mri\",\"mao\" },\n { \"msa\",\"may\" },\n { \"mya\",\"bur\" },\n { \"nld\",\"dut\" },\n { \"ron\",\"rum\" },\n { \"slk\",\"slo\" },\n { \"sqi\",\"alb\" },\n { \"zho\",\"chi\" },\n };\n public static readonly Dictionary ISO639_2B_TO_2T = new()\n {\n { \"alb\",\"sqi\" },\n { \"arm\",\"hye\" },\n { \"baq\",\"eus\" },\n { \"bur\",\"mya\" },\n { \"chi\",\"zho\" },\n { \"cze\",\"ces\" },\n { \"dut\",\"nld\" },\n { \"fre\",\"fra\" },\n { \"geo\",\"kat\" },\n { \"ger\",\"deu\" },\n { \"gre\",\"ell\" },\n { \"ice\",\"isl\" },\n { \"mac\",\"mkd\" },\n { \"mao\",\"mri\" },\n { \"may\",\"msa\" },\n { \"per\",\"fas\" },\n { \"rum\",\"ron\" },\n { \"slo\",\"slk\" },\n { \"tib\",\"bod\" },\n { \"wel\",\"cym\" },\n };\n\n public static Language English = Get(\"eng\");\n public static Language Unknown = Get(\"und\");\n\n public static List AllLanguages\n {\n get\n {\n if (field != null)\n {\n return field;\n }\n\n var neutralCultures = CultureInfo\n .GetCultures(CultureTypes.NeutralCultures)\n .Where(c => !string.IsNullOrEmpty(c.Name));\n\n var uniqueCultures = neutralCultures\n .GroupBy(c => c.ThreeLetterISOLanguageName)\n .Select(g => g.First());\n\n List languages = new();\n foreach (var culture in uniqueCultures)\n {\n languages.Add(Get(culture));\n }\n languages = languages.OrderBy(l => l.TopEnglishName, StringComparer.InvariantCulture).ToList();\n\n field = languages;\n\n return field;\n }\n }\n}\n"], ["/LLPlayer/LLPlayer/Controls/Settings/SettingsSubtitlesASR.xaml.cs", "using System.Collections.ObjectModel;\nusing System.Collections.Specialized;\nusing System.Diagnostics;\nusing System.Globalization;\nusing System.IO;\nusing System.Windows;\nusing System.Windows.Controls;\nusing System.Windows.Data;\nusing CliWrap.Builders;\nusing FlyleafLib;\nusing FlyleafLib.MediaPlayer;\nusing LLPlayer.Extensions;\nusing LLPlayer.Services;\nusing LLPlayer.Views;\nusing Whisper.net.LibraryLoader;\n\nnamespace LLPlayer.Controls.Settings;\n\npublic partial class SettingsSubtitlesASR : UserControl\n{\n public SettingsSubtitlesASR()\n {\n InitializeComponent();\n\n DataContext = ((App)Application.Current).Container.Resolve();\n }\n}\n\npublic class SettingsSubtitlesASRVM : Bindable\n{\n public FlyleafManager FL { get; }\n private readonly IDialogService _dialogService;\n\n public SettingsSubtitlesASRVM(FlyleafManager fl, IDialogService dialogService)\n {\n FL = fl;\n _dialogService = dialogService;\n\n LoadDownloadedModels();\n\n foreach (RuntimeLibrary library in FL.PlayerConfig.Subtitles.WhisperCppConfig.RuntimeLibraries)\n {\n SelectedLibraries.Add(library);\n }\n\n foreach (RuntimeLibrary library in Enum.GetValues().Where(l => l != RuntimeLibrary.CoreML))\n {\n if (!SelectedLibraries.Contains(library))\n {\n AvailableLibraries.Add(library);\n }\n }\n SelectedLibraries.CollectionChanged += SelectedLibrariesOnCollectionChanged;\n\n foreach (WhisperLanguage lang in WhisperLanguage.GetWhisperLanguages())\n {\n WhisperLanguages.Add(lang);\n }\n\n ActiveEngineTabNo = (int)FL.PlayerConfig.Subtitles.ASREngine;\n }\n\n public int ActiveEngineTabNo { get; }\n\n public ObservableCollection WhisperLanguages { get; } = new();\n\n #region whisper.cpp\n public ObservableCollection AvailableLibraries { get; } = new();\n public ObservableCollection SelectedLibraries { get; } = new();\n\n public RuntimeLibrary? SelectedAvailable\n {\n get;\n set\n {\n if (Set(ref field, value))\n {\n OnPropertyChanged(nameof(CanMoveRight));\n }\n }\n }\n\n public RuntimeLibrary? SelectedSelected\n {\n get;\n set\n {\n if (Set(ref field, value))\n {\n OnPropertyChanged(nameof(CanMoveLeft));\n OnPropertyChanged(nameof(CanMoveUp));\n OnPropertyChanged(nameof(CanMoveDown));\n }\n }\n }\n\n public bool CanMoveRight => SelectedAvailable.HasValue;\n public bool CanMoveLeft => SelectedSelected.HasValue;\n public bool CanMoveUp => SelectedSelected.HasValue && SelectedLibraries.IndexOf(SelectedSelected.Value) > 0;\n public bool CanMoveDown => SelectedSelected.HasValue && SelectedLibraries.IndexOf(SelectedSelected.Value) < SelectedLibraries.Count - 1;\n\n private void SelectedLibrariesOnCollectionChanged(object? sender, NotifyCollectionChangedEventArgs e)\n {\n // Apply to config\n FL.PlayerConfig.Subtitles.WhisperCppConfig.RuntimeLibraries = [.. SelectedLibraries];\n }\n\n private void LoadDownloadedModels()\n {\n WhisperCppModel? prevSelected = FL.PlayerConfig.Subtitles.WhisperCppConfig.Model;\n FL.PlayerConfig.Subtitles.WhisperCppConfig.Model = null;\n DownloadModels.Clear();\n\n List models = WhisperCppModelLoader.LoadDownloadedModels();\n foreach (var model in models)\n {\n DownloadModels.Add(model);\n }\n\n FL.PlayerConfig.Subtitles.WhisperCppConfig.Model = DownloadModels.FirstOrDefault(m => m.Equals(prevSelected));\n\n if (FL.PlayerConfig.Subtitles.WhisperCppConfig.Model == null && DownloadModels.Count == 1)\n {\n // automatically set first downloaded model\n FL.PlayerConfig.Subtitles.WhisperCppConfig.Model = DownloadModels.First();\n }\n }\n\n public ObservableCollection DownloadModels { get; set => Set(ref field, value); } = new();\n\n public OrderedDictionary PromptPresets { get; } = new()\n {\n [\"Use Chinese (Simplified), with punctuation\"] = \"以下是普通话的句子。\",\n [\"Use Chinese (Traditional), with punctuation\"] = \"以下是普通話的句子。\"\n };\n\n public KeyValuePair? SelectedPromptPreset\n {\n get;\n set\n {\n if (Set(ref field, value))\n {\n if (value.HasValue)\n {\n FL.PlayerConfig.Subtitles.WhisperCppConfig.Prompt = value.Value.Value;\n }\n }\n }\n }\n\n public DelegateCommand? CmdDownloadModel => field ??= new(() =>\n {\n _dialogService.ShowDialog(nameof(WhisperModelDownloadDialog));\n\n LoadDownloadedModels();\n });\n\n public DelegateCommand? CmdMoveRight => field ??= new DelegateCommand(() =>\n {\n if (SelectedAvailable.HasValue && !SelectedLibraries.Contains(SelectedAvailable.Value))\n {\n SelectedLibraries.Add(SelectedAvailable.Value);\n AvailableLibraries.Remove(SelectedAvailable.Value);\n }\n }).ObservesCanExecute(() => CanMoveRight);\n\n public DelegateCommand? CmdMoveLeft => field ??= new DelegateCommand(() =>\n {\n if (SelectedSelected.HasValue)\n {\n AvailableLibraries.Add(SelectedSelected.Value);\n SelectedLibraries.Remove(SelectedSelected.Value);\n }\n }).ObservesCanExecute(() => CanMoveLeft);\n\n public DelegateCommand? CmdMoveUp => field ??= new DelegateCommand(() =>\n {\n int index = SelectedLibraries.IndexOf(SelectedSelected!.Value);\n if (index > 0)\n {\n SelectedLibraries.Move(index, index - 1);\n OnPropertyChanged(nameof(CanMoveUp));\n OnPropertyChanged(nameof(CanMoveDown));\n }\n }).ObservesCanExecute(() => CanMoveUp);\n\n public DelegateCommand? CmdMoveDown => field ??= new DelegateCommand(() =>\n {\n int index = SelectedLibraries.IndexOf(SelectedSelected!.Value);\n if (index < SelectedLibraries.Count - 1)\n {\n SelectedLibraries.Move(index, index + 1);\n OnPropertyChanged(nameof(CanMoveUp));\n OnPropertyChanged(nameof(CanMoveDown));\n }\n }).ObservesCanExecute(() => CanMoveDown);\n #endregion\n\n #region faster-whisper\n public OrderedDictionary ExtraArgumentsPresets { get; } = new()\n {\n [\"Use CUDA device\"] = \"--device cuda\",\n [\"Use CUDA second device\"] = \"--device cuda:1\",\n [\"Use CPU device\"] = \"--device cpu\",\n [\"Use Chinese (Simplified), with punctuation\"] = \"--initial_prompt \\\"以下是普通话的句子。\\\"\",\n [\"Use Chinese (Traditional), with punctuation\"] = \"--initial_prompt \\\"以下是普通話的句子。\\\"\"\n };\n\n public KeyValuePair? SelectedExtraArgumentsPreset\n {\n get;\n set\n {\n if (Set(ref field, value))\n {\n if (value.HasValue)\n {\n FL.PlayerConfig.Subtitles.FasterWhisperConfig.ExtraArguments = value.Value.Value;\n }\n }\n }\n }\n\n public DelegateCommand? CmdDownloadEngine => field ??= new(() =>\n {\n _dialogService.ShowDialog(nameof(WhisperEngineDownloadDialog));\n\n // update binding of downloaded state forcefully\n var prev = FL.PlayerConfig.Subtitles.ASREngine;\n FL.PlayerConfig.Subtitles.ASREngine = SubASREngineType.WhisperCpp;\n FL.PlayerConfig.Subtitles.ASREngine = prev;\n });\n\n public DelegateCommand? CmdOpenModelFolder => field ??= new(() =>\n {\n if (!Directory.Exists(WhisperConfig.ModelsDirectory))\n return;\n\n Process.Start(new ProcessStartInfo\n {\n FileName = WhisperConfig.ModelsDirectory,\n UseShellExecute = true,\n CreateNoWindow = true\n });\n });\n\n public DelegateCommand? CmdCopyDebugCommand => field ??= new(() =>\n {\n var cmdBase = FasterWhisperASRService.BuildCommand(FL.PlayerConfig.Subtitles.FasterWhisperConfig,\n FL.PlayerConfig.Subtitles.WhisperConfig);\n\n var sampleWavePath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, \"Assets\", \"kennedy.wav\");\n ArgumentsBuilder args = new();\n args.Add(sampleWavePath);\n\n string addedArgs = args.Build();\n\n var cmd = cmdBase.WithArguments($\"{cmdBase.Arguments} {addedArgs}\");\n Clipboard.SetText(cmd.CommandToText());\n });\n\n public DelegateCommand? CmdCopyHelpCommand => field ??= new(() =>\n {\n var cmdBase = FasterWhisperASRService.BuildCommand(FL.PlayerConfig.Subtitles.FasterWhisperConfig,\n FL.PlayerConfig.Subtitles.WhisperConfig);\n\n var cmd = cmdBase.WithArguments(\"--help\");\n Clipboard.SetText(cmd.CommandToText());\n });\n#endregion\n}\n\n[ValueConversion(typeof(Enum), typeof(bool))]\npublic class ASREngineDownloadedConverter : IValueConverter\n{\n public object Convert(object value, Type targetType, object parameter, CultureInfo culture)\n {\n if (value is SubASREngineType engine)\n {\n if (engine == SubASREngineType.FasterWhisper)\n {\n if (File.Exists(FasterWhisperConfig.DefaultEnginePath))\n {\n return true;\n }\n }\n }\n\n return false;\n }\n\n public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture) => throw new NotImplementedException();\n}\n"], ["/LLPlayer/LLPlayer/Controls/Settings/SettingsKeys.xaml.cs", "using System.Collections.ObjectModel;\nusing System.ComponentModel;\nusing System.Configuration;\nusing System.Diagnostics;\nusing System.Windows;\nusing System.Windows.Controls;\nusing System.Windows.Data;\nusing System.Windows.Input;\nusing FlyleafLib.MediaPlayer;\nusing LLPlayer.Converters;\nusing LLPlayer.Extensions;\nusing LLPlayer.Services;\nusing KeyBinding = FlyleafLib.MediaPlayer.KeyBinding;\n\nnamespace LLPlayer.Controls.Settings;\n\npublic partial class SettingsKeys : UserControl\n{\n private SettingsKeysVM VM => (SettingsKeysVM)DataContext;\n\n public SettingsKeys()\n {\n InitializeComponent();\n\n DataContext = ((App)Application.Current).Container.Resolve();\n }\n\n // Enable ComboBox to open when double-clicking a cell in Action\n private void ComboBox_Loaded(object sender, RoutedEventArgs e)\n {\n if (sender is ComboBox comboBox)\n {\n comboBox.IsDropDownOpen = true;\n }\n }\n\n // Scroll to the added record when a new record is added.\n private void KeyBindingsDataGrid_OnSelectionChanged(object sender, SelectionChangedEventArgs e)\n {\n if (VM.CmdLoad!.IsExecuting)\n {\n return;\n }\n\n if (KeyBindingsDataGrid.SelectedItem != null)\n {\n KeyBindingsDataGrid.UpdateLayout();\n KeyBindingsDataGrid.ScrollIntoView(KeyBindingsDataGrid.SelectedItem);\n }\n }\n}\n\npublic class SettingsKeysVM : Bindable\n{\n public FlyleafManager FL { get; }\n\n public SettingsKeysVM(FlyleafManager fl)\n {\n FL = fl;\n\n CmdLoad!.PropertyChanged += (sender, args) =>\n {\n if (args.PropertyName == nameof(CmdLoad.IsExecuting))\n {\n OnPropertyChanged(nameof(CanApply));\n }\n };\n\n List mergeActions = new();\n\n foreach (KeyBindingAction action in Enum.GetValues())\n {\n if (action != KeyBindingAction.Custom)\n {\n mergeActions.Add(new ActionData()\n {\n Action = action,\n Description = action.GetDescription(),\n DisplayName = action.ToString(),\n Group = action.ToGroup()\n });\n }\n }\n\n foreach (CustomKeyBindingAction action in Enum.GetValues())\n {\n mergeActions.Add(new ActionData()\n {\n Action = KeyBindingAction.Custom,\n CustomAction = action,\n Description = action.GetDescription(),\n DisplayName = action.ToString() + @\" ©︎\", // c=custom\n Group = action.ToGroup()\n });\n }\n\n mergeActions.Sort();\n\n Actions = mergeActions;\n\n // Grouping when displaying actions in ComboBox\n _actionsView = (ListCollectionView)CollectionViewSource.GetDefaultView(Actions);\n _actionsView.SortDescriptions.Add(new SortDescription(nameof(ActionData.Group), ListSortDirection.Ascending));\n _actionsView.SortDescriptions.Add(new SortDescription(nameof(ActionData.DisplayName), ListSortDirection.Ascending));\n\n _actionsView.GroupDescriptions!.Add(new PropertyGroupDescription(nameof(ActionData.Group)));\n }\n\n public List Actions { get; }\n private readonly ListCollectionView _actionsView;\n\n public ObservableCollection KeyBindings { get; } = new();\n\n public KeyBindingWrapper? SelectedKeyBinding { get; set => Set(ref field, value); }\n\n public int DuplicationCount\n {\n get;\n set\n {\n if (Set(ref field, value))\n {\n OnPropertyChanged(nameof(CanApply));\n }\n }\n }\n\n // Disable Apply button if there are duplicates or during loading\n public bool CanApply => DuplicationCount == 0 && !CmdLoad!.IsExecuting;\n\n public DelegateCommand? CmdAdd => field ??= new(() =>\n {\n KeyBindingWrapper added = new(new KeyBinding { Action = KeyBindingAction.AudioDelayAdd }, this);\n KeyBindings.Add(added);\n SelectedKeyBinding = added;\n\n added.ValidateShortcut();\n });\n\n public AsyncDelegateCommand? CmdLoad => field ??= new(async () =>\n {\n KeyBindings.Clear();\n DuplicationCount = 0;\n\n var keys = FL.PlayerConfig.Player.KeyBindings.Keys;\n\n var keyBindings = await Task.Run(() =>\n {\n List keyBindings = new(keys.Count);\n\n foreach (var k in keys)\n {\n try\n {\n keyBindings.Add(new KeyBindingWrapper(k, this));\n }\n catch (SettingsPropertyNotFoundException)\n {\n // ignored\n // TODO: L: error handling\n Debug.Fail(\"Weird custom key for settings?\");\n }\n }\n\n return Task.FromResult(keyBindings);\n });\n\n foreach (var b in keyBindings)\n {\n KeyBindings.Add(b);\n }\n });\n\n /// \n /// Reflect customized key settings to Config.\n /// \n public DelegateCommand? CmdApply => field ??= new DelegateCommand(() =>\n {\n foreach (var b in KeyBindings)\n {\n Debug.Assert(!b.Duplicated, \"Duplicate check not working\");\n }\n\n var newKeys = KeyBindings.Select(k => k.ToKeyBinding()).ToList();\n\n foreach (var k in newKeys)\n {\n if (k.Action == KeyBindingAction.Custom)\n {\n if (!Enum.TryParse(k.ActionName, out CustomKeyBindingAction customAction))\n {\n Guards.Fail();\n }\n k.SetAction(FL.Action.CustomActions[customAction], k.IsKeyUp);\n }\n else\n {\n k.SetAction(FL.PlayerConfig.Player.KeyBindings.GetKeyBindingAction(k.Action), k.IsKeyUp);\n }\n }\n\n FL.PlayerConfig.Player.KeyBindings.RemoveAll();\n FL.PlayerConfig.Player.KeyBindings.Keys = newKeys;\n\n }).ObservesCanExecute(() => CanApply);\n}\n\npublic class ActionData : IComparable, IEquatable\n{\n public string Description { get; set; } = null!;\n public string DisplayName { get; set; } = null!;\n public KeyBindingActionGroup Group { get; set; }\n public KeyBindingAction Action { get; set; }\n public CustomKeyBindingAction? CustomAction { get; set; }\n\n public int CompareTo(ActionData? other)\n {\n if (ReferenceEquals(this, other))\n return 0;\n if (other is null)\n return 1;\n return string.Compare(DisplayName, other.DisplayName, StringComparison.Ordinal);\n }\n\n public bool Equals(ActionData? other)\n {\n if (other is null) return false;\n if (ReferenceEquals(this, other)) return true;\n return Action == other.Action && CustomAction == other.CustomAction;\n }\n\n public override bool Equals(object? obj) => obj is ActionData o && Equals(o);\n\n public override int GetHashCode()\n {\n return HashCode.Combine((int)Action, CustomAction);\n }\n}\n\npublic class KeyBindingWrapper : Bindable\n{\n private readonly SettingsKeysVM _parent;\n\n /// \n /// constructor\n /// \n /// \n /// \n /// \n public KeyBindingWrapper(KeyBinding keyBinding, SettingsKeysVM parent)\n {\n ArgumentNullException.ThrowIfNull(parent);\n\n // TODO: L: performance issues when initializing?\n _parent = parent;\n\n Key = keyBinding.Key;\n\n ActionData action = new()\n {\n Action = keyBinding.Action,\n };\n\n if (keyBinding.Action != KeyBindingAction.Custom)\n {\n action.Description = keyBinding.Action.GetDescription();\n action.DisplayName = keyBinding.Action.ToString();\n }\n else if (Enum.TryParse(keyBinding.ActionName, out CustomKeyBindingAction customAction))\n {\n action.CustomAction = customAction;\n action.Description = customAction.GetDescription();\n action.DisplayName = keyBinding.ActionName + @\" ©︎\";\n }\n else\n {\n throw new SettingsPropertyNotFoundException($\"Custom Action '{keyBinding.ActionName}' does not exist.\");\n }\n\n Action = action;\n Alt = keyBinding.Alt;\n Ctrl = keyBinding.Ctrl;\n Shift = keyBinding.Shift;\n IsKeyUp = keyBinding.IsKeyUp;\n IsEnabled = keyBinding.IsEnabled;\n }\n\n public bool IsEnabled\n {\n get;\n set\n {\n if (Set(ref field, value))\n {\n if (!value)\n {\n Duplicated = false;\n DuplicatedInfo = null;\n }\n else\n {\n ValidateShortcut();\n }\n\n ValidateKey(Key);\n }\n }\n }\n\n public bool Alt\n {\n get;\n set\n {\n if (Set(ref field, value) && IsEnabled)\n {\n ValidateShortcut();\n ValidateKey(Key);\n }\n }\n }\n\n public bool Ctrl\n {\n get;\n set\n {\n if (Set(ref field, value) && IsEnabled)\n {\n ValidateShortcut();\n ValidateKey(Key);\n }\n }\n }\n\n public bool Shift\n {\n get;\n set\n {\n if (Set(ref field, value) && IsEnabled)\n {\n ValidateShortcut();\n ValidateKey(Key);\n }\n }\n }\n\n public Key Key\n {\n get;\n set\n {\n Key prevKey = field;\n if (Set(ref field, value) && IsEnabled)\n {\n ValidateShortcut();\n ValidateKey(Key); // maybe don't need?\n // When the key is changed from A -> B, the state of A also needs to be updated.\n ValidateKey(prevKey);\n }\n }\n }\n\n public ActionData Action { get; set => Set(ref field, value); }\n\n public bool IsKeyUp { get; set => Set(ref field, value); }\n\n public bool Duplicated\n {\n get;\n private set\n {\n if (Set(ref field, value))\n {\n // Update duplicate counters held by the parent.\n _parent.DuplicationCount += value ? 1 : -1;\n }\n }\n }\n\n public string? DuplicatedInfo { get; private set => Set(ref field, value); }\n\n private bool IsSameKey(KeyBindingWrapper key)\n {\n return key.Key == Key && key.Alt == Alt && key.Shift == Shift && key.Ctrl == Ctrl;\n }\n\n private void ValidateKey(Key key)\n {\n foreach (var b in _parent.KeyBindings.Where(k => k.IsEnabled && k != this && k.Key == key))\n {\n b.ValidateShortcut();\n }\n }\n\n public KeyBindingWrapper Clone()\n {\n KeyBindingWrapper clone = (KeyBindingWrapper)MemberwiseClone();\n\n return clone;\n }\n\n /// \n /// Convert Wrapper to KeyBinding\n /// \n /// \n public KeyBinding ToKeyBinding()\n {\n KeyBinding binding = new()\n {\n Key = Key,\n Action = Action.Action,\n Ctrl = Ctrl,\n Alt = Alt,\n Shift = Shift,\n IsKeyUp = IsKeyUp,\n IsEnabled = IsEnabled\n };\n\n if (Action.Action == KeyBindingAction.Custom)\n {\n binding.ActionName = Action.CustomAction.ToString();\n }\n\n return binding;\n }\n\n // TODO: L: This validation might be better done in the parent with event firing (I want to eliminate references to the parent).\n public void ValidateShortcut()\n {\n List sameKeys = _parent.KeyBindings\n .Where(k => k != this && k.IsEnabled && k.IsSameKey(this)).ToList();\n\n bool isDuplicate = sameKeys.Count > 0;\n\n UpdateDuplicated(isDuplicate);\n\n // Other records with the same key also update duplicate status\n foreach (KeyBindingWrapper b in sameKeys)\n {\n b.UpdateDuplicated(isDuplicate);\n }\n }\n\n private void UpdateDuplicated(bool duplicated)\n {\n Duplicated = duplicated;\n\n if (duplicated)\n {\n List duplicateActions = _parent.KeyBindings\n .Where(k => k != this && k.IsSameKey(this)).Select(k => k.Action.DisplayName)\n .ToList();\n\n DuplicatedInfo = $\"Key:{Key} is conflicted.\\r\\nAction:{string.Join(',', duplicateActions)} already uses.\";\n }\n else\n {\n DuplicatedInfo = null;\n }\n }\n\n // TODO: L: Enable firing for multiple selections\n public DelegateCommand CmdDeleteRow => new((binding) =>\n {\n if (binding.Duplicated)\n {\n // Reduce duplicate counters of parents\n binding.Duplicated = false;\n }\n _parent.KeyBindings.Remove(binding);\n\n // Update other keys\n if (binding.IsEnabled)\n {\n ValidateKey(binding.Key);\n }\n });\n\n public DelegateCommand CmdSetKey => new((key) =>\n {\n if (key.HasValue)\n {\n Key = key.Value;\n }\n });\n\n public DelegateCommand CmdCloneRow => new((keyBinding) =>\n {\n int index = _parent.KeyBindings.IndexOf(keyBinding);\n if (index != -1)\n {\n KeyBindingWrapper clone = Clone();\n\n _parent.KeyBindings.Insert(index + 1, clone);\n\n // Select added record\n _parent.SelectedKeyBinding = clone;\n\n // validate it\n clone.ValidateShortcut();\n }\n });\n}\n\npublic class KeyCaptureTextBox : TextBox\n{\n private static readonly HashSet IgnoreKeys =\n [\n Key.LeftShift,\n Key.RightShift,\n Key.LeftCtrl,\n Key.RightCtrl,\n Key.LeftAlt,\n Key.RightAlt,\n Key.LWin,\n Key.RWin,\n Key.CapsLock,\n Key.NumLock,\n Key.Scroll\n ];\n\n public static readonly DependencyProperty KeyProperty =\n DependencyProperty.Register(nameof(Key), typeof(Key), typeof(KeyCaptureTextBox),\n new FrameworkPropertyMetadata(Key.None, FrameworkPropertyMetadataOptions.BindsTwoWayByDefault));\n public Key Key\n {\n get => (Key)GetValue(KeyProperty);\n set => SetValue(KeyProperty, value);\n }\n\n public KeyCaptureTextBox()\n {\n Loaded += KeyCaptureTextBox_Loaded;\n }\n\n // Key input does not get focus when mouse clicked, so it gets it.\n private void KeyCaptureTextBox_Loaded(object sender, RoutedEventArgs e)\n {\n Focus();\n Keyboard.Focus(this);\n }\n\n protected override void OnPreviewKeyDown(KeyEventArgs e)\n {\n if (IgnoreKeys.Contains(e.Key))\n {\n return;\n }\n\n // Press Enter to confirm.\n if (e.Key == Key.Enter)\n {\n // This would go to the right cell.\n //MoveFocus(new TraversalRequest(FocusNavigationDirection.Down));\n\n // If the Enter key is pressed, it remains in place and the edit is confirmed\n var dataGrid = UIHelper.FindParent(this);\n if (dataGrid != null)\n {\n dataGrid.CommitEdit(DataGridEditingUnit.Cell, true);\n }\n\n e.Handled = true; // Suppress default behavior (focus movement)\n }\n else\n {\n // Capture other key\n Key = e.Key;\n\n // Converts input key into human understandable name.\n if (KeyToStringConverter.KeyMappings.TryGetValue(e.Key, out string? keyName))\n {\n Text = keyName;\n }\n else\n {\n Text = e.Key.ToString();\n }\n e.Handled = true;\n }\n\n base.OnPreviewKeyDown(e);\n }\n}\n"], ["/LLPlayer/FlyleafLib/MediaFramework/MediaStream/ExternalStream.cs", "using System.Collections.Generic;\n\nusing FlyleafLib.MediaFramework.MediaDemuxer;\nusing FlyleafLib.MediaFramework.MediaPlaylist;\nusing FlyleafLib.MediaPlayer;\n\nnamespace FlyleafLib.MediaFramework.MediaStream;\n\npublic class ExternalStream : DemuxerInput\n{\n public string PluginName { get; set; }\n public PlaylistItem\n PlaylistItem { get; set; }\n public int Index { get; set; } = -1; // if we need it (already used to compare same type streams) we need to ensure we fix it in case of removing an item\n public string Protocol { get; set; }\n public string Codec { get; set; }\n public long BitRate { get; set; }\n public Dictionary\n Tag { get; set; } = new Dictionary();\n public void AddTag(object tag, string pluginName)\n {\n if (Tag.ContainsKey(pluginName))\n Tag[pluginName] = tag;\n else\n Tag.Add(pluginName, tag);\n }\n public object GetTag(string pluginName)\n => Tag.ContainsKey(pluginName) ? Tag[pluginName] : null;\n\n /// \n /// Whether the item is currently enabled or not\n /// \n public bool Enabled\n {\n get => _Enabled;\n set\n {\n Utils.UI(() =>\n {\n if (Set(ref _Enabled, value) && value)\n {\n OpenedCounter++;\n }\n\n Raise(nameof(EnabledPrimarySubtitle));\n Raise(nameof(EnabledSecondarySubtitle));\n Raise(nameof(SubtitlesStream.SelectedSubMethods));\n });\n }\n }\n bool _Enabled;\n\n /// \n /// Times this item has been used/opened\n /// \n public int OpenedCounter { get; set; }\n\n public MediaType\n Type => this is ExternalAudioStream ? MediaType.Audio : this is ExternalVideoStream ? MediaType.Video : MediaType.Subs;\n\n #region Subtitles\n // TODO: L: Used for subtitle streams only, but defined in the base class\n public bool EnabledPrimarySubtitle => Enabled && this.GetSubEnabled(0);\n public bool EnabledSecondarySubtitle => Enabled && this.GetSubEnabled(1);\n #endregion\n}\n"], ["/LLPlayer/FlyleafLib/MediaPlayer/Player.Keys.cs", "using System;\nusing System.Collections.Generic;\nusing System.ComponentModel;\nusing System.Runtime.InteropServices;\nusing System.Text.Json.Serialization;\nusing System.Windows.Input;\nusing static FlyleafLib.Logger;\n\nnamespace FlyleafLib.MediaPlayer;\n\npartial class Player\n{\n /* Player Key Bindings\n *\n * Config.Player.KeyBindings.Keys\n *\n * KeyDown / KeyUp Events (Control / WinFormsHost / WindowFront (FlyleafWindow))\n * Exposes KeyDown/KeyUp if required to listen on additional Controls/Windows\n * Allows KeyBindingAction.Custom to set an external Action for Key Binding\n */\n\n Tuple onKeyUpBinding;\n\n /// \n /// Can be used to route KeyDown events (WPF)\n /// \n /// \n /// \n public static bool KeyDown(Player player, KeyEventArgs e)\n {\n e.Handled = KeyDown(player, e.Key == Key.System ? e.SystemKey : e.Key);\n\n return e.Handled;\n }\n\n /// \n /// Can be used to route KeyDown events (WinForms)\n /// \n /// \n /// \n public static void KeyDown(Player player, System.Windows.Forms.KeyEventArgs e)\n => e.Handled = KeyDown(player, KeyInterop.KeyFromVirtualKey((int)e.KeyCode));\n\n /// \n /// Can be used to route KeyUp events (WPF)\n /// \n /// \n /// \n public static bool KeyUp(Player player, KeyEventArgs e)\n {\n e.Handled = KeyUp(player, e.Key == Key.System ? e.SystemKey : e.Key);\n\n return e.Handled;\n }\n\n /// \n /// Can be used to route KeyUp events (WinForms)\n /// \n /// \n /// \n public static void KeyUp(Player player, System.Windows.Forms.KeyEventArgs e)\n => e.Handled = KeyUp(player, KeyInterop.KeyFromVirtualKey((int)e.KeyCode));\n\n public static bool KeyDown(Player player, Key key)\n {\n if (player == null)\n return false;\n\n player.Activity.RefreshActive();\n\n if (player.onKeyUpBinding != null)\n {\n if (player.onKeyUpBinding.Item1.Key == key)\n return true;\n\n if (DateTime.UtcNow.Ticks - player.onKeyUpBinding.Item2 < TimeSpan.FromSeconds(2).Ticks)\n return false;\n\n player.onKeyUpBinding = null; // In case of keyboard lost capture (should be handled from hosts)\n }\n\n List keysList = new();\n var spanList = CollectionsMarshal.AsSpan(player.Config.Player.KeyBindings.Keys); // should create dictionary here with key+alt+ctrl+shift hash\n foreach(var binding in spanList)\n if (binding.Key == key && binding.IsEnabled)\n keysList.Add(binding);\n\n if (keysList.Count == 0)\n return false;\n\n bool alt, ctrl, shift;\n alt = Keyboard.IsKeyDown(Key.LeftAlt) || Keyboard.IsKeyDown(Key.RightAlt);\n ctrl = Keyboard.IsKeyDown(Key.LeftCtrl) || Keyboard.IsKeyDown(Key.RightCtrl);\n shift = Keyboard.IsKeyDown(Key.LeftShift) || Keyboard.IsKeyDown(Key.RightShift);\n\n var spanList2 = CollectionsMarshal.AsSpan(keysList);\n foreach(var binding in spanList2)\n {\n if (binding.Alt == alt && binding.Ctrl == ctrl && binding.Shift == shift && binding.IsEnabled)\n {\n if (binding.IsKeyUp)\n player.onKeyUpBinding = new(binding, DateTime.UtcNow.Ticks);\n else\n ExecuteBinding(player, binding, false);\n\n return true;\n }\n }\n\n return false;\n }\n public static bool KeyUp(Player player, Key key)\n {\n if (player == null || player.onKeyUpBinding == null || player.onKeyUpBinding.Item1.Key != key)\n return false;\n\n ExecuteBinding(player, player.onKeyUpBinding.Item1, true);\n player.onKeyUpBinding = null;\n return true;\n }\n\n static void ExecuteBinding(Player player, KeyBinding binding, bool isKeyUp)\n {\n if (CanDebug) player.Log.Debug($\"[Keys|{(isKeyUp ? \"Up\" : \"Down\")}] {(binding.Action == KeyBindingAction.Custom && binding.ActionName != null ? binding.ActionName : binding.Action)}\");\n binding.ActionInternal?.Invoke();\n }\n}\n\npublic class KeysConfig\n{\n /// \n /// Currently configured key bindings\n /// (Normally you should not access this directly)\n /// \n public List Keys { get ; set; }\n\n Player player;\n\n public KeysConfig() { }\n\n public KeysConfig Clone()\n {\n KeysConfig keys = (KeysConfig) MemberwiseClone();\n keys.player = null;\n keys.Keys = null;\n return keys;\n }\n\n internal void SetPlayer(Player player)\n {\n Keys ??= new List();\n\n if (!player.Config.Loaded && Keys.Count == 0)\n LoadDefault();\n\n this.player = player;\n\n foreach(var binding in Keys)\n {\n if (binding.Action != KeyBindingAction.Custom)\n binding.ActionInternal = GetKeyBindingAction(binding.Action);\n }\n }\n\n /// \n /// Adds a custom keybinding\n /// \n /// The key to bind\n /// If should fire on each keydown or just on keyup\n /// The action to execute\n /// A unique name to be able to identify it\n /// If Alt should be pressed\n /// If Ctrl should be pressed\n /// If Shift should be pressed\n /// Keybinding already exists\n public void AddCustom(Key key, bool isKeyUp, Action action, string actionName, bool alt = false, bool ctrl = false, bool shift = false)\n {\n for (int i=0; i\n /// Adds a new key binding\n /// \n /// The key to bind\n /// Which action from the available to assign\n /// If Alt should be pressed\n /// If Ctrl should be pressed\n /// If Shift should be pressed\n /// Keybinding already exists\n public void Add(Key key, KeyBindingAction action, bool alt = false, bool ctrl = false, bool shift = false)\n {\n for (int i=0; i\n /// Removes a binding based on Key/Ctrl combination\n /// \n /// The assigned key\n /// If Alt is assigned\n /// If Ctrl is assigned\n /// If Shift is assigned\n public void Remove(Key key, bool alt = false, bool ctrl = false, bool shift = false)\n {\n for (int i=Keys.Count-1; i >=0; i--)\n if (Keys[i].Key == key && Keys[i].Alt == alt && Keys[i].Ctrl == ctrl && Keys[i].Shift == shift)\n Keys.RemoveAt(i);\n }\n\n /// \n /// Removes a binding based on assigned action\n /// \n /// The assigned action\n public void Remove(KeyBindingAction action)\n {\n for (int i=Keys.Count-1; i >=0; i--)\n if (Keys[i].Action == action)\n Keys.RemoveAt(i);\n }\n\n /// \n /// Removes a binding based on assigned action's name\n /// \n /// The assigned action's name\n public void Remove(string actionName)\n {\n for (int i=Keys.Count-1; i >=0; i--)\n if (Keys[i].ActionName == actionName)\n Keys.RemoveAt(i);\n }\n\n /// \n /// Removes all the bindings\n /// \n public void RemoveAll() => Keys.Clear();\n\n /// \n /// Resets to default bindings\n /// \n public void LoadDefault()\n {\n if (Keys == null)\n Keys = new List();\n else\n Keys.Clear();\n\n Add(Key.OemSemicolon, KeyBindingAction.SubsDelayRemovePrimary);\n Add(Key.OemQuotes, KeyBindingAction.SubsDelayAddPrimary);\n Add(Key.OemSemicolon, KeyBindingAction.SubsDelayRemoveSecondary, shift: true);\n Add(Key.OemQuotes, KeyBindingAction.SubsDelayAddSecondary, shift: true);\n\n Add(Key.A, KeyBindingAction.SubsPrevSeek);\n Add(Key.S, KeyBindingAction.SubsCurSeek);\n Add(Key.D, KeyBindingAction.SubsNextSeek);\n\n Add(Key.J, KeyBindingAction.SubsPrevSeek);\n Add(Key.K, KeyBindingAction.SubsCurSeek);\n Add(Key.L, KeyBindingAction.SubsNextSeek);\n\n // Mouse backford/forward button\n Add(Key.Left, KeyBindingAction.SubsPrevSeekFallback, alt: true);\n Add(Key.Right, KeyBindingAction.SubsNextSeekFallback, alt: true);\n\n Add(Key.V, KeyBindingAction.OpenFromClipboardSafe, ctrl: true);\n Add(Key.O, KeyBindingAction.OpenFromFileDialog, ctrl: true);\n Add(Key.C, KeyBindingAction.CopyToClipboard, ctrl: true, shift: true);\n\n Add(Key.Left, KeyBindingAction.SeekBackward2);\n Add(Key.Left, KeyBindingAction.SeekBackward, ctrl: true);\n Add(Key.Right, KeyBindingAction.SeekForward2);\n Add(Key.Right, KeyBindingAction.SeekForward, ctrl: true);\n\n Add(Key.S, KeyBindingAction.ToggleSeekAccurate, ctrl: true);\n\n Add(Key.OemPlus, KeyBindingAction.SpeedAdd);\n Add(Key.OemPlus, KeyBindingAction.SpeedAdd2, shift: true);\n Add(Key.OemMinus, KeyBindingAction.SpeedRemove);\n Add(Key.OemMinus, KeyBindingAction.SpeedRemove2, shift: true);\n\n Add(Key.OemPlus, KeyBindingAction.ZoomIn, ctrl: true);\n Add(Key.OemMinus, KeyBindingAction.ZoomOut, ctrl: true);\n\n Add(Key.F, KeyBindingAction.ToggleFullScreen);\n\n Add(Key.Space, KeyBindingAction.TogglePlayPause);\n Add(Key.MediaPlayPause, KeyBindingAction.TogglePlayPause);\n Add(Key.Play, KeyBindingAction.TogglePlayPause);\n\n Add(Key.H, KeyBindingAction.ToggleSubtitlesVisibility);\n Add(Key.V, KeyBindingAction.ToggleSubtitlesVisibility);\n\n Add(Key.M, KeyBindingAction.ToggleMute);\n Add(Key.Up, KeyBindingAction.VolumeUp);\n Add(Key.Down, KeyBindingAction.VolumeDown);\n\n Add(Key.D0, KeyBindingAction.ResetAll);\n\n Add(Key.Escape, KeyBindingAction.NormalScreen);\n Add(Key.Q, KeyBindingAction.Stop, ctrl: true);\n }\n\n public Action GetKeyBindingAction(KeyBindingAction action)\n {\n switch (action)\n {\n case KeyBindingAction.ForceIdle:\n return player.Activity.ForceIdle;\n case KeyBindingAction.ForceActive:\n return player.Activity.ForceActive;\n case KeyBindingAction.ForceFullActive:\n return player.Activity.ForceFullActive;\n\n case KeyBindingAction.AudioDelayAdd:\n return player.Audio.DelayAdd;\n case KeyBindingAction.AudioDelayRemove:\n return player.Audio.DelayRemove;\n case KeyBindingAction.AudioDelayAdd2:\n return player.Audio.DelayAdd2;\n case KeyBindingAction.AudioDelayRemove2:\n return player.Audio.DelayRemove2;\n case KeyBindingAction.ToggleAudio:\n return player.Audio.Toggle;\n case KeyBindingAction.ToggleMute:\n return player.Audio.ToggleMute;\n case KeyBindingAction.VolumeUp:\n return player.Audio.VolumeUp;\n case KeyBindingAction.VolumeDown:\n return player.Audio.VolumeDown;\n\n case KeyBindingAction.ToggleVideo:\n return player.Video.Toggle;\n case KeyBindingAction.ToggleKeepRatio:\n return player.Video.ToggleKeepRatio;\n case KeyBindingAction.ToggleVideoAcceleration:\n return player.Video.ToggleVideoAcceleration;\n\n case KeyBindingAction.SubsDelayAddPrimary:\n return player.Subtitles.DelayAddPrimary;\n case KeyBindingAction.SubsDelayRemovePrimary:\n return player.Subtitles.DelayRemovePrimary;\n case KeyBindingAction.SubsDelayAdd2Primary:\n return player.Subtitles.DelayAdd2Primary;\n case KeyBindingAction.SubsDelayRemove2Primary:\n return player.Subtitles.DelayRemove2Primary;\n\n case KeyBindingAction.SubsDelayAddSecondary:\n return player.Subtitles.DelayAddSecondary;\n case KeyBindingAction.SubsDelayRemoveSecondary:\n return player.Subtitles.DelayRemoveSecondary;\n case KeyBindingAction.SubsDelayAdd2Secondary:\n return player.Subtitles.DelayAdd2Secondary;\n case KeyBindingAction.SubsDelayRemove2Secondary:\n return player.Subtitles.DelayRemove2Secondary;\n\n case KeyBindingAction.ToggleSubtitlesVisibility:\n return player.Subtitles.ToggleVisibility;\n case KeyBindingAction.ToggleSubtitlesVisibilityPrimary:\n return player.Subtitles.ToggleVisibilityPrimary;\n case KeyBindingAction.ToggleSubtitlesVisibilitySecondary:\n return player.Subtitles.ToggleVisibilitySecondary;\n\n case KeyBindingAction.OpenFromClipboard:\n return player.OpenFromClipboard;\n case KeyBindingAction.OpenFromClipboardSafe:\n return player.OpenFromClipboardSafe;\n\n case KeyBindingAction.OpenFromFileDialog:\n return player.OpenFromFileDialog;\n\n case KeyBindingAction.CopyToClipboard:\n return player.CopyToClipboard;\n\n case KeyBindingAction.CopyItemToClipboard:\n return player.CopyItemToClipboard;\n\n case KeyBindingAction.Flush:\n return player.Flush;\n\n case KeyBindingAction.Stop:\n return player.Stop;\n\n case KeyBindingAction.Pause:\n return player.Pause;\n\n case KeyBindingAction.Play:\n return player.Play;\n\n case KeyBindingAction.TogglePlayPause:\n return player.TogglePlayPause;\n\n case KeyBindingAction.TakeSnapshot:\n return player.Commands.TakeSnapshotAction;\n\n case KeyBindingAction.NormalScreen:\n return player.NormalScreen;\n\n case KeyBindingAction.FullScreen:\n return player.FullScreen;\n\n case KeyBindingAction.ToggleFullScreen:\n return player.ToggleFullScreen;\n\n case KeyBindingAction.ToggleRecording:\n return player.ToggleRecording;\n\n case KeyBindingAction.ToggleReversePlayback:\n return player.ToggleReversePlayback;\n\n case KeyBindingAction.ToggleLoopPlayback:\n return player.ToggleLoopPlayback;\n\n case KeyBindingAction.ToggleSeekAccurate:\n return player.ToggleSeekAccurate;\n\n case KeyBindingAction.SeekBackward:\n return player.SeekBackward;\n\n case KeyBindingAction.SeekForward:\n return player.SeekForward;\n\n case KeyBindingAction.SeekBackward2:\n return player.SeekBackward2;\n\n case KeyBindingAction.SeekForward2:\n return player.SeekForward2;\n\n case KeyBindingAction.SeekBackward3:\n return player.SeekBackward3;\n\n case KeyBindingAction.SeekForward3:\n return player.SeekForward3;\n\n case KeyBindingAction.SeekBackward4:\n return player.SeekBackward4;\n\n case KeyBindingAction.SeekForward4:\n return player.SeekForward4;\n\n case KeyBindingAction.SubsCurSeek:\n return player.Subtitles.CurSeek;\n case KeyBindingAction.SubsPrevSeek:\n return player.Subtitles.PrevSeek;\n case KeyBindingAction.SubsNextSeek:\n return player.Subtitles.NextSeek;\n case KeyBindingAction.SubsNextSeekFallback:\n return player.Subtitles.NextSeekFallback;\n case KeyBindingAction.SubsPrevSeekFallback:\n return player.Subtitles.PrevSeekFallback;\n\n case KeyBindingAction.SubsCurSeek2:\n return player.Subtitles.CurSeek2;\n case KeyBindingAction.SubsPrevSeek2:\n return player.Subtitles.PrevSeek2;\n case KeyBindingAction.SubsNextSeek2:\n return player.Subtitles.NextSeek2;\n case KeyBindingAction.SubsNextSeekFallback2:\n return player.Subtitles.NextSeekFallback2;\n case KeyBindingAction.SubsPrevSeekFallback2:\n return player.Subtitles.PrevSeekFallback2;\n\n case KeyBindingAction.SpeedAdd:\n return player.SpeedUp;\n\n case KeyBindingAction.SpeedAdd2:\n return player.SpeedUp2;\n\n case KeyBindingAction.SpeedRemove:\n return player.SpeedDown;\n\n case KeyBindingAction.SpeedRemove2:\n return player.SpeedDown2;\n\n case KeyBindingAction.ShowPrevFrame:\n return player.ShowFramePrev;\n\n case KeyBindingAction.ShowNextFrame:\n return player.ShowFrameNext;\n\n case KeyBindingAction.ZoomIn:\n return player.ZoomIn;\n\n case KeyBindingAction.ZoomOut:\n return player.ZoomOut;\n\n case KeyBindingAction.ResetAll:\n return player.ResetAll;\n\n case KeyBindingAction.ResetSpeed:\n return player.ResetSpeed;\n\n case KeyBindingAction.ResetRotation:\n return player.ResetRotation;\n\n case KeyBindingAction.ResetZoom:\n return player.ResetZoom;\n }\n\n return null;\n }\n private static HashSet isKeyUpBinding = new()\n {\n // TODO: Should Fire once one KeyDown and not again until KeyUp is fired (in case of Tasks keep track of already running actions?)\n\n // Having issues with alt/ctrl/shift (should save state of alt/ctrl/shift on keydown and not checked on keyup)\n\n { KeyBindingAction.OpenFromClipboard },\n { KeyBindingAction.OpenFromClipboardSafe },\n { KeyBindingAction.OpenFromFileDialog },\n { KeyBindingAction.CopyToClipboard },\n { KeyBindingAction.TakeSnapshot },\n { KeyBindingAction.NormalScreen },\n { KeyBindingAction.FullScreen },\n { KeyBindingAction.ToggleFullScreen },\n { KeyBindingAction.ToggleAudio },\n { KeyBindingAction.ToggleVideo },\n { KeyBindingAction.ToggleKeepRatio },\n { KeyBindingAction.ToggleVideoAcceleration },\n { KeyBindingAction.ToggleSubtitlesVisibility },\n { KeyBindingAction.ToggleSubtitlesVisibilityPrimary },\n { KeyBindingAction.ToggleSubtitlesVisibilitySecondary },\n { KeyBindingAction.ToggleMute },\n { KeyBindingAction.TogglePlayPause },\n { KeyBindingAction.ToggleRecording },\n { KeyBindingAction.ToggleReversePlayback },\n { KeyBindingAction.ToggleLoopPlayback },\n { KeyBindingAction.Play },\n { KeyBindingAction.Pause },\n { KeyBindingAction.Stop },\n { KeyBindingAction.Flush },\n { KeyBindingAction.ToggleSeekAccurate },\n { KeyBindingAction.SpeedAdd },\n { KeyBindingAction.SpeedAdd2 },\n { KeyBindingAction.SpeedRemove },\n { KeyBindingAction.SpeedRemove2 },\n { KeyBindingAction.ResetAll },\n { KeyBindingAction.ResetSpeed },\n { KeyBindingAction.ResetRotation },\n { KeyBindingAction.ResetZoom },\n { KeyBindingAction.ForceIdle },\n { KeyBindingAction.ForceActive },\n { KeyBindingAction.ForceFullActive }\n };\n}\npublic class KeyBinding\n{\n public bool IsEnabled { get; set; } = true;\n public bool Alt { get; set; }\n public bool Ctrl { get; set; }\n public bool Shift { get; set; }\n public Key Key { get; set; }\n public KeyBindingAction Action { get; set; }\n\n [JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)]\n public string ActionName\n {\n get => Action == KeyBindingAction.Custom ? field : null;\n set;\n }\n\n public bool IsKeyUp { get; set; }\n\n /// \n /// Sets action for custom key binding\n /// \n /// \n /// \n public void SetAction(Action action, bool isKeyUp)\n {\n ActionInternal = action;\n IsKeyUp = isKeyUp;\n }\n\n [JsonIgnore]\n public Action ActionInternal { get; internal set; }\n}\n\npublic enum KeyBindingAction\n{\n [Description(nameof(Custom))]\n Custom,\n [Description(\"Set Activity to Idle forcibly\")]\n ForceIdle,\n [Description(\"Set Activity to Active forcibly\")]\n ForceActive,\n [Description(\"Set Activity to FullActive forcibly\")]\n ForceFullActive,\n\n [Description(\"Increase Audio Delay (1)\")]\n AudioDelayAdd,\n [Description(\"Increase Audio Delay (2)\")]\n AudioDelayAdd2,\n [Description(\"Decrease Audio Delay (1)\")]\n AudioDelayRemove,\n [Description(\"Decrease Audio Delay (2)\")]\n AudioDelayRemove2,\n\n [Description(\"Toggle Audio Mute/Unmute\")]\n ToggleMute,\n [Description(\"Volume Up (1)\")]\n VolumeUp,\n [Description(\"Volume Down (1)\")]\n VolumeDown,\n\n [Description(\"Increase Primary Subtitles Delay (1)\")]\n SubsDelayAddPrimary,\n [Description(\"Increase Primary Subtitles Delay (2)\")]\n SubsDelayAdd2Primary,\n [Description(\"Decrease Primary Subtitles Delay (1)\")]\n SubsDelayRemovePrimary,\n [Description(\"Decrease Primary Subtitles Delay (2)\")]\n SubsDelayRemove2Primary,\n [Description(\"Increase Secondary Subtitles Delay (1)\")]\n SubsDelayAddSecondary,\n [Description(\"Increase Secondary Subtitles Delay (2)\")]\n SubsDelayAdd2Secondary,\n [Description(\"Decrease Secondary Subtitles Delay (1)\")]\n SubsDelayRemoveSecondary,\n [Description(\"Decrease Secondary Subtitles Delay (2)\")]\n SubsDelayRemove2Secondary,\n\n [Description(\"Copy Opened Item to Clipboard\")]\n CopyToClipboard,\n [Description(\"Copy Current Played Item to Clipboard\")]\n CopyItemToClipboard,\n [Description(\"Open a media from clipboard\")]\n OpenFromClipboard,\n [Description(\"Open a media from clipboard if not open\")]\n OpenFromClipboardSafe,\n [Description(\"Open a media from file dialog\")]\n OpenFromFileDialog,\n\n [Description(\"Stop playback\")]\n Stop,\n [Description(\"Pause playback\")]\n Pause,\n [Description(\"Play playback\")]\n Play,\n [Description(\"Toggle play playback\")]\n TogglePlayPause,\n\n [Description(\"Toggle reverse playback\")]\n ToggleReversePlayback,\n [Description(\"Toggle loop playback\")]\n ToggleLoopPlayback,\n [Description(\"Flushes the buffer of the player\")]\n Flush,\n [Description(\"Take snapshot\")]\n TakeSnapshot,\n [Description(\"Change to NormalScreen\")]\n NormalScreen,\n [Description(\"Change to FullScreen\")]\n FullScreen,\n [Description(\"Toggle NormalScreen / FullScreen\")]\n ToggleFullScreen,\n\n [Description(\"Toggle Audio Enabled\")]\n ToggleAudio,\n [Description(\"Toggle Video Enabled\")]\n ToggleVideo,\n\n [Description(\"Toggle All Subtitles Visibility\")]\n ToggleSubtitlesVisibility,\n [Description(\"Toggle Primary Subtitles Visibility\")]\n ToggleSubtitlesVisibilityPrimary,\n [Description(\"Toggle Secondary Subtitles Visibility\")]\n ToggleSubtitlesVisibilitySecondary,\n\n [Description(\"Toggle Keep Aspect Ratio\")]\n ToggleKeepRatio,\n [Description(\"Toggle Video Acceleration\")]\n ToggleVideoAcceleration,\n [Description(\"Toggle Recording\")]\n ToggleRecording,\n [Description(\"Toggle Always Seek Accurate Mode\")]\n ToggleSeekAccurate,\n\n [Description(\"Seek forwards (1)\")]\n SeekForward,\n [Description(\"Seek backwards (1)\")]\n SeekBackward,\n [Description(\"Seek forwards (2)\")]\n SeekForward2,\n [Description(\"Seek backwards (2)\")]\n SeekBackward2,\n [Description(\"Seek forwards (3)\")]\n SeekForward3,\n [Description(\"Seek backwards (3)\")]\n SeekBackward3,\n [Description(\"Seek forwards (4)\")]\n SeekForward4,\n [Description(\"Seek backwards (4)\")]\n SeekBackward4,\n\n [Description(\"Seek to the previous subtitle\")]\n SubsPrevSeek,\n [Description(\"Seek to the current subtitle\")]\n SubsCurSeek,\n [Description(\"Seek to the next subtitle\")]\n SubsNextSeek,\n [Description(\"Seek to the previous subtitle or seek backwards\")]\n SubsPrevSeekFallback,\n [Description(\"Seek to the next subtitle or seek forwards\")]\n SubsNextSeekFallback,\n\n [Description(\"Seek to the previous secondary subtitle\")]\n SubsPrevSeek2,\n [Description(\"Seek to the current secondary subtitle\")]\n SubsCurSeek2,\n [Description(\"Seek to the next secondary subtitle\")]\n SubsNextSeek2,\n [Description(\"Seek to the previous secondary subtitle or seek backwards\")]\n SubsPrevSeekFallback2,\n [Description(\"Seek to the next secondary subtitle or seek forwards\")]\n SubsNextSeekFallback2,\n\n [Description(\"Speed Up (1)\")]\n SpeedAdd,\n [Description(\"Speed Up (2)\")]\n SpeedAdd2,\n\n [Description(\"Speed Down (1)\")]\n SpeedRemove,\n [Description(\"Speed Down (2)\")]\n SpeedRemove2,\n\n [Description(\"Show Next Frame\")]\n ShowNextFrame,\n [Description(\"Show Previous Frame\")]\n ShowPrevFrame,\n\n [Description(\"Reset Zoom / Rotation / Speed\")]\n ResetAll,\n [Description(\"Reset Speed\")]\n ResetSpeed,\n [Description(\"Reset Rotation\")]\n ResetRotation,\n [Description(\"Reset Zoom\")]\n ResetZoom,\n\n [Description(\"Zoom In (1)\")]\n ZoomIn,\n [Description(\"Zoom Out (1)\")]\n ZoomOut,\n}\n"], ["/LLPlayer/FlyleafLib/MediaFramework/MediaPlaylist/PlaylistItem.cs", "using System.Collections.Generic;\nusing System.Collections.ObjectModel;\n\nusing FlyleafLib.MediaFramework.MediaDemuxer;\nusing FlyleafLib.MediaFramework.MediaStream;\n\nnamespace FlyleafLib.MediaFramework.MediaPlaylist;\n\npublic class PlaylistItem : DemuxerInput\n{\n public int Index { get; set; } = -1; // if we need it we need to ensure we fix it in case of removing an item\n\n /// \n /// While the Url can expire or be null DirectUrl can be used as a new input for re-opening\n /// \n public string DirectUrl { get; set; }\n\n /// \n /// Relative folder to playlist's folder base (can be empty, not null)\n /// Use Path.Combine(Playlist.FolderBase, Folder) to get absolute path for saving related files with the current selection item (such as subtitles)\n /// \n public string Folder { get; set; } = \"\";\n\n public long FileSize { get; set; }\n\n /// \n /// Usually just the filename part of the provided Url\n /// \n public string OriginalTitle { get => _OriginalTitle;set => SetUI(ref _OriginalTitle, value ?? \"\", false); }\n string _OriginalTitle = \"\";\n\n /// \n /// Movie/TVShow Title\n /// \n public string MediaTitle { get => _MediaTitle; set => SetUI(ref _MediaTitle, value ?? \"\", false); }\n string _MediaTitle = \"\";\n\n /// \n /// Movie/TVShow Title including Movie's Year or TVShow's Season/Episode\n /// \n public string Title { get => _Title; set { if (_Title == \"\") OriginalTitle = value; SetUI(ref _Title, value ?? \"\", false);} }\n string _Title = \"\";\n\n public List\n Chapters { get; set; } = new();\n\n public int Season { get; set; }\n public int Episode { get; set; }\n public int Year { get; set; }\n\n public Dictionary\n Tag { get; set; } = [];\n public void AddTag(object tag, string pluginName)\n {\n if (!Tag.TryAdd(pluginName, tag))\n Tag[pluginName] = tag;\n }\n\n public object GetTag(string pluginName)\n => Tag.TryGetValue(pluginName, out object value) ? value : null;\n\n public bool SearchedLocal { get; set; }\n public bool SearchedOnline { get; set; }\n\n /// \n /// Whether the item is currently enabled or not\n /// \n public bool Enabled { get => _Enabled; set { if (SetUI(ref _Enabled, value) && value == true) OpenedCounter++; } }\n bool _Enabled;\n public int OpenedCounter { get; set; }\n\n public ExternalVideoStream\n ExternalVideoStream { get; set; }\n public ExternalAudioStream\n ExternalAudioStream { get; set; }\n public ExternalSubtitlesStream[]\n ExternalSubtitlesStreams\n { get; set; } = new ExternalSubtitlesStream[2];\n\n public ObservableCollection\n ExternalVideoStreams { get; set; } = [];\n public ObservableCollection\n ExternalAudioStreams { get; set; } = [];\n public ObservableCollection\n ExternalSubtitlesStreamsAll\n { get; set; } = [];\n internal object lockExternalStreams = new();\n\n bool filled;\n public void FillMediaParts() // Called during OpenScrape (if file) & Open/Search Subtitles (to be able to search online and compare tvshow/movie properly)\n {\n if (filled)\n return;\n\n filled = true;\n var mp = Utils.GetMediaParts(OriginalTitle);\n Year = mp.Year;\n Season = mp.Season;\n Episode = mp.Episode;\n MediaTitle = mp.Title; // safe title to check with online subs\n\n if (mp.Season > 0 && mp.Episode > 0) // tvshow\n {\n var title = \"S\";\n title += Season > 9 ? Season : $\"0{Season}\";\n title += \"E\";\n title += Episode > 9 ? Episode : $\"0{Episode}\";\n\n Title = mp.Title == \"\" ? title : mp.Title + \" (\" + title + \")\";\n }\n else if (mp.Year > 0) // movie\n Title = mp.Title + \" (\" + mp.Year + \")\";\n }\n\n public static void AddExternalStream(ExternalStream extStream, PlaylistItem item, string pluginName, object tag = null)\n {\n lock (item.lockExternalStreams)\n {\n extStream.PlaylistItem = item;\n extStream.PluginName = pluginName;\n\n if (extStream is ExternalAudioStream astream)\n {\n item.ExternalAudioStreams.Add(astream);\n extStream.Index = item.ExternalAudioStreams.Count - 1;\n }\n else if (extStream is ExternalVideoStream vstream)\n {\n item.ExternalVideoStreams.Add(vstream);\n extStream.Index = item.ExternalVideoStreams.Count - 1;\n }\n else if (extStream is ExternalSubtitlesStream sstream)\n {\n item.ExternalSubtitlesStreamsAll.Add(sstream);\n extStream.Index = item.ExternalSubtitlesStreamsAll.Count - 1;\n }\n\n if (tag != null)\n extStream.AddTag(tag, pluginName);\n };\n }\n}\n"], ["/LLPlayer/FlyleafLib/Engine/Engine.Video.cs", "using System;\nusing System.Collections.Generic;\nusing System.Collections.ObjectModel;\n\nusing Vortice.DXGI;\n\nusing FlyleafLib.MediaFramework.MediaDevice;\n\nnamespace FlyleafLib;\n\npublic class VideoEngine\n{\n /// \n /// List of Video Capture Devices\n /// \n public ObservableCollection\n CapDevices { get; set; } = new();\n public void RefreshCapDevices() => VideoDevice.RefreshDevices();\n\n /// \n /// List of GPU Adpaters \n /// \n public Dictionary\n GPUAdapters { get; private set; }\n\n /// \n /// List of GPU Outputs from default GPU Adapter (Note: will no be updated on screen connect/disconnect)\n /// \n public List Screens { get; private set; } = new List();\n\n internal IDXGIFactory2 Factory;\n\n internal VideoEngine()\n {\n if (DXGI.CreateDXGIFactory1(out Factory).Failure)\n throw new InvalidOperationException(\"Cannot create IDXGIFactory1\");\n\n GPUAdapters = GetAdapters();\n }\n\n private Dictionary GetAdapters()\n {\n Dictionary adapters = new();\n\n string dump = \"\";\n\n for (uint i=0; Factory.EnumAdapters1(i, out var adapter).Success; i++)\n {\n bool hasOutput = false;\n\n List outputs = new();\n\n int maxHeight = 0;\n for (uint o=0; adapter.EnumOutputs(o, out var output).Success; o++)\n {\n GPUOutput gpout = new()\n {\n Id = GPUOutput.GPUOutputIdGenerator++,\n DeviceName= output.Description.DeviceName,\n Left = output.Description.DesktopCoordinates.Left,\n Top = output.Description.DesktopCoordinates.Top,\n Right = output.Description.DesktopCoordinates.Right,\n Bottom = output.Description.DesktopCoordinates.Bottom,\n IsAttached= output.Description.AttachedToDesktop,\n Rotation = (int)output.Description.Rotation\n };\n\n if (maxHeight < gpout.Height)\n maxHeight = gpout.Height;\n\n outputs.Add(gpout);\n\n if (gpout.IsAttached)\n hasOutput = true;\n\n output.Dispose();\n }\n\n if (Screens.Count == 0 && outputs.Count > 0)\n Screens = outputs;\n\n adapters[adapter.Description1.Luid] = new GPUAdapter()\n {\n SystemMemory = adapter.Description1.DedicatedSystemMemory.Value,\n VideoMemory = adapter.Description1.DedicatedVideoMemory.Value,\n SharedMemory = adapter.Description1.SharedSystemMemory.Value,\n Vendor = VendorIdStr(adapter.Description1.VendorId),\n Description = adapter.Description1.Description,\n Id = adapter.Description1.DeviceId,\n Luid = adapter.Description1.Luid,\n MaxHeight = maxHeight,\n HasOutput = hasOutput,\n Outputs = outputs\n };\n\n dump += $\"[#{i+1}] {adapters[adapter.Description1.Luid]}\\r\\n\";\n\n adapter.Dispose();\n }\n\n Engine.Log.Info($\"GPU Adapters\\r\\n{dump}\");\n\n return adapters;\n }\n\n // Use instead System.Windows.Forms.Screen.FromPoint\n public GPUOutput GetScreenFromPosition(int top, int left)\n {\n foreach(var screen in Screens)\n {\n if (top >= screen.Top && top <= screen.Bottom && left >= screen.Left && left <= screen.Right)\n return screen;\n }\n\n return null;\n }\n\n private static string VendorIdStr(uint vendorId)\n {\n switch (vendorId)\n {\n case 0x1002:\n return \"ATI\";\n case 0x10DE:\n return \"NVIDIA\";\n case 0x1106:\n return \"VIA\";\n case 0x8086:\n return \"Intel\";\n case 0x5333:\n return \"S3 Graphics\";\n case 0x4D4F4351:\n return \"Qualcomm\";\n default:\n return \"Unknown\";\n }\n }\n}\n"], ["/LLPlayer/FlyleafLib/MediaPlayer/Translation/SubtitlesTranslator.cs", "using System.Collections.Generic;\nusing System.ComponentModel;\nusing System.Diagnostics;\nusing System.Linq;\nusing System.Threading;\nusing System.Threading.Tasks;\nusing FlyleafLib.MediaPlayer.Translation.Services;\nusing static FlyleafLib.Logger;\n\nnamespace FlyleafLib.MediaPlayer.Translation;\n\n#nullable enable\n\npublic class SubTranslator\n{\n private readonly SubManager _subManager;\n private readonly Config.SubtitlesConfig _config;\n private readonly int _subIndex;\n\n private ITranslateService? _translateService;\n private CancellationTokenSource? _translationCancellation;\n private readonly TranslateServiceFactory _translateServiceFactory;\n private Task? _translateTask;\n private bool _isReset;\n private Language? _srcLang;\n\n private bool IsEnabled => _config[_subIndex].EnabledTranslated;\n\n private readonly LogHandler Log;\n\n public SubTranslator(SubManager subManager, Config.SubtitlesConfig config, int subIndex)\n {\n _subManager = subManager;\n _config = config;\n _subIndex = subIndex;\n\n _subManager.PropertyChanged += SubManager_OnPropertyChanged;\n\n // apply config changes\n _config.PropertyChanged += SubtitlesConfig_OnPropertyChanged;\n _config.SubConfigs[subIndex].PropertyChanged += SubConfig_OnPropertyChanged;\n _config.TranslateChatConfig.PropertyChanged += TranslateChatConfig_OnPropertyChanged;\n\n _translateServiceFactory = new TranslateServiceFactory(config);\n\n Log = new LogHandler((\"[#1]\").PadRight(8, ' ') + $\" [Translator{subIndex + 1} ] \");\n }\n\n private int _oldIndex = -1;\n private CancellationTokenSource? _translationStartCancellation;\n\n private void SubManager_OnPropertyChanged(object? sender, PropertyChangedEventArgs e)\n {\n switch (e.PropertyName)\n {\n case nameof(SubManager.CurrentIndex):\n if (!IsEnabled || _subManager.Subs.Count == 0 || _subManager.Language == null)\n return;\n\n if (_translateService == null)\n {\n // capture for later initialization\n _srcLang = _subManager.Language;\n }\n\n if (_translationStartCancellation != null)\n {\n _translationStartCancellation.Cancel();\n _translationStartCancellation.Dispose();\n _translationStartCancellation = null;\n }\n _translationStartCancellation = new CancellationTokenSource();\n _ = UpdateCurrentIndexAsync(_subManager.CurrentIndex, _translationStartCancellation.Token);\n break;\n case nameof(SubManager.Language):\n _ = Reset();\n break;\n }\n }\n\n private void SubtitlesConfig_OnPropertyChanged(object? sender, PropertyChangedEventArgs e)\n {\n string languageFallbackPropName = _subIndex == 0 ?\n nameof(Config.SubtitlesConfig.LanguageFallbackPrimary) :\n nameof(Config.SubtitlesConfig.LanguageFallbackSecondary);\n\n if (e.PropertyName is\n nameof(Config.SubtitlesConfig.TranslateServiceType) or\n nameof(Config.SubtitlesConfig.TranslateTargetLanguage)\n ||\n e.PropertyName == languageFallbackPropName)\n {\n // Apply translating config changes\n _ = Reset();\n }\n }\n\n private void SubConfig_OnPropertyChanged(object? sender, PropertyChangedEventArgs e)\n {\n // Reset when translation is off\n if (e.PropertyName is nameof(Config.SubConfig.EnabledTranslated))\n {\n if (!IsEnabled)\n {\n _ = Reset();\n }\n }\n }\n\n private void TranslateChatConfig_OnPropertyChanged(object? sender, PropertyChangedEventArgs e)\n {\n _ = Reset();\n }\n\n private async Task Reset()\n {\n if (_translateService == null)\n return;\n\n try\n {\n _isReset = true;\n await Cancel();\n\n _translateService?.Dispose();\n _translateService = null;\n _srcLang = null;\n }\n finally\n {\n _isReset = false;\n }\n }\n\n private async Task Cancel()\n {\n _translationCancellation?.Cancel();\n Task? pendingTask = _translateTask;\n if (pendingTask != null)\n {\n await pendingTask;\n }\n _translateTask = null;\n }\n\n private async Task UpdateCurrentIndexAsync(int newIndex, CancellationToken token)\n {\n if (newIndex != -1 && _subManager.Subs.Any())\n {\n int indexDiff = Math.Abs(_oldIndex - newIndex);\n bool isForward = newIndex > _oldIndex;\n _oldIndex = newIndex;\n\n if ((isForward && indexDiff > _config.TranslateCountForward) ||\n (!isForward && indexDiff > _config.TranslateCountBackward))\n {\n // Cancel a running translation request when a large seek is performed\n await Cancel();\n }\n else if (_translateTask != null)\n {\n // for performance\n return;\n }\n\n // Prevent continuous firing when continuously switching subtitles with sub seek\n if (indexDiff == 1)\n {\n if (_subManager.Subs[newIndex].Duration.TotalMilliseconds > 320)\n {\n await Task.Delay(300, token);\n }\n }\n token.ThrowIfCancellationRequested();\n\n if (_translateTask == null && !_isReset)\n {\n // singleton task\n // Ensure that it is not executed in the main thread because it scans all subtitles\n Task task = Task.Run(async () =>\n {\n try\n {\n await TranslateAheadAsync(newIndex, _config.TranslateCountBackward, _config.TranslateCountForward);\n }\n finally\n {\n _translateTask = null;\n }\n });\n _translateTask = task;\n }\n }\n }\n\n private readonly Lock _initLock = new();\n // initialize TranslateService lazily\n private void EnsureTranslationService()\n {\n if (_translateService != null)\n {\n return;\n }\n\n // double-check lock pattern\n lock (_initLock)\n {\n if (_translateService == null)\n {\n var service = _translateServiceFactory.GetService(_config.TranslateServiceType, false);\n service.Initialize(_srcLang!, _config.TranslateTargetLanguage);\n\n Volatile.Write(ref _translateService, service);\n }\n }\n }\n\n private async Task TranslateAheadAsync(int currentIndex, int countBackward, int countForward)\n {\n try\n {\n // Token for canceling translation, releasing previous one to prevent leakage\n _translationCancellation?.Dispose();\n _translationCancellation = new CancellationTokenSource();\n\n var token = _translationCancellation.Token;\n int start = Math.Max(0, currentIndex - countBackward);\n int end = Math.Min(start + countForward - 1, _subManager.Subs.Count - 1);\n\n List translateSubs = new();\n for (int i = start; i <= end; i++)\n {\n if (token.IsCancellationRequested)\n break;\n if (i >= _subManager.Subs.Count)\n break;\n\n var sub = _subManager.Subs[i];\n if (!sub.IsTranslated && !string.IsNullOrEmpty(sub.Text))\n {\n translateSubs.Add(sub);\n }\n }\n\n if (translateSubs.Count == 0)\n return;\n\n int concurrency = _config.TranslateMaxConcurrency;\n\n if (concurrency > 1 && _config.TranslateServiceType.IsLLM() &&\n _config.TranslateChatConfig.TranslateMethod == ChatTranslateMethod.KeepContext)\n {\n // fixed to 1\n // it must be sequential because of maintaining context\n concurrency = 1;\n }\n\n if (concurrency <= 1)\n {\n // sequentially (important to maintain execution order for LLM)\n foreach (var sub in translateSubs)\n {\n await TranslateSubAsync(sub, token);\n }\n }\n else\n {\n // concurrently\n ParallelOptions parallelOptions = new()\n {\n CancellationToken = token,\n MaxDegreeOfParallelism = concurrency\n };\n\n await Parallel.ForEachAsync(\n translateSubs,\n parallelOptions,\n async (sub, ct) =>\n {\n await TranslateSubAsync(sub, ct);\n });\n }\n }\n catch (OperationCanceledException)\n {\n // ignore\n }\n catch (Exception ex)\n {\n Log.Error($\"Translation failed: {ex.Message}\");\n\n bool isConfigError = ex is TranslationConfigException;\n\n // Unable to translate, so turn off the translation and notify\n _config[_subIndex].EnabledTranslated = false;\n _ = Reset().ContinueWith((_) =>\n {\n if (isConfigError)\n {\n _config.player.RaiseKnownErrorOccurred($\"Translation Failed: {ex.Message}\", KnownErrorType.Configuration);\n }\n else\n {\n _config.player.RaiseUnknownErrorOccurred($\"Translation Failed: {ex.Message}\", UnknownErrorType.Translation, ex);\n }\n });\n }\n }\n\n private async Task TranslateSubAsync(SubtitleData sub, CancellationToken token)\n {\n string? text = sub.Text;\n if (string.IsNullOrEmpty(text))\n return;\n\n try\n {\n long start = Stopwatch.GetTimestamp();\n string translateText = SubtitleTextUtil.FlattenText(text);\n if (CanDebug) Log.Debug($\"Translation Start {sub.Index} - {translateText}\");\n EnsureTranslationService();\n string translated = await _translateService!.TranslateAsync(translateText, token);\n sub.TranslatedText = translated;\n\n if (CanDebug)\n {\n TimeSpan elapsed = Stopwatch.GetElapsedTime(start);\n Log.Debug($\"Translation End {sub.Index} in {elapsed.TotalMilliseconds} - {translated}\");\n }\n }\n catch (OperationCanceledException)\n {\n if (CanDebug) Log.Debug($\"Translation Cancel {sub.Index}\");\n throw;\n }\n }\n}\n"], ["/LLPlayer/LLPlayer/Services/AppConfig.cs", "using System.Collections.ObjectModel;\nusing System.ComponentModel;\nusing System.IO;\nusing System.Text.Json;\nusing System.Text.Json.Serialization;\nusing System.Windows;\nusing System.Windows.Input;\nusing System.Windows.Media;\nusing FlyleafLib;\nusing FlyleafLib.MediaPlayer;\nusing FlyleafLib.MediaPlayer.Translation.Services;\nusing LLPlayer.Extensions;\nusing MaterialDesignThemes.Wpf;\nusing Vortice.Mathematics;\nusing Color = System.Windows.Media.Color;\nusing Colors = System.Windows.Media.Colors;\nusing Size = System.Windows.Size;\n\nnamespace LLPlayer.Services;\n\npublic class AppConfig : Bindable\n{\n private FlyleafManager FL = null!;\n\n public void Initialize(FlyleafManager fl)\n {\n FL = fl;\n Loaded = true;\n\n Subs.Initialize(this, fl);\n }\n\n public string Version { get; set; } = \"\";\n\n /// \n /// State to skip the setter run when reading JSON\n /// \n [JsonIgnore]\n public bool Loaded { get; private set; }\n\n public void FlyleafHostLoaded()\n {\n Subs.FlyleafHostLoaded();\n\n // Ensure that FlyeafHost reflects the configuration values when restoring the configuration.\n FL.FlyleafHost!.ActivityTimeout = FL.Config.ActivityTimeout;\n }\n\n public AppConfigSubs Subs { get; set => Set(ref field, value); } = new();\n\n public static AppConfig Load(string path)\n {\n AppConfig config = JsonSerializer.Deserialize(File.ReadAllText(path), GetJsonSerializerOptions())!;\n\n return config;\n }\n\n public void Save(string path)\n {\n Version = App.Version;\n File.WriteAllText(path, JsonSerializer.Serialize(this, GetJsonSerializerOptions()));\n\n Subs.SaveAfter();\n }\n\n public AppConfigTheme Theme { get; set => Set(ref field, value); } = new();\n\n public bool AlwaysOnTop { get; set => Set(ref field, value); }\n\n [JsonIgnore]\n public double ScreenWidth\n {\n private get;\n set => Set(ref field, value);\n }\n\n // Video Screen Height (including black background), without titlebar height\n [JsonIgnore]\n public double ScreenHeight\n {\n internal get;\n set\n {\n if (Set(ref field, value))\n {\n Subs.UpdateSubsConfig();\n }\n }\n }\n\n public bool IsDarkTitlebar { get; set => Set(ref field, value); } = true;\n\n public int ActivityTimeout\n {\n get;\n set\n {\n if (Set(ref field, value))\n {\n if (Loaded && FL.FlyleafHost != null)\n {\n FL.FlyleafHost.ActivityTimeout = value;\n }\n }\n }\n } = 1200;\n\n public bool ShowSidebar { get; set => Set(ref field, value); } = true;\n\n [JsonIgnore]\n public bool ShowDebug\n {\n get;\n set\n {\n if (Set(ref field, value))\n {\n FL.PlayerConfig.Player.Stats = value;\n }\n }\n }\n\n\n #region FlyleafBar\n public bool SeekBarShowOnlyMouseOver { get; set => Set(ref field, value); } = false;\n public int SeekBarFadeInTimeMs { get; set => Set(ref field, value); } = 80;\n public int SeekBarFadeOutTimeMs { get; set => Set(ref field, value); } = 150;\n #endregion\n\n #region Mouse\n public bool MouseSingleClickToPlay { get; set => Set(ref field, value); } = true;\n public bool MouseDoubleClickToFullScreen { get; set => Set(ref field, value); }\n public bool MouseWheelToVolumeUpDown { get; set => Set(ref field, value); } = true;\n #endregion\n\n // TODO: L: should be move to AppConfigSubs?\n public bool SidebarLeft\n {\n get;\n set\n {\n if (Set(ref field, value))\n {\n OnPropertyChanged(nameof(SidebarFlowDirection));\n }\n }\n }\n\n [JsonIgnore]\n public FlowDirection SidebarFlowDirection => !SidebarLeft ? FlowDirection.LeftToRight : FlowDirection.RightToLeft;\n\n public int SidebarWidth { get; set => Set(ref field, value); } = 300;\n\n public int SidebarSubPadding { get; set => Set(ref field, value); } = 5;\n\n [JsonIgnore]\n public bool SidebarShowSecondary { get; set => Set(ref field, value); }\n\n public bool SidebarShowOriginalText { get; set => Set(ref field, value); }\n\n public bool SidebarTextMask { get; set => Set(ref field, value); }\n\n [JsonIgnore]\n public bool SidebarSearchActive { get; set => Set(ref field, value); }\n\n public string SidebarFontFamily { get; set => Set(ref field, value); } = \"Segoe UI\";\n\n public double SidebarFontSize { get; set => Set(ref field, value); } = 16;\n\n public string SidebarFontWeight { get; set => Set(ref field, value); } = FontWeights.Normal.ToString();\n\n public static JsonSerializerOptions GetJsonSerializerOptions()\n {\n Dictionary typeMappingMenuAction = new()\n {\n { nameof(ClipboardMenuAction), typeof(ClipboardMenuAction) },\n { nameof(ClipboardAllMenuAction), typeof(ClipboardAllMenuAction) },\n { nameof(SearchMenuAction), typeof(SearchMenuAction) },\n };\n\n Dictionary typeMappingTranslateSettings = new()\n {\n { nameof(GoogleV1TranslateSettings), typeof(GoogleV1TranslateSettings) },\n { nameof(DeepLTranslateSettings), typeof(DeepLTranslateSettings) },\n { nameof(DeepLXTranslateSettings), typeof(DeepLXTranslateSettings) },\n { nameof(OllamaTranslateSettings), typeof(OllamaTranslateSettings) },\n { nameof(LMStudioTranslateSettings), typeof(LMStudioTranslateSettings) },\n { nameof(KoboldCppTranslateSettings), typeof(KoboldCppTranslateSettings) },\n { nameof(OpenAITranslateSettings), typeof(OpenAITranslateSettings) },\n { nameof(OpenAILikeTranslateSettings), typeof(OpenAILikeTranslateSettings) },\n { nameof(ClaudeTranslateSettings), typeof(ClaudeTranslateSettings) },\n { nameof(LiteLLMTranslateSettings), typeof(LiteLLMTranslateSettings) }\n };\n\n JsonSerializerOptions jsonOptions = new()\n {\n WriteIndented = true,\n DefaultIgnoreCondition = JsonIgnoreCondition.WhenWritingNull,\n Converters =\n {\n new JsonStringEnumConverter(),\n // TODO: L: should separate converters for different types of config?\n new JsonInterfaceConcreteConverter(typeMappingMenuAction),\n new JsonInterfaceConcreteConverter(typeMappingTranslateSettings),\n new ColorHexJsonConverter()\n }\n };\n\n return jsonOptions;\n }\n}\n\npublic class AppConfigSubs : Bindable\n{\n private AppConfig _rootConfig = null!;\n private FlyleafManager FL = null!;\n\n [JsonIgnore]\n public bool Loaded { get; private set; }\n\n public void Initialize(AppConfig rootConfig, FlyleafManager fl)\n {\n _rootConfig = rootConfig;\n FL = fl;\n Loaded = true;\n\n // Save the initial value of the position for reset.\n _subsPositionInitial = SubsPosition;\n\n // register event handler\n var pSubsAutoCopy = SubsAutoTextCopy;\n SubsAutoTextCopy = false;\n SubsAutoTextCopy = pSubsAutoCopy;\n }\n\n public void FlyleafHostLoaded()\n {\n Viewport = FL.Player.renderer.GetViewport;\n\n FL.Player.renderer.ViewportChanged += (sender, args) =>\n {\n Utils.UIIfRequired(() =>\n {\n Viewport = FL.Player.renderer.GetViewport;\n });\n };\n }\n\n public void SaveAfter()\n {\n // Update initial value\n _subsPositionInitial = SubsPosition;\n }\n\n [JsonIgnore]\n public Viewport Viewport\n {\n get;\n private set\n {\n var prev = Viewport;\n if (Set(ref field, value))\n {\n if ((int)prev.Width != (int)value.Width)\n {\n // update font size if width changed\n OnPropertyChanged(nameof(SubsFontSizeFix));\n OnPropertyChanged(nameof(SubsFontSize2Fix));\n }\n\n if ((int)prev.Height != (int)value.Height ||\n (int)prev.Y != (int)value.Y)\n {\n // update font margin/distance if height/Y changed\n UpdateSubsConfig();\n }\n }\n }\n }\n\n public bool SubsUseSeparateFonts\n {\n get;\n set\n {\n if (Set(ref field, value))\n {\n // update subtitles\n UpdateSecondaryFonts();\n\n OnPropertyChanged(nameof(SubsFontColor2Fix));\n OnPropertyChanged(nameof(SubsBackgroundBrush2));\n }\n }\n }\n\n internal void UpdateSecondaryFonts()\n {\n // update subtitles display\n OnPropertyChanged(nameof(SubsFontFamily2Fix));\n OnPropertyChanged(nameof(SubsFontStretch2Fix));\n OnPropertyChanged(nameof(SubsFontWeight2Fix));\n OnPropertyChanged(nameof(SubsFontStyle2Fix));\n\n CmdResetSubsFont2!.RaiseCanExecuteChanged();\n }\n\n // Primary Subtitle Size\n public double SubsFontSize\n {\n get;\n set\n {\n if (value <= 0)\n {\n return;\n }\n\n if (Set(ref field, Math.Round(value)))\n {\n OnPropertyChanged(nameof(SubsFontSizeFix));\n CmdResetSubsFontSize2!.RaiseCanExecuteChanged();\n }\n }\n } = 44;\n\n [JsonIgnore]\n public double SubsFontSizeFix => GetFixFontSize(SubsFontSize);\n\n // Secondary Subtitle Size\n public double SubsFontSize2\n {\n get;\n set\n {\n if (value <= 0)\n {\n return;\n }\n\n if (Set(ref field, Math.Round(value)))\n {\n OnPropertyChanged(nameof(SubsFontSize2Fix));\n CmdResetSubsFontSize2!.RaiseCanExecuteChanged();\n }\n }\n } = 44;\n\n [JsonIgnore]\n public double SubsFontSize2Fix => GetFixFontSize(SubsFontSize2);\n\n private double GetFixFontSize(double fontSize)\n {\n double scaleFactor = Viewport.Width / 1920;\n double size = fontSize * scaleFactor;\n if (size > 0)\n {\n return size;\n }\n\n return fontSize;\n }\n\n private const string DefaultFont = \"Segoe UI\";\n public string SubsFontFamily { get; set => Set(ref field, value); } = DefaultFont;\n public string SubsFontStretch { get; set => Set(ref field, value); } = FontStretches.Normal.ToString();\n public string SubsFontWeight { get; set => Set(ref field, value); } = FontWeights.Bold.ToString();\n public string SubsFontStyle { get; set => Set(ref field, value); } = FontStyles.Normal.ToString();\n public Color SubsFontColor\n {\n get;\n set\n {\n if (Set(ref field, value))\n {\n OnPropertyChanged(nameof(SubsFontColor2Fix));\n CmdResetSubsFontColor2!.RaiseCanExecuteChanged();\n }\n }\n } = Colors.White;\n\n [JsonIgnore]\n public string SubsFontFamily2Fix => SubsUseSeparateFonts ? SubsFontFamily2 : SubsFontFamily;\n public string SubsFontFamily2 { get; set => Set(ref field, value); } = DefaultFont;\n\n [JsonIgnore]\n public string SubsFontStretch2Fix => SubsUseSeparateFonts ? SubsFontStretch2 : SubsFontStretch;\n public string SubsFontStretch2 { get; set => Set(ref field, value); } = FontStretches.Normal.ToString();\n\n [JsonIgnore]\n public string SubsFontWeight2Fix => SubsUseSeparateFonts ? SubsFontWeight2 : SubsFontWeight;\n public string SubsFontWeight2 { get; set => Set(ref field, value); } = FontWeights.SemiBold.ToString(); // change from bold\n\n [JsonIgnore]\n public string SubsFontStyle2Fix => SubsUseSeparateFonts ? SubsFontStyle2 : SubsFontStyle;\n public string SubsFontStyle2 { get; set => Set(ref field, value); } = FontStyles.Normal.ToString();\n\n [JsonIgnore]\n public Color SubsFontColor2Fix => SubsUseSeparateFonts ? SubsFontColor2 : SubsFontColor;\n public Color SubsFontColor2\n {\n get;\n set\n {\n if (Set(ref field, value))\n {\n OnPropertyChanged(nameof(SubsFontColor2Fix));\n CmdResetSubsFontColor2!.RaiseCanExecuteChanged();\n }\n }\n } = Color.FromRgb(231, 231, 231); // #E7E7E7\n\n public Color SubsStrokeColor { get; set => Set(ref field, value); } = Colors.Black;\n public double SubsStrokeThickness { get; set => Set(ref field, value); } = 3.2;\n\n public Color SubsBackgroundColor\n {\n get;\n set\n {\n if (Set(ref field, value))\n {\n OnPropertyChanged(nameof(SubsBackgroundBrush));\n OnPropertyChanged(nameof(SubsBackgroundBrush2));\n }\n }\n } = Colors.Black;\n\n public double SubsBackgroundOpacity\n {\n get;\n set\n {\n if (value < 0.0 || value > 1.0)\n {\n return;\n }\n\n if (Set(ref field, Math.Round(value, 2)))\n {\n OnPropertyChanged(nameof(SubsBackgroundBrush));\n OnPropertyChanged(nameof(SubsBackgroundBrush2));\n CmdResetSubsBackgroundOpacity2!.RaiseCanExecuteChanged();\n }\n }\n } = 0; // default no background\n\n [JsonIgnore]\n public SolidColorBrush SubsBackgroundBrush\n {\n get\n {\n byte alpha = (byte)(SubsBackgroundOpacity * 255);\n return new SolidColorBrush(Color.FromArgb(alpha, SubsBackgroundColor.R, SubsBackgroundColor.G, SubsBackgroundColor.B));\n }\n }\n\n [JsonIgnore]\n private double SubsBackgroundOpacity2Fix => SubsUseSeparateFonts ? SubsBackgroundOpacity2 : SubsBackgroundOpacity;\n public double SubsBackgroundOpacity2\n {\n get;\n set\n {\n if (value < 0.0 || value > 1.0)\n {\n return;\n }\n\n if (Set(ref field, Math.Round(value, 2)))\n {\n OnPropertyChanged(nameof(SubsBackgroundBrush2));\n CmdResetSubsBackgroundOpacity2!.RaiseCanExecuteChanged();\n }\n }\n } = 0;\n\n [JsonIgnore]\n public SolidColorBrush SubsBackgroundBrush2\n {\n get\n {\n byte alpha = (byte)(SubsBackgroundOpacity2Fix * 255);\n return new SolidColorBrush(Color.FromArgb(alpha, SubsBackgroundColor.R, SubsBackgroundColor.G, SubsBackgroundColor.B));\n }\n }\n\n [JsonIgnore]\n public DelegateCommand? CmdResetSubsFontSize2 => field ??= new(() =>\n {\n SubsFontSize2 = SubsFontSize;\n }, () => SubsFontSize2 != SubsFontSize);\n\n [JsonIgnore]\n public DelegateCommand? CmdResetSubsFont2 => field ??= new(() =>\n {\n SubsFontFamily2 = SubsFontFamily;\n SubsFontStretch2 = SubsFontStretch;\n SubsFontWeight2 = SubsFontWeight;\n SubsFontStyle2 = SubsFontStyle;\n\n UpdateSecondaryFonts();\n }, () =>\n SubsFontFamily2 != SubsFontFamily ||\n SubsFontStretch2 != SubsFontStretch ||\n SubsFontWeight2 != SubsFontWeight ||\n SubsFontStyle2 != SubsFontStyle\n );\n\n [JsonIgnore]\n public DelegateCommand? CmdResetSubsFontColor2 => field ??= new(() =>\n {\n SubsFontColor2 = SubsFontColor;\n }, () => SubsFontColor2 != SubsFontColor);\n\n [JsonIgnore]\n public DelegateCommand? CmdResetSubsBackgroundOpacity2 => field ??= new(() =>\n {\n SubsBackgroundOpacity2 = SubsBackgroundOpacity;\n }, () => SubsBackgroundOpacity2 != SubsBackgroundOpacity);\n\n [JsonIgnore]\n public Size SubsPanelSize\n {\n private get;\n set\n {\n if (Set(ref field, value))\n {\n UpdateSubsMargin();\n }\n }\n }\n\n private bool _isSubsOverflowBottom;\n\n [JsonIgnore]\n public Thickness SubsMargin\n {\n get;\n set => Set(ref field, value);\n }\n\n private double _subsPositionInitial;\n public void ResetSubsPosition()\n {\n SubsPosition = _subsPositionInitial;\n }\n\n #region Offsets\n\n public double SubsPositionOffset { get; set => Set(ref field, value); } = 2;\n public int SubsFontSizeOffset { get; set => Set(ref field, value); } = 2;\n public double SubsBitmapScaleOffset { get; set => Set(ref field, value); } = 4;\n public double SubsDistanceOffset { get; set => Set(ref field, value); } = 5;\n\n #endregion\n\n // -25%-150%\n // Allow some going up and down from ViewPort\n public double SubsPosition\n {\n get;\n set\n {\n if (_isSubsOverflowBottom && SubsPanelSize.Height > 0 && field < value)\n {\n // Prohibit going further down when it overflows below.\n return;\n }\n\n if (value < -25 || value > 150)\n {\n return;\n }\n\n if (Set(ref field, Math.Round(value)))\n {\n UpdateSubsMargin();\n }\n }\n } = 85;\n\n public SubPositionAlignment SubsPositionAlignment\n {\n get;\n set\n {\n if (Set(ref field, value))\n {\n UpdateSubsConfig();\n }\n }\n } = SubPositionAlignment.Center;\n\n public SubPositionAlignment SubsPositionAlignmentWhenDual\n {\n get;\n set\n {\n if (Set(ref field, value))\n {\n UpdateSubsConfig();\n }\n }\n } = SubPositionAlignment.Top;\n\n // 0%-100%\n public double SubsFixOverflowMargin\n {\n get;\n set\n {\n if (value < 0.0 || value > 100.0)\n {\n return;\n }\n\n Set(ref field, value);\n }\n } = 3.0;\n\n [JsonIgnore]\n public double SubsDistanceFix { get; set => Set(ref field, value); }\n\n public double SubsDistance\n {\n get;\n set\n {\n if (value < 1)\n {\n return;\n }\n\n if (Set(ref field, Math.Round(value)))\n {\n UpdateSubsDistance();\n }\n }\n } = 16;\n\n public double SubsSeparatorMaxWidth { get; set => Set(ref field, value); } = 280;\n public double SubsSeparatorOpacity\n {\n get;\n set\n {\n if (value < 0.0 || value > 1.0)\n {\n return;\n }\n\n Set(ref field, value);\n }\n } = 0.3;\n\n public double SubsWidthPercentage\n {\n get;\n set\n {\n if (value < 1.0 || value > 100.0)\n {\n return;\n }\n\n Set(ref field, value);\n }\n } = 66.0;\n\n public double SubsMaxWidth\n {\n get;\n set\n {\n if (value < 0)\n {\n return;\n }\n\n Set(ref field, value);\n }\n } = 0;\n\n public bool SubsIgnoreLineBreak { get; set => Set(ref field, value); }\n\n internal void UpdateSubsConfig()\n {\n if (!Loaded)\n return;\n\n UpdateSubsDistance();\n UpdateSubsMargin();\n }\n\n private void UpdateSubsDistance()\n {\n if (!Loaded)\n return;\n\n float scaleFactor = Viewport.Height / 1080;\n double newDistance = SubsDistance * scaleFactor;\n\n SubsDistanceFix = newDistance;\n }\n\n private void UpdateSubsMargin()\n {\n if (!Loaded)\n return;\n\n // Set the margin from the top based on Viewport, not Window\n // Allow going above or below the Viewport\n float offset = Viewport.Y;\n float height = Viewport.Height;\n\n double marginTop = height * (SubsPosition / 100.0);\n double marginTopFix = marginTop + offset;\n\n // Adjustment for vertical alignment of subtitles\n SubPositionAlignment alignment = SubsPositionAlignment;\n if (FL.Player.Subtitles[0].Enabled && FL.Player.Subtitles[1].Enabled)\n {\n alignment = SubsPositionAlignmentWhenDual;\n }\n\n if (alignment == SubPositionAlignment.Center)\n {\n marginTopFix -= SubsPanelSize.Height / 2;\n }\n else if (alignment == SubPositionAlignment.Bottom)\n {\n marginTopFix -= SubsPanelSize.Height;\n }\n\n // Corrects for off-screen subtitles if they are detected.\n marginTopFix = FixOverflowSubsPosition(marginTopFix);\n\n SubsMargin = new Thickness(SubsMargin.Left, marginTopFix, SubsMargin.Right, SubsMargin.Bottom);\n }\n\n /// \n /// Detects whether subtitles are placed off-screen and corrects them if they appear\n /// \n /// \n /// \n private double FixOverflowSubsPosition(double marginTop)\n {\n double subHeight = SubsPanelSize.Height;\n\n double bottomMargin = Viewport.Height * (SubsFixOverflowMargin / 100.0);\n\n if (subHeight + marginTop + bottomMargin > _rootConfig.ScreenHeight)\n {\n // It overflowed, so fix it.\n _isSubsOverflowBottom = true;\n double fixedMargin = _rootConfig.ScreenHeight - subHeight - bottomMargin;\n return fixedMargin;\n }\n\n _isSubsOverflowBottom = false;\n return marginTop;\n }\n\n public bool SubsExportUTF8WithBom { get; set => Set(ref field, value); } = true;\n\n public bool SubsAutoTextCopy\n {\n get;\n set\n {\n if (Set(ref field, value) && Loaded)\n {\n if (value)\n {\n FL.Player.Subtitles[0].Data.PropertyChanged += SubtitleTextOnPropertyChanged;\n FL.Player.Subtitles[1].Data.PropertyChanged += SubtitleTextOnPropertyChanged;\n }\n else\n {\n FL.Player.Subtitles[0].Data.PropertyChanged -= SubtitleTextOnPropertyChanged;\n FL.Player.Subtitles[1].Data.PropertyChanged -= SubtitleTextOnPropertyChanged;\n }\n }\n }\n }\n\n public SubAutoTextCopyTarget SubsAutoTextCopyTarget { get; set => Set(ref field, value); } = SubAutoTextCopyTarget.Primary;\n\n private void SubtitleTextOnPropertyChanged(object? sender, PropertyChangedEventArgs e)\n {\n if (e.PropertyName != nameof(SubsData.Text))\n return;\n\n switch (SubsAutoTextCopyTarget)\n {\n case SubAutoTextCopyTarget.All:\n if (FL.Player.Subtitles[0].Data.Text != \"\" ||\n FL.Player.Subtitles[1].Data.Text != \"\")\n {\n FL.Action.CmdSubsTextCopy.Execute(true);\n }\n break;\n case SubAutoTextCopyTarget.Primary:\n if (FL.Player.Subtitles[0].Data == sender && FL.Player.Subtitles[0].Data.Text != \"\")\n {\n FL.Action.CmdSubsPrimaryTextCopy.Execute(true);\n }\n break;\n case SubAutoTextCopyTarget.Secondary:\n if (FL.Player.Subtitles[1].Data == sender && FL.Player.Subtitles[1].Data.Text != \"\")\n {\n FL.Action.CmdSubsSecondaryTextCopy.Execute(true);\n }\n break;\n }\n }\n\n public WordClickAction WordClickActionMethod { get; set => Set(ref field, value); }\n public bool WordCopyOnSelected { get; set => Set(ref field, value); } = true;\n public bool WordLastSearchOnSelected { get; set => Set(ref field, value); } = true;\n\n public ModifierKeys WordLastSearchOnSelectedModifier { get; set => Set(ref field, value); } = ModifierKeys.Control;\n public ObservableCollection WordMenuActions { get; set => Set(ref field, value); } = new(\n [\n new ClipboardMenuAction(),\n new ClipboardAllMenuAction(),\n new SearchMenuAction{ Title = \"Search Google\", Url = \"https://www.google.com/search?q=%w\" },\n new SearchMenuAction{ Title = \"Search Wiktionary\", Url = \"https://en.wiktionary.org/wiki/Special:Search?search=%w&go=Look+up\" },\n new SearchMenuAction{ Title = \"Search Longman\", Url = \"https://www.ldoceonline.com/search/english/direct/?q=%w\" },\n ]);\n public string? PDICPipeExecutablePath { get; set => Set(ref field, value); }\n}\n\npublic enum SubAutoTextCopyTarget\n{\n Primary,\n Secondary,\n All\n}\n\npublic enum SubPositionAlignment\n{\n Top, // This is useful for dual subs because primary sub position is stayed\n Center, // Same as bitmap subs\n Bottom // Normal video players use this\n}\n\npublic class AppConfigTheme : Bindable\n{\n private readonly PaletteHelper _paletteHelper = new();\n\n public Color PrimaryColor\n {\n get;\n set\n {\n if (Set(ref field, value))\n {\n Theme cur = _paletteHelper.GetTheme();\n cur.SetPrimaryColor(value);\n _paletteHelper.SetTheme(cur);\n }\n }\n } = (Color)ColorConverter.ConvertFromString(\"#D23D6F\"); // Pink\n // Desaturate and lighten from material pink 500\n // https://m2.material.io/design/color/the-color-system.html#tools-for-picking-colors\n // $ pastel color E91E63 | pastel desaturate 0.2 | pastel lighten 0.015\n\n public Color SecondaryColor\n {\n get;\n set\n {\n if (Set(ref field, value))\n {\n Theme cur = _paletteHelper.GetTheme();\n cur.SetSecondaryColor(value);\n _paletteHelper.SetTheme(cur);\n }\n }\n } = (Color)ColorConverter.ConvertFromString(\"#00B8D4\"); // Cyan\n}\n\npublic interface IMenuAction : INotifyPropertyChanged, ICloneable\n{\n [JsonIgnore]\n string Type { get; }\n string Title { get; set; }\n bool IsEnabled { get; set; }\n}\n\npublic class SearchMenuAction : Bindable, IMenuAction\n{\n [JsonIgnore]\n public string Type => \"Search\";\n public required string Title { get; set; }\n public required string Url { get; set => Set(ref field, value); }\n public bool IsEnabled { get; set => Set(ref field, value); } = true;\n\n public object Clone()\n {\n return new SearchMenuAction\n {\n Title = Title,\n Url = Url,\n IsEnabled = IsEnabled\n };\n }\n}\n\npublic class ClipboardMenuAction : Bindable, IMenuAction\n{\n [JsonIgnore]\n public string Type => \"Clipboard\";\n public string Title { get; set; } = \"Copy\";\n public bool ToLower { get; set => Set(ref field, value); }\n public bool IsEnabled { get; set => Set(ref field, value); } = true;\n\n public object Clone()\n {\n return new ClipboardMenuAction\n {\n Title = Title,\n ToLower = ToLower,\n IsEnabled = IsEnabled\n };\n }\n}\n\npublic class ClipboardAllMenuAction : Bindable, IMenuAction\n{\n [JsonIgnore]\n public string Type => \"ClipboardAll\";\n public string Title { get; set; } = \"Copy All\";\n public bool ToLower { get; set => Set(ref field, value); }\n public bool IsEnabled { get; set => Set(ref field, value); } = true;\n\n public object Clone()\n {\n return new ClipboardAllMenuAction\n {\n Title = Title,\n ToLower = ToLower,\n IsEnabled = IsEnabled\n };\n }\n}\n\npublic enum WordClickAction\n{\n Translation,\n Clipboard,\n ClipboardAll,\n PDIC\n}\n"], ["/LLPlayer/FlyleafLib/MediaFramework/MediaDecoder/SubtitlesDecoder.cs", "using System.Collections.Concurrent;\nusing System.Diagnostics;\nusing System.Threading;\nusing FlyleafLib.MediaFramework.MediaDemuxer;\nusing FlyleafLib.MediaFramework.MediaStream;\nusing FlyleafLib.MediaFramework.MediaFrame;\nusing FlyleafLib.MediaFramework.MediaRenderer;\nusing static FlyleafLib.Logger;\n\nnamespace FlyleafLib.MediaFramework.MediaDecoder;\n\npublic unsafe class SubtitlesDecoder : DecoderBase\n{\n public SubtitlesStream SubtitlesStream => (SubtitlesStream) Stream;\n\n public ConcurrentQueue\n Frames { get; protected set; } = new ConcurrentQueue();\n\n public PacketQueue SubtitlesPackets;\n\n public SubtitlesDecoder(Config config, int uniqueId = -1, int subIndex = 0) : base(config, uniqueId)\n {\n this.subIndex = subIndex;\n }\n\n private readonly int subIndex;\n protected override int Setup(AVCodec* codec)\n {\n lock (lockCodecCtx)\n {\n if (demuxer.avioCtx != null)\n {\n // Disable check since already converted to UTF-8\n codecCtx->sub_charenc_mode = SubCharencModeFlags.Ignore;\n }\n }\n\n return 0;\n }\n\n protected override void DisposeInternal()\n => DisposeFrames();\n\n public void Flush()\n {\n lock (lockActions)\n lock (lockCodecCtx)\n {\n if (Disposed) return;\n\n if (Status == Status.Ended) Status = Status.Stopped;\n //else if (Status == Status.Draining) Status = Status.Stopping;\n\n DisposeFrames();\n avcodec_flush_buffers(codecCtx);\n }\n }\n\n protected override void RunInternal()\n {\n int ret = 0;\n int allowedErrors = Config.Decoder.MaxErrors;\n AVPacket *packet;\n\n SubtitlesPackets = demuxer.SubtitlesPackets[subIndex];\n\n do\n {\n // Wait until Queue not Full or Stopped\n if (Frames.Count >= Config.Decoder.MaxSubsFrames)\n {\n lock (lockStatus)\n if (Status == Status.Running) Status = Status.QueueFull;\n\n while (Frames.Count >= Config.Decoder.MaxSubsFrames && Status == Status.QueueFull) Thread.Sleep(20);\n\n lock (lockStatus)\n {\n if (Status != Status.QueueFull) break;\n Status = Status.Running;\n }\n }\n\n // While Packets Queue Empty (Ended | Quit if Demuxer stopped | Wait until we get packets)\n if (SubtitlesPackets.Count == 0)\n {\n CriticalArea = true;\n\n lock (lockStatus)\n if (Status == Status.Running) Status = Status.QueueEmpty;\n\n while (SubtitlesPackets.Count == 0 && Status == Status.QueueEmpty)\n {\n if (demuxer.Status == Status.Ended)\n {\n Status = Status.Ended;\n break;\n }\n else if (!demuxer.IsRunning)\n {\n if (CanDebug) Log.Debug($\"Demuxer is not running [Demuxer Status: {demuxer.Status}]\");\n\n int retries = 5;\n\n while (retries > 0)\n {\n retries--;\n Thread.Sleep(10);\n if (demuxer.IsRunning) break;\n }\n\n lock (demuxer.lockStatus)\n lock (lockStatus)\n {\n if (demuxer.Status == Status.Pausing || demuxer.Status == Status.Paused)\n Status = Status.Pausing;\n else if (demuxer.Status != Status.Ended)\n Status = Status.Stopping;\n else\n continue;\n }\n\n break;\n }\n\n Thread.Sleep(20);\n }\n\n lock (lockStatus)\n {\n CriticalArea = false;\n if (Status != Status.QueueEmpty) break;\n Status = Status.Running;\n }\n }\n\n lock (lockCodecCtx)\n {\n if (Status == Status.Stopped || SubtitlesPackets.Count == 0) continue;\n packet = SubtitlesPackets.Dequeue();\n\n int gotFrame = 0;\n SubtitlesFrame subFrame = new();\n\n fixed(AVSubtitle* subPtr = &subFrame.sub)\n ret = avcodec_decode_subtitle2(codecCtx, subPtr, &gotFrame, packet);\n\n if (ret < 0)\n {\n allowedErrors--;\n if (CanWarn) Log.Warn($\"{FFmpegEngine.ErrorCodeToMsg(ret)} ({ret})\");\n\n if (allowedErrors == 0) { Log.Error(\"Too many errors!\"); Status = Status.Stopping; break; }\n\n continue;\n }\n\n if (gotFrame == 0)\n {\n av_packet_free(&packet);\n continue;\n }\n\n long pts = subFrame.sub.pts != AV_NOPTS_VALUE ? subFrame.sub.pts /*mcs*/ * 10 : (packet->pts != AV_NOPTS_VALUE ? (long)(packet->pts * SubtitlesStream.Timebase) : AV_NOPTS_VALUE);\n av_packet_free(&packet);\n\n if (pts == AV_NOPTS_VALUE)\n continue;\n\n pts += subFrame.sub.start_display_time /*ms*/ * 10000L;\n\n if (!filledFromCodec) // TODO: CodecChanged? And when findstreaminfo is disabled as it is an external demuxer will not know the main demuxer's start time\n {\n filledFromCodec = true;\n avcodec_parameters_from_context(Stream.AVStream->codecpar, codecCtx);\n SubtitlesStream.Refresh();\n\n CodecChanged?.Invoke(this);\n }\n\n if (subFrame.sub.num_rects < 1)\n {\n if (SubtitlesStream.IsBitmap) // clear prev subs frame\n {\n subFrame.duration = uint.MaxValue;\n subFrame.timestamp = pts - demuxer.StartTime + Config.Subtitles[subIndex].Delay;\n subFrame.isBitmap = true;\n Frames.Enqueue(subFrame);\n }\n\n fixed(AVSubtitle* subPtr = &subFrame.sub)\n avsubtitle_free(subPtr);\n\n continue;\n }\n\n subFrame.duration = subFrame.sub.end_display_time;\n subFrame.timestamp = pts - demuxer.StartTime + Config.Subtitles[subIndex].Delay;\n\n if (subFrame.sub.rects[0]->type == AVSubtitleType.Ass)\n {\n subFrame.text = Utils.BytePtrToStringUTF8(subFrame.sub.rects[0]->ass).Trim();\n Config.Subtitles.Parser(subFrame);\n\n fixed(AVSubtitle* subPtr = &subFrame.sub)\n avsubtitle_free(subPtr);\n\n if (string.IsNullOrEmpty(subFrame.text))\n continue;\n }\n else if (subFrame.sub.rects[0]->type == AVSubtitleType.Text)\n {\n subFrame.text = Utils.BytePtrToStringUTF8(subFrame.sub.rects[0]->text).Trim();\n\n fixed(AVSubtitle* subPtr = &subFrame.sub)\n avsubtitle_free(subPtr);\n\n if (string.IsNullOrEmpty(subFrame.text))\n continue;\n }\n else if (subFrame.sub.rects[0]->type == AVSubtitleType.Bitmap)\n {\n var rect = subFrame.sub.rects[0];\n byte[] data = Renderer.ConvertBitmapSub(subFrame.sub, false);\n\n subFrame.isBitmap = true;\n subFrame.bitmap = new SubtitlesFrameBitmap()\n {\n data = data,\n width = rect->w,\n height = rect->h,\n x = rect->x,\n y = rect->y,\n };\n }\n\n if (CanTrace) Log.Trace($\"Processes {Utils.TicksToTime(subFrame.timestamp)}\");\n\n Frames.Enqueue(subFrame);\n }\n } while (Status == Status.Running);\n }\n\n public static void DisposeFrame(SubtitlesFrame frame)\n {\n Debug.Assert(frame != null, \"frame is already disposed (race condition)\");\n if (frame != null && frame.sub.num_rects > 0)\n fixed(AVSubtitle* ptr = &frame.sub)\n avsubtitle_free(ptr);\n }\n\n public void DisposeFrames()\n {\n if (!SubtitlesStream.IsBitmap)\n Frames = new ConcurrentQueue();\n else\n {\n while (!Frames.IsEmpty)\n {\n Frames.TryDequeue(out var frame);\n DisposeFrame(frame);\n }\n }\n }\n}\n"], ["/LLPlayer/LLPlayer/ViewModels/MainWindowVM.cs", "using System.IO;\nusing System.Windows;\nusing System.Windows.Media;\nusing System.Windows.Media.Imaging;\nusing System.Windows.Shell;\nusing FlyleafLib;\nusing FlyleafLib.MediaPlayer;\nusing LLPlayer.Extensions;\nusing LLPlayer.Services;\nusing InputType = FlyleafLib.InputType;\n\nnamespace LLPlayer.ViewModels;\n\npublic class MainWindowVM : Bindable\n{\n public FlyleafManager FL { get; }\n private readonly LogHandler Log;\n\n public MainWindowVM(FlyleafManager fl)\n {\n FL = fl;\n Log = new LogHandler(\"[App] [MainWindowVM ] \");\n }\n\n public string Title { get; set => Set(ref field, value); } = App.Name;\n\n #region Progress in TaskBar\n public double TaskBarProgressValue\n {\n get;\n set\n {\n double v = value;\n if (v < 0.01)\n {\n // Set to 1% because it is not displayed.\n v = 0.01;\n }\n Set(ref field, v);\n }\n }\n\n public TaskbarItemProgressState TaskBarProgressState { get; set => Set(ref field, value); }\n #endregion\n\n #region Action Button in TaskBar\n public Visibility PlayPauseVisibility { get; set => Set(ref field, value); } = Visibility.Collapsed;\n public ImageSource PlayPauseImageSource { get; set => Set(ref field, value); } = PlayIcon;\n\n private static readonly BitmapImage PlayIcon = new(\n new Uri(\"pack://application:,,,/Resources/Images/play.png\"));\n\n private static readonly BitmapImage PauseIcon = new(\n new Uri(\"pack://application:,,,/Resources/Images/pause.png\"));\n #endregion\n\n public DelegateCommand? CmdOnLoaded => field ??= new(() =>\n {\n // error handling\n FL.Player.KnownErrorOccurred += (sender, args) =>\n {\n Utils.UI(() =>\n {\n Log.Error($\"Known error occurred in Flyleaf: {args.Message} ({args.ErrorType.ToString()})\");\n ErrorDialogHelper.ShowKnownErrorPopup(args.Message, args.ErrorType);\n });\n };\n\n FL.Player.UnknownErrorOccurred += (sender, args) =>\n {\n Utils.UI(() =>\n {\n Log.Error($\"Unknown error occurred in Flyleaf: {args.Message}: {args.Exception}\");\n ErrorDialogHelper.ShowUnknownErrorPopup(args.Message, args.ErrorType, args.Exception);\n });\n };\n\n FL.Player.PropertyChanged += (sender, args) =>\n {\n switch (args.PropertyName)\n {\n case nameof(FL.Player.CurTime):\n {\n double prevValue = TaskBarProgressValue;\n double newValue = (double)FL.Player.CurTime / FL.Player.Duration;\n\n if (Math.Abs(newValue - prevValue) >= 0.01) // prevent frequent update\n {\n TaskBarProgressValue = newValue;\n }\n\n break;\n }\n case nameof(FL.Player.Status):\n // Progress in TaskBar (and title)\n switch (FL.Player.Status)\n {\n case Status.Stopped:\n // reset\n Title = App.Name;\n TaskBarProgressState = TaskbarItemProgressState.None;\n TaskBarProgressValue = 0;\n break;\n case Status.Playing:\n TaskBarProgressState = TaskbarItemProgressState.Normal;\n break;\n case Status.Opening:\n TaskBarProgressState = TaskbarItemProgressState.Indeterminate;\n TaskBarProgressValue = 0;\n break;\n case Status.Paused:\n TaskBarProgressState = TaskbarItemProgressState.Paused;\n break;\n case Status.Ended:\n TaskBarProgressState = TaskbarItemProgressState.Paused;\n TaskBarProgressValue = 1;\n break;\n case Status.Failed:\n TaskBarProgressState = TaskbarItemProgressState.Error;\n break;\n }\n\n // Action Button in TaskBar\n switch (FL.Player.Status)\n {\n case Status.Paused:\n case Status.Playing:\n PlayPauseVisibility = Visibility.Visible;\n PlayPauseImageSource = FL.Player.Status == Status.Playing ? PauseIcon : PlayIcon;\n break;\n default:\n PlayPauseVisibility = Visibility.Collapsed;\n break;\n }\n\n break;\n }\n };\n\n FL.Player.OpenCompleted += (sender, args) =>\n {\n if (!args.Success || args.IsSubtitles)\n {\n return;\n }\n\n string name = Path.GetFileName(args.Url);\n if (FL.Player.Playlist.InputType == InputType.Web)\n {\n name = FL.Player.Playlist.Selected.Title;\n }\n Title = $\"{name} - {App.Name}\";\n TaskBarProgressValue = 0;\n TaskBarProgressState = TaskbarItemProgressState.Normal;\n };\n\n if (App.CmdUrl != null)\n {\n FL.Player.OpenAsync(App.CmdUrl);\n }\n });\n\n public DelegateCommand? CmdOnClosing => field ??= new(() =>\n {\n FL.Player.Dispose();\n });\n}\n"], ["/LLPlayer/LLPlayer/ViewModels/WhisperModelDownloadDialogVM.cs", "using System.Collections.ObjectModel;\nusing System.Diagnostics;\nusing System.IO;\nusing System.Windows;\nusing FlyleafLib;\nusing LLPlayer.Extensions;\nusing LLPlayer.Services;\nusing Whisper.net.Ggml;\n\nnamespace LLPlayer.ViewModels;\n\npublic class WhisperModelDownloadDialogVM : Bindable, IDialogAware\n{\n public FlyleafManager FL { get; }\n\n public WhisperModelDownloadDialogVM(FlyleafManager fl)\n {\n FL = fl;\n\n List models = WhisperCppModelLoader.LoadAllModels();\n foreach (var model in models)\n {\n Models.Add(model);\n }\n\n SelectedModel = Models.First();\n\n CmdDownloadModel!.PropertyChanged += (sender, args) =>\n {\n if (args.PropertyName == nameof(CmdDownloadModel.IsExecuting))\n {\n OnPropertyChanged(nameof(CanDownload));\n OnPropertyChanged(nameof(CanDelete));\n }\n };\n }\n\n private const string TempExtension = \".tmp\";\n\n public ObservableCollection Models { get; set => Set(ref field, value); } = new();\n\n public WhisperCppModel SelectedModel\n {\n get;\n set\n {\n if (Set(ref field, value))\n {\n OnPropertyChanged(nameof(CanDownload));\n OnPropertyChanged(nameof(CanDelete));\n }\n }\n }\n\n public string StatusText { get; set => Set(ref field, value); } = \"Select a model to download.\";\n\n public long DownloadedSize { get; set => Set(ref field, value); }\n\n public bool CanDownload =>\n SelectedModel is { Downloaded: false } && !CmdDownloadModel!.IsExecuting;\n\n public bool CanDelete =>\n SelectedModel is { Downloaded: true } && !CmdDownloadModel!.IsExecuting;\n\n private CancellationTokenSource? _cts;\n\n public AsyncDelegateCommand? CmdDownloadModel => field ??= new AsyncDelegateCommand(async () =>\n {\n _cts = new CancellationTokenSource();\n CancellationToken token = _cts.Token;\n\n WhisperCppModel downloadModel = SelectedModel;\n string tempModelPath = downloadModel.ModelFilePath + TempExtension;\n\n try\n {\n if (downloadModel.Downloaded)\n {\n StatusText = $\"Model '{SelectedModel}' is already downloaded\";\n return;\n }\n\n // Delete temporary files if they exist (forces re-download)\n if (!DeleteTempModel())\n {\n StatusText = $\"Failed to remove temp model\";\n return;\n }\n\n StatusText = $\"Model '{downloadModel}' downloading..\";\n\n long modelSize = await DownloadModelWithProgressAsync(downloadModel.Model, tempModelPath, token);\n\n // After successful download, rename temporary file to final file\n File.Move(tempModelPath, downloadModel.ModelFilePath);\n\n // Update downloaded status\n downloadModel.Size = modelSize;\n OnDownloadStatusChanged();\n\n StatusText = $\"Model '{SelectedModel}' is downloaded successfully\";\n }\n catch (OperationCanceledException)\n {\n StatusText = \"Download canceled\";\n }\n catch (Exception ex)\n {\n StatusText = $\"Failed to download: {ex.Message}\";\n }\n finally\n {\n _cts = null;\n DeleteTempModel();\n }\n\n return;\n\n bool DeleteTempModel()\n {\n // Delete temporary files if they exist\n if (File.Exists(tempModelPath))\n {\n try\n {\n File.Delete(tempModelPath);\n }\n catch (Exception)\n {\n // ignore\n\n return false;\n }\n }\n\n return true;\n }\n }).ObservesCanExecute(() => CanDownload);\n\n public DelegateCommand? CmdCancelDownloadModel => field ??= new(() =>\n {\n _cts?.Cancel();\n });\n\n public DelegateCommand? CmdDeleteModel => field ??= new DelegateCommand(() =>\n {\n try\n {\n StatusText = $\"Model '{SelectedModel}' deleting...\";\n\n WhisperCppModel deleteModel = SelectedModel;\n\n // Delete model file if exists\n if (File.Exists(deleteModel.ModelFilePath))\n {\n File.Delete(deleteModel.ModelFilePath);\n }\n\n // Update downloaded status\n deleteModel.Size = 0;\n OnDownloadStatusChanged();\n\n StatusText = $\"Model '{deleteModel}' is deleted successfully\";\n }\n catch (Exception ex)\n {\n StatusText = $\"Failed to delete model: {ex.Message}\";\n }\n }).ObservesCanExecute(() => CanDelete);\n\n public DelegateCommand? CmdOpenFolder => field ??= new(() =>\n {\n if (!Directory.Exists(WhisperConfig.ModelsDirectory))\n return;\n\n try\n {\n Process.Start(new ProcessStartInfo\n {\n FileName = WhisperConfig.ModelsDirectory,\n UseShellExecute = true,\n CreateNoWindow = true\n });\n }\n catch (Exception ex)\n {\n MessageBox.Show($\"Failed to open folder: {ex.Message}\", \"Error\", MessageBoxButton.OK, MessageBoxImage.Error);\n }\n });\n\n private void OnDownloadStatusChanged()\n {\n OnPropertyChanged(nameof(CanDownload));\n OnPropertyChanged(nameof(CanDelete));\n }\n\n private async Task DownloadModelWithProgressAsync(GgmlType modelType, string destinationPath, CancellationToken token)\n {\n DownloadedSize = 0;\n\n await using Stream modelStream = await WhisperGgmlDownloader.Default.GetGgmlModelAsync(modelType, default, token);\n await using FileStream fileWriter = File.OpenWrite(destinationPath);\n\n byte[] buffer = new byte[1024 * 128];\n int bytesRead;\n long totalBytesRead = 0;\n\n Stopwatch sw = new();\n sw.Start();\n\n while ((bytesRead = await modelStream.ReadAsync(buffer, 0, buffer.Length, token)) > 0)\n {\n await fileWriter.WriteAsync(buffer, 0, bytesRead, token);\n totalBytesRead += bytesRead;\n\n if (sw.Elapsed > TimeSpan.FromMilliseconds(50))\n {\n DownloadedSize = totalBytesRead;\n sw.Restart();\n }\n\n token.ThrowIfCancellationRequested();\n }\n\n return totalBytesRead;\n }\n\n #region IDialogAware\n public string Title { get; set => Set(ref field, value); } = $\"Whisper Downloader - {App.Name}\";\n public double WindowWidth { get; set => Set(ref field, value); } = 400;\n public double WindowHeight { get; set => Set(ref field, value); } = 200;\n\n public bool CanCloseDialog() => !CmdDownloadModel!.IsExecuting;\n public void OnDialogClosed() { }\n public void OnDialogOpened(IDialogParameters parameters) { }\n public DialogCloseListener RequestClose { get; }\n #endregion IDialogAware\n}\n"], ["/LLPlayer/FlyleafLib/Plugins/StreamSuggester.cs", "using System.Collections.Generic;\nusing System.Collections.ObjectModel;\nusing System.Linq;\n\nusing FlyleafLib.MediaFramework.MediaPlaylist;\nusing FlyleafLib.MediaFramework.MediaStream;\n\nnamespace FlyleafLib.Plugins;\n\npublic unsafe class StreamSuggester : PluginBase, ISuggestPlaylistItem, ISuggestAudioStream, ISuggestVideoStream, ISuggestSubtitlesStream, ISuggestSubtitles, ISuggestBestExternalSubtitles\n{\n public new int Priority { get; set; } = 3000;\n\n public AudioStream SuggestAudio(ObservableCollection streams)\n {\n lock (streams[0].Demuxer.lockActions)\n {\n foreach (var lang in Config.Audio.Languages)\n foreach (var stream in streams)\n if (stream.Language == lang)\n {\n if (stream.Demuxer.Programs.Count < 2)\n {\n Log.Info($\"Audio based on language\");\n return stream;\n }\n\n for (int i = 0; i < stream.Demuxer.Programs.Count; i++)\n {\n bool aExists = false, vExists = false;\n foreach (var pstream in stream.Demuxer.Programs[i].Streams)\n {\n if (pstream.StreamIndex == stream.StreamIndex) aExists = true;\n else if (pstream.StreamIndex == stream.Demuxer.VideoStream?.StreamIndex) vExists = true;\n }\n\n if (aExists && vExists)\n {\n Log.Info($\"Audio based on language and same program #{i}\");\n return stream;\n }\n }\n }\n\n // Fall-back to FFmpeg's default\n int streamIndex;\n lock (streams[0].Demuxer.lockFmtCtx)\n streamIndex = av_find_best_stream(streams[0].Demuxer.FormatContext, AVMediaType.Audio, -1, streams[0].Demuxer.VideoStream != null ? streams[0].Demuxer.VideoStream.StreamIndex : -1, null, 0);\n\n foreach (var stream in streams)\n if (stream.StreamIndex == streamIndex)\n {\n Log.Info($\"Audio based on av_find_best_stream\");\n return stream;\n }\n\n if (streams.Count > 0) // FFmpeg will not suggest anything when findstreaminfo is disable\n return streams[0];\n\n return null;\n }\n }\n\n public VideoStream SuggestVideo(ObservableCollection streams)\n {\n // Try to find best video stream based on current screen resolution\n var iresults =\n from vstream in streams\n where vstream.Type == MediaType.Video && vstream.Height <= Config.Video.MaxVerticalResolution //Decoder.VideoDecoder.Renderer.Info.ScreenBounds.Height\n orderby vstream.Height descending\n select vstream;\n\n List results = iresults.ToList();\n\n if (results.Count != 0)\n return iresults.ToList()[0];\n else\n {\n // Fall-back to FFmpeg's default\n int streamIndex;\n lock (streams[0].Demuxer.lockFmtCtx)\n streamIndex = av_find_best_stream(streams[0].Demuxer.FormatContext, AVMediaType.Video, -1, -1, null, 0);\n if (streamIndex < 0) return null;\n\n foreach (var vstream in streams)\n if (vstream.StreamIndex == streamIndex)\n return vstream;\n }\n\n if (streams.Count > 0) // FFmpeg will not suggest anything when findstreaminfo is disable\n return streams[0];\n\n return null;\n }\n\n public PlaylistItem SuggestItem()\n => Playlist.Items[0];\n\n public void SuggestSubtitles(out SubtitlesStream stream, out ExternalSubtitlesStream extStream)\n {\n stream = null;\n extStream = null;\n\n List langs = new();\n\n foreach (var lang in Config.Subtitles.Languages)\n langs.Add(lang);\n\n langs.Add(Language.Unknown);\n\n var extStreams = Selected.ExternalSubtitlesStreamsAll\n .Where(x => (Config.Subtitles.OpenAutomaticSubs || !x.Automatic))\n .OrderBy(x => x.Language.ToString())\n .ThenBy(x => x.Downloaded)\n .ThenBy(x => x.ManualDownloaded);\n\n foreach (var lang in langs)\n {\n foreach(var embStream in decoder.VideoDemuxer.SubtitlesStreamsAll)\n if (embStream.Language == lang)\n {\n stream = embStream;\n return;\n }\n\n foreach(var extStream2 in extStreams)\n if (extStream2.Language == lang)\n {\n extStream = extStream2;\n return;\n }\n }\n }\n\n public ExternalSubtitlesStream SuggestBestExternalSubtitles()\n {\n var extStreams = Selected.ExternalSubtitlesStreamsAll\n .Where(x => (Config.Subtitles.OpenAutomaticSubs || !x.Automatic))\n .OrderBy(x => x.Language.ToString())\n .ThenBy(x => x.Downloaded)\n .ThenBy(x => x.ManualDownloaded);\n\n foreach(var extStream in extStreams)\n if (extStream.Language == Config.Subtitles.Languages[0])\n return extStream;\n\n return null;\n }\n\n public SubtitlesStream SuggestSubtitles(ObservableCollection streams, List langs)\n {\n foreach(var lang in langs)\n foreach(var stream in streams)\n if (lang == stream.Language)\n return stream;\n\n return null;\n }\n}\n"], ["/LLPlayer/FlyleafLib/MediaFramework/MediaStream/StreamBase.cs", "using System.Collections.Generic;\n\nusing FlyleafLib.MediaFramework.MediaDemuxer;\nusing FlyleafLib.MediaPlayer;\n\nnamespace FlyleafLib.MediaFramework.MediaStream;\n\npublic abstract unsafe class StreamBase : NotifyPropertyChanged\n{\n public ExternalStream ExternalStream { get; set; }\n\n public Demuxer Demuxer { get; internal set; }\n public AVStream* AVStream { get; internal set; }\n internal playlist* HLSPlaylist { get; set; }\n public int StreamIndex { get; internal set; } = -1;\n public double Timebase { get; internal set; }\n\n // TBR: To update Pop-up menu's (Player.Audio/Player.Video ... should inherit this?)\n public bool Enabled\n {\n get => _Enabled;\n internal set\n {\n Utils.UI(() =>\n {\n Set(ref _Enabled, value);\n\n Raise(nameof(EnabledPrimarySubtitle));\n Raise(nameof(EnabledSecondarySubtitle));\n Raise(nameof(SubtitlesStream.SelectedSubMethods));\n });\n }\n }\n\n bool _Enabled;\n\n public long BitRate { get; internal set; }\n public Language Language { get; internal set; }\n public string Title { get; internal set; }\n public string Codec { get; internal set; }\n\n public AVCodecID CodecID { get; internal set; }\n public long StartTime { get; internal set; }\n public long StartTimePts { get; internal set; }\n public long Duration { get; internal set; }\n public Dictionary Metadata { get; internal set; } = new Dictionary();\n public MediaType Type { get; internal set; }\n\n #region Subtitles\n // TODO: L: Used for subtitle streams only, but defined in the base class\n public bool EnabledPrimarySubtitle => Enabled && this.GetSubEnabled(0);\n public bool EnabledSecondarySubtitle => Enabled && this.GetSubEnabled(1);\n #endregion\n\n public abstract string GetDump();\n public StreamBase() { }\n public StreamBase(Demuxer demuxer, AVStream* st)\n {\n Demuxer = demuxer;\n AVStream = st;\n }\n\n public virtual void Refresh()\n {\n BitRate = AVStream->codecpar->bit_rate;\n CodecID = AVStream->codecpar->codec_id;\n Codec = avcodec_get_name(AVStream->codecpar->codec_id);\n StreamIndex = AVStream->index;\n Timebase = av_q2d(AVStream->time_base) * 10000.0 * 1000.0;\n StartTime = AVStream->start_time != AV_NOPTS_VALUE && Demuxer.hlsCtx == null ? (long)(AVStream->start_time * Timebase) : Demuxer.StartTime;\n StartTimePts= AVStream->start_time != AV_NOPTS_VALUE ? AVStream->start_time : av_rescale_q(StartTime/10, Engine.FFmpeg.AV_TIMEBASE_Q, AVStream->time_base);\n Duration = AVStream->duration != AV_NOPTS_VALUE ? (long)(AVStream->duration * Timebase) : Demuxer.Duration;\n Type = this is VideoStream ? MediaType.Video : (this is AudioStream ? MediaType.Audio : (this is SubtitlesStream ? MediaType.Subs : MediaType.Data));\n\n if (Demuxer.hlsCtx != null)\n {\n for (int i=0; in_playlists; i++)\n {\n playlist** playlists = Demuxer.hlsCtx->playlists;\n for (int l=0; ln_main_streams; l++)\n if (playlists[i]->main_streams[l]->index == StreamIndex)\n {\n Demuxer.Log.Debug($\"Stream #{StreamIndex} Found in playlist {i}\");\n HLSPlaylist = playlists[i];\n break;\n }\n }\n }\n\n Metadata.Clear();\n\n AVDictionaryEntry* b = null;\n while (true)\n {\n b = av_dict_get(AVStream->metadata, \"\", b, DictReadFlags.IgnoreSuffix);\n if (b == null) break;\n Metadata.Add(Utils.BytePtrToStringUTF8(b->key), Utils.BytePtrToStringUTF8(b->value));\n }\n\n foreach (var kv in Metadata)\n {\n string keyLower = kv.Key.ToLower();\n\n if (Language == null && (keyLower == \"language\" || keyLower == \"lang\"))\n Language = Language.Get(kv.Value);\n else if (keyLower == \"title\")\n Title = kv.Value;\n }\n\n if (Language == null)\n Language = Language.Unknown;\n }\n}\n"], ["/LLPlayer/FlyleafLib/Controls/WPF/FlyleafHost.cs", "using System;\nusing System.ComponentModel;\nusing System.Windows.Controls;\nusing System.Windows;\nusing System.Windows.Media;\nusing System.Windows.Input;\nusing System.Windows.Interop;\n\nusing FlyleafLib.MediaPlayer;\n\nusing static FlyleafLib.Utils;\nusing static FlyleafLib.Utils.NativeMethods;\n\nusing Brushes = System.Windows.Media.Brushes;\n\nnamespace FlyleafLib.Controls.WPF;\n\npublic class FlyleafHost : ContentControl, IHostPlayer, IDisposable\n{\n /* -= FlyleafHost Properties Notes =-\n\n Player\t\t\t\t\t\t\t[Can be changed, can be null]\n ReplicaPlayer | Replicates frames of the assigned Player (useful for interactive zoom) without the pan/zoom config\n\n Surface\t\t\t\t\t\t\t[ReadOnly / Required]\n Overlay\t\t\t\t\t\t\t[AutoCreated OnContentChanged | Provided directly | Provided in Stand Alone Constructor]\n\n Content\t\t\t\t\t\t\t[Overlay's Content]\n DetachedContent\t\t\t\t\t[Host's actual content]\n\n DataContext\t\t\t\t\t\t[Set by the user or default inheritance]\n HostDataContext\t\t\t\t\t[Will be set Sync with DataContext as helper to Overlay when we pass this as Overlay's DataContext]\n\n OpenOnDrop\t\t\t\t\t\t[None, Surface, Overlay, Both]\t\t| Requires Player and AllowDrop\n SwapOnDrop\t\t\t\t\t\t[None, Surface, Overlay, Both]\t\t| Requires Player and AllowDrop\n\n SwapDragEnterOnShift\t\t\t[None, Surface, Overlay, Both]\t\t| Requires Player and SwapOnDrop\n ToggleFullScreenOnDoubleClick\t[None, Surface, Overlay, Both]\n\n PanMoveOnCtrl\t\t\t\t\t[None, Surface, Overlay, Both]\t\t| Requires Player and VideoStream Opened\n PanZoomOnCtrlWheel\t\t\t [None, Surface, Overlay, Both]\t\t| Requires Player and VideoStream Opened\n PanRotateOnShiftWheel [None, Surface, Overlay, Both] | Requires Player and VideoStream Opened\n\n AttachedDragMove\t\t\t\t[None, Surface, Overlay, Both, SurfaceOwner, OverlayOwner, BothOwner]\n DetachedDragMove\t\t\t\t[None, Surface, Overlay, Both]\n\n AttachedResize\t\t\t\t\t[None, Surface, Overlay, Both]\n DetachedResize\t\t\t\t\t[None, Surface, Overlay, Both]\n KeepRatioOnResize\t\t\t\t[False, True]\n PreferredLandscapeWidth [X] | When KeepRatioOnResize will use it as helper and try to stay close to this value (CurResizeRatio >= 1) - Will be updated when user resizes a landscape\n PreferredPortraitHeight [Y] | When KeepRatioOnResize will use it as helper and try to stay close to this value (CurResizeRatio < 1) - Will be updated when user resizes a portrait\n CurResizeRatio [0 if not Keep Ratio or Player's aspect ratio]\n ResizeSensitivity Pixels sensitivity from the window's edges\n\n BringToFrontOnClick [False, True]\n\n DetachedPosition\t\t\t\t[Custom, TopLeft, TopCenter, TopRight, CenterLeft, CenterCenter, CenterRight, BottomLeft, BottomCenter, BottomRight]\n DetachedPositionMargin\t\t\t[X, Y, CX, CY]\t\t\t\t\t\t| Does not affect the Size / Eg. No point to provide both X/CX\n DetachedFixedPosition\t\t\t[X, Y]\t\t\t\t\t\t\t\t| if remember only first time\n DetachedFixedSize\t\t\t\t[CX, CY]\t\t\t\t\t\t\t| if remember only first time\n DetachedRememberPosition\t\t[False, True]\n DetachedRememberSize\t\t\t[False, True]\n DetachedTopMost\t\t\t\t\t[False, True] (Surfaces Only Required?)\n DetachedShowInTaskbar [False, True] | When Detached or Fullscreen will be in Switch Apps\n DetachedNoOwner [False, True] | When Detached will not follow the owner's window state (Minimize/Maximize)\n\n KeyBindings\t\t\t\t\t\t[None, Surface, Overlay, Both]\n MouseBindings [None, Surface, Overlay, Both] | Required for all other mouse events\n\n ActivityTimeout\t\t\t\t\t[0: Disabled]\t\t\t\t\t\t| Requires Player?\n ActivityRefresh?\t\t\t\t[None, Surface, Overlay, Both]\t\t| MouseMove / MouseDown / KeyUp\n\n PassWheelToOwner?\t\t\t\t[None, Surface, Overlay, Both]\t\t| When host belongs to ScrollViewer\n\n IsAttached [False, True]\n IsFullScreen [False, True] | Should be used instead of WindowStates\n IsMinimized [False, True] | Should be used instead of WindowStates\n IsResizing\t\t\t\t\t\t[ReadOnly]\n IsSwapping\t\t\t\t\t\t[ReadOnly]\n IsStandAlone\t\t\t\t\t[ReadOnly]\n */\n\n /* TODO\n * 1) The surface / overlay events code is repeated\n * 2) PassWheelToOwner (Related with LayoutUpdate performance / ScrollViewer) / ActivityRefresh\n * 3) Attach to different Owner (Load/Unload) and change Overlay?\n * 4) WindowStates should not be used by user directly. Use IsMinimized and IsFullScreen instead.\n * 5) WS_EX_NOACTIVATE should be set but for some reason is not required (for none-styled windows)? Currently BringToFront does the job but (only for left clicks?)\n */\n\n #region Properties / Variables\n public Window Owner { get; private set; }\n public Window Surface { get; private set; }\n public IntPtr SurfaceHandle { get; private set; }\n public IntPtr OverlayHandle { get; private set; }\n public IntPtr OwnerHandle { get; private set; }\n public int ResizingSide { get; private set; }\n\n public int UniqueId { get; private set; }\n public bool Disposed { get; private set; }\n\n\n public event EventHandler SurfaceCreated;\n public event EventHandler OverlayCreated;\n public event DragEventHandler OnSurfaceDrop;\n public event DragEventHandler OnOverlayDrop;\n\n static bool isDesignMode;\n static int idGenerator = 1;\n static nint NONE_STYLE = (nint) (WindowStyles.WS_MINIMIZEBOX | WindowStyles.WS_CLIPSIBLINGS | WindowStyles.WS_CLIPCHILDREN | WindowStyles.WS_VISIBLE); // WS_MINIMIZEBOX required for swapchain\n static Rect rectRandom = new(1, 2, 3, 4);\n\n float curResizeRatio;\n float curResizeRatioIfEnabled;\n bool surfaceClosed, surfaceClosing, overlayClosed;\n int panPrevX, panPrevY;\n bool isMouseBindingsSubscribedSurface;\n bool isMouseBindingsSubscribedOverlay;\n Window standAloneOverlay;\n\n CornerRadius zeroCornerRadius = new(0);\n Point zeroPoint = new(0, 0);\n Point mouseLeftDownPoint = new(0, 0);\n Point mouseMoveLastPoint = new(0, 0);\n Point ownerZeroPointPos = new();\n\n Rect zeroRect = new(0, 0, 0, 0);\n Rect rectDetachedLast = Rect.Empty;\n Rect rectInit;\n Rect rectInitLast = rectRandom;\n Rect rectIntersect;\n Rect rectIntersectLast = rectRandom;\n RECT beforeResizeRect = new();\n RECT curRect = new();\n\n private class FlyleafHostDropWrap { public FlyleafHost FlyleafHost; } // To allow non FlyleafHosts to drag & drop\n protected readonly LogHandler Log;\n #endregion\n\n #region Dependency Properties\n public void BringToFront() => SetWindowPos(SurfaceHandle, IntPtr.Zero, 0, 0, 0, 0, (UInt32)(SetWindowPosFlags.SWP_SHOWWINDOW | SetWindowPosFlags.SWP_NOSIZE | SetWindowPosFlags.SWP_NOMOVE));\n public bool BringToFrontOnClick\n {\n get { return (bool)GetValue(BringToFrontOnClickProperty); }\n set { SetValue(BringToFrontOnClickProperty, value); }\n }\n public static readonly DependencyProperty BringToFrontOnClickProperty =\n DependencyProperty.Register(nameof(BringToFrontOnClick), typeof(bool), typeof(FlyleafHost), new PropertyMetadata(true));\n\n public AvailableWindows OpenOnDrop\n {\n get => (AvailableWindows)GetValue(OpenOnDropProperty);\n set => SetValue(OpenOnDropProperty, value);\n }\n public static readonly DependencyProperty OpenOnDropProperty =\n DependencyProperty.Register(nameof(OpenOnDrop), typeof(AvailableWindows), typeof(FlyleafHost), new PropertyMetadata(AvailableWindows.Surface, new PropertyChangedCallback(DropChanged)));\n\n public AvailableWindows SwapOnDrop\n {\n get => (AvailableWindows)GetValue(SwapOnDropProperty);\n set => SetValue(SwapOnDropProperty, value);\n }\n public static readonly DependencyProperty SwapOnDropProperty =\n DependencyProperty.Register(nameof(SwapOnDrop), typeof(AvailableWindows), typeof(FlyleafHost), new PropertyMetadata(AvailableWindows.Surface, new PropertyChangedCallback(DropChanged)));\n\n public AvailableWindows SwapDragEnterOnShift\n {\n get => (AvailableWindows)GetValue(SwapDragEnterOnShiftProperty);\n set => SetValue(SwapDragEnterOnShiftProperty, value);\n }\n public static readonly DependencyProperty SwapDragEnterOnShiftProperty =\n DependencyProperty.Register(nameof(SwapDragEnterOnShift), typeof(AvailableWindows), typeof(FlyleafHost), new PropertyMetadata(AvailableWindows.Surface));\n\n public AvailableWindows ToggleFullScreenOnDoubleClick\n {\n get => (AvailableWindows)GetValue(ToggleFullScreenOnDoubleClickProperty);\n set => SetValue(ToggleFullScreenOnDoubleClickProperty, value);\n }\n public static readonly DependencyProperty ToggleFullScreenOnDoubleClickProperty =\n DependencyProperty.Register(nameof(ToggleFullScreenOnDoubleClick), typeof(AvailableWindows), typeof(FlyleafHost), new PropertyMetadata(AvailableWindows.Surface));\n\n public AvailableWindows PanMoveOnCtrl\n {\n get => (AvailableWindows)GetValue(PanMoveOnCtrlProperty);\n set => SetValue(PanMoveOnCtrlProperty, value);\n }\n public static readonly DependencyProperty PanMoveOnCtrlProperty =\n DependencyProperty.Register(nameof(PanMoveOnCtrl), typeof(AvailableWindows), typeof(FlyleafHost), new PropertyMetadata(AvailableWindows.Surface));\n\n public AvailableWindows PanRotateOnShiftWheel\n {\n get => (AvailableWindows)GetValue(PanRotateOnShiftWheelProperty);\n set => SetValue(PanRotateOnShiftWheelProperty, value);\n }\n public static readonly DependencyProperty PanRotateOnShiftWheelProperty =\n DependencyProperty.Register(nameof(PanRotateOnShiftWheel), typeof(AvailableWindows), typeof(FlyleafHost), new PropertyMetadata(AvailableWindows.Surface));\n\n public AvailableWindows PanZoomOnCtrlWheel\n {\n get => (AvailableWindows)GetValue(PanZoomOnCtrlWheelProperty);\n set => SetValue(PanZoomOnCtrlWheelProperty, value);\n }\n public static readonly DependencyProperty PanZoomOnCtrlWheelProperty =\n DependencyProperty.Register(nameof(PanZoomOnCtrlWheel), typeof(AvailableWindows), typeof(FlyleafHost), new PropertyMetadata(AvailableWindows.Surface));\n\n public AttachedDragMoveOptions AttachedDragMove\n {\n get => (AttachedDragMoveOptions)GetValue(AttachedDragMoveProperty);\n set => SetValue(AttachedDragMoveProperty, value);\n }\n public static readonly DependencyProperty AttachedDragMoveProperty =\n DependencyProperty.Register(nameof(AttachedDragMove), typeof(AttachedDragMoveOptions), typeof(FlyleafHost), new PropertyMetadata(AttachedDragMoveOptions.Surface));\n\n public AvailableWindows DetachedDragMove\n {\n get => (AvailableWindows)GetValue(DetachedDragMoveProperty);\n set => SetValue(DetachedDragMoveProperty, value);\n }\n public static readonly DependencyProperty DetachedDragMoveProperty =\n DependencyProperty.Register(nameof(DetachedDragMove), typeof(AvailableWindows), typeof(FlyleafHost), new PropertyMetadata(AvailableWindows.Surface));\n\n public AvailableWindows AttachedResize\n {\n get => (AvailableWindows)GetValue(AttachedResizeProperty);\n set => SetValue(AttachedResizeProperty, value);\n }\n public static readonly DependencyProperty AttachedResizeProperty =\n DependencyProperty.Register(nameof(AttachedResize), typeof(AvailableWindows), typeof(FlyleafHost), new PropertyMetadata(AvailableWindows.Surface));\n\n public AvailableWindows DetachedResize\n {\n get => (AvailableWindows)GetValue(DetachedResizeProperty);\n set => SetValue(DetachedResizeProperty, value);\n }\n public static readonly DependencyProperty DetachedResizeProperty =\n DependencyProperty.Register(nameof(DetachedResize), typeof(AvailableWindows), typeof(FlyleafHost), new PropertyMetadata(AvailableWindows.Surface));\n\n public bool KeepRatioOnResize\n {\n get => (bool)GetValue(KeepRatioOnResizeProperty);\n set => SetValue(KeepRatioOnResizeProperty, value);\n }\n public static readonly DependencyProperty KeepRatioOnResizeProperty =\n DependencyProperty.Register(nameof(KeepRatioOnResize), typeof(bool), typeof(FlyleafHost), new PropertyMetadata(false, new PropertyChangedCallback(OnKeepRatioOnResizeChanged)));\n\n public int PreferredLandscapeWidth\n {\n get { return (int)GetValue(PreferredLandscapeWidthProperty); }\n set { SetValue(PreferredLandscapeWidthProperty, value); }\n }\n public static readonly DependencyProperty PreferredLandscapeWidthProperty =\n DependencyProperty.Register(nameof(PreferredLandscapeWidth), typeof(int), typeof(FlyleafHost), new PropertyMetadata(0));\n\n public int PreferredPortraitHeight\n {\n get { return (int)GetValue(PreferredPortraitHeightProperty); }\n set { SetValue(PreferredPortraitHeightProperty, value); }\n }\n public static readonly DependencyProperty PreferredPortraitHeightProperty =\n DependencyProperty.Register(nameof(PreferredPortraitHeight), typeof(int), typeof(FlyleafHost), new PropertyMetadata(0));\n\n public int ResizeSensitivity\n {\n get => (int)GetValue(ResizeSensitivityProperty);\n set => SetValue(ResizeSensitivityProperty, value);\n }\n public static readonly DependencyProperty ResizeSensitivityProperty =\n DependencyProperty.Register(nameof(ResizeSensitivity), typeof(int), typeof(FlyleafHost), new PropertyMetadata(6));\n\n public DetachedPositionOptions DetachedPosition\n {\n get => (DetachedPositionOptions)GetValue(DetachedPositionProperty);\n set => SetValue(DetachedPositionProperty, value);\n }\n public static readonly DependencyProperty DetachedPositionProperty =\n DependencyProperty.Register(nameof(DetachedPosition), typeof(DetachedPositionOptions), typeof(FlyleafHost), new PropertyMetadata(DetachedPositionOptions.CenterCenter));\n\n public Thickness DetachedPositionMargin\n {\n get => (Thickness)GetValue(DetachedPositionMarginProperty);\n set => SetValue(DetachedPositionMarginProperty, value);\n }\n public static readonly DependencyProperty DetachedPositionMarginProperty =\n DependencyProperty.Register(nameof(DetachedPositionMargin), typeof(Thickness), typeof(FlyleafHost), new PropertyMetadata(new Thickness(0, 0, 0, 0)));\n\n public Point DetachedFixedPosition\n {\n get => (Point)GetValue(DetachedFixedPositionProperty);\n set => SetValue(DetachedFixedPositionProperty, value);\n }\n public static readonly DependencyProperty DetachedFixedPositionProperty =\n DependencyProperty.Register(nameof(DetachedFixedPosition), typeof(Point), typeof(FlyleafHost), new PropertyMetadata(new Point()));\n\n public Size DetachedFixedSize\n {\n get => (Size)GetValue(DetachedFixedSizeProperty);\n set => SetValue(DetachedFixedSizeProperty, value);\n }\n public static readonly DependencyProperty DetachedFixedSizeProperty =\n DependencyProperty.Register(nameof(DetachedFixedSize), typeof(Size), typeof(FlyleafHost), new PropertyMetadata(new Size(300, 200)));\n\n public bool DetachedRememberPosition\n {\n get => (bool)GetValue(DetachedRememberPositionProperty);\n set => SetValue(DetachedRememberPositionProperty, value);\n }\n public static readonly DependencyProperty DetachedRememberPositionProperty =\n DependencyProperty.Register(nameof(DetachedRememberPosition), typeof(bool), typeof(FlyleafHost), new PropertyMetadata(true));\n\n public bool DetachedRememberSize\n {\n get => (bool)GetValue(DetachedRememberSizeProperty);\n set => SetValue(DetachedRememberSizeProperty, value);\n }\n public static readonly DependencyProperty DetachedRememberSizeProperty =\n DependencyProperty.Register(nameof(DetachedRememberSize), typeof(bool), typeof(FlyleafHost), new PropertyMetadata(true));\n\n public bool DetachedTopMost\n {\n get => (bool)GetValue(DetachedTopMostProperty);\n set => SetValue(DetachedTopMostProperty, value);\n }\n public static readonly DependencyProperty DetachedTopMostProperty =\n DependencyProperty.Register(nameof(DetachedTopMost), typeof(bool), typeof(FlyleafHost), new PropertyMetadata(false, new PropertyChangedCallback(OnDetachedTopMostChanged)));\n\n public bool DetachedShowInTaskbar\n {\n get { return (bool)GetValue(DetachedShowInTaskbarProperty); }\n set { SetValue(DetachedShowInTaskbarProperty, value); }\n }\n public static readonly DependencyProperty DetachedShowInTaskbarProperty =\n DependencyProperty.Register(nameof(DetachedShowInTaskbar), typeof(bool), typeof(FlyleafHost), new PropertyMetadata(false, new PropertyChangedCallback(OnShowInTaskBarChanged)));\n\n public bool DetachedNoOwner\n {\n get { return (bool)GetValue(DetachedNoOwnerProperty); }\n set { SetValue(DetachedNoOwnerProperty, value); }\n }\n public static readonly DependencyProperty DetachedNoOwnerProperty =\n DependencyProperty.Register(nameof(DetachedNoOwner), typeof(bool), typeof(FlyleafHost), new PropertyMetadata(false, new PropertyChangedCallback(OnNoOwnerChanged)));\n\n public int DetachedMinHeight\n {\n get { return (int)GetValue(DetachedMinHeightProperty); }\n set { SetValue(DetachedMinHeightProperty, value); }\n }\n public static readonly DependencyProperty DetachedMinHeightProperty =\n DependencyProperty.Register(nameof(DetachedMinHeight), typeof(int), typeof(FlyleafHost), new PropertyMetadata(0));\n\n public int DetachedMinWidth\n {\n get { return (int)GetValue(DetachedMinWidthProperty); }\n set { SetValue(DetachedMinWidthProperty, value); }\n }\n public static readonly DependencyProperty DetachedMinWidthProperty =\n DependencyProperty.Register(nameof(DetachedMinWidth), typeof(int), typeof(FlyleafHost), new PropertyMetadata(0));\n\n public double DetachedMaxHeight\n {\n get { return (double)GetValue(DetachedMaxHeightProperty); }\n set { SetValue(DetachedMaxHeightProperty, value); }\n }\n public static readonly DependencyProperty DetachedMaxHeightProperty =\n DependencyProperty.Register(nameof(DetachedMaxHeight), typeof(double), typeof(FlyleafHost), new PropertyMetadata(double.PositiveInfinity));\n\n public double DetachedMaxWidth\n {\n get { return (double)GetValue(DetachedMaxWidthProperty); }\n set { SetValue(DetachedMaxWidthProperty, value); }\n }\n public static readonly DependencyProperty DetachedMaxWidthProperty =\n DependencyProperty.Register(nameof(DetachedMaxWidth), typeof(double), typeof(FlyleafHost), new PropertyMetadata(double.PositiveInfinity));\n\n public AvailableWindows KeyBindings\n {\n get => (AvailableWindows)GetValue(KeyBindingsProperty);\n set => SetValue(KeyBindingsProperty, value);\n }\n public static readonly DependencyProperty KeyBindingsProperty =\n DependencyProperty.Register(nameof(KeyBindings), typeof(AvailableWindows), typeof(FlyleafHost), new PropertyMetadata(AvailableWindows.Surface));\n\n public AvailableWindows MouseBindings\n {\n get => (AvailableWindows)GetValue(MouseBindingsProperty);\n set => SetValue(MouseBindingsProperty, value);\n }\n public static readonly DependencyProperty MouseBindingsProperty =\n DependencyProperty.Register(nameof(MouseBindings), typeof(AvailableWindows), typeof(FlyleafHost), new PropertyMetadata(AvailableWindows.Both, new PropertyChangedCallback(OnMouseBindings)));\n\n public int ActivityTimeout\n {\n get => (int)GetValue(ActivityTimeoutProperty);\n set => SetValue(ActivityTimeoutProperty, value);\n }\n public static readonly DependencyProperty ActivityTimeoutProperty =\n DependencyProperty.Register(nameof(ActivityTimeout), typeof(int), typeof(FlyleafHost), new PropertyMetadata(0, new PropertyChangedCallback(OnActivityTimeoutChanged)));\n\n public bool IsAttached\n {\n get => (bool)GetValue(IsAttachedProperty);\n set => SetValue(IsAttachedProperty, value);\n }\n public static readonly DependencyProperty IsAttachedProperty =\n DependencyProperty.Register(nameof(IsAttached), typeof(bool), typeof(FlyleafHost), new PropertyMetadata(true, new PropertyChangedCallback(OnIsAttachedChanged)));\n\n public bool IsMinimized\n {\n get => (bool)GetValue(IsMinimizedProperty);\n set => SetValue(IsMinimizedProperty, value);\n }\n public static readonly DependencyProperty IsMinimizedProperty =\n DependencyProperty.Register(nameof(IsMinimized), typeof(bool), typeof(FlyleafHost), new PropertyMetadata(false, new PropertyChangedCallback(OnIsMinimizedChanged)));\n\n public bool IsFullScreen\n {\n get => (bool)GetValue(IsFullScreenProperty);\n set => SetValue(IsFullScreenProperty, value);\n }\n public static readonly DependencyProperty IsFullScreenProperty =\n DependencyProperty.Register(nameof(IsFullScreen), typeof(bool), typeof(FlyleafHost), new PropertyMetadata(false, new PropertyChangedCallback(OnIsFullScreenChanged)));\n\n public bool IsResizing\n {\n get => (bool)GetValue(IsResizingProperty);\n private set => SetValue(IsResizingProperty, value);\n }\n public static readonly DependencyProperty IsResizingProperty =\n DependencyProperty.Register(nameof(IsResizing), typeof(bool), typeof(FlyleafHost), new PropertyMetadata(false));\n\n public bool IsStandAlone\n {\n get => (bool)GetValue(IsStandAloneProperty);\n private set => SetValue(IsStandAloneProperty, value);\n }\n public static readonly DependencyProperty IsStandAloneProperty =\n DependencyProperty.Register(nameof(IsStandAlone), typeof(bool), typeof(FlyleafHost), new PropertyMetadata(false));\n\n public bool IsSwappingStarted\n {\n get => (bool)GetValue(IsSwappingStartedProperty);\n private set => SetValue(IsSwappingStartedProperty, value);\n }\n public static readonly DependencyProperty IsSwappingStartedProperty =\n DependencyProperty.Register(nameof(IsSwappingStarted), typeof(bool), typeof(FlyleafHost), new PropertyMetadata(false));\n\n public bool IsPanMoving\n {\n get { return (bool)GetValue(IsPanMovingProperty); }\n private set { SetValue(IsPanMovingProperty, value); }\n }\n public static readonly DependencyProperty IsPanMovingProperty =\n DependencyProperty.Register(nameof(IsPanMoving), typeof(bool), typeof(FlyleafHost), new PropertyMetadata(false));\n\n public bool IsDragMoving\n {\n get { return (bool)GetValue(IsDragMovingProperty); }\n set { SetValue(IsDragMovingProperty, value); }\n }\n public static readonly DependencyProperty IsDragMovingProperty =\n DependencyProperty.Register(nameof(IsDragMoving), typeof(bool), typeof(FlyleafHost), new PropertyMetadata(false));\n\n public bool IsDragMovingOwner\n {\n get { return (bool)GetValue(IsDragMovingOwnerProperty); }\n set { SetValue(IsDragMovingOwnerProperty, value); }\n }\n public static readonly DependencyProperty IsDragMovingOwnerProperty =\n DependencyProperty.Register(nameof(IsDragMovingOwner), typeof(bool), typeof(FlyleafHost), new PropertyMetadata(false));\n\n public FrameworkElement MarginTarget\n {\n get => (FrameworkElement)GetValue(MarginTargetProperty);\n set => SetValue(MarginTargetProperty, value);\n }\n public static readonly DependencyProperty MarginTargetProperty =\n DependencyProperty.Register(nameof(MarginTarget), typeof(FrameworkElement), typeof(FlyleafHost), new PropertyMetadata(null));\n\n public object HostDataContext\n {\n get => GetValue(HostDataContextProperty);\n set => SetValue(HostDataContextProperty, value);\n }\n public static readonly DependencyProperty HostDataContextProperty =\n DependencyProperty.Register(nameof(HostDataContext), typeof(object), typeof(FlyleafHost), new PropertyMetadata(null));\n\n public object DetachedContent\n {\n get => GetValue(DetachedContentProperty);\n set => SetValue(DetachedContentProperty, value);\n }\n public static readonly DependencyProperty DetachedContentProperty =\n DependencyProperty.Register(nameof(DetachedContent), typeof(object), typeof(FlyleafHost), new PropertyMetadata(null));\n\n public Player Player\n {\n get => (Player)GetValue(PlayerProperty);\n set => SetValue(PlayerProperty, value);\n }\n public static readonly DependencyProperty PlayerProperty =\n DependencyProperty.Register(nameof(Player), typeof(Player), typeof(FlyleafHost), new PropertyMetadata(null, OnPlayerChanged));\n\n public Player ReplicaPlayer\n {\n get => (Player)GetValue(ReplicaPlayerProperty);\n set => SetValue(ReplicaPlayerProperty, value);\n }\n public static readonly DependencyProperty ReplicaPlayerProperty =\n DependencyProperty.Register(nameof(ReplicaPlayer), typeof(Player), typeof(FlyleafHost), new PropertyMetadata(null, OnReplicaPlayerChanged));\n\n public ControlTemplate OverlayTemplate\n {\n get => (ControlTemplate)GetValue(OverlayTemplateProperty);\n set => SetValue(OverlayTemplateProperty, value);\n }\n public static readonly DependencyProperty OverlayTemplateProperty =\n DependencyProperty.Register(nameof(OverlayTemplate), typeof(ControlTemplate), typeof(FlyleafHost), new PropertyMetadata(null, new PropertyChangedCallback(OnOverlayTemplateChanged)));\n\n public Window Overlay\n {\n get => (Window)GetValue(OverlayProperty);\n set => SetValue(OverlayProperty, value);\n }\n public static readonly DependencyProperty OverlayProperty =\n DependencyProperty.Register(nameof(Overlay), typeof(Window), typeof(FlyleafHost), new PropertyMetadata(null, new PropertyChangedCallback(OnOverlayChanged)));\n\n public CornerRadius CornerRadius\n {\n get => (CornerRadius)GetValue(CornerRadiusProperty);\n set => SetValue(CornerRadiusProperty, value);\n }\n public static readonly DependencyProperty CornerRadiusProperty =\n DependencyProperty.Register(nameof(CornerRadius), typeof(CornerRadius), typeof(FlyleafHost), new PropertyMetadata(new CornerRadius(0), new PropertyChangedCallback(OnCornerRadiusChanged)));\n #endregion\n\n #region Events\n private static void OnMouseBindings(DependencyObject d, DependencyPropertyChangedEventArgs e)\n {\n if (isDesignMode)\n return;\n\n FlyleafHost host = d as FlyleafHost;\n if (host.Disposed)\n return;\n\n host.SetMouseSurface();\n host.SetMouseOverlay();\n }\n private static void OnDetachedTopMostChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)\n {\n if (isDesignMode)\n return;\n\n FlyleafHost host = d as FlyleafHost;\n if (host.Disposed)\n return;\n\n if (host.Surface != null)\n host.Surface.Topmost = !host.IsAttached && host.DetachedTopMost;\n }\n private static void DropChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)\n {\n FlyleafHost host = d as FlyleafHost;\n if (host.Disposed)\n return;\n\n if (host.Surface == null)\n return;\n\n host.Surface.AllowDrop =\n host.OpenOnDrop == AvailableWindows.Surface || host.OpenOnDrop == AvailableWindows.Both ||\n host.SwapOnDrop == AvailableWindows.Surface || host.SwapOnDrop == AvailableWindows.Both;\n\n if (host.Overlay == null)\n return;\n\n host.Overlay.AllowDrop =\n host.OpenOnDrop == AvailableWindows.Overlay || host.OpenOnDrop == AvailableWindows.Both ||\n host.SwapOnDrop == AvailableWindows.Overlay || host.SwapOnDrop == AvailableWindows.Both;\n }\n private void UpdateCurRatio()\n {\n if (!KeepRatioOnResize || IsFullScreen)\n return;\n\n if (Player != null && Player.Video.AspectRatio.Value > 0)\n curResizeRatio = Player.Video.AspectRatio.Value;\n else if (ReplicaPlayer != null && ReplicaPlayer.Video.AspectRatio.Value > 0)\n curResizeRatio = ReplicaPlayer.Video.AspectRatio.Value;\n else\n curResizeRatio = (float)(16.0/9.0);\n\n curResizeRatioIfEnabled = curResizeRatio;\n\n Rect screen;\n\n if (IsAttached)\n {\n if (Owner == null)\n {\n Height = ActualWidth / curResizeRatio;\n return;\n }\n\n screen = new(zeroPoint, Owner.RenderSize);\n }\n else\n {\n if (Surface == null)\n return;\n\n var bounds = System.Windows.Forms.Screen.FromPoint(new System.Drawing.Point((int)Surface.Top, (int)Surface.Left)).Bounds;\n screen = new(bounds.Left / DpiX, bounds.Top / DpiY, bounds.Width / DpiX, bounds.Height / DpiY);\n }\n\n double WindowWidth;\n double WindowHeight;\n\n if (curResizeRatio >= 1)\n {\n WindowHeight = PreferredLandscapeWidth / curResizeRatio;\n\n if (WindowHeight < Surface.MinHeight)\n {\n WindowHeight = Surface.MinHeight;\n WindowWidth = WindowHeight * curResizeRatio;\n }\n else if (WindowHeight > Surface.MaxHeight)\n {\n WindowHeight = Surface.MaxHeight;\n WindowWidth = Surface.Height * curResizeRatio;\n }\n else if (WindowHeight > screen.Height)\n {\n WindowHeight = screen.Height;\n WindowWidth = WindowHeight * curResizeRatio;\n }\n else\n WindowWidth = PreferredLandscapeWidth;\n }\n else\n {\n WindowWidth = PreferredPortraitHeight * curResizeRatio;\n\n if (WindowWidth < Surface.MinWidth)\n {\n WindowWidth = Surface.MinWidth;\n WindowHeight = WindowWidth / curResizeRatio;\n }\n else if (WindowWidth > Surface.MaxWidth)\n {\n WindowWidth = Surface.MaxWidth;\n WindowHeight = WindowWidth / curResizeRatio;\n }\n else if (WindowWidth > screen.Width)\n {\n WindowWidth = screen.Width;\n WindowHeight = WindowWidth / curResizeRatio;\n }\n else\n WindowHeight = PreferredPortraitHeight;\n }\n\n if (IsAttached)\n {\n\n Height = WindowHeight;\n Width = WindowWidth;\n }\n\n else if (Surface != null)\n {\n double WindowLeft;\n double WindowTop;\n\n if (Surface.Left + Surface.Width / 2 > screen.Width / 2)\n WindowLeft = Math.Min(Math.Max(Surface.Left + Surface.Width - WindowWidth, 0), screen.Width - WindowWidth);\n else\n WindowLeft = Surface.Left;\n\n if (Surface.Top + Surface.Height / 2 > screen.Height / 2)\n WindowTop = Math.Min(Math.Max(Surface.Top + Surface.Height - WindowHeight, 0), screen.Height - WindowHeight);\n else\n WindowTop = Surface.Top;\n\n WindowLeft *= DpiX;\n WindowTop *= DpiY;\n WindowWidth *= DpiX;\n WindowHeight*= DpiY;\n\n SetWindowPos(SurfaceHandle, IntPtr.Zero,\n (int)WindowLeft,\n (int)WindowTop,\n (int)Math.Ceiling(WindowWidth),\n (int)Math.Ceiling(WindowHeight),\n (uint)(SetWindowPosFlags.SWP_NOZORDER | SetWindowPosFlags.SWP_NOACTIVATE));\n }\n }\n private static void OnShowInTaskBarChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)\n {\n FlyleafHost host = d as FlyleafHost;\n if (host.Disposed)\n return;\n\n if (host.Surface == null)\n return;\n\n if (host.DetachedShowInTaskbar)\n SetWindowLong(host.SurfaceHandle, (int)WindowLongFlags.GWL_EXSTYLE, GetWindowLong(host.SurfaceHandle, (int)WindowLongFlags.GWL_EXSTYLE) | (nint)WindowStylesEx.WS_EX_APPWINDOW);\n else\n SetWindowLong(host.SurfaceHandle, (int)WindowLongFlags.GWL_EXSTYLE, GetWindowLong(host.SurfaceHandle, (int)WindowLongFlags.GWL_EXSTYLE) & ~(nint)WindowStylesEx.WS_EX_APPWINDOW);\n }\n private static void OnNoOwnerChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)\n {\n FlyleafHost host = d as FlyleafHost;\n if (host.Disposed)\n return;\n\n if (host.Surface == null)\n return;\n\n if (!host.IsAttached)\n host.Surface.Owner = host.DetachedNoOwner ? null : host.Owner;\n }\n private static void OnKeepRatioOnResizeChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)\n {\n if (isDesignMode)\n return;\n\n FlyleafHost host = d as FlyleafHost;\n if (host.Disposed)\n return;\n\n if (!host.KeepRatioOnResize)\n host.curResizeRatioIfEnabled = 0;\n else\n host.UpdateCurRatio();\n }\n private static void OnPlayerChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)\n {\n if (isDesignMode)\n return;\n\n FlyleafHost host = d as FlyleafHost;\n if (host.Disposed)\n return;\n\n host.SetPlayer((Player)e.OldValue);\n }\n private static void OnReplicaPlayerChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)\n {\n if (isDesignMode)\n return;\n\n FlyleafHost host = d as FlyleafHost;\n if (host.Disposed)\n return;\n\n host.SetReplicaPlayer((Player)e.OldValue);\n }\n private static void OnIsFullScreenChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)\n {\n if (isDesignMode)\n return;\n\n FlyleafHost host = d as FlyleafHost;\n if (host.Disposed)\n return;\n\n host.RefreshNormalFullScreen();\n }\n private static void OnIsMinimizedChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)\n {\n if (isDesignMode)\n return;\n\n FlyleafHost host = d as FlyleafHost;\n if (host.Disposed)\n return;\n\n host.Surface.WindowState = host.IsMinimized ? WindowState.Minimized : (host.IsFullScreen ? WindowState.Maximized : WindowState.Normal);\n }\n private static void OnIsAttachedChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)\n {\n if (isDesignMode)\n return;\n\n FlyleafHost host = d as FlyleafHost;\n if (host.Disposed)\n return;\n\n if (host.IsStandAlone)\n {\n host.IsAttached = false;\n return;\n }\n\n if (!host.IsLoaded)\n return;\n\n if (host.IsAttached)\n host.Attach();\n else\n host.Detach();\n }\n private static void OnActivityTimeoutChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)\n {\n FlyleafHost host = d as FlyleafHost;\n if (host.Disposed)\n return;\n\n if (host.Player == null)\n return;\n\n host.Player.Activity.Timeout = host.ActivityTimeout;\n }\n bool setTemplate; // Issue #481 - FlyleafME override SetOverlay will not have a template to initialize properly *bool required if SetOverlay can be called multiple times and with different configs\n private static void OnOverlayTemplateChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)\n {\n if (isDesignMode)\n return;\n\n FlyleafHost host = d as FlyleafHost;\n if (host.Disposed)\n return;\n\n if (host.Overlay == null)\n {\n host.setTemplate= true;\n host.Overlay = new Window() { WindowStyle = WindowStyle.None, ResizeMode = ResizeMode.NoResize, AllowsTransparency = true };\n host.setTemplate= false;\n }\n else\n host.Overlay.Template = host.OverlayTemplate;\n }\n private static void OnOverlayChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)\n {\n FlyleafHost host = d as FlyleafHost;\n if (host.Disposed)\n return;\n\n if (!isDesignMode)\n host.SetOverlay();\n else\n {\n // XSurface.Wpf.Window (can this work on designer?\n }\n }\n private static void OnCornerRadiusChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)\n {\n if (isDesignMode)\n return;\n\n FlyleafHost host = d as FlyleafHost;\n if (host.Disposed)\n return;\n\n if (host.Surface == null)\n return;\n\n if (host.CornerRadius == host.zeroCornerRadius)\n host.Surface.Background = Brushes.Black;\n else\n {\n host.Surface.Background = Brushes.Transparent;\n host.SetCornerRadiusBorder();\n }\n\n if (host?.Player == null)\n return;\n\n host.Player.renderer.CornerRadius = (CornerRadius)e.NewValue;\n\n }\n private void SetCornerRadiusBorder()\n {\n // Required to handle mouse events as the window's background will be transparent\n // This does not set the background color we do that with the renderer (which causes some issues eg. when returning from fullscreen to normalscreen)\n Surface.Content = new Border()\n {\n Background = Brushes.Black, // TBR: for alpha channel -> Background == Brushes.Transparent || Background ==null ? new SolidColorBrush(Color.FromArgb(1,0,0,0)) : Background\n HorizontalAlignment = HorizontalAlignment.Stretch,\n VerticalAlignment = VerticalAlignment.Stretch,\n CornerRadius = CornerRadius,\n };\n }\n private static object OnContentChanging(DependencyObject d, object baseValue)\n {\n if (isDesignMode)\n return baseValue;\n\n FlyleafHost host = d as FlyleafHost;\n if (host.Disposed)\n return host.DetachedContent;\n\n if (baseValue != null && host.Overlay == null)\n host.Overlay = new Window() { WindowStyle = WindowStyle.None, ResizeMode = ResizeMode.NoResize, AllowsTransparency = true };\n\n if (host.Overlay != null)\n host.Overlay.Content = baseValue;\n\n return host.DetachedContent;\n }\n\n private void Host_Loaded(object sender, RoutedEventArgs e)\n {\n Window owner = Window.GetWindow(this);\n if (owner == null)\n return;\n\n var ownerHandle = new WindowInteropHelper(owner).EnsureHandle();\n\n // Owner Changed\n if (Owner != null)\n {\n if (!IsAttached || OwnerHandle == ownerHandle)\n return; // Check OwnerHandle changed (NOTE: Owner can be the same class/window but the handle can be different)\n\n Owner.SizeChanged -= Owner_SizeChanged;\n\n Surface.Hide();\n Overlay?.Hide();\n Detach();\n\n Owner = owner;\n OwnerHandle = ownerHandle;\n Surface.Title = Owner.Title;\n Surface.Icon = Owner.Icon;\n\n Owner.SizeChanged += Owner_SizeChanged;\n Attach();\n rectDetachedLast = Rect.Empty; // Attach will set it wrong first time\n Host_IsVisibleChanged(null, new());\n\n return;\n }\n\n Owner = owner;\n OwnerHandle = ownerHandle;\n HostDataContext = DataContext;\n\n SetSurface();\n\n Surface.Title = Owner.Title;\n Surface.Icon = Owner.Icon;\n\n Owner.SizeChanged += Owner_SizeChanged;\n DataContextChanged += Host_DataContextChanged;\n LayoutUpdated += Host_LayoutUpdated;\n IsVisibleChanged += Host_IsVisibleChanged;\n\n // TBR: We need to ensure that Surface/Overlay will be initial Show once to work properly (issue #415)\n if (IsAttached)\n {\n Attach();\n rectDetachedLast = Rect.Empty; // Attach will set it wrong first time\n Surface.Show();\n Overlay?.Show();\n Host_IsVisibleChanged(null, new());\n }\n else\n {\n Detach();\n\n if (PreferredLandscapeWidth == 0)\n PreferredLandscapeWidth = (int)Surface.Width;\n\n if (PreferredPortraitHeight == 0)\n PreferredPortraitHeight = (int)Surface.Height;\n\n UpdateCurRatio();\n Surface.Show();\n Overlay?.Show();\n }\n }\n\n // WindowChrome Issue #410: It will not properly move child windows when resized from top or left\n private void Owner_SizeChanged(object sender, SizeChangedEventArgs e)\n => rectInitLast = Rect.Empty;\n\n private void Host_DataContextChanged(object sender, DependencyPropertyChangedEventArgs e) =>\n // TBR\n // 1. this.DataContext: FlyleafHost's DataContext will not be affected (Inheritance)\n // 2. Overlay.DataContext: Overlay's DataContext will be FlyleafHost itself\n // 3. Overlay.DataContext.HostDataContext: FlyleafHost's DataContext includes HostDataContext to access FlyleafHost's DataContext\n // 4. In case of Stand Alone will let the user to decide\n\n HostDataContext = DataContext;\n private void Host_IsVisibleChanged(object sender, DependencyPropertyChangedEventArgs e)\n {\n if (!IsAttached)\n return;\n\n if (IsVisible)\n {\n Host_Loaded(null, null);\n Surface.Show();\n\n if (Overlay != null)\n {\n Overlay.Show();\n\n // It happens (eg. with MetroWindow) that overlay left will not be equal to surface left so we reset it by detach/attach the overlay to surface (https://github.com/SuRGeoNix/Flyleaf/issues/370)\n RECT surfRect = new();\n RECT overRect = new();\n GetWindowRect(SurfaceHandle, ref surfRect);\n GetWindowRect(OverlayHandle, ref overRect);\n\n if (surfRect.Left != overRect.Left)\n {\n // Detach Overlay\n SetParent(OverlayHandle, IntPtr.Zero);\n SetWindowLong(OverlayHandle, (int)WindowLongFlags.GWL_STYLE, NONE_STYLE);\n Overlay.Owner = null;\n\n SetWindowPos(OverlayHandle, IntPtr.Zero, 0, 0, (int)Surface.ActualWidth, (int)Surface.ActualHeight,\n (uint)(SetWindowPosFlags.SWP_NOZORDER | SetWindowPosFlags.SWP_NOACTIVATE));\n\n // Attache Overlay\n SetWindowLong(OverlayHandle, (int)WindowLongFlags.GWL_STYLE, NONE_STYLE | (nint)(WindowStyles.WS_CHILD | WindowStyles.WS_MAXIMIZE));\n Overlay.Owner = Surface;\n SetParent(OverlayHandle, SurfaceHandle);\n\n // Required to restore overlay\n Rect tt1 = new(0, 0, 0, 0);\n SetRect(ref tt1);\n }\n }\n\n // TBR: First time loaded in a tab control could cause UCEERR_RENDERTHREADFAILURE (can be avoided by hide/show again here)\n }\n else\n {\n Surface.Hide();\n Overlay?.Hide();\n }\n }\n private void Host_LayoutUpdated(object sender, EventArgs e)\n {\n // Finds Rect Intersect with FlyleafHost's parents and Clips Surface/Overlay (eg. within ScrollViewer)\n // TBR: Option not to clip rect or stop at first/second parent?\n // For performance should focus only on ScrollViewer if any and Owner Window (other sources that clip our host?)\n\n if (!IsVisible || !IsAttached || IsFullScreen || IsResizing)\n return;\n\n try\n {\n rectInit = rectIntersect = new(TransformToAncestor(Owner).Transform(zeroPoint), RenderSize);\n\n FrameworkElement parent = this;\n while ((parent = VisualTreeHelper.GetParent(parent) as FrameworkElement) != null)\n {\n if (parent.FlowDirection == FlowDirection.RightToLeft)\n {\n var location = parent.TransformToAncestor(Owner).Transform(zeroPoint);\n location.X -= parent.RenderSize.Width;\n rectIntersect.Intersect(new Rect(location, parent.RenderSize));\n }\n else\n rectIntersect.Intersect(new Rect(parent.TransformToAncestor(Owner).Transform(zeroPoint), parent.RenderSize));\n }\n\n if (rectInit != rectInitLast)\n {\n SetRect(ref rectInit);\n rectInitLast = rectInit;\n }\n\n if (rectIntersect == Rect.Empty)\n {\n if (rectIntersect == rectIntersectLast)\n return;\n\n rectIntersectLast = rectIntersect;\n SetVisibleRect(ref zeroRect);\n }\n else\n {\n rectIntersect.X -= rectInit.X;\n rectIntersect.Y -= rectInit.Y;\n\n if (rectIntersect == rectIntersectLast)\n return;\n\n rectIntersectLast = rectIntersect;\n\n SetVisibleRect(ref rectIntersect);\n }\n }\n catch (Exception ex)\n {\n // It has been noticed with NavigationService (The visual tree changes, visual root IsVisible is false but FlyleafHost is still visible)\n if (Logger.CanDebug) Log.Debug($\"Host_LayoutUpdated: {ex.Message}\");\n\n // TBR: (Currently handle on each time Visible=true) It's possible that the owner/parent has been changed (for some reason Host_Loaded will not be called) *probably when the Owner stays the same but the actual Handle changes\n //if (ex.Message == \"The specified Visual is not an ancestor of this Visual.\")\n //Host_Loaded(null, null);\n }\n }\n private void Player_Video_PropertyChanged(object sender, PropertyChangedEventArgs e)\n {\n if (KeepRatioOnResize && e.PropertyName == nameof(Player.Video.AspectRatio) && Player.Video.AspectRatio.Value > 0)\n UpdateCurRatio();\n }\n private void ReplicaPlayer_Video_PropertyChanged(object sender, PropertyChangedEventArgs e)\n {\n if (KeepRatioOnResize && e.PropertyName == nameof(ReplicaPlayer.Video.AspectRatio) && ReplicaPlayer.Video.AspectRatio.Value > 0)\n UpdateCurRatio();\n }\n #endregion\n\n #region Events Surface / Overlay\n private void Surface_KeyDown(object sender, KeyEventArgs e) { if (KeyBindings == AvailableWindows.Surface || KeyBindings == AvailableWindows.Both) e.Handled = Player.KeyDown(Player, e); }\n private void Overlay_KeyDown(object sender, KeyEventArgs e) { if (KeyBindings == AvailableWindows.Overlay || KeyBindings == AvailableWindows.Both) e.Handled = Player.KeyDown(Player, e); }\n\n private void Surface_KeyUp(object sender, KeyEventArgs e) { if (KeyBindings == AvailableWindows.Surface || KeyBindings == AvailableWindows.Both) e.Handled = Player.KeyUp(Player, e); }\n private void Overlay_KeyUp(object sender, KeyEventArgs e) { if (KeyBindings == AvailableWindows.Overlay || KeyBindings == AvailableWindows.Both) e.Handled = Player.KeyUp(Player, e); }\n\n private void Surface_Drop(object sender, DragEventArgs e)\n {\n IsSwappingStarted = false;\n Surface.ReleaseMouseCapture();\n FlyleafHostDropWrap hostWrap = (FlyleafHostDropWrap) e.Data.GetData(typeof(FlyleafHostDropWrap));\n\n // Swap FlyleafHosts\n if (hostWrap != null)\n {\n (hostWrap.FlyleafHost.Player, Player) = (Player, hostWrap.FlyleafHost.Player);\n Surface.Activate();\n return;\n }\n\n if (Player == null)\n return;\n\n // Invoke event first and see if it gets handled\n OnSurfaceDrop?.Invoke(this, e);\n\n if (!e.Handled)\n {\n // Player Open Text (TBR: Priority matters, eg. firefox will set both - cached file thumbnail of a video & the link of the video)\n if (e.Data.GetDataPresent(DataFormats.Text))\n {\n string text = e.Data.GetData(DataFormats.Text, false).ToString();\n if (text.Length > 0)\n Player.OpenAsync(text);\n }\n\n // Player Open File\n else if (e.Data.GetDataPresent(DataFormats.FileDrop))\n {\n string filename = ((string[])e.Data.GetData(DataFormats.FileDrop, false))[0];\n Player.OpenAsync(filename);\n }\n }\n\n Surface.Activate();\n }\n private void Overlay_Drop(object sender, DragEventArgs e)\n {\n IsSwappingStarted = false;\n Overlay.ReleaseMouseCapture();\n FlyleafHostDropWrap hostWrap = (FlyleafHostDropWrap) e.Data.GetData(typeof(FlyleafHostDropWrap));\n\n // Swap FlyleafHosts\n if (hostWrap != null)\n {\n (hostWrap.FlyleafHost.Player, Player) = (Player, hostWrap.FlyleafHost.Player);\n Overlay.Activate();\n return;\n }\n\n if (Player == null)\n return;\n\n // Invoke event first and see if it gets handled\n OnOverlayDrop?.Invoke(this, e);\n\n if (!e.Handled)\n {\n // Player Open Text\n if (e.Data.GetDataPresent(DataFormats.Text))\n {\n string text = e.Data.GetData(DataFormats.Text, false).ToString();\n if (text.Length > 0)\n Player.OpenAsync(text);\n }\n\n // Player Open File\n else if (e.Data.GetDataPresent(DataFormats.FileDrop))\n {\n string filename = ((string[])e.Data.GetData(DataFormats.FileDrop, false))[0];\n Player.OpenAsync(filename);\n }\n }\n\n Overlay.Activate();\n }\n private void Surface_DragEnter(object sender, DragEventArgs e) { if (Player != null) e.Effects = DragDropEffects.All; }\n private void Overlay_DragEnter(object sender, DragEventArgs e) { if (Player != null) e.Effects = DragDropEffects.All; }\n private void Surface_StateChanged(object sender, EventArgs e)\n {\n switch (Surface.WindowState)\n {\n case WindowState.Maximized:\n IsFullScreen = true;\n IsMinimized = false;\n Player?.Activity.RefreshFullActive();\n\n break;\n\n case WindowState.Normal:\n\n IsFullScreen = false;\n IsMinimized = false;\n Player?.Activity.RefreshFullActive();\n\n break;\n\n case WindowState.Minimized:\n\n IsMinimized = true;\n break;\n }\n }\n\n private void Surface_MouseLeftButtonDown(object sender, MouseButtonEventArgs e) => SO_MouseLeftButtonDown(e, Surface);\n private void Overlay_MouseLeftButtonDown(object sender, MouseButtonEventArgs e) => SO_MouseLeftButtonDown(e, Overlay);\n private void SO_MouseLeftButtonDown(MouseButtonEventArgs e, Window window)\n {\n AvailableWindows availWindow;\n AttachedDragMoveOptions availDragMove;\n AttachedDragMoveOptions availDragMoveOwner;\n\n if (window == Surface)\n {\n availWindow = AvailableWindows.Surface;\n availDragMove = AttachedDragMoveOptions.Surface;\n availDragMoveOwner = AttachedDragMoveOptions.SurfaceOwner;\n }\n else\n {\n availWindow = AvailableWindows.Overlay;\n availDragMove = AttachedDragMoveOptions.Overlay;\n availDragMoveOwner = AttachedDragMoveOptions.OverlayOwner;\n }\n\n if (BringToFrontOnClick) // Activate and Z-order top\n BringToFront();\n\n window.Focus();\n Player?.Activity.RefreshFullActive();\n\n mouseLeftDownPoint = e.GetPosition(window);\n IsSwappingStarted = false; // currently we don't care if it was cancelled (it can be stay true if we miss the mouse up) - QueryContinueDrag\n\n // Resize\n if (ResizingSide != 0)\n {\n IsResizing = true;\n\n if (IsAttached)\n {\n ownerZeroPointPos = Owner.PointToScreen(zeroPoint);\n GetWindowRect(SurfaceHandle, ref beforeResizeRect);\n LayoutUpdated -= Host_LayoutUpdated;\n ResetVisibleRect();\n }\n }\n\n // Swap\n else if ((SwapOnDrop == availWindow || SwapOnDrop == AvailableWindows.Both) &&\n (Keyboard.IsKeyDown(Key.LeftShift) || Keyboard.IsKeyDown(Key.RightShift)))\n {\n IsSwappingStarted = true;\n DragDrop.DoDragDrop(this, new FlyleafHostDropWrap() { FlyleafHost = this }, DragDropEffects.Move);\n\n return; // No Capture\n }\n\n // PanMove\n else if (Player != null &&\n (PanMoveOnCtrl == availWindow || PanMoveOnCtrl == AvailableWindows.Both) &&\n (Keyboard.IsKeyDown(Key.LeftCtrl) || Keyboard.IsKeyDown(Key.RightCtrl)))\n {\n panPrevX = Player.PanXOffset;\n panPrevY = Player.PanYOffset;\n IsPanMoving = true;\n }\n\n // DragMoveOwner\n else if (IsAttached && Owner != null &&\n (AttachedDragMove == availDragMoveOwner || AttachedDragMove == AttachedDragMoveOptions.BothOwner))\n IsDragMovingOwner = true;\n\n\n // DragMove (Attach|Detach)\n else if ((IsAttached && (AttachedDragMove == availDragMove || AttachedDragMove == AttachedDragMoveOptions.Both))\n || (!IsAttached && (DetachedDragMove == availWindow || DetachedDragMove == AvailableWindows.Both)))\n IsDragMoving = true;\n\n else\n return; // No Capture\n\n window.CaptureMouse();\n }\n\n private void Surface_MouseLeftButtonUp(object sender, MouseButtonEventArgs e) => Surface_ReleaseCapture();\n private void Overlay_MouseLeftButtonUp(object sender, MouseButtonEventArgs e) => Overlay_ReleaseCapture();\n private void Surface_LostMouseCapture(object sender, MouseEventArgs e) => Surface_ReleaseCapture();\n private void Overlay_LostMouseCapture(object sender, MouseEventArgs e) => Overlay_ReleaseCapture();\n private void Surface_ReleaseCapture()\n {\n if (!IsResizing && !IsPanMoving && !IsDragMoving && !IsDragMovingOwner)\n return;\n\n Surface.ReleaseMouseCapture();\n\n if (IsResizing)\n {\n ResizingSide = 0;\n Surface.Cursor = Cursors.Arrow;\n IsResizing = false;\n\n if (IsAttached)\n {\n GetWindowRect(SurfaceHandle, ref curRect);\n MarginTarget.Margin = new(MarginTarget.Margin.Left + (curRect.Left - beforeResizeRect.Left) / DpiX, MarginTarget.Margin.Top + (curRect.Top - beforeResizeRect.Top) / DpiY, MarginTarget.Margin.Right, MarginTarget.Margin.Bottom);\n Width = Surface.Width;\n Height = Surface.Height;\n Host_LayoutUpdated(null, null); // When attached to restore the clipped rect\n LayoutUpdated += Host_LayoutUpdated;\n }\n }\n else if (IsPanMoving)\n IsPanMoving = false;\n else if (IsDragMoving)\n IsDragMoving = false;\n else if (IsDragMovingOwner)\n IsDragMovingOwner = false;\n else\n return;\n }\n private void Overlay_ReleaseCapture()\n {\n if (!IsResizing && !IsPanMoving && !IsDragMoving && !IsDragMovingOwner)\n return;\n\n Overlay.ReleaseMouseCapture();\n\n if (IsResizing)\n {\n ResizingSide = 0;\n Overlay.Cursor = Cursors.Arrow;\n IsResizing = false;\n\n if (IsAttached)\n {\n GetWindowRect(SurfaceHandle, ref curRect);\n MarginTarget.Margin = new(MarginTarget.Margin.Left + (curRect.Left - beforeResizeRect.Left) / DpiX, MarginTarget.Margin.Top + (curRect.Top - beforeResizeRect.Top) / DpiY, MarginTarget.Margin.Right, MarginTarget.Margin.Bottom);\n Width = Surface.Width;\n Height = Surface.Height;\n Host_LayoutUpdated(null, null); // When attached to restore the clipped rect\n LayoutUpdated += Host_LayoutUpdated;\n }\n }\n else if (IsPanMoving)\n IsPanMoving = false;\n else if (IsDragMoving)\n IsDragMoving = false;\n else if (IsDragMovingOwner)\n IsDragMovingOwner = false;\n }\n\n private void Surface_MouseMove(object sender, MouseEventArgs e)\n {\n var cur = e.GetPosition(Surface);\n\n if (Player != null && cur != mouseMoveLastPoint)\n {\n Player.Activity.RefreshFullActive();\n mouseMoveLastPoint = cur;\n }\n\n // Resize Sides (CanResize + !MouseDown + !FullScreen)\n if (e.MouseDevice.LeftButton != MouseButtonState.Pressed)\n {\n if ( !IsFullScreen &&\n ((IsAttached && (AttachedResize == AvailableWindows.Surface || AttachedResize == AvailableWindows.Both)) ||\n (!IsAttached && (DetachedResize == AvailableWindows.Surface || DetachedResize == AvailableWindows.Both))))\n {\n ResizingSide = ResizeSides(Surface, cur, ResizeSensitivity, CornerRadius);\n }\n\n return;\n }\n\n SO_MouseLeftDownAndMove(cur);\n }\n private void Overlay_MouseMove(object sender, MouseEventArgs e)\n {\n var cur = e.GetPosition(Overlay);\n\n if (Player != null && cur != mouseMoveLastPoint)\n {\n Player.Activity.RefreshFullActive();\n mouseMoveLastPoint = cur;\n }\n\n // Resize Sides (CanResize + !MouseDown + !FullScreen)\n if (e.MouseDevice.LeftButton != MouseButtonState.Pressed)\n {\n if (!IsFullScreen && cur != zeroPoint &&\n ((IsAttached && (AttachedResize == AvailableWindows.Overlay || AttachedResize == AvailableWindows.Both)) ||\n (!IsAttached && (DetachedResize == AvailableWindows.Overlay || DetachedResize == AvailableWindows.Both))))\n {\n ResizingSide = ResizeSides(Overlay, cur, ResizeSensitivity, CornerRadius);\n }\n\n return;\n }\n\n SO_MouseLeftDownAndMove(cur);\n }\n private void SO_MouseLeftDownAndMove(Point cur)\n {\n if (IsSwappingStarted)\n return;\n\n // Player's Pan Move (Ctrl + Drag Move)\n if (IsPanMoving)\n {\n Player.PanXOffset = panPrevX + (int) (cur.X - mouseLeftDownPoint.X);\n Player.PanYOffset = panPrevY + (int) (cur.Y - mouseLeftDownPoint.Y);\n\n return;\n }\n\n if (IsFullScreen)\n return;\n\n // Resize (MouseDown + ResizeSide != 0)\n if (IsResizing)\n Resize(cur, ResizingSide, curResizeRatioIfEnabled);\n\n // Drag Move Self (Attached|Detached)\n else if (IsDragMoving)\n {\n if (IsAttached)\n {\n MarginTarget.Margin = new(\n MarginTarget.Margin.Left + cur.X - mouseLeftDownPoint.X,\n MarginTarget.Margin.Top + cur.Y - mouseLeftDownPoint.Y,\n MarginTarget.Margin.Right,\n MarginTarget.Margin.Bottom);\n }\n else\n {\n Surface.Left += cur.X - mouseLeftDownPoint.X;\n Surface.Top += cur.Y - mouseLeftDownPoint.Y;\n }\n }\n\n // Drag Move Owner (Attached)\n else if (IsDragMovingOwner)\n {\n if (Owner.Owner != null)\n {\n Owner.Owner.Left += cur.X - mouseLeftDownPoint.X;\n Owner.Owner.Top += cur.Y - mouseLeftDownPoint.Y;\n }\n else\n {\n Owner.Left += cur.X - mouseLeftDownPoint.X;\n Owner.Top += cur.Y - mouseLeftDownPoint.Y;\n }\n }\n }\n\n private void Surface_MouseLeave(object sender, MouseEventArgs e) { ResizingSide = 0; Surface.Cursor = Cursors.Arrow; }\n private void Overlay_MouseLeave(object sender, MouseEventArgs e) { ResizingSide = 0; Overlay.Cursor = Cursors.Arrow; }\n\n private void Surface_MouseDoubleClick(object sender, MouseButtonEventArgs e) { if (ToggleFullScreenOnDoubleClick == AvailableWindows.Surface || ToggleFullScreenOnDoubleClick == AvailableWindows.Both) { IsFullScreen = !IsFullScreen; e.Handled = true; } }\n private void Overlay_MouseDoubleClick(object sender, MouseButtonEventArgs e) { if (ToggleFullScreenOnDoubleClick == AvailableWindows.Overlay || ToggleFullScreenOnDoubleClick == AvailableWindows.Both) { IsFullScreen = !IsFullScreen; e.Handled = true; } }\n\n private void Surface_MouseWheel(object sender, MouseWheelEventArgs e)\n {\n if (Player == null || e.Delta == 0)\n return;\n\n if ((Keyboard.IsKeyDown(Key.LeftCtrl) || Keyboard.IsKeyDown(Key.RightCtrl)) &&\n (PanZoomOnCtrlWheel == AvailableWindows.Surface || PanZoomOnCtrlWheel == AvailableWindows.Both))\n {\n var cur = e.GetPosition(Surface);\n Point curDpi = new(cur.X * DpiX, cur.Y * DpiY);\n if (e.Delta > 0)\n Player.ZoomIn(curDpi);\n else\n Player.ZoomOut(curDpi);\n }\n else if ((Keyboard.IsKeyDown(Key.LeftShift) || Keyboard.IsKeyDown(Key.RightShift)) &&\n (PanRotateOnShiftWheel == AvailableWindows.Surface || PanZoomOnCtrlWheel == AvailableWindows.Both))\n {\n if (e.Delta > 0)\n Player.RotateRight();\n else\n Player.RotateLeft();\n }\n\n //else if (IsAttached) // TBR ScrollViewer\n //{\n // RaiseEvent(e);\n //}\n }\n private void Overlay_MouseWheel(object sender, MouseWheelEventArgs e)\n {\n if (Player == null || e.Delta == 0)\n return;\n\n if ((Keyboard.IsKeyDown(Key.LeftCtrl) || Keyboard.IsKeyDown(Key.RightCtrl)) &&\n (PanZoomOnCtrlWheel == AvailableWindows.Overlay || PanZoomOnCtrlWheel == AvailableWindows.Both))\n {\n var cur = e.GetPosition(Overlay);\n Point curDpi = new(cur.X * DpiX, cur.Y * DpiY);\n if (e.Delta > 0)\n Player.ZoomIn(curDpi);\n else\n Player.ZoomOut(curDpi);\n }\n else if ((Keyboard.IsKeyDown(Key.LeftShift) || Keyboard.IsKeyDown(Key.RightShift)) &&\n (PanRotateOnShiftWheel == AvailableWindows.Overlay || PanZoomOnCtrlWheel == AvailableWindows.Both))\n {\n if (e.Delta > 0)\n Player.RotateRight();\n else\n Player.RotateLeft();\n }\n }\n\n private void Surface_Closed(object sender, EventArgs e)\n {\n surfaceClosed = true;\n Dispose();\n }\n private void Surface_Closing(object sender, CancelEventArgs e) => surfaceClosing = true;\n private void Overlay_Closed(object sender, EventArgs e)\n {\n overlayClosed = true;\n if (!surfaceClosing)\n Surface?.Close();\n }\n private void OverlayStandAlone_Loaded(object sender, RoutedEventArgs e)\n {\n if (Overlay != null)\n return;\n\n if (standAloneOverlay.WindowStyle != WindowStyle.None || standAloneOverlay.AllowsTransparency == false)\n throw new Exception(\"Stand-alone FlyleafHost requires WindowStyle = WindowStyle.None and AllowsTransparency = true\");\n\n SetSurface();\n Overlay = standAloneOverlay;\n Overlay.IsVisibleChanged += OverlayStandAlone_IsVisibleChanged;\n Surface.ShowInTaskbar = false; Surface.ShowInTaskbar = true; // It will not be visible in taskbar if user clicks in another window when loading\n OverlayStandAlone_IsVisibleChanged(null, new());\n }\n private void OverlayStandAlone_IsVisibleChanged(object sender, DependencyPropertyChangedEventArgs e)\n {\n // Surface should be visible first (this happens only on initialization of standalone)\n\n if (Surface.IsVisible)\n return;\n\n if (Overlay.IsVisible)\n {\n Surface.Show();\n ShowWindow(OverlayHandle, (int)ShowWindowCommands.SW_SHOWMINIMIZED);\n ShowWindow(OverlayHandle, (int)ShowWindowCommands.SW_SHOWMAXIMIZED);\n }\n }\n\n public void Resize(Point p, int resizingSide, double ratio = 0.0)\n {\n double WindowWidth = Surface.ActualWidth;\n double WindowHeight = Surface.ActualHeight;\n double WindowLeft;\n double WindowTop;\n\n if (IsAttached) // NOTE: Window.Left will not be updated when the Owner moves, don't use it when attached\n {\n GetWindowRect(SurfaceHandle, ref curRect);\n WindowLeft = (curRect.Left - ownerZeroPointPos.X) / DpiX;\n WindowTop = (curRect.Top - ownerZeroPointPos.Y) / DpiY;\n }\n else\n {\n WindowLeft = Surface.Left;\n WindowTop = Surface.Top;\n }\n\n if (resizingSide == 2 || resizingSide == 3 || resizingSide == 6)\n {\n p.X += 5;\n\n WindowWidth = p.X > Surface.MinWidth ?\n p.X < Surface.MaxWidth ? p.X : Surface.MaxWidth :\n Surface.MinWidth;\n }\n else if (resizingSide == 1 || resizingSide == 4 || resizingSide == 5)\n {\n p.X -= 5;\n double temp = Surface.ActualWidth - p.X;\n if (temp > Surface.MinWidth && temp < Surface.MaxWidth)\n {\n WindowWidth = temp;\n WindowLeft = WindowLeft + p.X;\n }\n }\n\n if (resizingSide == 2 || resizingSide == 4 || resizingSide == 8)\n {\n p.Y += 5;\n\n if (p.Y > Surface.MinHeight)\n {\n WindowHeight = p.Y < Surface.MaxHeight ? p.Y : Surface.MaxHeight;\n }\n else\n return;\n }\n else if (resizingSide == 1 || resizingSide == 3 || resizingSide == 7)\n {\n if (ratio != 0 && resizingSide != 7)\n {\n double temp = WindowWidth / ratio;\n if (temp > Surface.MinHeight && temp < Surface.MaxHeight)\n WindowTop += Surface.ActualHeight - temp;\n else\n return;\n }\n else\n {\n p.Y -= 5;\n double temp = Surface.ActualHeight - p.Y;\n if (temp > Surface.MinHeight && temp < Surface.MaxHeight)\n {\n WindowHeight= temp;\n WindowTop += p.Y;\n }\n else\n return;\n }\n }\n\n if (ratio != 0)\n {\n if (resizingSide == 7 || resizingSide == 8)\n WindowWidth = WindowHeight * ratio;\n else\n WindowHeight = WindowWidth / ratio;\n }\n\n if (WindowWidth >= WindowHeight)\n PreferredLandscapeWidth = (int)WindowWidth;\n else\n PreferredPortraitHeight = (int)WindowHeight;\n\n WindowLeft *= DpiX;\n WindowTop *= DpiY;\n WindowWidth *= DpiX;\n WindowHeight*= DpiY;\n\n SetWindowPos(SurfaceHandle, IntPtr.Zero,\n (int)WindowLeft,\n (int)WindowTop,\n (int)Math.Ceiling(WindowWidth),\n (int)Math.Ceiling(WindowHeight),\n (uint)(SetWindowPosFlags.SWP_NOZORDER | SetWindowPosFlags.SWP_NOACTIVATE));\n }\n public static int ResizeSides(Window Window, Point p, int ResizeSensitivity, CornerRadius cornerRadius)\n {\n if (p.X <= ResizeSensitivity + (cornerRadius.TopLeft / 2) && p.Y <= ResizeSensitivity + (cornerRadius.TopLeft / 2))\n {\n Window.Cursor = Cursors.SizeNWSE;\n return 1;\n }\n else if (p.X + ResizeSensitivity + (cornerRadius.BottomRight / 2) >= Window.ActualWidth && p.Y + ResizeSensitivity + (cornerRadius.BottomRight / 2) >= Window.ActualHeight)\n {\n Window.Cursor = Cursors.SizeNWSE;\n return 2;\n }\n else if (p.X + ResizeSensitivity + (cornerRadius.TopRight / 2) >= Window.ActualWidth && p.Y <= ResizeSensitivity + (cornerRadius.TopRight / 2))\n {\n Window.Cursor = Cursors.SizeNESW;\n return 3;\n }\n else if (p.X <= ResizeSensitivity + (cornerRadius.BottomLeft / 2) && p.Y + ResizeSensitivity + (cornerRadius.BottomLeft / 2) >= Window.ActualHeight)\n {\n Window.Cursor = Cursors.SizeNESW;\n return 4;\n }\n else if (p.X <= ResizeSensitivity)\n {\n Window.Cursor = Cursors.SizeWE;\n return 5;\n }\n else if (p.X + ResizeSensitivity >= Window.ActualWidth)\n {\n Window.Cursor = Cursors.SizeWE;\n return 6;\n }\n else if (p.Y <= ResizeSensitivity)\n {\n Window.Cursor = Cursors.SizeNS;\n return 7;\n }\n else if (p.Y + ResizeSensitivity >= Window.ActualHeight)\n {\n Window.Cursor = Cursors.SizeNS;\n return 8;\n }\n else\n {\n Window.Cursor = Cursors.Arrow;\n return 0;\n }\n }\n #endregion\n\n #region Constructors\n static FlyleafHost()\n {\n DefaultStyleKeyProperty.OverrideMetadata(typeof(FlyleafHost), new FrameworkPropertyMetadata(typeof(FlyleafHost)));\n ContentProperty.OverrideMetadata(typeof(FlyleafHost), new FrameworkPropertyMetadata(null, new CoerceValueCallback(OnContentChanging)));\n }\n public FlyleafHost()\n {\n UniqueId = idGenerator++;\n isDesignMode = DesignerProperties.GetIsInDesignMode(this);\n if (isDesignMode)\n return;\n\n MarginTarget= this;\n Log = new LogHandler((\"[#\" + UniqueId + \"]\").PadRight(8, ' ') + $\" [FlyleafHost NP] \");\n Loaded += Host_Loaded;\n }\n public FlyleafHost(Window standAloneOverlay)\n {\n UniqueId = idGenerator++;\n Log = new LogHandler((\"[#\" + UniqueId + \"]\").PadRight(8, ' ') + $\" [FlyleafHost NP] \");\n\n IsStandAlone = true;\n IsAttached = false;\n\n this.standAloneOverlay = standAloneOverlay;\n standAloneOverlay.Loaded += OverlayStandAlone_Loaded;\n if (standAloneOverlay.IsLoaded)\n OverlayStandAlone_Loaded(null, null);\n }\n #endregion\n\n #region Methods\n public virtual void SetReplicaPlayer(Player oldPlayer)\n {\n if (oldPlayer != null)\n {\n oldPlayer.renderer.SetChildHandle(IntPtr.Zero);\n oldPlayer.Video.PropertyChanged -= ReplicaPlayer_Video_PropertyChanged;\n }\n\n if (ReplicaPlayer == null)\n return;\n\n if (Surface != null)\n ReplicaPlayer.renderer.SetChildHandle(SurfaceHandle);\n\n ReplicaPlayer.Video.PropertyChanged += ReplicaPlayer_Video_PropertyChanged;\n }\n public virtual void SetPlayer(Player oldPlayer)\n {\n // De-assign old Player's Handle/FlyleafHost\n if (oldPlayer != null)\n {\n Log.Debug($\"De-assign Player #{oldPlayer.PlayerId}\");\n\n oldPlayer.Video.PropertyChanged -= Player_Video_PropertyChanged;\n oldPlayer.VideoDecoder.DestroySwapChain();\n oldPlayer.Host = null;\n }\n\n if (Player == null)\n return;\n\n Log.Prefix = (\"[#\" + UniqueId + \"]\").PadRight(8, ' ') + $\" [FlyleafHost #{Player.PlayerId}] \";\n\n // De-assign new Player's Handle/FlyleafHost\n Player.Host?.Player_Disposed();\n\n if (Player == null) // We might just de-assign our Player\n return;\n\n // Assign new Player's (Handle/FlyleafHost)\n Log.Debug($\"Assign Player #{Player.PlayerId}\");\n\n Player.Host = this;\n Player.Activity.Timeout = ActivityTimeout;\n if (Player.renderer != null) // TBR: using as AudioOnly with a Control*\n Player.renderer.CornerRadius = IsFullScreen ? zeroCornerRadius : CornerRadius;\n\n if (Surface != null)\n {\n if (CornerRadius == zeroCornerRadius)\n Surface.Background = new SolidColorBrush(Player.Config.Video.BackgroundColor);\n //else // TBR: this border probably not required? only when we don't have a renderer?\n //((Border)Surface.Content).Background = new SolidColorBrush(Player.Config.Video.BackgroundColor);\n\n Player.VideoDecoder.CreateSwapChain(SurfaceHandle);\n }\n\n Player.Video.PropertyChanged += Player_Video_PropertyChanged;\n UpdateCurRatio();\n }\n public virtual void SetSurface(bool fromSetOverlay = false)\n {\n if (Surface != null)\n return;\n\n // Required for some reason (WindowStyle.None will not be updated with our style)\n Surface = new();\n Surface.Name = $\"Surface_{UniqueId}\";\n Surface.Width = Surface.Height = 1; // Will be set on loaded\n Surface.WindowStyle = WindowStyle.None;\n Surface.ResizeMode = ResizeMode.NoResize;\n Surface.ShowInTaskbar = false;\n\n // CornerRadius must be set initially to AllowsTransparency!\n if (CornerRadius == zeroCornerRadius)\n Surface.Background = Player != null ? new SolidColorBrush(Player.Config.Video.BackgroundColor) : Brushes.Black;\n else\n {\n Surface.AllowsTransparency = true;\n Surface.Background = Brushes.Transparent;\n SetCornerRadiusBorder();\n }\n\n // When using ItemsControl with ObservableCollection to fill DataTemplates with FlyleafHost EnsureHandle will call Host_loaded\n if (IsAttached) Loaded -= Host_Loaded;\n SurfaceHandle = new WindowInteropHelper(Surface).EnsureHandle();\n if (IsAttached) Loaded += Host_Loaded;\n\n if (IsAttached)\n {\n SetWindowLong(SurfaceHandle, (int)WindowLongFlags.GWL_STYLE, NONE_STYLE | (nint)WindowStyles.WS_CHILD);\n SetWindowLong(SurfaceHandle, (int)WindowLongFlags.GWL_EXSTYLE, (nint)WindowStylesEx.WS_EX_LAYERED);\n }\n else // Detached || StandAlone\n {\n SetWindowLong(SurfaceHandle, (int)WindowLongFlags.GWL_STYLE, NONE_STYLE);\n if (DetachedShowInTaskbar || IsStandAlone)\n SetWindowLong(SurfaceHandle, (int)WindowLongFlags.GWL_EXSTYLE, (nint)(WindowStylesEx.WS_EX_APPWINDOW | WindowStylesEx.WS_EX_LAYERED));\n else\n SetWindowLong(SurfaceHandle, (int)WindowLongFlags.GWL_EXSTYLE, (nint)WindowStylesEx.WS_EX_LAYERED);\n }\n\n if (Player != null)\n Player.VideoDecoder.CreateSwapChain(SurfaceHandle);\n\n if (ReplicaPlayer != null)\n ReplicaPlayer.renderer.SetChildHandle(SurfaceHandle);\n\n Surface.Closed += Surface_Closed;\n Surface.Closing += Surface_Closing;\n Surface.KeyDown += Surface_KeyDown;\n Surface.KeyUp += Surface_KeyUp;\n Surface.Drop += Surface_Drop;\n Surface.DragEnter += Surface_DragEnter;\n Surface.StateChanged+= Surface_StateChanged;\n Surface.SizeChanged += SetRectOverlay;\n\n SetMouseSurface();\n\n Surface.AllowDrop =\n OpenOnDrop == AvailableWindows.Surface || OpenOnDrop == AvailableWindows.Both ||\n SwapOnDrop == AvailableWindows.Surface || SwapOnDrop == AvailableWindows.Both;\n\n if (IsAttached && IsLoaded && Owner == null && !fromSetOverlay)\n Host_Loaded(null, null);\n\n SurfaceCreated?.Invoke(this, new());\n }\n public virtual void SetOverlay()\n {\n if (Overlay == null)\n return;\n\n SetSurface(true);\n\n if (IsAttached) Loaded -= Host_Loaded;\n OverlayHandle = new WindowInteropHelper(Overlay).EnsureHandle();\n if (IsAttached) Loaded += Host_Loaded;\n\n if (IsStandAlone)\n {\n if (PreferredLandscapeWidth == 0)\n PreferredLandscapeWidth = (int)Overlay.Width;\n\n if (PreferredPortraitHeight == 0)\n PreferredPortraitHeight = (int)Overlay.Height;\n\n SetWindowPos(SurfaceHandle, IntPtr.Zero, (int)Math.Round(Overlay.Left * DpiX), (int)Math.Round(Overlay.Top * DpiY), (int)Math.Round(Overlay.ActualWidth * DpiX), (int)Math.Round(Overlay.ActualHeight * DpiY),\n (uint)(SetWindowPosFlags.SWP_NOZORDER | SetWindowPosFlags.SWP_NOACTIVATE));\n\n Surface.Title = Overlay.Title;\n Surface.Icon = Overlay.Icon;\n Surface.MinHeight = Overlay.MinHeight;\n Surface.MaxHeight = Overlay.MaxHeight;\n Surface.MinWidth = Overlay.MinWidth;\n Surface.MaxWidth = Overlay.MaxWidth;\n Surface.Topmost = DetachedTopMost;\n }\n else\n {\n Overlay.Resources = Resources;\n Overlay.DataContext = this; // TBR: or this.DataContext?\n }\n\n SetWindowPos(OverlayHandle, IntPtr.Zero, 0, 0, (int)Surface.ActualWidth, (int)Surface.ActualHeight,\n (uint)(SetWindowPosFlags.SWP_NOZORDER | SetWindowPosFlags.SWP_NOACTIVATE));\n\n Overlay.Name = $\"Overlay_{UniqueId}\";\n Overlay.Background = Brushes.Transparent;\n Overlay.ShowInTaskbar = false;\n Overlay.Owner = Surface;\n SetParent(OverlayHandle, SurfaceHandle);\n SetWindowLong(OverlayHandle, (int)WindowLongFlags.GWL_STYLE, NONE_STYLE | (nint)(WindowStyles.WS_CHILD | WindowStyles.WS_MAXIMIZE)); // TBR: WS_MAXIMIZE required? (possible better for DWM on fullscreen?)\n\n Overlay.KeyUp += Overlay_KeyUp;\n Overlay.KeyDown += Overlay_KeyDown;\n Overlay.Closed += Overlay_Closed;\n Overlay.Drop += Overlay_Drop;\n Overlay.DragEnter += Overlay_DragEnter;\n\n SetMouseOverlay();\n\n // Owner will close the overlay\n Overlay.KeyDown += (o, e) => { if (e.Key == Key.System && e.SystemKey == Key.F4) Surface?.Focus(); };\n\n Overlay.AllowDrop =\n OpenOnDrop == AvailableWindows.Overlay || OpenOnDrop == AvailableWindows.Both ||\n SwapOnDrop == AvailableWindows.Overlay || SwapOnDrop == AvailableWindows.Both;\n\n if (setTemplate)\n Overlay.Template = OverlayTemplate;\n\n if (Surface.IsVisible)\n Overlay.Show();\n else if (!IsStandAlone && !Overlay.IsVisible)\n {\n Overlay.Show();\n Overlay.Hide();\n }\n\n if (IsAttached && IsLoaded && Owner == null)\n Host_Loaded(null, null);\n\n OverlayCreated?.Invoke(this, new());\n }\n private void SetMouseSurface()\n {\n if (Surface == null)\n return;\n\n if ((MouseBindings == AvailableWindows.Surface || MouseBindings == AvailableWindows.Both) && !isMouseBindingsSubscribedSurface)\n {\n Surface.LostMouseCapture += Surface_LostMouseCapture;\n Surface.MouseLeftButtonDown += Surface_MouseLeftButtonDown;\n Surface.MouseLeftButtonUp += Surface_MouseLeftButtonUp;\n if (PanZoomOnCtrlWheel != AvailableWindows.None ||\n PanRotateOnShiftWheel != AvailableWindows.None)\n {\n Surface.MouseWheel += Surface_MouseWheel;\n }\n Surface.MouseMove += Surface_MouseMove;\n Surface.MouseLeave += Surface_MouseLeave;\n if (ToggleFullScreenOnDoubleClick != AvailableWindows.None)\n {\n Surface.MouseDoubleClick += Surface_MouseDoubleClick;\n }\n isMouseBindingsSubscribedSurface = true;\n }\n else if (isMouseBindingsSubscribedSurface)\n {\n Surface.LostMouseCapture -= Surface_LostMouseCapture;\n Surface.MouseLeftButtonDown -= Surface_MouseLeftButtonDown;\n Surface.MouseLeftButtonUp -= Surface_MouseLeftButtonUp;\n if (PanZoomOnCtrlWheel != AvailableWindows.None ||\n PanRotateOnShiftWheel != AvailableWindows.None)\n {\n Surface.MouseWheel -= Surface_MouseWheel;\n }\n Surface.MouseMove -= Surface_MouseMove;\n Surface.MouseLeave -= Surface_MouseLeave;\n if (ToggleFullScreenOnDoubleClick != AvailableWindows.None)\n {\n Surface.MouseDoubleClick -= Surface_MouseDoubleClick;\n }\n isMouseBindingsSubscribedSurface = false;\n }\n }\n private void SetMouseOverlay()\n {\n if (Overlay == null)\n return;\n\n if ((MouseBindings == AvailableWindows.Overlay || MouseBindings == AvailableWindows.Both) && !isMouseBindingsSubscribedOverlay)\n {\n Overlay.LostMouseCapture += Overlay_LostMouseCapture;\n Overlay.MouseLeftButtonDown += Overlay_MouseLeftButtonDown;\n Overlay.MouseLeftButtonUp += Overlay_MouseLeftButtonUp;\n if (PanZoomOnCtrlWheel != AvailableWindows.None ||\n PanRotateOnShiftWheel != AvailableWindows.None)\n {\n Overlay.MouseWheel += Overlay_MouseWheel;\n }\n Overlay.MouseMove += Overlay_MouseMove;\n Overlay.MouseLeave += Overlay_MouseLeave;\n if (ToggleFullScreenOnDoubleClick != AvailableWindows.None)\n {\n Overlay.MouseDoubleClick += Overlay_MouseDoubleClick;\n }\n isMouseBindingsSubscribedOverlay = true;\n }\n else if (isMouseBindingsSubscribedOverlay)\n {\n Overlay.LostMouseCapture -= Overlay_LostMouseCapture;\n Overlay.MouseLeftButtonDown -= Overlay_MouseLeftButtonDown;\n Overlay.MouseLeftButtonUp -= Overlay_MouseLeftButtonUp;\n if (PanZoomOnCtrlWheel != AvailableWindows.None ||\n PanRotateOnShiftWheel != AvailableWindows.None)\n {\n Overlay.MouseWheel -= Overlay_MouseWheel;\n }\n Overlay.MouseMove -= Overlay_MouseMove;\n Overlay.MouseLeave -= Overlay_MouseLeave;\n if (ToggleFullScreenOnDoubleClick != AvailableWindows.None)\n {\n Overlay.MouseDoubleClick -= Overlay_MouseDoubleClick;\n }\n\n isMouseBindingsSubscribedOverlay = false;\n }\n }\n\n public virtual void Attach(bool ignoreRestoreRect = false)\n {\n Window wasFocus = Overlay != null && Overlay.IsKeyboardFocusWithin ? Overlay : Surface;\n\n if (IsFullScreen)\n {\n IsFullScreen = false;\n return;\n }\n if (!ignoreRestoreRect)\n rectDetachedLast= new(Surface.Left, Surface.Top, Surface.Width, Surface.Height);\n\n Surface.Topmost = false;\n Surface.MinWidth = MinWidth;\n Surface.MinHeight = MinHeight;\n Surface.MaxWidth = MaxWidth;\n Surface.MaxHeight = MaxHeight;\n\n SetWindowLong(SurfaceHandle, (int)WindowLongFlags.GWL_STYLE, NONE_STYLE | (nint)WindowStyles.WS_CHILD);\n Surface.Owner = Owner;\n SetParent(SurfaceHandle, OwnerHandle);\n\n rectInitLast = rectIntersectLast = rectRandom;\n Host_LayoutUpdated(null, null);\n Owner.Activate();\n wasFocus.Focus();\n }\n public virtual void Detach()\n {\n if (IsFullScreen)\n IsFullScreen = false;\n\n Surface.MinWidth = DetachedMinWidth;\n Surface.MinHeight = DetachedMinHeight;\n Surface.MaxWidth = DetachedMaxWidth;\n Surface.MaxHeight = DetachedMaxHeight;\n\n // Calculate Size\n var newSize = DetachedRememberSize && rectDetachedLast != Rect.Empty\n ? new Size(rectDetachedLast.Width, rectDetachedLast.Height)\n : DetachedFixedSize;\n\n // Calculate Position\n Point newPos;\n if (DetachedRememberPosition && rectDetachedLast != Rect.Empty)\n newPos = new Point(rectDetachedLast.X, rectDetachedLast.Y);\n else\n {\n var screen = System.Windows.Forms.Screen.FromPoint(new System.Drawing.Point((int)Surface.Top, (int)Surface.Left)).Bounds;\n\n // Drop Dpi to work with screen (no Dpi)\n newSize.Width *= DpiX;\n newSize.Height *= DpiY;\n\n switch (DetachedPosition)\n {\n case DetachedPositionOptions.TopLeft:\n newPos = new Point(screen.Left, screen.Top);\n break;\n case DetachedPositionOptions.TopCenter:\n newPos = new Point(screen.Left + (screen.Width / 2) - (newSize.Width / 2), screen.Top);\n break;\n\n case DetachedPositionOptions.TopRight:\n newPos = new Point(screen.Left + screen.Width - newSize.Width, screen.Top);\n break;\n\n case DetachedPositionOptions.CenterLeft:\n newPos = new Point(screen.Left, screen.Top + (screen.Height / 2) - (newSize.Height / 2));\n break;\n\n case DetachedPositionOptions.CenterCenter:\n newPos = new Point(screen.Left + (screen.Width / 2) - (newSize.Width / 2), screen.Top + (screen.Height / 2) - (newSize.Height / 2));\n break;\n\n case DetachedPositionOptions.CenterRight:\n newPos = new Point(screen.Left + screen.Width - newSize.Width, screen.Top + (screen.Height / 2) - (newSize.Height / 2));\n break;\n\n case DetachedPositionOptions.BottomLeft:\n newPos = new Point(screen.Left, screen.Top + screen.Height - newSize.Height);\n break;\n\n case DetachedPositionOptions.BottomCenter:\n newPos = new Point(screen.Left + (screen.Width / 2) - (newSize.Width / 2), screen.Top + screen.Height - newSize.Height);\n break;\n\n case DetachedPositionOptions.BottomRight:\n newPos = new Point(screen.Left + screen.Width - newSize.Width, screen.Top + screen.Height - newSize.Height);\n break;\n\n case DetachedPositionOptions.Custom:\n newPos = DetachedFixedPosition;\n break;\n\n default:\n newPos = new(); //satisfy the compiler\n break;\n }\n\n // SetRect will drop DPI so we add it\n newPos.X /= DpiX;\n newPos.Y /= DpiY;\n\n newPos.X += DetachedPositionMargin.Left - DetachedPositionMargin.Right;\n newPos.Y += DetachedPositionMargin.Top - DetachedPositionMargin.Bottom;\n\n // Restore DPI\n newSize.Width /= DpiX;\n newSize.Height /= DpiY;\n }\n\n Rect final = new(newPos.X, newPos.Y, newSize.Width, newSize.Height);\n\n // Detach (Parent=Null, Owner=Null ?, ShowInTaskBar?, TopMost?)\n SetParent(SurfaceHandle, IntPtr.Zero);\n SetWindowLong(SurfaceHandle, (int)WindowLongFlags.GWL_STYLE, NONE_STYLE); // TBR (also in Attach/FullScren): Needs to be after SetParent. when detached and trying to close the owner will take two clicks (like mouse capture without release) //SetWindowLong(SurfaceHandle, (int)WindowLongFlags.GWL_STYLE, GetWindowLong(SurfaceHandle, (int)WindowLongFlags.GWL_STYLE) & ~(nint)WindowStyles.WS_CHILD);\n Surface.Owner = DetachedNoOwner ? null : Owner;\n Surface.Topmost = DetachedTopMost;\n\n SetRect(ref final);\n ResetVisibleRect();\n\n if (Surface.IsVisible) // Initially detached will not be visible yet and activate not required (in case of multiple)\n Surface.Activate();\n }\n\n public void RefreshNormalFullScreen()\n {\n if (IsFullScreen)\n {\n if (IsAttached)\n {\n // When we set the parent to null we don't really know in which left/top will be transfered and maximized into random screen\n GetWindowRect(SurfaceHandle, ref curRect);\n\n ResetVisibleRect();\n SetParent(SurfaceHandle, IntPtr.Zero);\n SetWindowLong(SurfaceHandle, (int)WindowLongFlags.GWL_STYLE, NONE_STYLE); // TBR (also in Attach/FullScren): Needs to be after SetParent. when detached and trying to close the owner will take two clicks (like mouse capture without release) //SetWindowLong(SurfaceHandle, (int)WindowLongFlags.GWL_STYLE, GetWindowLong(SurfaceHandle, (int)WindowLongFlags.GWL_STYLE) & ~(nint)WindowStyles.WS_CHILD);\n Surface.Owner = DetachedNoOwner ? null : Owner;\n Surface.Topmost = DetachedTopMost;\n\n SetWindowPos(SurfaceHandle, IntPtr.Zero, curRect.Left, curRect.Top, 0, 0, (uint)(SetWindowPosFlags.SWP_NOZORDER | SetWindowPosFlags.SWP_NOACTIVATE | SetWindowPosFlags.SWP_NOSIZE));\n }\n\n if (Player != null)\n Player.renderer.CornerRadius = zeroCornerRadius;\n\n if (CornerRadius != zeroCornerRadius)\n ((Border)Surface.Content).CornerRadius = zeroCornerRadius;\n\n Surface.WindowState = WindowState.Maximized;\n\n // If it was above the borders and double click (mouse didn't move to refresh)\n Surface.Cursor = Cursors.Arrow;\n if (Overlay != null)\n Overlay.Cursor = Cursors.Arrow;\n }\n else\n {\n if (IsStandAlone)\n Surface.WindowState = WindowState.Normal;\n\n if (IsAttached)\n {\n Attach(true);\n InvalidateVisual(); // To force the FlyleafSharedOverlay (if any) redraw on-top\n }\n else if (Surface.Topmost || DetachedTopMost) // Bring to front (in Desktop, above windows bar)\n {\n Surface.Topmost = false;\n Surface.Topmost = true;\n }\n\n UpdateCurRatio();\n\n // TBR: CornerRadius background has issue it's like a mask color?\n if (Player != null)\n Player.renderer.CornerRadius = CornerRadius;\n\n if (CornerRadius != zeroCornerRadius)\n ((Border)Surface.Content).CornerRadius = CornerRadius;\n\n if (!IsStandAlone) //when play with alpha video and not standalone, we need to set window state to normal last, otherwise it will be lost the background\n Surface.WindowState = WindowState.Normal;\n }\n }\n public void SetRect(ref Rect rect)\n => SetWindowPos(SurfaceHandle, IntPtr.Zero, (int)Math.Round(rect.X * DpiX), (int)Math.Round(rect.Y * DpiY), (int)Math.Round(rect.Width * DpiX), (int)Math.Round(rect.Height * DpiY),\n (uint)(SetWindowPosFlags.SWP_NOZORDER | SetWindowPosFlags.SWP_NOACTIVATE));\n\n private void SetRectOverlay(object sender, SizeChangedEventArgs e)\n {\n if (Overlay != null)\n SetWindowPos(OverlayHandle, IntPtr.Zero, 0, 0, (int)Math.Round(Surface.ActualWidth * DpiX), (int)Math.Round(Surface.ActualHeight * DpiY),\n (uint)(SetWindowPosFlags.SWP_NOZORDER | SetWindowPosFlags.SWP_NOMOVE | SetWindowPosFlags.SWP_NOACTIVATE));\n }\n\n public void ResetVisibleRect()\n {\n SetWindowRgn(SurfaceHandle, IntPtr.Zero, true);\n if (Overlay != null)\n SetWindowRgn(OverlayHandle, IntPtr.Zero, true);\n }\n public void SetVisibleRect(ref Rect rect)\n {\n SetWindowRgn(SurfaceHandle, CreateRectRgn((int)Math.Round(rect.X * DpiX), (int)Math.Round(rect.Y * DpiY), (int)Math.Round(rect.Right * DpiX), (int)Math.Round(rect.Bottom * DpiY)), true);\n if (Overlay != null)\n SetWindowRgn(OverlayHandle, CreateRectRgn((int)Math.Round(rect.X * DpiX), (int)Math.Round(rect.Y * DpiY), (int)Math.Round(rect.Right * DpiX), (int)Math.Round(rect.Bottom * DpiY)), true);\n }\n\n /// \n /// Disposes the Surface and Overlay Windows and de-assigns the Player\n /// \n public void Dispose()\n {\n lock (this)\n {\n if (Disposed)\n return;\n\n // Disposes SwapChain Only\n Player = null;\n ReplicaPlayer = null;\n Disposed = true;\n\n DataContextChanged -= Host_DataContextChanged;\n LayoutUpdated -= Host_LayoutUpdated;\n IsVisibleChanged -= Host_IsVisibleChanged;\n Loaded \t\t\t-= Host_Loaded;\n\n if (Overlay != null)\n {\n if (isMouseBindingsSubscribedOverlay)\n SetMouseOverlay();\n\n Overlay.IsVisibleChanged-= OverlayStandAlone_IsVisibleChanged;\n Overlay.KeyUp -= Overlay_KeyUp;\n Overlay.KeyDown -= Overlay_KeyDown;\n Overlay.Closed -= Overlay_Closed;\n Overlay.Drop -= Overlay_Drop;\n Overlay.DragEnter -= Overlay_DragEnter;\n }\n\n if (Surface != null)\n {\n if (isMouseBindingsSubscribedSurface)\n SetMouseSurface();\n\n Surface.Closed -= Surface_Closed;\n Surface.Closing -= Surface_Closing;\n Surface.KeyDown -= Surface_KeyDown;\n Surface.KeyUp -= Surface_KeyUp;\n Surface.Drop -= Surface_Drop;\n Surface.DragEnter -= Surface_DragEnter;\n Surface.StateChanged-= Surface_StateChanged;\n Surface.SizeChanged -= SetRectOverlay;\n\n // If not shown yet app will not close properly\n if (!surfaceClosed)\n {\n Surface.Owner = null;\n SetParent(SurfaceHandle, IntPtr.Zero);\n Surface.Width = Surface.Height = 1;\n Surface.Show();\n if (!overlayClosed)\n Overlay?.Show();\n Surface.Close();\n }\n }\n\n if (Owner != null)\n Owner.SizeChanged -= Owner_SizeChanged;\n\n Surface = null;\n Overlay = null;\n Owner = null;\n\n SurfaceHandle = IntPtr.Zero;\n OverlayHandle = IntPtr.Zero;\n OwnerHandle = IntPtr.Zero;\n\n Log.Debug(\"Disposed\");\n }\n }\n\n public bool Player_CanHideCursor() => (Surface != null && Surface.IsMouseOver) ||\n (Overlay != null && Overlay.IsActive);\n public bool Player_GetFullScreen() => IsFullScreen;\n public void Player_SetFullScreen(bool value) => IsFullScreen = value;\n public void Player_Disposed() => UIInvokeIfRequired(() => Player = null);\n #endregion\n}\n\npublic enum AvailableWindows\n{\n None, Surface, Overlay, Both\n}\n\npublic enum AttachedDragMoveOptions\n{\n None, Surface, Overlay, Both, SurfaceOwner, OverlayOwner, BothOwner\n}\n\npublic enum DetachedPositionOptions\n{\n Custom, TopLeft, TopCenter, TopRight, CenterLeft, CenterCenter, CenterRight, BottomLeft, BottomCenter, BottomRight\n}\n"], ["/LLPlayer/FlyleafLib/MediaPlayer/Activity.cs", "using System.Diagnostics;\nusing System.Windows.Forms;\n\nnamespace FlyleafLib.MediaPlayer;\n\npublic class Activity : NotifyPropertyChanged\n{\n /* Player Activity Mode ( Idle / Active / FullActive )\n *\n * Required Engine's Thread (UIRefresh)\n *\n * TODO: Static?\n */\n\n public ActivityMode Mode\n {\n get => mode;\n set {\n\n if (value == mode)\n return;\n\n mode = value;\n\n if (value == ActivityMode.Idle)\n {\n swKeyboard.Reset();\n swMouse.Reset();\n }\n else if (value == ActivityMode.Active)\n swKeyboard.Restart();\n else\n swMouse.Restart();\n\n Utils.UI(() => SetMode());\n }\n }\n internal ActivityMode _Mode = ActivityMode.FullActive, mode = ActivityMode.FullActive;\n\n /// \n /// Should use Timeout to Enable/Disable it. Use this only for temporary disable.\n /// \n public bool IsEnabled { get => _IsEnabled;\n set {\n\n if (value && _Timeout <= 0)\n {\n if (_IsEnabled)\n {\n _IsEnabled = false;\n RaiseUI(nameof(IsEnabled));\n }\n else\n _IsEnabled = false;\n\n }\n else\n {\n if (_IsEnabled == value)\n return;\n\n if (value)\n {\n swKeyboard.Restart();\n swMouse.Restart();\n }\n\n _IsEnabled = value;\n RaiseUI(nameof(IsEnabled));\n }\n }\n }\n bool _IsEnabled;\n\n public int Timeout { get => _Timeout; set { _Timeout = value; IsEnabled = value > 0; } }\n int _Timeout;\n\n Player player;\n Stopwatch swKeyboard = new();\n Stopwatch swMouse = new();\n\n public Activity(Player player) => this.player = player;\n\n /// \n /// Updates Mode UI value and shows/hides mouse cursor if required\n /// Must be called from a UI Thread\n /// \n internal void SetMode()\n {\n _Mode = mode;\n Raise(nameof(Mode));\n player.Log.Trace(mode.ToString());\n\n if (player.Activity.Mode == ActivityMode.Idle && player.Host != null /*&& player.Host.Player_GetFullScreen() */&& player.Host.Player_CanHideCursor())\n {\n lock (cursorLocker)\n {\n while (Utils.NativeMethods.ShowCursor(false) >= 0) { }\n isCursorHidden = true;\n }\n\n }\n else if (isCursorHidden && player.Activity.Mode == ActivityMode.FullActive)\n {\n lock (cursorLocker)\n {\n while (Utils.NativeMethods.ShowCursor(true) < 0) { }\n isCursorHidden = false;\n }\n }\n }\n\n /// \n /// Refreshes mode value based on current timestamps\n /// \n internal void RefreshMode()\n {\n if (!IsEnabled)\n mode = ActivityMode.FullActive;\n else mode = swMouse.IsRunning && swMouse.ElapsedMilliseconds < Timeout\n ? ActivityMode.FullActive\n : swKeyboard.IsRunning && swKeyboard.ElapsedMilliseconds < Timeout ? ActivityMode.Active : ActivityMode.Idle;\n }\n\n /// \n /// Sets Mode to Idle\n /// \n public void ForceIdle()\n {\n if (Timeout > 0)\n Mode = ActivityMode.Idle;\n }\n /// \n /// Sets Mode to Active\n /// \n public void ForceActive() => Mode = ActivityMode.Active;\n /// \n /// Sets Mode to Full Active\n /// \n public void ForceFullActive() => Mode = ActivityMode.FullActive;\n\n /// \n /// Updates Active Timestamp\n /// \n public void RefreshActive() => swKeyboard.Restart();\n\n /// \n /// Updates Full Active Timestamp\n /// \n public void RefreshFullActive() => swMouse.Restart();\n\n #region Ensures we catch the mouse move even when the Cursor is hidden\n static bool isCursorHidden;\n static object cursorLocker = new();\n public class GlobalMouseHandler : IMessageFilter\n {\n public bool PreFilterMessage(ref Message m)\n {\n if (isCursorHidden && m.Msg == 0x0200)\n {\n try\n {\n lock (cursorLocker)\n {\n while (Utils.NativeMethods.ShowCursor(true) < 0) { }\n isCursorHidden = false;\n foreach(var player in Engine.Players)\n player.Activity.RefreshFullActive();\n }\n\n } catch { }\n }\n\n return false;\n }\n }\n static Activity()\n {\n GlobalMouseHandler gmh = new();\n Application.AddMessageFilter(gmh);\n }\n #endregion\n}\n\npublic enum ActivityMode\n{\n Idle,\n Active, // Keyboard only\n FullActive // Mouse\n}\n"], ["/LLPlayer/FlyleafLib/MediaFramework/MediaRenderer/Renderer.PresentOffline.cs", "using System.Drawing.Imaging;\nusing System.Drawing;\nusing System.Threading;\nusing System.Windows.Media.Imaging;\n\nusing SharpGen.Runtime;\n\nusing Vortice;\nusing Vortice.Direct3D11;\nusing Vortice.DXGI;\nusing Vortice.Mathematics;\n\nusing FlyleafLib.MediaFramework.MediaDecoder;\nusing FlyleafLib.MediaFramework.MediaFrame;\n\nusing ID3D11Texture2D = Vortice.Direct3D11.ID3D11Texture2D;\n\nnamespace FlyleafLib.MediaFramework.MediaRenderer;\n\npublic partial class Renderer\n{\n // subs\n Texture2DDescription overlayTextureDesc;\n ID3D11Texture2D overlayTexture;\n ID3D11ShaderResourceView overlayTextureSrv;\n int overlayTextureOriginalWidth;\n int overlayTextureOriginalHeight;\n int overlayTextureOriginalPosX;\n int overlayTextureOriginalPosY;\n\n ID3D11ShaderResourceView[] overlayTextureSRVs = new ID3D11ShaderResourceView[1];\n\n // Used for off screen rendering\n Texture2DDescription singleStageDesc, singleGpuDesc;\n ID3D11Texture2D singleStage;\n ID3D11Texture2D singleGpu;\n ID3D11RenderTargetView singleGpuRtv;\n Viewport singleViewport;\n\n // Used for parallel off screen rendering\n ID3D11RenderTargetView[] rtv2;\n ID3D11Texture2D[] backBuffer2;\n bool[] backBuffer2busy;\n\n unsafe internal void PresentOffline(VideoFrame frame, ID3D11RenderTargetView rtv, Viewport viewport)\n {\n if (videoProcessor == VideoProcessors.D3D11)\n {\n var tmpResource = rtv.Resource;\n vd1.CreateVideoProcessorOutputView(tmpResource, vpe, vpovd, out var vpov);\n\n RawRect rect = new((int)viewport.X, (int)viewport.Y, (int)(viewport.Width + viewport.X), (int)(viewport.Height + viewport.Y));\n vc.VideoProcessorSetStreamSourceRect(vp, 0, true, VideoRect);\n vc.VideoProcessorSetStreamDestRect(vp, 0, true, rect);\n vc.VideoProcessorSetOutputTargetRect(vp, true, rect);\n\n if (frame.avFrame != null)\n {\n vpivd.Texture2D.ArraySlice = (uint) frame.avFrame->data[1];\n vd1.CreateVideoProcessorInputView(VideoDecoder.textureFFmpeg, vpe, vpivd, out vpiv);\n }\n else\n {\n vpivd.Texture2D.ArraySlice = 0;\n vd1.CreateVideoProcessorInputView(frame.textures[0], vpe, vpivd, out vpiv);\n }\n\n vpsa[0].InputSurface = vpiv;\n vc.VideoProcessorBlt(vp, vpov, 0, 1, vpsa);\n vpiv.Dispose();\n vpov.Dispose();\n tmpResource.Dispose();\n }\n else\n {\n context.OMSetRenderTargets(rtv);\n context.ClearRenderTargetView(rtv, Config.Video._BackgroundColor);\n context.RSSetViewport(viewport);\n context.PSSetShaderResources(0, frame.srvs);\n context.Draw(6, 0);\n }\n }\n\n /// \n /// Gets bitmap from a video frame\n /// \n /// Specify the width (-1: will keep the ratio based on height)\n /// Specify the height (-1: will keep the ratio based on width)\n /// Video frame to process (null: will use the current/last frame)\n /// \n unsafe public Bitmap GetBitmap(int width = -1, int height = -1, VideoFrame frame = null)\n {\n try\n {\n lock (lockDevice)\n {\n frame ??= LastFrame;\n\n if (Disposed || frame == null || (frame.textures == null && frame.avFrame == null))\n return null;\n\n if (width == -1 && height == -1)\n {\n width = VideoRect.Right;\n height = VideoRect.Bottom;\n }\n else if (width != -1 && height == -1)\n height = (int)(width / curRatio);\n else if (height != -1 && width == -1)\n width = (int)(height * curRatio);\n\n if (singleStageDesc.Width != width || singleStageDesc.Height != height)\n {\n singleGpu?.Dispose();\n singleStage?.Dispose();\n singleGpuRtv?.Dispose();\n\n singleStageDesc.Width = (uint)width;\n singleStageDesc.Height = (uint)height;\n singleGpuDesc.Width = (uint)width;\n singleGpuDesc.Height = (uint)height;\n\n singleStage = Device.CreateTexture2D(singleStageDesc);\n singleGpu = Device.CreateTexture2D(singleGpuDesc);\n singleGpuRtv= Device.CreateRenderTargetView(singleGpu);\n\n singleViewport = new Viewport(width, height);\n }\n\n PresentOffline(frame, singleGpuRtv, singleViewport);\n\n if (videoProcessor == VideoProcessors.D3D11)\n SetViewport();\n }\n\n context.CopyResource(singleStage, singleGpu);\n return GetBitmap(singleStage);\n\n } catch (Exception e)\n {\n Log.Warn($\"GetBitmap failed with: {e.Message}\");\n return null;\n }\n }\n public Bitmap GetBitmap(ID3D11Texture2D stageTexture)\n {\n Bitmap bitmap = new((int)stageTexture.Description.Width, (int)stageTexture.Description.Height);\n var db = context.Map(stageTexture, 0, MapMode.Read, Vortice.Direct3D11.MapFlags.None);\n var bitmapData = bitmap.LockBits(new Rectangle(0, 0, bitmap.Width, bitmap.Height), ImageLockMode.WriteOnly, PixelFormat.Format32bppArgb);\n\n if (db.RowPitch == bitmapData.Stride)\n MemoryHelpers.CopyMemory(bitmapData.Scan0, db.DataPointer, bitmap.Width * bitmap.Height * 4);\n else\n {\n var sourcePtr = db.DataPointer;\n var destPtr = bitmapData.Scan0;\n\n for (int y = 0; y < bitmap.Height; y++)\n {\n MemoryHelpers.CopyMemory(destPtr, sourcePtr, bitmap.Width * 4);\n\n sourcePtr = IntPtr.Add(sourcePtr, (int)db.RowPitch);\n destPtr = IntPtr.Add(destPtr, bitmapData.Stride);\n }\n }\n\n bitmap.UnlockBits(bitmapData);\n context.Unmap(stageTexture, 0);\n\n return bitmap;\n }\n /// \n /// Gets BitmapSource from a video frame\n /// \n /// Specify the width (-1: will keep the ratio based on height)\n /// Specify the height (-1: will keep the ratio based on width)\n /// Video frame to process (null: will use the current/last frame)\n /// \n unsafe public BitmapSource GetBitmapSource(int width = -1, int height = -1, VideoFrame frame = null)\n {\n try\n {\n lock (lockDevice)\n {\n frame ??= LastFrame;\n\n if (Disposed || frame == null || (frame.textures == null && frame.avFrame == null))\n return null;\n\n if (width == -1 && height == -1)\n {\n width = VideoRect.Right;\n height = VideoRect.Bottom;\n }\n else if (width != -1 && height == -1)\n height = (int)(width / curRatio);\n else if (height != -1 && width == -1)\n width = (int)(height * curRatio);\n\n if (singleStageDesc.Width != width || singleStageDesc.Height != height)\n {\n singleGpu?.Dispose();\n singleStage?.Dispose();\n singleGpuRtv?.Dispose();\n\n singleStageDesc.Width = (uint)width;\n singleStageDesc.Height = (uint)height;\n singleGpuDesc.Width = (uint)width;\n singleGpuDesc.Height = (uint)height;\n\n singleStage = Device.CreateTexture2D(singleStageDesc);\n singleGpu = Device.CreateTexture2D(singleGpuDesc);\n singleGpuRtv = Device.CreateRenderTargetView(singleGpu);\n\n singleViewport = new Viewport(width, height);\n }\n\n PresentOffline(frame, singleGpuRtv, singleViewport);\n\n if (videoProcessor == VideoProcessors.D3D11)\n SetViewport();\n }\n\n context.CopyResource(singleStage, singleGpu);\n return GetBitmapSource(singleStage);\n\n }\n catch (Exception e)\n {\n Log.Warn($\"GetBitmapSource failed with: {e.Message}\");\n return null;\n }\n }\n public BitmapSource GetBitmapSource(ID3D11Texture2D stageTexture)\n {\n WriteableBitmap bitmap = new((int)stageTexture.Description.Width, (int)stageTexture.Description.Height, 96, 96, System.Windows.Media.PixelFormats.Bgra32, null);\n var db = context.Map(stageTexture, 0, MapMode.Read, Vortice.Direct3D11.MapFlags.None);\n bitmap.Lock();\n\n if (db.RowPitch == bitmap.BackBufferStride)\n MemoryHelpers.CopyMemory(bitmap.BackBuffer, db.DataPointer, bitmap.PixelWidth * bitmap.PixelHeight * 4);\n else\n {\n var sourcePtr = db.DataPointer;\n var destPtr = bitmap.BackBuffer;\n\n for (int y = 0; y < bitmap.Height; y++)\n {\n MemoryHelpers.CopyMemory(destPtr, sourcePtr, bitmap.PixelWidth * 4);\n\n sourcePtr = IntPtr.Add(sourcePtr, (int)db.RowPitch);\n destPtr = IntPtr.Add(destPtr, bitmap.BackBufferStride);\n }\n }\n\n bitmap.Unlock();\n context.Unmap(stageTexture, 0);\n\n // Freezing animated wpf assets improves performance\n bitmap.Freeze();\n\n return bitmap;\n }\n\n /// \n /// Extracts a bitmap from a video frame\n /// (Currently cannot be used in parallel with the rendering)\n /// \n /// \n /// \n public Bitmap ExtractFrame(VideoFrame frame)\n {\n if (Device == null || frame == null) return null;\n\n int subresource = -1;\n\n Texture2DDescription stageDesc = new()\n {\n Usage = ResourceUsage.Staging,\n Width = VideoDecoder.VideoStream.Width,\n Height = VideoDecoder.VideoStream.Height,\n Format = Format.B8G8R8A8_UNorm,\n ArraySize = 1,\n MipLevels = 1,\n BindFlags = BindFlags.None,\n CPUAccessFlags = CpuAccessFlags.Read,\n SampleDescription = new SampleDescription(1, 0)\n };\n var stage = Device.CreateTexture2D(stageDesc);\n\n lock (lockDevice)\n {\n while (true)\n {\n for (int i=0; i Right- Left;\n public int Height => Bottom- Top;\n public bool IsAttached { get; internal set; }\n public int Rotation { get; internal set; }\n\n public override string ToString()\n {\n int gcd = Utils.GCD(Width, Height);\n return $\"{DeviceName,-20} [Id: {Id,-4}\\t, Top: {Top,-4}, Left: {Left,-4}, Width: {Width,-4}, Height: {Height,-4}, Ratio: [\" + (gcd > 0 ? $\"{Width/gcd}:{Height/gcd}]\" : \"]\");\n }\n}\n\npublic class GPUAdapter\n{\n public int MaxHeight { get; internal set; }\n public nuint SystemMemory { get; internal set; }\n public nuint VideoMemory { get; internal set; }\n public nuint SharedMemory { get; internal set; }\n\n\n public uint Id { get; internal set; }\n public string Vendor { get; internal set; }\n public string Description { get; internal set; }\n public long Luid { get; internal set; }\n public bool HasOutput { get; internal set; }\n public List\n Outputs { get; internal set; }\n\n public override string ToString()\n => (Vendor + \" \" + Description).PadRight(40) + $\"[ID: {Id,-6}, LUID: {Luid,-6}, DVM: {Utils.GetBytesReadable(VideoMemory),-8}, DSM: {Utils.GetBytesReadable(SystemMemory),-8}, SSM: {Utils.GetBytesReadable(SharedMemory)}]\";\n}\npublic enum VideoFilters\n{\n // Ensure we have the same values with Vortice.Direct3D11.VideoProcessorFilterCaps (d3d11.h) | we can extended if needed with other values\n\n Brightness = 0x01,\n Contrast = 0x02,\n Hue = 0x04,\n Saturation = 0x08,\n NoiseReduction = 0x10,\n EdgeEnhancement = 0x20,\n AnamorphicScaling = 0x40,\n StereoAdjustment = 0x80\n}\n\npublic struct AspectRatio : IEquatable\n{\n public static readonly AspectRatio Keep = new(-1, 1);\n public static readonly AspectRatio Fill = new(-2, 1);\n public static readonly AspectRatio Custom = new(-3, 1);\n public static readonly AspectRatio Invalid = new(-999, 1);\n\n public static readonly List AspectRatios = new()\n {\n Keep,\n Fill,\n Custom,\n new AspectRatio(1, 1),\n new AspectRatio(4, 3),\n new AspectRatio(16, 9),\n new AspectRatio(16, 10),\n new AspectRatio(2.35f, 1),\n };\n\n public static implicit operator AspectRatio(string value) => new AspectRatio(value);\n\n public float Num { get; set; }\n public float Den { get; set; }\n\n public float Value\n {\n get => Num / Den;\n set { Num = value; Den = 1; }\n }\n\n public string ValueStr\n {\n get => ToString();\n set => FromString(value);\n }\n\n public AspectRatio(float value) : this(value, 1) { }\n public AspectRatio(float num, float den) { Num = num; Den = den; }\n public AspectRatio(string value) { Num = Invalid.Num; Den = Invalid.Den; FromString(value); }\n\n public bool Equals(AspectRatio other) => Num == other.Num && Den == other.Den;\n public override bool Equals(object obj) => obj is AspectRatio o && Equals(o);\n public override int GetHashCode() => HashCode.Combine(Num, Den);\n public static bool operator ==(AspectRatio a, AspectRatio b) => a.Equals(b);\n public static bool operator !=(AspectRatio a, AspectRatio b) => !(a == b);\n\n public void FromString(string value)\n {\n if (value == \"Keep\")\n { Num = Keep.Num; Den = Keep.Den; return; }\n else if (value == \"Fill\")\n { Num = Fill.Num; Den = Fill.Den; return; }\n else if (value == \"Custom\")\n { Num = Custom.Num; Den = Custom.Den; return; }\n else if (value == \"Invalid\")\n { Num = Invalid.Num; Den = Invalid.Den; return; }\n\n string newvalue = value.ToString().Replace(',', '.');\n\n if (Regex.IsMatch(newvalue.ToString(), @\"^\\s*[0-9\\.]+\\s*[:/]\\s*[0-9\\.]+\\s*$\"))\n {\n string[] values = newvalue.ToString().Split(':');\n if (values.Length < 2)\n values = newvalue.ToString().Split('/');\n\n Num = float.Parse(values[0], NumberStyles.Any, CultureInfo.InvariantCulture);\n Den = float.Parse(values[1], NumberStyles.Any, CultureInfo.InvariantCulture);\n }\n\n else if (float.TryParse(newvalue.ToString(), NumberStyles.Any, CultureInfo.InvariantCulture, out float result))\n { Num = result; Den = 1; }\n\n else\n { Num = Invalid.Num; Den = Invalid.Den; }\n }\n public override string ToString() => this == Keep ? \"Keep\" : (this == Fill ? \"Fill\" : (this == Custom ? \"Custom\" : (this == Invalid ? \"Invalid\" : $\"{Num}:{Den}\")));\n}\n\nclass PlayerStats\n{\n public long TotalBytes { get; set; }\n public long VideoBytes { get; set; }\n public long AudioBytes { get; set; }\n public long FramesDisplayed { get; set; }\n}\npublic class NotifyPropertyChanged : INotifyPropertyChanged\n{\n public event PropertyChangedEventHandler PropertyChanged;\n\n //public bool DisableNotifications { get; set; }\n\n //private static bool IsUI() => System.Threading.Thread.CurrentThread.ManagedThreadId == System.Windows.Application.Current.Dispatcher.Thread.ManagedThreadId;\n\n protected bool Set(ref T field, T value, bool check = true, [CallerMemberName] string propertyName = \"\")\n {\n //Utils.Log($\"[===| {propertyName} |===] | Set | {IsUI()}\");\n\n if (!check || !EqualityComparer.Default.Equals(field, value))\n {\n field = value;\n\n //if (!DisableNotifications)\n PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));\n\n return true;\n }\n\n return false;\n }\n\n protected bool SetUI(ref T field, T value, bool check = true, [CallerMemberName] string propertyName = \"\")\n {\n //Utils.Log($\"[===| {propertyName} |===] | SetUI | {IsUI()}\");\n\n if (!check || !EqualityComparer.Default.Equals(field, value))\n {\n field = value;\n\n //if (!DisableNotifications)\n Utils.UI(() => PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName)));\n\n return true;\n }\n\n return false;\n }\n protected void Raise([CallerMemberName] string propertyName = \"\")\n {\n //Utils.Log($\"[===| {propertyName} |===] | Raise | {IsUI()}\");\n\n //if (!DisableNotifications)\n PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));\n }\n\n\n protected void RaiseUI([CallerMemberName] string propertyName = \"\")\n {\n //Utils.Log($\"[===| {propertyName} |===] | RaiseUI | {IsUI()}\");\n\n //if (!DisableNotifications)\n Utils.UI(() => PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName)));\n }\n}\n"], ["/LLPlayer/FlyleafLib/MediaFramework/MediaDecoder/VideoDecoder.cs", "using System.Collections.Concurrent;\nusing System.Collections.Generic;\nusing System.Runtime.InteropServices;\nusing System.Threading;\n\nusing Vortice.DXGI;\nusing Vortice.Direct3D11;\n\nusing ID3D11Texture2D = Vortice.Direct3D11.ID3D11Texture2D;\n\nusing FlyleafLib.MediaFramework.MediaStream;\nusing FlyleafLib.MediaFramework.MediaFrame;\nusing FlyleafLib.MediaFramework.MediaRenderer;\nusing FlyleafLib.MediaFramework.MediaRemuxer;\n\nusing static FlyleafLib.Logger;\n\nnamespace FlyleafLib.MediaFramework.MediaDecoder;\n\npublic unsafe class VideoDecoder : DecoderBase\n{\n public ConcurrentQueue\n Frames { get; protected set; } = new ConcurrentQueue();\n public Renderer Renderer { get; private set; }\n public bool VideoAccelerated { get; internal set; }\n public bool ZeroCopy { get; internal set; }\n\n public VideoStream VideoStream => (VideoStream) Stream;\n\n public long StartTime { get; internal set; } = AV_NOPTS_VALUE;\n public long StartRecordTime { get; internal set; } = AV_NOPTS_VALUE;\n\n const AVPixelFormat PIX_FMT_HWACCEL = AVPixelFormat.D3d11;\n const SwsFlags SCALING_HQ = SwsFlags.AccurateRnd | SwsFlags.Bitexact | SwsFlags.Lanczos | SwsFlags.FullChrHInt | SwsFlags.FullChrHInp;\n const SwsFlags SCALING_LQ = SwsFlags.Bicublin;\n\n internal SwsContext* swsCtx;\n IntPtr swsBufferPtr;\n internal byte_ptrArray4 swsData;\n internal int_array4 swsLineSize;\n\n internal bool swFallback;\n internal bool keyPacketRequired;\n internal long lastFixedPts;\n\n bool checkExtraFrames; // DecodeFrameNext\n\n // Reverse Playback\n ConcurrentStack>\n curReverseVideoStack = new();\n List curReverseVideoPackets = new();\n List curReverseVideoFrames = new();\n int curReversePacketPos = 0;\n\n // Drop frames if FPS is higher than allowed\n int curSpeedFrame = 9999; // don't skip first frame (on start/after seek-flush)\n double skipSpeedFrames = 0;\n\n public VideoDecoder(Config config, int uniqueId = -1) : base(config, uniqueId)\n => getHWformat = new AVCodecContext_get_format(get_format);\n\n protected override void OnSpeedChanged(double value)\n {\n if (VideoStream == null) return;\n speed = value;\n skipSpeedFrames = speed * VideoStream.FPS / Config.Video.MaxOutputFps;\n }\n\n /// \n /// Prevents to get the first frame after seek/flush\n /// \n public void ResetSpeedFrame()\n => curSpeedFrame = 0;\n\n public void CreateRenderer() // TBR: It should be in the constructor but DecoderContext will not work with null VideoDecoder for AudioOnly\n {\n if (Renderer == null)\n Renderer = new Renderer(this, IntPtr.Zero, UniqueId);\n else if (Renderer.Disposed)\n Renderer.Initialize();\n }\n public void DestroyRenderer() => Renderer?.Dispose();\n public void CreateSwapChain(IntPtr handle)\n {\n CreateRenderer();\n Renderer.InitializeSwapChain(handle);\n }\n public void CreateSwapChain(Action swapChainWinUIClbk)\n {\n Renderer.SwapChainWinUIClbk = swapChainWinUIClbk;\n if (Renderer.SwapChainWinUIClbk != null)\n Renderer.InitializeWinUISwapChain();\n\n }\n public void DestroySwapChain() => Renderer?.DisposeSwapChain();\n\n #region Video Acceleration (Should be disposed seperately)\n const int AV_CODEC_HW_CONFIG_METHOD_HW_DEVICE_CTX = 0x01;\n const AVHWDeviceType HW_DEVICE = AVHWDeviceType.D3d11va;\n\n internal ID3D11Texture2D\n textureFFmpeg;\n AVCodecContext_get_format\n getHWformat;\n AVBufferRef* hwframes;\n AVBufferRef* hw_device_ctx;\n\n internal static bool CheckCodecSupport(AVCodec* codec)\n {\n for (int i = 0; ; i++)\n {\n var config = avcodec_get_hw_config(codec, i);\n if (config == null) break;\n if ((config->methods & AVCodecHwConfigMethod.HwDeviceCtx) == 0 || config->pix_fmt == AVPixelFormat.None) continue;\n\n if (config->device_type == HW_DEVICE && config->pix_fmt == PIX_FMT_HWACCEL) return true;\n }\n\n return false;\n }\n internal int InitVA()\n {\n int ret;\n AVHWDeviceContext* device_ctx;\n AVD3D11VADeviceContext* d3d11va_device_ctx;\n\n if (Renderer.Device == null || hw_device_ctx != null) return -1;\n\n hw_device_ctx = av_hwdevice_ctx_alloc(HW_DEVICE);\n\n device_ctx = (AVHWDeviceContext*) hw_device_ctx->data;\n d3d11va_device_ctx = (AVD3D11VADeviceContext*) device_ctx->hwctx;\n d3d11va_device_ctx->device\n = (Flyleaf.FFmpeg.ID3D11Device*) Renderer.Device.NativePointer;\n\n ret = av_hwdevice_ctx_init(hw_device_ctx);\n if (ret != 0)\n {\n Log.Error($\"VA Failed - {FFmpegEngine.ErrorCodeToMsg(ret)} ({ret})\");\n\n fixed(AVBufferRef** ptr = &hw_device_ctx)\n av_buffer_unref(ptr);\n\n hw_device_ctx = null;\n }\n\n Renderer.Device.AddRef(); // Important to give another reference for FFmpeg so we can dispose without issues\n\n return ret;\n }\n\n private AVPixelFormat get_format(AVCodecContext* avctx, AVPixelFormat* pix_fmts)\n {\n if (CanDebug)\n {\n Log.Debug($\"Codec profile '{VideoStream.Codec} {avcodec_profile_name(codecCtx->codec_id, codecCtx->profile)}'\");\n\n if (CanTrace)\n {\n var save = pix_fmts;\n while (*pix_fmts != AVPixelFormat.None)\n {\n Log.Trace($\"{*pix_fmts}\");\n pix_fmts++;\n }\n pix_fmts = save;\n }\n }\n\n bool foundHWformat = false;\n\n while (*pix_fmts != AVPixelFormat.None)\n {\n if ((*pix_fmts) == PIX_FMT_HWACCEL)\n {\n foundHWformat = true;\n break;\n }\n\n pix_fmts++;\n }\n\n int ret = ShouldAllocateNew();\n\n if (foundHWformat && ret == 0)\n {\n if (codecCtx->hw_frames_ctx == null && hwframes != null)\n codecCtx->hw_frames_ctx = av_buffer_ref(hwframes);\n\n return PIX_FMT_HWACCEL;\n }\n\n lock (lockCodecCtx)\n {\n if (!foundHWformat || !VideoAccelerated || AllocateHWFrames() != 0)\n {\n if (CanWarn)\n Log.Warn(\"HW format not found. Fallback to sw format\");\n\n swFallback = true;\n return avcodec_default_get_format(avctx, pix_fmts);\n }\n\n if (CanDebug)\n Log.Debug(\"HW frame allocation completed\");\n\n // TBR: Catch codec changed on live streams (check codec/profiles and check even on sw frames)\n if (ret == 2)\n {\n Log.Warn($\"Codec changed {VideoStream.CodecID} {VideoStream.Width}x{VideoStream.Height} => {codecCtx->codec_id} {codecCtx->width}x{codecCtx->height}\");\n filledFromCodec = false;\n }\n\n return PIX_FMT_HWACCEL;\n }\n }\n private int ShouldAllocateNew() // 0: No, 1: Yes, 2: Yes+Codec Changed\n {\n if (hwframes == null)\n return 1;\n\n AVHWFramesContext* t2 = (AVHWFramesContext*) hwframes->data;\n\n if (codecCtx->coded_width != t2->width)\n return 2;\n\n if (codecCtx->coded_height != t2->height)\n return 2;\n\n // TBR: Codec changed (seems ffmpeg changes codecCtx by itself\n //if (codecCtx->codec_id != VideoStream.CodecID)\n // return 2;\n\n //var fmt = codecCtx->sw_pix_fmt == (AVPixelFormat)AV_PIX_FMT_YUV420P10LE ? (AVPixelFormat)AV_PIX_FMT_P010LE : (codecCtx->sw_pix_fmt == (AVPixelFormat)AV_PIX_FMT_P010BE ? (AVPixelFormat)AV_PIX_FMT_P010BE : AVPixelFormat.AV_PIX_FMT_NV12);\n //if (fmt != t2->sw_format)\n // return 2;\n\n return 0;\n }\n\n private int AllocateHWFrames()\n {\n if (hwframes != null)\n fixed(AVBufferRef** ptr = &hwframes)\n av_buffer_unref(ptr);\n\n hwframes = null;\n\n if (codecCtx->hw_frames_ctx != null)\n av_buffer_unref(&codecCtx->hw_frames_ctx);\n\n if (avcodec_get_hw_frames_parameters(codecCtx, codecCtx->hw_device_ctx, PIX_FMT_HWACCEL, &codecCtx->hw_frames_ctx) != 0)\n return -1;\n\n AVHWFramesContext* hw_frames_ctx = (AVHWFramesContext*)codecCtx->hw_frames_ctx->data;\n //hw_frames_ctx->initial_pool_size += Config.Decoder.MaxVideoFrames; // TBR: Texture 2D Array seems to have up limit to 128 (total=17+MaxVideoFrames)? (should use extra hw frames instead**)\n\n AVD3D11VAFramesContext *va_frames_ctx = (AVD3D11VAFramesContext *)hw_frames_ctx->hwctx;\n va_frames_ctx->BindFlags |= (uint)BindFlags.Decoder | (uint)BindFlags.ShaderResource;\n\n hwframes = av_buffer_ref(codecCtx->hw_frames_ctx);\n\n int ret = av_hwframe_ctx_init(codecCtx->hw_frames_ctx);\n if (ret == 0)\n {\n lock (Renderer.lockDevice)\n {\n textureFFmpeg = new ID3D11Texture2D((IntPtr) va_frames_ctx->texture);\n ZeroCopy = Config.Decoder.ZeroCopy == FlyleafLib.ZeroCopy.Enabled || (Config.Decoder.ZeroCopy == FlyleafLib.ZeroCopy.Auto && codecCtx->width == textureFFmpeg.Description.Width && codecCtx->height == textureFFmpeg.Description.Height);\n filledFromCodec = false;\n }\n }\n\n return ret;\n }\n internal void RecalculateZeroCopy()\n {\n lock (Renderer.lockDevice)\n {\n bool save = ZeroCopy;\n ZeroCopy = VideoAccelerated && (Config.Decoder.ZeroCopy == FlyleafLib.ZeroCopy.Enabled || (Config.Decoder.ZeroCopy == FlyleafLib.ZeroCopy.Auto && codecCtx->width == textureFFmpeg.Description.Width && codecCtx->height == textureFFmpeg.Description.Height));\n if (save != ZeroCopy)\n {\n Renderer?.ConfigPlanes();\n CodecChanged?.Invoke(this);\n }\n }\n }\n #endregion\n\n protected override int Setup(AVCodec* codec)\n {\n // Ensures we have a renderer (no swap chain is required)\n CreateRenderer();\n\n VideoAccelerated = false;\n\n if (!swFallback && Config.Video.VideoAcceleration && Renderer.Device.FeatureLevel >= Vortice.Direct3D.FeatureLevel.Level_10_0)\n {\n if (CheckCodecSupport(codec))\n {\n if (InitVA() == 0)\n {\n codecCtx->hw_device_ctx = av_buffer_ref(hw_device_ctx);\n VideoAccelerated = true;\n Log.Debug(\"VA Success\");\n }\n }\n else\n Log.Info($\"VA {codec->id} not supported\");\n }\n else\n Log.Debug(\"VA Disabled\");\n\n // Can't get data from here?\n //var t1 = av_stream_get_side_data(VideoStream.AVStream, AVPacketSideDataType.AV_PKT_DATA_MASTERING_DISPLAY_METADATA, null);\n //var t2 = av_stream_get_side_data(VideoStream.AVStream, AVPacketSideDataType.AV_PKT_DATA_CONTENT_LIGHT_LEVEL, null);\n\n // TBR: during swFallback (keyFrameRequiredPacket should not reset, currenlty saved in SWFallback)\n keyPacketRequired = false; // allow no key packet after open (lot of videos missing this)\n ZeroCopy = false;\n filledFromCodec = false;\n\n lastFixedPts = 0; // TBR: might need to set this to first known pts/dts\n\n if (VideoAccelerated)\n {\n codecCtx->thread_count = 1;\n codecCtx->hwaccel_flags |= HWAccelFlags.IgnoreLevel;\n if (Config.Decoder.AllowProfileMismatch)\n codecCtx->hwaccel_flags|= HWAccelFlags.AllowProfileMismatch;\n\n codecCtx->get_format = getHWformat;\n codecCtx->extra_hw_frames = Config.Decoder.MaxVideoFrames;\n }\n else\n codecCtx->thread_count = Math.Min(Config.Decoder.VideoThreads, codecCtx->codec_id == AVCodecID.Hevc ? 32 : 16);\n\n return 0;\n }\n internal bool SetupSws()\n {\n Marshal.FreeHGlobal(swsBufferPtr);\n var fmt = AVPixelFormat.Rgba;\n swsData = new byte_ptrArray4();\n swsLineSize = new int_array4();\n int outBufferSize\n = av_image_get_buffer_size(fmt, codecCtx->width, codecCtx->height, 1);\n swsBufferPtr = Marshal.AllocHGlobal(outBufferSize);\n av_image_fill_arrays(ref swsData, ref swsLineSize, (byte*) swsBufferPtr, fmt, codecCtx->width, codecCtx->height, 1);\n swsCtx = sws_getContext(codecCtx->coded_width, codecCtx->coded_height, codecCtx->pix_fmt, codecCtx->width, codecCtx->height, fmt, Config.Video.SwsHighQuality ? SCALING_HQ : SCALING_LQ, null, null, null);\n\n if (swsCtx == null)\n {\n Log.Error($\"Failed to allocate SwsContext\");\n return false;\n }\n\n return true;\n }\n internal void Flush()\n {\n lock (lockActions)\n lock (lockCodecCtx)\n {\n if (Disposed) return;\n\n if (Status == Status.Ended)\n Status = Status.Stopped;\n else if (Status == Status.Draining)\n Status = Status.Stopping;\n\n DisposeFrames();\n avcodec_flush_buffers(codecCtx);\n\n keyPacketRequired\n = true;\n StartTime = AV_NOPTS_VALUE;\n curSpeedFrame = 9999;\n }\n }\n\n protected override void RunInternal()\n {\n if (demuxer.IsReversePlayback)\n {\n RunInternalReverse();\n return;\n }\n\n int ret = 0;\n int allowedErrors = Config.Decoder.MaxErrors;\n int sleepMs = Config.Decoder.MaxVideoFrames > 2 && Config.Player.MaxLatency == 0 ? 10 : 2;\n AVPacket *packet;\n\n do\n {\n // Wait until Queue not Full or Stopped\n if (Frames.Count >= Config.Decoder.MaxVideoFrames)\n {\n lock (lockStatus)\n if (Status == Status.Running) Status = Status.QueueFull;\n\n while (Frames.Count >= Config.Decoder.MaxVideoFrames && Status == Status.QueueFull)\n Thread.Sleep(sleepMs);\n\n lock (lockStatus)\n {\n if (Status != Status.QueueFull) break;\n Status = Status.Running;\n }\n }\n\n // While Packets Queue Empty (Drain | Quit if Demuxer stopped | Wait until we get packets)\n if (demuxer.VideoPackets.Count == 0)\n {\n CriticalArea = true;\n\n lock (lockStatus)\n if (Status == Status.Running) Status = Status.QueueEmpty;\n\n while (demuxer.VideoPackets.Count == 0 && Status == Status.QueueEmpty)\n {\n if (demuxer.Status == Status.Ended)\n {\n lock (lockStatus)\n {\n // TODO: let the demuxer push the draining packet\n Log.Debug(\"Draining\");\n Status = Status.Draining;\n var drainPacket = av_packet_alloc();\n drainPacket->data = null;\n drainPacket->size = 0;\n demuxer.VideoPackets.Enqueue(drainPacket);\n }\n\n break;\n }\n else if (!demuxer.IsRunning)\n {\n if (CanDebug) Log.Debug($\"Demuxer is not running [Demuxer Status: {demuxer.Status}]\");\n\n int retries = 5;\n\n while (retries > 0)\n {\n retries--;\n Thread.Sleep(10);\n if (demuxer.IsRunning) break;\n }\n\n lock (demuxer.lockStatus)\n lock (lockStatus)\n {\n if (demuxer.Status == Status.Pausing || demuxer.Status == Status.Paused)\n Status = Status.Pausing;\n else if (demuxer.Status != Status.Ended)\n Status = Status.Stopping;\n else\n continue;\n }\n\n break;\n }\n\n Thread.Sleep(sleepMs);\n }\n\n lock (lockStatus)\n {\n CriticalArea = false;\n if (Status != Status.QueueEmpty && Status != Status.Draining) break;\n if (Status != Status.Draining) Status = Status.Running;\n }\n }\n\n lock (lockCodecCtx)\n {\n if (Status == Status.Stopped)\n continue;\n\n packet = demuxer.VideoPackets.Dequeue();\n\n if (packet == null)\n continue;\n\n if (isRecording)\n {\n if (!recKeyPacketRequired && (packet->flags & PktFlags.Key) != 0)\n {\n recKeyPacketRequired = true;\n StartRecordTime = (long)(packet->pts * VideoStream.Timebase) - demuxer.StartTime;\n }\n\n if (recKeyPacketRequired)\n curRecorder.Write(av_packet_clone(packet));\n }\n\n if (keyPacketRequired)\n {\n if (packet->flags.HasFlag(PktFlags.Key))\n keyPacketRequired = false;\n else\n {\n if (CanWarn) Log.Warn(\"Ignoring non-key packet\");\n av_packet_unref(packet);\n continue;\n }\n }\n\n // TBR: AVERROR(EAGAIN) means avcodec_receive_frame but after resend the same packet\n ret = avcodec_send_packet(codecCtx, packet);\n\n if (swFallback) // Should use 'global' packet to reset it in get_format (same packet should use also from DecoderContext)\n {\n SWFallback();\n ret = avcodec_send_packet(codecCtx, packet);\n }\n\n if (ret != 0 && ret != AVERROR(EAGAIN))\n {\n // TBR: Possible check for VA failed here (normally this will happen during get_format)\n av_packet_free(&packet);\n\n if (ret == AVERROR_EOF)\n {\n if (demuxer.VideoPackets.Count > 0) { avcodec_flush_buffers(codecCtx); continue; } // TBR: Happens on HLS while switching video streams\n Status = Status.Ended;\n break;\n }\n else\n {\n allowedErrors--;\n if (CanWarn) Log.Warn($\"{FFmpegEngine.ErrorCodeToMsg(ret)} ({ret})\");\n\n if (allowedErrors == 0) { Log.Error(\"Too many errors!\"); Status = Status.Stopping; break; }\n\n continue;\n }\n }\n\n while (true)\n {\n ret = avcodec_receive_frame(codecCtx, frame);\n if (ret != 0) { av_frame_unref(frame); break; }\n\n // GetFormat checks already for this but only for hardware accelerated (should also check for codec/fps* and possible reset sws if required)\n // Might use AVERROR_INPUT_CHANGED to let ffmpeg check for those (requires a flag to be set*)\n if (frame->height != VideoStream.Height || frame->width != VideoStream.Width)\n {\n // THIS IS Wrong and can cause filledFromCodec all the time. comparing frame<->videostream dimensions but we update the videostream from codecparam dimensions (which we pass from codecCtx w/h)\n // Related with display dimensions / coded dimensions / frame-crop dimensions (and apply_cropping) - it could happen when frame->crop... are not 0\n Log.Warn($\"Codec changed {VideoStream.CodecID} {VideoStream.Width}x{VideoStream.Height} => {codecCtx->codec_id} {frame->width}x{frame->height}\");\n filledFromCodec = false;\n }\n\n if (frame->best_effort_timestamp != AV_NOPTS_VALUE)\n frame->pts = frame->best_effort_timestamp;\n\n else if (frame->pts == AV_NOPTS_VALUE)\n {\n if (!VideoStream.FixTimestamps && VideoStream.Duration > TimeSpan.FromSeconds(1).Ticks)\n {\n // TBR: it is possible to have a single frame / image with no dts/pts which actually means pts = 0 ? (ticket_3449.264) - GenPts will not affect it\n // TBR: first frame might no have dts/pts which probably means pts = 0 (and not start time!)\n av_frame_unref(frame);\n continue;\n }\n\n // Create timestamps for h264/hevc raw streams (Needs also to handle this with the remuxer / no recording currently supported!)\n frame->pts = lastFixedPts + VideoStream.StartTimePts;\n lastFixedPts += av_rescale_q(VideoStream.FrameDuration / 10, Engine.FFmpeg.AV_TIMEBASE_Q, VideoStream.AVStream->time_base);\n }\n\n if (StartTime == NoTs)\n StartTime = (long)(frame->pts * VideoStream.Timebase) - demuxer.StartTime;\n\n if (!filledFromCodec) // Ensures we have a proper frame before filling from codec\n {\n ret = FillFromCodec(frame);\n if (ret == -1234)\n {\n Status = Status.Stopping;\n break;\n }\n }\n\n if (skipSpeedFrames > 1)\n {\n curSpeedFrame++;\n if (curSpeedFrame < skipSpeedFrames)\n {\n av_frame_unref(frame);\n continue;\n }\n curSpeedFrame = 0;\n }\n\n var mFrame = Renderer.FillPlanes(frame);\n if (mFrame != null) Frames.Enqueue(mFrame); // TBR: Does not respect Config.Decoder.MaxVideoFrames\n\n if (!Config.Video.PresentFlags.HasFlag(PresentFlags.DoNotWait) && Frames.Count > 2)\n Thread.Sleep(10);\n }\n\n av_packet_free(&packet);\n }\n\n } while (Status == Status.Running);\n\n checkExtraFrames = true;\n\n if (isRecording) { StopRecording(); recCompleted(MediaType.Video); }\n\n if (Status == Status.Draining) Status = Status.Ended;\n }\n\n internal int FillFromCodec(AVFrame* frame)\n {\n lock (Renderer.lockDevice)\n {\n int ret = 0;\n\n filledFromCodec = true;\n\n avcodec_parameters_from_context(Stream.AVStream->codecpar, codecCtx);\n VideoStream.AVStream->time_base = codecCtx->pkt_timebase;\n VideoStream.Refresh(VideoAccelerated && codecCtx->sw_pix_fmt != AVPixelFormat.None ? codecCtx->sw_pix_fmt : codecCtx->pix_fmt, frame);\n\n if (!(VideoStream.FPS > 0)) // NaN\n {\n VideoStream.FPS = av_q2d(codecCtx->framerate) > 0 ? av_q2d(codecCtx->framerate) : 0;\n VideoStream.FrameDuration = VideoStream.FPS > 0 ? (long) (10000000 / VideoStream.FPS) : 0;\n if (VideoStream.FrameDuration > 0)\n VideoStream.Demuxer.VideoPackets.frameDuration = VideoStream.FrameDuration;\n }\n\n skipSpeedFrames = speed * VideoStream.FPS / Config.Video.MaxOutputFps;\n CodecChanged?.Invoke(this);\n\n if (VideoStream.PixelFormat == AVPixelFormat.None || !Renderer.ConfigPlanes())\n {\n Log.Error(\"[Pixel Format] Unknown\");\n return -1234;\n }\n\n return ret;\n }\n }\n\n internal string SWFallback()\n {\n lock (Renderer.lockDevice)\n {\n string ret;\n\n DisposeInternal();\n if (codecCtx != null)\n fixed (AVCodecContext** ptr = &codecCtx)\n avcodec_free_context(ptr);\n\n codecCtx = null;\n swFallback = true;\n bool oldKeyFrameRequiredPacket\n = keyPacketRequired;\n ret = Open2(Stream, null, false); // TBR: Dispose() on failure could cause a deadlock\n keyPacketRequired\n = oldKeyFrameRequiredPacket;\n swFallback = false;\n filledFromCodec = false;\n\n return ret;\n }\n }\n\n private void RunInternalReverse()\n {\n // Bug with B-frames, we should not remove the ref packets (we miss frames each time we restart decoding the gop)\n\n int ret = 0;\n int allowedErrors = Config.Decoder.MaxErrors;\n AVPacket *packet;\n\n do\n {\n // While Packets Queue Empty (Drain | Quit if Demuxer stopped | Wait until we get packets)\n if (demuxer.VideoPacketsReverse.IsEmpty && curReverseVideoStack.IsEmpty && curReverseVideoPackets.Count == 0)\n {\n CriticalArea = true;\n\n lock (lockStatus)\n if (Status == Status.Running) Status = Status.QueueEmpty;\n\n while (demuxer.VideoPacketsReverse.IsEmpty && Status == Status.QueueEmpty)\n {\n if (demuxer.Status == Status.Ended) // TODO\n {\n lock (lockStatus) Status = Status.Ended;\n\n break;\n }\n else if (!demuxer.IsRunning)\n {\n if (CanDebug) Log.Debug($\"Demuxer is not running [Demuxer Status: {demuxer.Status}]\");\n\n int retries = 5;\n\n while (retries > 0)\n {\n retries--;\n Thread.Sleep(10);\n if (demuxer.IsRunning) break;\n }\n\n lock (demuxer.lockStatus)\n lock (lockStatus)\n {\n if (demuxer.Status == Status.Pausing || demuxer.Status == Status.Paused)\n Status = Status.Pausing;\n else if (demuxer.Status != Status.Ended)\n Status = Status.Stopping;\n else\n continue;\n }\n\n break;\n }\n\n Thread.Sleep(20);\n }\n\n lock (lockStatus)\n {\n CriticalArea = false;\n if (Status != Status.QueueEmpty) break;\n Status = Status.Running;\n }\n }\n\n if (curReverseVideoPackets.Count == 0)\n {\n if (curReverseVideoStack.IsEmpty)\n demuxer.VideoPacketsReverse.TryDequeue(out curReverseVideoStack);\n\n curReverseVideoStack.TryPop(out curReverseVideoPackets);\n curReversePacketPos = 0;\n }\n\n while (curReverseVideoPackets.Count > 0 && Status == Status.Running)\n {\n // Wait until Queue not Full or Stopped\n if (Frames.Count + curReverseVideoFrames.Count >= Config.Decoder.MaxVideoFrames)\n {\n lock (lockStatus)\n if (Status == Status.Running) Status = Status.QueueFull;\n\n while (Frames.Count + curReverseVideoFrames.Count >= Config.Decoder.MaxVideoFrames && Status == Status.QueueFull) Thread.Sleep(20);\n\n lock (lockStatus)\n {\n if (Status != Status.QueueFull) break;\n Status = Status.Running;\n }\n }\n\n lock (lockCodecCtx)\n {\n if (keyPacketRequired == true)\n {\n keyPacketRequired = false;\n curReversePacketPos = 0;\n break;\n }\n\n packet = (AVPacket*)curReverseVideoPackets[curReversePacketPos++];\n ret = avcodec_send_packet(codecCtx, packet);\n\n if (ret != 0 && ret != AVERROR(EAGAIN))\n {\n if (ret == AVERROR_EOF) { Status = Status.Ended; break; }\n\n if (CanWarn) Log.Warn($\"{FFmpegEngine.ErrorCodeToMsg(ret)} ({ret})\");\n\n allowedErrors--;\n if (allowedErrors == 0) { Log.Error(\"Too many errors!\"); Status = Status.Stopping; break; }\n\n for (int i=curReverseVideoPackets.Count-1; i>=curReversePacketPos-1; i--)\n {\n packet = (AVPacket*)curReverseVideoPackets[i];\n av_packet_free(&packet);\n curReverseVideoPackets[curReversePacketPos - 1] = IntPtr.Zero;\n curReverseVideoPackets.RemoveAt(i);\n }\n\n avcodec_flush_buffers(codecCtx);\n curReversePacketPos = 0;\n\n for (int i=curReverseVideoFrames.Count -1; i>=0; i--)\n Frames.Enqueue(curReverseVideoFrames[i]);\n\n curReverseVideoFrames.Clear();\n\n continue;\n }\n\n while (true)\n {\n ret = avcodec_receive_frame(codecCtx, frame);\n if (ret != 0) { av_frame_unref(frame); break; }\n\n if (frame->best_effort_timestamp != AV_NOPTS_VALUE)\n frame->pts = frame->best_effort_timestamp;\n else if (frame->pts == AV_NOPTS_VALUE)\n { av_frame_unref(frame); continue; }\n\n bool shouldProcess = curReverseVideoPackets.Count - curReversePacketPos < Config.Decoder.MaxVideoFrames;\n\n if (shouldProcess)\n {\n av_packet_free(&packet);\n curReverseVideoPackets[curReversePacketPos - 1] = IntPtr.Zero;\n var mFrame = Renderer.FillPlanes(frame);\n if (mFrame != null) curReverseVideoFrames.Add(mFrame);\n }\n else\n av_frame_unref(frame);\n }\n\n if (curReversePacketPos == curReverseVideoPackets.Count)\n {\n curReverseVideoPackets.RemoveRange(Math.Max(0, curReverseVideoPackets.Count - Config.Decoder.MaxVideoFrames), Math.Min(curReverseVideoPackets.Count, Config.Decoder.MaxVideoFrames) );\n avcodec_flush_buffers(codecCtx);\n curReversePacketPos = 0;\n\n for (int i=curReverseVideoFrames.Count -1; i>=0; i--)\n Frames.Enqueue(curReverseVideoFrames[i]);\n\n curReverseVideoFrames.Clear();\n\n break; // force recheck for max queues etc...\n }\n\n } // Lock CodecCtx\n\n // Import Sleep required to prevent delay during Renderer.Present for waitable swap chains\n if (!Config.Video.PresentFlags.HasFlag(PresentFlags.DoNotWait) && Frames.Count > 2)\n Thread.Sleep(10);\n\n } // while curReverseVideoPackets.Count > 0\n\n } while (Status == Status.Running);\n\n if (Status != Status.Pausing && Status != Status.Paused)\n curReversePacketPos = 0;\n }\n\n public void RefreshMaxVideoFrames()\n {\n lock (lockActions)\n {\n if (VideoStream == null)\n return;\n\n bool wasRunning = IsRunning;\n\n var stream = Stream;\n\n Dispose();\n Open(stream);\n\n if (wasRunning)\n Start();\n }\n }\n\n public int GetFrameNumber(long timestamp)\n {\n // Incoming timestamps are zero-base from demuxer start time (not from video stream start time)\n timestamp -= VideoStream.StartTime - demuxer.StartTime;\n\n if (timestamp < 1)\n return 0;\n\n // offset 2ms\n return (int) ((timestamp + 20000) / VideoStream.FrameDuration);\n }\n\n /// \n /// Performs accurate seeking to the requested VideoFrame and returns it\n /// \n /// Zero based frame index\n /// The requested VideoFrame or null on failure\n public VideoFrame GetFrame(int index)\n {\n int ret;\n\n // Calculation of FrameX timestamp (based on fps/avgFrameDuration) | offset 2ms\n long frameTimestamp = VideoStream.StartTime + (index * VideoStream.FrameDuration) - 20000;\n //Log.Debug($\"Searching for {Utils.TicksToTime(frameTimestamp)}\");\n\n demuxer.Pause();\n Pause();\n\n // TBR\n //if (demuxer.FormatContext->pb != null)\n // avio_flush(demuxer.FormatContext->pb);\n //avformat_flush(demuxer.FormatContext);\n\n // Seeking at frameTimestamp or previous I/Key frame and flushing codec | Temp fix (max I/distance 3sec) for ffmpeg bug that fails to seek on keyframe with HEVC\n // More issues with mpegts seeking backwards (those should be used also in the reverse playback in the demuxer)\n demuxer.Interrupter.SeekRequest();\n ret = codecCtx->codec_id == AVCodecID.Hevc|| (demuxer.FormatContext->iformat != null) // TBR: this is on FFInputFormat now -> && demuxer.FormatContext->iformat-> read_seek.Pointer == IntPtr.Zero)\n ? av_seek_frame(demuxer.FormatContext, -1, Math.Max(0, frameTimestamp - Config.Player.SeekGetFrameFixMargin) / 10, SeekFlags.Any)\n : av_seek_frame(demuxer.FormatContext, -1, frameTimestamp / 10, SeekFlags.Frame | SeekFlags.Backward);\n\n demuxer.DisposePackets();\n\n if (demuxer.Status == Status.Ended) demuxer.Status = Status.Stopped;\n if (ret < 0) return null; // handle seek error\n Flush();\n checkExtraFrames = false;\n\n while (DecodeFrameNext() == 0)\n {\n // Skip frames before our actual requested frame\n if ((long)(frame->pts * VideoStream.Timebase) < frameTimestamp)\n {\n //Log.Debug($\"[Skip] [pts: {frame->pts}] [time: {Utils.TicksToTime((long)(frame->pts * VideoStream.Timebase))}] | [fltime: {Utils.TicksToTime(((long)(frame->pts * VideoStream.Timebase) - demuxer.StartTime))}]\");\n av_frame_unref(frame);\n continue;\n }\n\n //Log.Debug($\"[Found] [pts: {frame->pts}] [time: {Utils.TicksToTime((long)(frame->pts * VideoStream.Timebase))}] | {Utils.TicksToTime(VideoStream.StartTime + (index * VideoStream.FrameDuration))} | [fltime: {Utils.TicksToTime(((long)(frame->pts * VideoStream.Timebase) - demuxer.StartTime))}]\");\n return Renderer.FillPlanes(frame);\n }\n\n return null;\n }\n\n /// \n /// Gets next VideoFrame (Decoder/Demuxer must not be running)\n /// \n /// The next VideoFrame\n public VideoFrame GetFrameNext()\n => DecodeFrameNext() == 0 ? Renderer.FillPlanes(frame) : null;\n\n /// \n /// Pushes the decoder to the next available VideoFrame (Decoder/Demuxer must not be running)\n /// \n /// \n public int DecodeFrameNext()\n {\n int ret;\n int allowedErrors = Config.Decoder.MaxErrors;\n\n if (checkExtraFrames)\n {\n if (Status == Status.Ended)\n return AVERROR_EOF;\n\n if (DecodeFrameNextInternal() == 0)\n return 0;\n\n if (Demuxer.Status == Status.Ended && demuxer.VideoPackets.Count == 0 && Frames.IsEmpty)\n {\n Stop();\n Status = Status.Ended;\n return AVERROR_EOF;\n }\n\n checkExtraFrames = false;\n }\n\n while (true)\n {\n ret = demuxer.GetNextVideoPacket();\n if (ret != 0)\n {\n if (demuxer.Status != Status.Ended)\n return ret;\n\n // Drain\n ret = avcodec_send_packet(codecCtx, demuxer.packet);\n av_packet_unref(demuxer.packet);\n\n if (ret != 0)\n return AVERROR_EOF;\n\n checkExtraFrames = true;\n return DecodeFrameNext();\n }\n\n if (keyPacketRequired)\n {\n if (demuxer.packet->flags.HasFlag(PktFlags.Key))\n keyPacketRequired = false;\n else\n {\n if (CanWarn) Log.Warn(\"Ignoring non-key packet\");\n av_packet_unref(demuxer.packet);\n continue;\n }\n }\n\n ret = avcodec_send_packet(codecCtx, demuxer.packet);\n\n if (swFallback) // Should use 'global' packet to reset it in get_format (same packet should use also from DecoderContext)\n {\n SWFallback();\n ret = avcodec_send_packet(codecCtx, demuxer.packet);\n }\n\n av_packet_unref(demuxer.packet);\n\n if (ret != 0 && ret != AVERROR(EAGAIN))\n {\n if (CanWarn) Log.Warn($\"{FFmpegEngine.ErrorCodeToMsg(ret)} ({ret})\");\n\n if (allowedErrors-- < 1)\n { Log.Error(\"Too many errors!\"); return ret; }\n\n continue;\n }\n\n if (DecodeFrameNextInternal() == 0)\n {\n checkExtraFrames = true;\n return 0;\n }\n }\n\n }\n private int DecodeFrameNextInternal()\n {\n int ret = avcodec_receive_frame(codecCtx, frame);\n if (ret != 0) { av_frame_unref(frame); return ret; }\n\n if (frame->best_effort_timestamp != AV_NOPTS_VALUE)\n frame->pts = frame->best_effort_timestamp;\n\n else if (frame->pts == AV_NOPTS_VALUE)\n {\n if (!VideoStream.FixTimestamps)\n {\n av_frame_unref(frame);\n\n return DecodeFrameNextInternal();\n }\n\n frame->pts = lastFixedPts + VideoStream.StartTimePts;\n lastFixedPts += av_rescale_q(VideoStream.FrameDuration / 10, Engine.FFmpeg.AV_TIMEBASE_Q, VideoStream.AVStream->time_base);\n }\n\n if (StartTime == NoTs)\n StartTime = (long)(frame->pts * VideoStream.Timebase) - demuxer.StartTime;\n\n if (!filledFromCodec) // Ensures we have a proper frame before filling from codec\n {\n ret = FillFromCodec(frame);\n if (ret == -1234)\n return -1;\n }\n\n return 0;\n }\n\n #region Dispose\n public void DisposeFrames()\n {\n while (!Frames.IsEmpty)\n {\n Frames.TryDequeue(out var frame);\n DisposeFrame(frame);\n }\n\n DisposeFramesReverse();\n }\n private void DisposeFramesReverse()\n {\n while (!curReverseVideoStack.IsEmpty)\n {\n curReverseVideoStack.TryPop(out var t2);\n for (int i = 0; i recCompleted;\n Remuxer curRecorder;\n bool recKeyPacketRequired;\n internal bool isRecording;\n\n internal void StartRecording(Remuxer remuxer)\n {\n if (Disposed || isRecording) return;\n\n StartRecordTime = AV_NOPTS_VALUE;\n curRecorder = remuxer;\n recKeyPacketRequired= false;\n isRecording = true;\n }\n internal void StopRecording() => isRecording = false;\n #endregion\n\n #region TODO Decoder Profiles\n\n /* Use the same as FFmpeg\n * https://github.com/FFmpeg/FFmpeg/blob/master/libavcodec/dxva2.c\n * https://github.com/FFmpeg/FFmpeg/blob/master/libavcodec/avcodec.h\n */\n\n //internal enum DecoderProfiles\n //{\n // DXVA_ModeMPEG2and1_VLD,\n // DXVA_ModeMPEG1_VLD,\n // DXVA2_ModeMPEG2_VLD,\n // DXVA2_ModeMPEG2_IDCT,\n // DXVA2_ModeMPEG2_MoComp,\n // DXVA_ModeH264_A,\n // DXVA_ModeH264_B,\n // DXVA_ModeH264_C,\n // DXVA_ModeH264_D,\n // DXVA_ModeH264_E,\n // DXVA_ModeH264_F,\n // DXVA_ModeH264_VLD_Stereo_Progressive_NoFGT,\n // DXVA_ModeH264_VLD_Stereo_NoFGT,\n // DXVA_ModeH264_VLD_Multiview_NoFGT,\n // DXVA_ModeWMV8_A,\n // DXVA_ModeWMV8_B,\n // DXVA_ModeWMV9_A,\n // DXVA_ModeWMV9_B,\n // DXVA_ModeWMV9_C,\n // DXVA_ModeVC1_A,\n // DXVA_ModeVC1_B,\n // DXVA_ModeVC1_C,\n // DXVA_ModeVC1_D,\n // DXVA_ModeVC1_D2010,\n // DXVA_ModeMPEG4pt2_VLD_Simple,\n // DXVA_ModeMPEG4pt2_VLD_AdvSimple_NoGMC,\n // DXVA_ModeMPEG4pt2_VLD_AdvSimple_GMC,\n // DXVA_ModeHEVC_VLD_Main,\n // DXVA_ModeHEVC_VLD_Main10,\n // DXVA_ModeVP8_VLD,\n // DXVA_ModeVP9_VLD_Profile0,\n // DXVA_ModeVP9_VLD_10bit_Profile2,\n // DXVA_ModeMPEG1_A,\n // DXVA_ModeMPEG2_A,\n // DXVA_ModeMPEG2_B,\n // DXVA_ModeMPEG2_C,\n // DXVA_ModeMPEG2_D,\n // DXVA_ModeH261_A,\n // DXVA_ModeH261_B,\n // DXVA_ModeH263_A,\n // DXVA_ModeH263_B,\n // DXVA_ModeH263_C,\n // DXVA_ModeH263_D,\n // DXVA_ModeH263_E,\n // DXVA_ModeH263_F,\n // DXVA_ModeH264_VLD_WithFMOASO_NoFGT,\n // DXVA_ModeH264_VLD_Multiview,\n // DXVADDI_Intel_ModeH264_A,\n // DXVADDI_Intel_ModeH264_C,\n // DXVA_Intel_H264_NoFGT_ClearVideo,\n // DXVA_ModeH264_VLD_NoFGT_Flash,\n // DXVA_Intel_VC1_ClearVideo,\n // DXVA_Intel_VC1_ClearVideo_2,\n // DXVA_nVidia_MPEG4_ASP,\n // DXVA_ModeMPEG4pt2_VLD_AdvSimple_Avivo,\n // DXVA_ModeHEVC_VLD_Main_Intel,\n // DXVA_ModeHEVC_VLD_Main10_Intel,\n // DXVA_ModeHEVC_VLD_Main12_Intel,\n // DXVA_ModeHEVC_VLD_Main422_10_Intel,\n // DXVA_ModeHEVC_VLD_Main422_12_Intel,\n // DXVA_ModeHEVC_VLD_Main444_Intel,\n // DXVA_ModeHEVC_VLD_Main444_10_Intel,\n // DXVA_ModeHEVC_VLD_Main444_12_Intel,\n // DXVA_ModeH264_VLD_SVC_Scalable_Baseline,\n // DXVA_ModeH264_VLD_SVC_Restricted_Scalable_Baseline,\n // DXVA_ModeH264_VLD_SVC_Scalable_High,\n // DXVA_ModeH264_VLD_SVC_Restricted_Scalable_High_Progressive,\n // DXVA_ModeVP9_VLD_Intel,\n // DXVA_ModeAV1_VLD_Profile0,\n // DXVA_ModeAV1_VLD_Profile1,\n // DXVA_ModeAV1_VLD_Profile2,\n // DXVA_ModeAV1_VLD_12bit_Profile2,\n // DXVA_ModeAV1_VLD_12bit_Profile2_420\n //}\n //internal static Dictionary DXVADecoderProfiles = new()\n //{\n // { new(0x86695f12, 0x340e, 0x4f04, 0x9f, 0xd3, 0x92, 0x53, 0xdd, 0x32, 0x74, 0x60), DecoderProfiles.DXVA_ModeMPEG2and1_VLD },\n // { new(0x6f3ec719, 0x3735, 0x42cc, 0x80, 0x63, 0x65, 0xcc, 0x3c, 0xb3, 0x66, 0x16), DecoderProfiles.DXVA_ModeMPEG1_VLD },\n // { new(0xee27417f, 0x5e28,0x4e65, 0xbe, 0xea, 0x1d, 0x26, 0xb5, 0x08, 0xad, 0xc9), DecoderProfiles.DXVA2_ModeMPEG2_VLD },\n // { new(0xbf22ad00, 0x03ea,0x4690, 0x80, 0x77, 0x47, 0x33, 0x46, 0x20, 0x9b, 0x7e), DecoderProfiles.DXVA2_ModeMPEG2_IDCT },\n // { new(0xe6a9f44b, 0x61b0,0x4563, 0x9e, 0xa4, 0x63, 0xd2, 0xa3, 0xc6, 0xfe, 0x66), DecoderProfiles.DXVA2_ModeMPEG2_MoComp },\n // { new(0x1b81be64, 0xa0c7,0x11d3, 0xb9, 0x84, 0x00, 0xc0, 0x4f, 0x2e, 0x73, 0xc5), DecoderProfiles.DXVA_ModeH264_A },\n // { new(0x1b81be65, 0xa0c7,0x11d3, 0xb9, 0x84, 0x00, 0xc0, 0x4f, 0x2e, 0x73, 0xc5), DecoderProfiles.DXVA_ModeH264_B },\n // { new(0x1b81be66, 0xa0c7,0x11d3, 0xb9, 0x84, 0x00, 0xc0, 0x4f, 0x2e, 0x73, 0xc5), DecoderProfiles.DXVA_ModeH264_C },\n // { new(0x1b81be67, 0xa0c7,0x11d3, 0xb9, 0x84, 0x00, 0xc0, 0x4f, 0x2e, 0x73, 0xc5), DecoderProfiles.DXVA_ModeH264_D },\n // { new(0x1b81be68, 0xa0c7,0x11d3, 0xb9, 0x84, 0x00, 0xc0, 0x4f, 0x2e, 0x73, 0xc5), DecoderProfiles.DXVA_ModeH264_E },\n // { new(0x1b81be69, 0xa0c7,0x11d3, 0xb9, 0x84, 0x00, 0xc0, 0x4f, 0x2e, 0x73, 0xc5), DecoderProfiles.DXVA_ModeH264_F },\n // { new(0xd79be8da, 0x0cf1,0x4c81, 0xb8, 0x2a, 0x69, 0xa4, 0xe2, 0x36, 0xf4, 0x3d), DecoderProfiles.DXVA_ModeH264_VLD_Stereo_Progressive_NoFGT },\n // { new(0xf9aaccbb, 0xc2b6,0x4cfc, 0x87, 0x79, 0x57, 0x07, 0xb1, 0x76, 0x05, 0x52), DecoderProfiles.DXVA_ModeH264_VLD_Stereo_NoFGT },\n // { new(0x705b9d82, 0x76cf,0x49d6, 0xb7, 0xe6, 0xac, 0x88, 0x72, 0xdb, 0x01, 0x3c), DecoderProfiles.DXVA_ModeH264_VLD_Multiview_NoFGT },\n // { new(0x1b81be80, 0xa0c7,0x11d3, 0xb9, 0x84, 0x00, 0xc0, 0x4f, 0x2e, 0x73, 0xc5), DecoderProfiles.DXVA_ModeWMV8_A },\n // { new(0x1b81be81, 0xa0c7,0x11d3, 0xb9, 0x84, 0x00, 0xc0, 0x4f, 0x2e, 0x73, 0xc5), DecoderProfiles.DXVA_ModeWMV8_B },\n // { new(0x1b81be90, 0xa0c7,0x11d3, 0xb9, 0x84, 0x00, 0xc0, 0x4f, 0x2e, 0x73, 0xc5), DecoderProfiles.DXVA_ModeWMV9_A },\n // { new(0x1b81be91, 0xa0c7,0x11d3, 0xb9, 0x84, 0x00, 0xc0, 0x4f, 0x2e, 0x73, 0xc5), DecoderProfiles.DXVA_ModeWMV9_B },\n // { new(0x1b81be94, 0xa0c7,0x11d3, 0xb9, 0x84, 0x00, 0xc0, 0x4f, 0x2e, 0x73, 0xc5), DecoderProfiles.DXVA_ModeWMV9_C },\n // { new(0x1b81beA0, 0xa0c7,0x11d3, 0xb9, 0x84, 0x00, 0xc0, 0x4f, 0x2e, 0x73, 0xc5), DecoderProfiles.DXVA_ModeVC1_A },\n // { new(0x1b81beA1, 0xa0c7,0x11d3, 0xb9, 0x84, 0x00, 0xc0, 0x4f, 0x2e, 0x73, 0xc5), DecoderProfiles.DXVA_ModeVC1_B },\n // { new(0x1b81beA2, 0xa0c7,0x11d3, 0xb9, 0x84, 0x00, 0xc0, 0x4f, 0x2e, 0x73, 0xc5), DecoderProfiles.DXVA_ModeVC1_C },\n // { new(0x1b81beA3, 0xa0c7,0x11d3, 0xb9, 0x84, 0x00, 0xc0, 0x4f, 0x2e, 0x73, 0xc5), DecoderProfiles.DXVA_ModeVC1_D },\n // { new(0x1b81bea4, 0xa0c7,0x11d3, 0xb9, 0x84, 0x00, 0xc0, 0x4f, 0x2e, 0x73, 0xc5), DecoderProfiles.DXVA_ModeVC1_D2010 },\n // { new(0xefd64d74, 0xc9e8,0x41d7, 0xa5, 0xe9, 0xe9, 0xb0, 0xe3, 0x9f, 0xa3, 0x19), DecoderProfiles.DXVA_ModeMPEG4pt2_VLD_Simple },\n // { new(0xed418a9f, 0x010d,0x4eda, 0x9a, 0xe3, 0x9a, 0x65, 0x35, 0x8d, 0x8d, 0x2e), DecoderProfiles.DXVA_ModeMPEG4pt2_VLD_AdvSimple_NoGMC },\n // { new(0xab998b5b, 0x4258,0x44a9, 0x9f, 0xeb, 0x94, 0xe5, 0x97, 0xa6, 0xba, 0xae), DecoderProfiles.DXVA_ModeMPEG4pt2_VLD_AdvSimple_GMC },\n // { new(0x5b11d51b, 0x2f4c,0x4452, 0xbc, 0xc3, 0x09, 0xf2, 0xa1, 0x16, 0x0c, 0xc0), DecoderProfiles.DXVA_ModeHEVC_VLD_Main },\n // { new(0x107af0e0, 0xef1a,0x4d19, 0xab, 0xa8, 0x67, 0xa1, 0x63, 0x07, 0x3d, 0x13), DecoderProfiles.DXVA_ModeHEVC_VLD_Main10 },\n // { new(0x90b899ea, 0x3a62,0x4705, 0x88, 0xb3, 0x8d, 0xf0, 0x4b, 0x27, 0x44, 0xe7), DecoderProfiles.DXVA_ModeVP8_VLD },\n // { new(0x463707f8, 0xa1d0,0x4585, 0x87, 0x6d, 0x83, 0xaa, 0x6d, 0x60, 0xb8, 0x9e), DecoderProfiles.DXVA_ModeVP9_VLD_Profile0 },\n // { new(0xa4c749ef, 0x6ecf,0x48aa, 0x84, 0x48, 0x50, 0xa7, 0xa1, 0x16, 0x5f, 0xf7), DecoderProfiles.DXVA_ModeVP9_VLD_10bit_Profile2 },\n // { new(0x1b81be09, 0xa0c7, 0x11d3, 0xb9, 0x84, 0x00, 0xc0, 0x4f, 0x2e, 0x73, 0xc5), DecoderProfiles.DXVA_ModeMPEG1_A },\n // { new(0x1b81be0A, 0xa0c7, 0x11d3, 0xb9, 0x84, 0x00, 0xc0, 0x4f, 0x2e, 0x73, 0xc5), DecoderProfiles.DXVA_ModeMPEG2_A },\n // { new(0x1b81be0B, 0xa0c7, 0x11d3, 0xb9, 0x84, 0x00, 0xc0, 0x4f, 0x2e, 0x73, 0xc5), DecoderProfiles.DXVA_ModeMPEG2_B },\n // { new(0x1b81be0C, 0xa0c7, 0x11d3, 0xb9, 0x84, 0x00, 0xc0, 0x4f, 0x2e, 0x73, 0xc5), DecoderProfiles.DXVA_ModeMPEG2_C },\n // { new(0x1b81be0D, 0xa0c7, 0x11d3, 0xb9, 0x84, 0x00, 0xc0, 0x4f, 0x2e, 0x73, 0xc5), DecoderProfiles.DXVA_ModeMPEG2_D },\n // { new(0x1b81be01, 0xa0c7, 0x11d3, 0xb9, 0x84, 0x00, 0xc0, 0x4f, 0x2e, 0x73, 0xc5), DecoderProfiles.DXVA_ModeH261_A },\n // { new(0x1b81be02, 0xa0c7, 0x11d3, 0xb9, 0x84, 0x00, 0xc0, 0x4f, 0x2e, 0x73, 0xc5), DecoderProfiles.DXVA_ModeH261_B },\n // { new(0x1b81be03, 0xa0c7, 0x11d3, 0xb9, 0x84, 0x00, 0xc0, 0x4f, 0x2e, 0x73, 0xc5), DecoderProfiles.DXVA_ModeH263_A },\n // { new(0x1b81be04, 0xa0c7, 0x11d3, 0xb9, 0x84, 0x00, 0xc0, 0x4f, 0x2e, 0x73, 0xc5), DecoderProfiles.DXVA_ModeH263_B },\n // { new(0x1b81be05, 0xa0c7, 0x11d3, 0xb9, 0x84, 0x00, 0xc0, 0x4f, 0x2e, 0x73, 0xc5), DecoderProfiles.DXVA_ModeH263_C },\n // { new(0x1b81be06, 0xa0c7, 0x11d3, 0xb9, 0x84, 0x00, 0xc0, 0x4f, 0x2e, 0x73, 0xc5), DecoderProfiles.DXVA_ModeH263_D },\n // { new(0x1b81be07, 0xa0c7, 0x11d3, 0xb9, 0x84, 0x00, 0xc0, 0x4f, 0x2e, 0x73, 0xc5), DecoderProfiles.DXVA_ModeH263_E },\n // { new(0x1b81be08, 0xa0c7, 0x11d3, 0xb9, 0x84, 0x00, 0xc0, 0x4f, 0x2e, 0x73, 0xc5), DecoderProfiles.DXVA_ModeH263_F },\n // { new(0xd5f04ff9, 0x3418, 0x45d8, 0x95, 0x61, 0x32, 0xa7, 0x6a, 0xae, 0x2d, 0xdd), DecoderProfiles.DXVA_ModeH264_VLD_WithFMOASO_NoFGT },\n // { new(0x9901CCD3, 0xca12, 0x4b7e, 0x86, 0x7a, 0xe2, 0x22, 0x3d, 0x92, 0x55, 0xc3), DecoderProfiles.DXVA_ModeH264_VLD_Multiview },\n // { new(0x604F8E64, 0x4951, 0x4c54, 0x88, 0xFE, 0xAB, 0xD2, 0x5C, 0x15, 0xB3, 0xD6), DecoderProfiles.DXVADDI_Intel_ModeH264_A },\n // { new(0x604F8E66, 0x4951, 0x4c54, 0x88, 0xFE, 0xAB, 0xD2, 0x5C, 0x15, 0xB3, 0xD6), DecoderProfiles.DXVADDI_Intel_ModeH264_C },\n // { new(0x604F8E68, 0x4951, 0x4c54, 0x88, 0xFE, 0xAB, 0xD2, 0x5C, 0x15, 0xB3, 0xD6), DecoderProfiles.DXVA_Intel_H264_NoFGT_ClearVideo },\n // { new(0x4245F676, 0x2BBC, 0x4166, 0xa0, 0xBB, 0x54, 0xE7, 0xB8, 0x49, 0xC3, 0x80), DecoderProfiles.DXVA_ModeH264_VLD_NoFGT_Flash },\n // { new(0xBCC5DB6D, 0xA2B6, 0x4AF0, 0xAC, 0xE4, 0xAD, 0xB1, 0xF7, 0x87, 0xBC, 0x89), DecoderProfiles.DXVA_Intel_VC1_ClearVideo },\n // { new(0xE07EC519, 0xE651, 0x4CD6, 0xAC, 0x84, 0x13, 0x70, 0xCC, 0xEE, 0xC8, 0x51), DecoderProfiles.DXVA_Intel_VC1_ClearVideo_2 },\n // { new(0x9947EC6F, 0x689B, 0x11DC, 0xA3, 0x20, 0x00, 0x19, 0xDB, 0xBC, 0x41, 0x84), DecoderProfiles.DXVA_nVidia_MPEG4_ASP },\n // { new(0x7C74ADC6, 0xe2ba, 0x4ade, 0x86, 0xde, 0x30, 0xbe, 0xab, 0xb4, 0x0c, 0xc1), DecoderProfiles.DXVA_ModeMPEG4pt2_VLD_AdvSimple_Avivo },\n // { new(0x8c56eb1e, 0x2b47, 0x466f, 0x8d, 0x33, 0x7d, 0xbc, 0xd6, 0x3f, 0x3d, 0xf2), DecoderProfiles.DXVA_ModeHEVC_VLD_Main_Intel },\n // { new(0x75fc75f7, 0xc589, 0x4a07, 0xa2, 0x5b, 0x72, 0xe0, 0x3b, 0x03, 0x83, 0xb3), DecoderProfiles.DXVA_ModeHEVC_VLD_Main10_Intel },\n // { new(0x8ff8a3aa, 0xc456, 0x4132, 0xb6, 0xef, 0x69, 0xd9, 0xdd, 0x72, 0x57, 0x1d), DecoderProfiles.DXVA_ModeHEVC_VLD_Main12_Intel },\n // { new(0xe484dcb8, 0xcac9, 0x4859, 0x99, 0xf5, 0x5c, 0x0d, 0x45, 0x06, 0x90, 0x89), DecoderProfiles.DXVA_ModeHEVC_VLD_Main422_10_Intel },\n // { new(0xc23dd857, 0x874b, 0x423c, 0xb6, 0xe0, 0x82, 0xce, 0xaa, 0x9b, 0x11, 0x8a), DecoderProfiles.DXVA_ModeHEVC_VLD_Main422_12_Intel },\n // { new(0x41a5af96, 0xe415, 0x4b0c, 0x9d, 0x03, 0x90, 0x78, 0x58, 0xe2, 0x3e, 0x78), DecoderProfiles.DXVA_ModeHEVC_VLD_Main444_Intel },\n // { new(0x6a6a81ba, 0x912a, 0x485d, 0xb5, 0x7f, 0xcc, 0xd2, 0xd3, 0x7b, 0x8d, 0x94), DecoderProfiles.DXVA_ModeHEVC_VLD_Main444_10_Intel },\n // { new(0x5b08e35d, 0x0c66, 0x4c51, 0xa6, 0xf1, 0x89, 0xd0, 0x0c, 0xb2, 0xc1, 0x97), DecoderProfiles.DXVA_ModeHEVC_VLD_Main444_12_Intel },\n // { new(0xc30700c4, 0xe384, 0x43e0, 0xb9, 0x82, 0x2d, 0x89, 0xee, 0x7f, 0x77, 0xc4), DecoderProfiles.DXVA_ModeH264_VLD_SVC_Scalable_Baseline },\n // { new(0x9b8175d4, 0xd670, 0x4cf2, 0xa9, 0xf0, 0xfa, 0x56, 0xdf, 0x71, 0xa1, 0xae), DecoderProfiles.DXVA_ModeH264_VLD_SVC_Restricted_Scalable_Baseline },\n // { new(0x728012c9, 0x66a8, 0x422f, 0x97, 0xe9, 0xb5, 0xe3, 0x9b, 0x51, 0xc0, 0x53), DecoderProfiles.DXVA_ModeH264_VLD_SVC_Scalable_High },\n // { new(0x8efa5926, 0xbd9e, 0x4b04, 0x8b, 0x72, 0x8f, 0x97, 0x7d, 0xc4, 0x4c, 0x36), DecoderProfiles.DXVA_ModeH264_VLD_SVC_Restricted_Scalable_High_Progressive },\n // { new(0x76988a52, 0xdf13, 0x419a, 0x8e, 0x64, 0xff, 0xcf, 0x4a, 0x33, 0x6c, 0xf5), DecoderProfiles.DXVA_ModeVP9_VLD_Intel },\n // { new(0xb8be4ccb, 0xcf53, 0x46ba, 0x8d, 0x59, 0xd6, 0xb8, 0xa6, 0xda, 0x5d, 0x2a), DecoderProfiles.DXVA_ModeAV1_VLD_Profile0 },\n // { new(0x6936ff0f, 0x45b1, 0x4163, 0x9c, 0xc1, 0x64, 0x6e, 0xf6, 0x94, 0x61, 0x08), DecoderProfiles.DXVA_ModeAV1_VLD_Profile1 },\n // { new(0x0c5f2aa1, 0xe541, 0x4089, 0xbb, 0x7b, 0x98, 0x11, 0x0a, 0x19, 0xd7, 0xc8), DecoderProfiles.DXVA_ModeAV1_VLD_Profile2 },\n // { new(0x17127009, 0xa00f, 0x4ce1, 0x99, 0x4e, 0xbf, 0x40, 0x81, 0xf6, 0xf3, 0xf0), DecoderProfiles.DXVA_ModeAV1_VLD_12bit_Profile2 },\n // { new(0x2d80bed6, 0x9cac, 0x4835, 0x9e, 0x91, 0x32, 0x7b, 0xbc, 0x4f, 0x9e, 0xe8), DecoderProfiles.DXVA_ModeAV1_VLD_12bit_Profile2_420 },\n\n\n //};\n //internal static Dictionary DXVADecoderProfilesDesc = new()\n //{\n // { DecoderProfiles.DXVA_ModeMPEG1_A, \"MPEG-1 decoder, restricted profile A\" },\n // { DecoderProfiles.DXVA_ModeMPEG2_A, \"MPEG-2 decoder, restricted profile A\" },\n // { DecoderProfiles.DXVA_ModeMPEG2_B, \"MPEG-2 decoder, restricted profile B\" },\n // { DecoderProfiles.DXVA_ModeMPEG2_C, \"MPEG-2 decoder, restricted profile C\" },\n // { DecoderProfiles.DXVA_ModeMPEG2_D, \"MPEG-2 decoder, restricted profile D\" },\n // { DecoderProfiles.DXVA2_ModeMPEG2_VLD, \"MPEG-2 variable-length decoder\" },\n // { DecoderProfiles.DXVA_ModeMPEG2and1_VLD, \"MPEG-2 & MPEG-1 variable-length decoder\" },\n // { DecoderProfiles.DXVA2_ModeMPEG2_MoComp, \"MPEG-2 motion compensation\" },\n // { DecoderProfiles.DXVA2_ModeMPEG2_IDCT, \"MPEG-2 inverse discrete cosine transform\" },\n // { DecoderProfiles.DXVA_ModeMPEG1_VLD, \"MPEG-1 variable-length decoder, no D pictures\" },\n // { DecoderProfiles.DXVA_ModeH264_F, \"H.264 variable-length decoder, film grain technology\" },\n // { DecoderProfiles.DXVA_ModeH264_E, \"H.264 variable-length decoder, no film grain technology\" },\n // { DecoderProfiles.DXVA_Intel_H264_NoFGT_ClearVideo, \"H.264 variable-length decoder, no film grain technology (Intel ClearVideo)\" },\n // { DecoderProfiles.DXVA_ModeH264_VLD_WithFMOASO_NoFGT, \"H.264 variable-length decoder, no film grain technology, FMO/ASO\" },\n // { DecoderProfiles.DXVA_ModeH264_VLD_NoFGT_Flash, \"H.264 variable-length decoder, no film grain technology, Flash\" },\n // { DecoderProfiles.DXVA_ModeH264_D, \"H.264 inverse discrete cosine transform, film grain technology\" },\n // { DecoderProfiles.DXVA_ModeH264_C, \"H.264 inverse discrete cosine transform, no film grain technology\" },\n // { DecoderProfiles.DXVADDI_Intel_ModeH264_C, \"H.264 inverse discrete cosine transform, no film grain technology (Intel)\" },\n // { DecoderProfiles.DXVA_ModeH264_B, \"H.264 motion compensation, film grain technology\" },\n // { DecoderProfiles.DXVA_ModeH264_A, \"H.264 motion compensation, no film grain technology\" },\n // { DecoderProfiles.DXVADDI_Intel_ModeH264_A, \"H.264 motion compensation, no film grain technology (Intel)\" },\n // { DecoderProfiles.DXVA_ModeH264_VLD_Stereo_Progressive_NoFGT, \"H.264 stereo high profile, mbs flag set\" },\n // { DecoderProfiles.DXVA_ModeH264_VLD_Stereo_NoFGT, \"H.264 stereo high profile\" },\n // { DecoderProfiles.DXVA_ModeH264_VLD_Multiview_NoFGT, \"H.264 multiview high profile\" },\n // { DecoderProfiles.DXVA_ModeH264_VLD_SVC_Scalable_Baseline, \"H.264 scalable video coding, Scalable Baseline Profile\" },\n // { DecoderProfiles.DXVA_ModeH264_VLD_SVC_Restricted_Scalable_Baseline, \"H.264 scalable video coding, Scalable Constrained Baseline Profile\" },\n // { DecoderProfiles.DXVA_ModeH264_VLD_SVC_Scalable_High, \"H.264 scalable video coding, Scalable High Profile\" },\n // { DecoderProfiles.DXVA_ModeH264_VLD_SVC_Restricted_Scalable_High_Progressive, \"H.264 scalable video coding, Scalable Constrained High Profile\" },\n // { DecoderProfiles.DXVA_ModeWMV8_B, \"Windows Media Video 8 motion compensation\" },\n // { DecoderProfiles.DXVA_ModeWMV8_A, \"Windows Media Video 8 post processing\" },\n // { DecoderProfiles.DXVA_ModeWMV9_C, \"Windows Media Video 9 IDCT\" },\n // { DecoderProfiles.DXVA_ModeWMV9_B, \"Windows Media Video 9 motion compensation\" },\n // { DecoderProfiles.DXVA_ModeWMV9_A, \"Windows Media Video 9 post processing\" },\n // { DecoderProfiles.DXVA_ModeVC1_D, \"VC-1 variable-length decoder\" },\n // { DecoderProfiles.DXVA_ModeVC1_D2010, \"VC-1 variable-length decoder\" },\n // { DecoderProfiles.DXVA_Intel_VC1_ClearVideo_2, \"VC-1 variable-length decoder 2 (Intel)\" },\n // { DecoderProfiles.DXVA_Intel_VC1_ClearVideo, \"VC-1 variable-length decoder (Intel)\" },\n // { DecoderProfiles.DXVA_ModeVC1_C, \"VC-1 inverse discrete cosine transform\" },\n // { DecoderProfiles.DXVA_ModeVC1_B, \"VC-1 motion compensation\" },\n // { DecoderProfiles.DXVA_ModeVC1_A, \"VC-1 post processing\" },\n // { DecoderProfiles.DXVA_nVidia_MPEG4_ASP, \"MPEG-4 Part 2 nVidia bitstream decoder\" },\n // { DecoderProfiles.DXVA_ModeMPEG4pt2_VLD_Simple, \"MPEG-4 Part 2 variable-length decoder, Simple Profile\" },\n // { DecoderProfiles.DXVA_ModeMPEG4pt2_VLD_AdvSimple_NoGMC, \"MPEG-4 Part 2 variable-length decoder, Simple&Advanced Profile, no GMC\" },\n // { DecoderProfiles.DXVA_ModeMPEG4pt2_VLD_AdvSimple_GMC, \"MPEG-4 Part 2 variable-length decoder, Simple&Advanced Profile, GMC\" },\n // { DecoderProfiles.DXVA_ModeMPEG4pt2_VLD_AdvSimple_Avivo, \"MPEG-4 Part 2 variable-length decoder, Simple&Advanced Profile, Avivo\" },\n // { DecoderProfiles.DXVA_ModeHEVC_VLD_Main_Intel, \"HEVC Main profile (Intel)\" },\n // { DecoderProfiles.DXVA_ModeHEVC_VLD_Main10_Intel, \"HEVC Main 10 profile (Intel)\" },\n // { DecoderProfiles.DXVA_ModeHEVC_VLD_Main12_Intel, \"HEVC Main profile 4:2:2 Range Extension (Intel)\" },\n // { DecoderProfiles.DXVA_ModeHEVC_VLD_Main422_10_Intel, \"HEVC Main 10 profile 4:2:2 Range Extension (Intel)\" },\n // { DecoderProfiles.DXVA_ModeHEVC_VLD_Main422_12_Intel, \"HEVC Main 12 profile 4:2:2 Range Extension (Intel)\" },\n // { DecoderProfiles.DXVA_ModeHEVC_VLD_Main444_Intel, \"HEVC Main profile 4:4:4 Range Extension (Intel)\" },\n // { DecoderProfiles.DXVA_ModeHEVC_VLD_Main444_10_Intel, \"HEVC Main 10 profile 4:4:4 Range Extension (Intel)\" },\n // { DecoderProfiles.DXVA_ModeHEVC_VLD_Main444_12_Intel, \"HEVC Main 12 profile 4:4:4 Range Extension (Intel)\" },\n // { DecoderProfiles.DXVA_ModeHEVC_VLD_Main, \"HEVC Main profile\" },\n // { DecoderProfiles.DXVA_ModeHEVC_VLD_Main10, \"HEVC Main 10 profile\" },\n // { DecoderProfiles.DXVA_ModeH261_A, \"H.261 decoder, restricted profile A\" },\n // { DecoderProfiles.DXVA_ModeH261_B, \"H.261 decoder, restricted profile B\" },\n // { DecoderProfiles.DXVA_ModeH263_A, \"H.263 decoder, restricted profile A\" },\n // { DecoderProfiles.DXVA_ModeH263_B, \"H.263 decoder, restricted profile B\" },\n // { DecoderProfiles.DXVA_ModeH263_C, \"H.263 decoder, restricted profile C\" },\n // { DecoderProfiles.DXVA_ModeH263_D, \"H.263 decoder, restricted profile D\" },\n // { DecoderProfiles.DXVA_ModeH263_E, \"H.263 decoder, restricted profile E\" },\n // { DecoderProfiles.DXVA_ModeH263_F, \"H.263 decoder, restricted profile F\" },\n // { DecoderProfiles.DXVA_ModeVP8_VLD, \"VP8\" },\n // { DecoderProfiles.DXVA_ModeVP9_VLD_Profile0, \"VP9 profile 0\" },\n // { DecoderProfiles.DXVA_ModeVP9_VLD_10bit_Profile2, \"VP9 profile\" },\n // { DecoderProfiles.DXVA_ModeVP9_VLD_Intel, \"VP9 profile Intel\" },\n // { DecoderProfiles.DXVA_ModeAV1_VLD_Profile0, \"AV1 Main profile\" },\n // { DecoderProfiles.DXVA_ModeAV1_VLD_Profile1, \"AV1 High profile\" },\n //};\n #endregion\n}\n"], ["/LLPlayer/FlyleafLib/MediaFramework/MediaPlaylist/Playlist.cs", "using System.Collections.ObjectModel;\nusing System.IO;\n\nusing FlyleafLib.MediaFramework.MediaContext;\n\nusing static FlyleafLib.Utils;\n\nnamespace FlyleafLib.MediaFramework.MediaPlaylist;\n\npublic class Playlist : NotifyPropertyChanged\n{\n /// \n /// Url provided by user\n /// \n public string Url { get => _Url; set { string fixedUrl = FixFileUrl(value); SetUI(ref _Url, fixedUrl); } }\n string _Url;\n\n /// \n /// IOStream provided by user\n /// \n public Stream IOStream { get; set; }\n\n /// \n /// Playlist's folder base which can be used to save related files\n /// \n public string FolderBase { get; set; }\n\n /// \n /// Playlist's title\n /// \n public string Title { get => _Title; set => SetUI(ref _Title, value); }\n string _Title;\n\n public int ExpectingItems { get => _ExpectingItems; set => SetUI(ref _ExpectingItems, value); }\n int _ExpectingItems;\n\n public bool Completed { get; set; }\n\n /// \n /// Playlist's opened/selected item\n /// \n public PlaylistItem Selected { get => _Selected; internal set { SetUI(ref _Selected, value); UpdatePrevNextItem(); } }\n PlaylistItem _Selected;\n\n public PlaylistItem NextItem { get => _NextItem; internal set => SetUI(ref _NextItem, value); }\n PlaylistItem _NextItem;\n\n public PlaylistItem PrevItem { get => _PrevItem; internal set => SetUI(ref _PrevItem, value); }\n PlaylistItem _PrevItem;\n\n internal void UpdatePrevNextItem()\n {\n if (Selected == null)\n {\n PrevItem = NextItem = null;\n return;\n }\n\n for (int i=0; i < Items.Count; i++)\n {\n if (Items[i] == Selected)\n {\n PrevItem = i > 0 ? Items[i - 1] : null;\n NextItem = i < Items.Count - 1 ? Items[i + 1] : null;\n\n return;\n }\n }\n }\n\n /// \n /// Type of the provided input (such as File, UNC, Torrent, Web, etc.)\n /// \n public InputType InputType { get; set; }\n\n // TODO: MediaType (Music/MusicClip/Movie/TVShow/etc.) probably should go per Playlist Item\n\n public ObservableCollection\n Items { get; set; } = new ObservableCollection();\n object lockItems = new();\n\n long openCounter;\n //long openItemCounter;\n internal DecoderContext decoder;\n LogHandler Log;\n\n public Playlist(int uniqueId)\n {\n Log = new LogHandler((\"[#\" + uniqueId + \"]\").PadRight(8, ' ') + \" [Playlist] \");\n UIInvokeIfRequired(() => System.Windows.Data.BindingOperations.EnableCollectionSynchronization(Items, lockItems));\n }\n\n public void Reset()\n {\n openCounter = decoder.OpenCounter;\n\n lock (lockItems)\n Items.Clear();\n\n bool noupdate = _Url == null && _Title == null && _Selected == null;\n\n _Url = null;\n _Title = null;\n _Selected = null;\n PrevItem = null;\n NextItem = null;\n IOStream = null;\n FolderBase = null;\n Completed = false;\n ExpectingItems = 0;\n\n InputType = InputType.Unknown;\n\n if (!noupdate)\n UI(() =>\n {\n Raise(nameof(Url));\n Raise(nameof(Title));\n Raise(nameof(Selected));\n });\n }\n\n public void AddItem(PlaylistItem item, string pluginName, object tag = null)\n {\n if (openCounter != decoder.OpenCounter)\n {\n Log.Debug(\"AddItem Cancelled\");\n return;\n }\n\n lock (lockItems)\n {\n Items.Add(item);\n Items[^1].Index = Items.Count - 1;\n\n UpdatePrevNextItem();\n\n if (tag != null)\n item.AddTag(tag, pluginName);\n };\n\n decoder.ScrapeItem(item);\n\n UIInvokeIfRequired(() =>\n {\n System.Windows.Data.BindingOperations.EnableCollectionSynchronization(item.ExternalAudioStreams, item.lockExternalStreams);\n System.Windows.Data.BindingOperations.EnableCollectionSynchronization(item.ExternalVideoStreams, item.lockExternalStreams);\n System.Windows.Data.BindingOperations.EnableCollectionSynchronization(item.ExternalSubtitlesStreamsAll, item.lockExternalStreams);\n });\n }\n}\n"], ["/LLPlayer/LLPlayer/Controls/WordPopup.xaml.cs", "using System.ComponentModel;\nusing System.Diagnostics;\nusing System.Runtime.CompilerServices;\nusing System.Windows;\nusing System.Windows.Controls;\nusing System.Windows.Controls.Primitives;\nusing System.Windows.Input;\nusing System.Windows.Threading;\nusing FlyleafLib;\nusing FlyleafLib.MediaPlayer;\nusing FlyleafLib.MediaPlayer.Translation;\nusing FlyleafLib.MediaPlayer.Translation.Services;\nusing LLPlayer.Extensions;\nusing LLPlayer.Services;\n\nnamespace LLPlayer.Controls;\n\npublic partial class WordPopup : UserControl, INotifyPropertyChanged\n{\n public FlyleafManager FL { get; }\n private ITranslateService? _translateService;\n private readonly TranslateServiceFactory _translateServiceFactory;\n private PDICSender? _pdicSender;\n private readonly Lock _locker = new();\n\n private string _clickedWords = string.Empty;\n private string _clickedText = string.Empty;\n\n private CancellationTokenSource? _cts;\n private readonly Dictionary _translateCache = new();\n private string? _lastSearchActionUrl;\n\n public WordPopup()\n {\n InitializeComponent();\n\n FL = ((App)Application.Current).Container.Resolve();\n\n FL.Player.PropertyChanged += Player_OnPropertyChanged;\n\n _translateServiceFactory = new TranslateServiceFactory(FL.PlayerConfig.Subtitles);\n\n FL.PlayerConfig.Subtitles.PropertyChanged += SubtitlesOnPropertyChanged;\n FL.PlayerConfig.Subtitles.TranslateChatConfig.PropertyChanged += ChatConfigOnPropertyChanged;\n FL.Player.SubtitlesManager[0].PropertyChanged += SubManagerOnPropertyChanged;\n FL.Player.SubtitlesManager[1].PropertyChanged += SubManagerOnPropertyChanged;\n FL.Config.Subs.PropertyChanged += SubsOnPropertyChanged;\n\n InitializeContextMenu();\n }\n\n public bool IsLoading { get; set => Set(ref field, value); }\n\n public bool IsOpen { get; set => Set(ref field, value); }\n\n public UIElement? PopupPlacementTarget { get; set => Set(ref field, value); }\n\n public double PopupHorizontalOffset { get; set => Set(ref field, value); }\n\n public double PopupVerticalOffset { get; set => Set(ref field, value); }\n\n public ContextMenu? PopupContextMenu { get; set => Set(ref field, value); }\n public ContextMenu? WordContextMenu { get; set => Set(ref field, value); }\n\n public bool IsSidebar { get; set; }\n\n private void SubtitlesOnPropertyChanged(object? sender, PropertyChangedEventArgs e)\n {\n switch (e.PropertyName)\n {\n case nameof(Config.SubtitlesConfig.TranslateWordServiceType):\n case nameof(Config.SubtitlesConfig.TranslateTargetLanguage):\n case nameof(Config.SubtitlesConfig.LanguageFallbackPrimary):\n // Apply translating settings changes\n Clear();\n break;\n }\n }\n\n private void ChatConfigOnPropertyChanged(object? sender, PropertyChangedEventArgs e)\n {\n // Apply translating settings changes\n Clear();\n }\n\n private void SubManagerOnPropertyChanged(object? sender, PropertyChangedEventArgs e)\n {\n if (e.PropertyName == nameof(SubManager.Language))\n {\n // Apply source language changes\n Clear();\n }\n }\n\n private void SubsOnPropertyChanged(object? sender, PropertyChangedEventArgs e)\n {\n if (e.PropertyName == nameof(AppConfigSubs.WordMenuActions))\n {\n // Apply word action settings changes\n InitializeContextMenu();\n }\n }\n\n private void Clear()\n {\n _translateService?.Dispose();\n _translateService = null;\n // clear cache\n _translateCache.Clear();\n }\n\n private void InitializeContextMenu()\n {\n var contextMenuStyle = (Style)FindResource(\"FlyleafContextMenu\");\n\n ContextMenu popupMenu = new()\n {\n Placement = PlacementMode.Mouse,\n Style = contextMenuStyle\n };\n\n SetupContextMenu(popupMenu);\n PopupContextMenu = popupMenu;\n\n ContextMenu wordMenu = new()\n {\n Placement = PlacementMode.Mouse,\n Style = contextMenuStyle\n };\n\n SetupContextMenu(wordMenu);\n WordContextMenu = wordMenu;\n }\n\n private void SetupContextMenu(ContextMenu contextMenu)\n {\n IEnumerable actions = FL.Config.Subs.WordMenuActions.Where(a => a.IsEnabled);\n foreach (IMenuAction action in actions)\n {\n MenuItem menuItem = new() { Header = action.Title };\n\n // Initialize default action at the top\n // TODO: L: want to make the default action bold.\n if (_lastSearchActionUrl == null && action is SearchMenuAction sa)\n {\n // Only word search available\n if (sa.Url.Contains(\"%w\") || sa.Url.Contains(\"%lw\"))\n {\n _lastSearchActionUrl = sa.Url;\n }\n }\n\n menuItem.Click += (o, args) =>\n {\n if (action is SearchMenuAction searchAction)\n {\n // Only word search available\n if (searchAction.Url.Contains(\"%w\") || searchAction.Url.Contains(\"%lw\"))\n {\n _lastSearchActionUrl = searchAction.Url;\n }\n\n OpenWeb(searchAction.Url, _clickedWords, _clickedText);\n }\n else if (action is ClipboardMenuAction clipboardAction)\n {\n CopyToClipboard(_clickedWords, clipboardAction.ToLower);\n }\n else if (action is ClipboardAllMenuAction clipboardAllAction)\n {\n CopyToClipboard(_clickedText, clipboardAllAction.ToLower);\n }\n };\n contextMenu.Items.Add(menuItem);\n }\n }\n\n // Click on video screen to close pop-up\n private void Player_OnPropertyChanged(object? sender, PropertyChangedEventArgs args)\n {\n if (args.PropertyName == nameof(FL.Player.Status) && FL.Player.Status == Status.Playing)\n {\n IsOpen = false;\n }\n }\n\n private async ValueTask TranslateWithCache(string text, WordClickedEventArgs e, CancellationToken token)\n {\n // already translated by translator\n if (e.IsTranslated)\n {\n return text;\n }\n\n var srcLang = FL.Player.SubtitlesManager[e.SubIndex].Language;\n var targetLang = FL.PlayerConfig.Subtitles.TranslateTargetLanguage;\n\n // Not set language or same language\n if (srcLang == null || srcLang.ISO6391 == targetLang.ToISO6391())\n {\n return text;\n }\n\n string lower = text.ToLower();\n if (_translateCache.TryGetValue(lower, out var cache))\n {\n return cache;\n }\n\n if (_translateService == null)\n {\n try\n {\n var service = _translateServiceFactory.GetService(FL.PlayerConfig.Subtitles.TranslateWordServiceType, true);\n service.Initialize(srcLang, targetLang);\n _translateService = service;\n }\n catch (TranslationConfigException ex)\n {\n Clear();\n ErrorDialogHelper.ShowKnownErrorPopup(ex.Message, KnownErrorType.Configuration);\n\n return text;\n }\n }\n\n try\n {\n string result = await _translateService.TranslateAsync(text, token);\n _translateCache.TryAdd(lower, result);\n\n return result;\n }\n catch (TranslationException ex)\n {\n ErrorDialogHelper.ShowUnknownErrorPopup(ex.Message, UnknownErrorType.Translation, ex);\n\n return text;\n }\n }\n\n public async Task OnWordClicked(WordClickedEventArgs e)\n {\n _clickedWords = e.Words;\n _clickedText = e.Text;\n\n if (FL.Player.Status == Status.Playing)\n {\n FL.Player.Pause();\n }\n\n if (e.Mouse is MouseClick.Left or MouseClick.Middle)\n {\n switch (FL.Config.Subs.WordClickActionMethod)\n {\n case WordClickAction.Clipboard:\n CopyToClipboard(e.Words);\n break;\n\n case WordClickAction.ClipboardAll:\n CopyToClipboard(e.Text);\n break;\n\n default:\n await Popup(e);\n break;\n }\n }\n else if (e.Mouse == MouseClick.Right)\n {\n WordContextMenu!.IsOpen = true;\n }\n }\n\n private async Task Popup(WordClickedEventArgs e)\n {\n if (FL.Config.Subs.WordCopyOnSelected)\n {\n CopyToClipboard(e.Words);\n }\n\n if (FL.Config.Subs.WordClickActionMethod == WordClickAction.PDIC && e.IsWord)\n {\n if (_pdicSender == null)\n {\n // Initialize PDIC lazily\n lock (_locker)\n {\n _pdicSender ??= ((App)Application.Current).Container.Resolve();\n }\n }\n\n _ = _pdicSender.SendWithPipe(e.Text, e.WordOffset + 1);\n return;\n }\n\n if (_cts != null)\n {\n // Canceled if running ahead\n _cts.Cancel();\n _cts.Dispose();\n }\n\n _cts = new CancellationTokenSource();\n\n string source = e.Words;\n\n IsLoading = true;\n\n SourceText.Text = source;\n TranslationText.Text = \"\";\n\n if (IsSidebar && e.Sender is SelectableTextBox)\n {\n var listBoxItem = UIHelper.FindParent(e.Sender);\n if (listBoxItem != null)\n {\n PopupPlacementTarget = listBoxItem;\n }\n }\n\n if (FL.Config.Subs.WordLastSearchOnSelected)\n {\n if (Keyboard.Modifiers == FL.Config.Subs.WordLastSearchOnSelectedModifier)\n {\n if (_lastSearchActionUrl != null)\n {\n OpenWeb(_lastSearchActionUrl, source);\n }\n }\n }\n\n IsOpen = true;\n\n await UpdatePosition();\n\n try\n {\n string result = await TranslateWithCache(source, e, _cts.Token);\n TranslationText.Text = result;\n IsLoading = false;\n }\n catch (OperationCanceledException)\n {\n return;\n }\n\n await UpdatePosition();\n\n return;\n\n async Task UpdatePosition()\n {\n // ActualWidth is updated asynchronously, so it needs to be offloaded in the Dispatcher.\n await Dispatcher.BeginInvoke(() =>\n {\n if (IsSidebar && PopupPlacementTarget != null)\n {\n // for sidebar\n PopupVerticalOffset = (((ListBoxItem)PopupPlacementTarget).ActualHeight - ActualHeight) / 2;\n PopupHorizontalOffset = -ActualWidth - 10;\n }\n else\n {\n // for subtitle\n PopupHorizontalOffset = e.WordsX + ((e.WordsWidth - ActualWidth) / 2);\n PopupVerticalOffset = -ActualHeight;\n }\n\n }, DispatcherPriority.Background);\n }\n }\n\n private void CloseButton_OnMouseLeftButtonUp(object sender, MouseButtonEventArgs e)\n {\n IsOpen = false;\n }\n\n private void SourceText_OnMouseLeftButtonUp(object sender, MouseButtonEventArgs e)\n {\n if (_lastSearchActionUrl != null)\n {\n OpenWeb(_lastSearchActionUrl, SourceText.Text);\n }\n }\n\n private static void CopyToClipboard(string text, bool toLower = false)\n {\n if (string.IsNullOrWhiteSpace(text))\n {\n return;\n }\n\n if (toLower)\n {\n text = text.ToLower();\n }\n\n // copy word\n try\n {\n // slow (10ms)\n //Clipboard.SetText(text);\n\n WindowsClipboard.SetText(text);\n }\n catch\n {\n // ignored\n }\n }\n\n private static void OpenWeb(string url, string words, string sentence = \"\")\n {\n if (url.Contains(\"%lw\"))\n {\n url = url.Replace(\"%lw\", Uri.EscapeDataString(words.ToLower()));\n }\n\n if (url.Contains(\"%w\"))\n {\n url = url.Replace(\"%w\", Uri.EscapeDataString(words));\n }\n\n if (url.Contains(\"%s\"))\n {\n url = url.Replace(\"%s\", Uri.EscapeDataString(sentence));\n }\n\n Process.Start(new ProcessStartInfo\n {\n FileName = url,\n UseShellExecute = true\n });\n }\n\n #region INotifyPropertyChanged\n public event PropertyChangedEventHandler? PropertyChanged;\n\n protected virtual void OnPropertyChanged([CallerMemberName] string? propertyName = null)\n {\n PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));\n }\n\n protected bool Set(ref T field, T value, [CallerMemberName] string? propertyName = null)\n {\n if (EqualityComparer.Default.Equals(field, value))\n return false;\n field = value;\n OnPropertyChanged(propertyName);\n return true;\n }\n #endregion\n}\n"], ["/LLPlayer/LLPlayer/ViewModels/TesseractDownloadDialogVM.cs", "using System.Collections.ObjectModel;\nusing System.Diagnostics;\nusing System.IO;\nusing System.Net.Http;\nusing FlyleafLib;\nusing LLPlayer.Extensions;\nusing LLPlayer.Services;\n\nnamespace LLPlayer.ViewModels;\n\n// TODO: L: consider commonization with WhisperModelDownloadDialogVM\npublic class TesseractDownloadDialogVM : Bindable, IDialogAware\n{\n public FlyleafManager FL { get; }\n\n public TesseractDownloadDialogVM(FlyleafManager fl)\n {\n FL = fl;\n\n List models = TesseractModelLoader.LoadAllModels();\n foreach (var model in models)\n {\n Models.Add(model);\n }\n\n SelectedModel = Models.First();\n\n CmdDownloadModel!.PropertyChanged += (sender, args) =>\n {\n if (args.PropertyName == nameof(CmdDownloadModel.IsExecuting))\n {\n OnPropertyChanged(nameof(CanDownload));\n OnPropertyChanged(nameof(CanDelete));\n }\n };\n }\n\n private const string TempExtension = \".tmp\";\n\n public ObservableCollection Models { get; set => Set(ref field, value); } = new();\n\n public TesseractModel SelectedModel\n {\n get;\n set\n {\n if (Set(ref field, value))\n {\n OnPropertyChanged(nameof(CanDownload));\n OnPropertyChanged(nameof(CanDelete));\n }\n }\n }\n\n public string StatusText { get; set => Set(ref field, value); } = \"Select a model to download.\";\n\n public long DownloadedSize { get; set => Set(ref field, value); }\n\n public bool CanDownload =>\n SelectedModel is { Downloaded: false } && !CmdDownloadModel!.IsExecuting;\n\n public bool CanDelete =>\n SelectedModel is { Downloaded: true } && !CmdDownloadModel!.IsExecuting;\n\n private CancellationTokenSource? _cts;\n\n public AsyncDelegateCommand? CmdDownloadModel => field ??= new AsyncDelegateCommand(async () =>\n {\n _cts = new CancellationTokenSource();\n CancellationToken token = _cts.Token;\n\n TesseractModel downloadModel = SelectedModel;\n string tempModelPath = downloadModel.ModelFilePath + TempExtension;\n\n try\n {\n if (downloadModel.Downloaded)\n {\n StatusText = $\"Model '{SelectedModel}' is already downloaded\";\n return;\n }\n\n // Delete temporary files if they exist (forces re-download)\n if (!DeleteTempModel())\n {\n StatusText = \"Failed to remove temp model\";\n return;\n }\n\n StatusText = $\"Model '{downloadModel}' downloading..\";\n\n long modelSize = await DownloadModelWithProgressAsync(downloadModel.LangCode, tempModelPath, token);\n\n // After successful download, rename temporary file to final file\n File.Move(tempModelPath, downloadModel.ModelFilePath);\n\n // Update downloaded status\n downloadModel.Size = modelSize;\n OnDownloadStatusChanged();\n\n StatusText = $\"Model '{SelectedModel}' is downloaded successfully\";\n }\n catch (OperationCanceledException ex)\n when (!ex.Message.StartsWith(\"The request was canceled due to the configured HttpClient.Timeout\"))\n {\n StatusText = \"Download canceled\";\n }\n catch (Exception ex)\n {\n StatusText = $\"Failed to download: {ex.Message}\";\n }\n finally\n {\n _cts = null;\n DeleteTempModel();\n }\n\n return;\n\n bool DeleteTempModel()\n {\n // Delete temporary files if they exist\n if (File.Exists(tempModelPath))\n {\n try\n {\n File.Delete(tempModelPath);\n }\n catch (Exception)\n {\n // ignore\n\n return false;\n }\n }\n\n return true;\n }\n }).ObservesCanExecute(() => CanDownload);\n\n public DelegateCommand? CmdCancelDownloadModel => field ??= new(() =>\n {\n _cts?.Cancel();\n });\n\n public DelegateCommand? CmdDeleteModel => field ??= new DelegateCommand(() =>\n {\n try\n {\n StatusText = $\"Model '{SelectedModel}' deleting...\";\n\n TesseractModel deleteModel = SelectedModel;\n\n // Delete model file if exists\n if (File.Exists(deleteModel.ModelFilePath))\n {\n File.Delete(deleteModel.ModelFilePath);\n }\n\n // Update downloaded status\n deleteModel.Size = 0;\n OnDownloadStatusChanged();\n\n StatusText = $\"Model '{deleteModel}' is deleted successfully\";\n }\n catch (Exception ex)\n {\n StatusText = $\"Failed to delete model: {ex.Message}\";\n }\n }).ObservesCanExecute(() => CanDelete);\n\n public DelegateCommand? CmdOpenFolder => field ??= new(() =>\n {\n if (!Directory.Exists(TesseractModel.ModelsDirectory))\n return;\n\n Process.Start(new ProcessStartInfo\n {\n FileName = TesseractModel.ModelsDirectory,\n UseShellExecute = true,\n CreateNoWindow = true\n });\n });\n\n private void OnDownloadStatusChanged()\n {\n OnPropertyChanged(nameof(CanDownload));\n OnPropertyChanged(nameof(CanDelete));\n }\n\n private async Task DownloadModelWithProgressAsync(string langCode, string destinationPath, CancellationToken token)\n {\n DownloadedSize = 0;\n\n using HttpClient httpClient = new();\n httpClient.Timeout = TimeSpan.FromSeconds(10);\n\n using var response = await httpClient.GetAsync($\"https://github.com/tesseract-ocr/tessdata/raw/refs/heads/main/{langCode}.traineddata\", HttpCompletionOption.ResponseHeadersRead, token);\n\n response.EnsureSuccessStatusCode();\n\n await using Stream modelStream = await response.Content.ReadAsStreamAsync(token);\n await using FileStream fileWriter = File.OpenWrite(destinationPath);\n\n byte[] buffer = new byte[1024 * 128];\n int bytesRead;\n long totalBytesRead = 0;\n\n Stopwatch sw = new();\n sw.Start();\n\n while ((bytesRead = await modelStream.ReadAsync(buffer, 0, buffer.Length, token)) > 0)\n {\n await fileWriter.WriteAsync(buffer, 0, bytesRead, token);\n totalBytesRead += bytesRead;\n\n if (sw.Elapsed > TimeSpan.FromMilliseconds(50))\n {\n DownloadedSize = totalBytesRead;\n sw.Restart();\n }\n\n token.ThrowIfCancellationRequested();\n }\n\n return totalBytesRead;\n }\n\n #region IDialogAware\n public string Title { get; set => Set(ref field, value); } = $\"Tesseract Downloader - {App.Name}\";\n public double WindowWidth { get; set => Set(ref field, value); } = 400;\n public double WindowHeight { get; set => Set(ref field, value); } = 200;\n\n public bool CanCloseDialog() => !CmdDownloadModel!.IsExecuting;\n public void OnDialogClosed() { }\n public void OnDialogOpened(IDialogParameters parameters) { }\n public DialogCloseListener RequestClose { get; }\n #endregion IDialogAware\n}\n"], ["/LLPlayer/FlyleafLib/MediaFramework/RunThreadBase.cs", "using System.Threading;\n\nusing static FlyleafLib.Logger;\n\nnamespace FlyleafLib.MediaFramework;\n\npublic abstract class RunThreadBase : NotifyPropertyChanged\n{\n Status _Status = Status.Stopped;\n public Status Status {\n get => _Status;\n set\n {\n lock (lockStatus)\n {\n if (CanDebug && _Status != Status.QueueFull && value != Status.QueueFull && _Status != Status.QueueEmpty && value != Status.QueueEmpty)\n Log.Debug($\"{_Status} -> {value}\");\n\n _Status = value;\n }\n }\n }\n public bool IsRunning {\n get\n {\n bool ret = false;\n lock (lockStatus) ret = thread != null && thread.IsAlive && Status != Status.Paused;\n return ret;\n }\n }\n\n public bool CriticalArea { get; protected set; }\n public bool Disposed { get; protected set; } = true;\n public int UniqueId { get; protected set; } = -1;\n public bool PauseOnQueueFull{ get; set; }\n\n protected Thread thread;\n protected AutoResetEvent threadARE = new(false);\n protected string threadName {\n get => _threadName;\n set\n {\n _threadName = value;\n Log = new LogHandler((\"[#\" + UniqueId + \"]\").PadRight(8, ' ') + $\" [{threadName}] \");\n }\n }\n string _threadName;\n\n internal LogHandler Log;\n internal object lockActions = new();\n internal object lockStatus = new();\n\n public RunThreadBase(int uniqueId = -1)\n => UniqueId = uniqueId == -1 ? Utils.GetUniqueId() : uniqueId;\n\n public void Pause()\n {\n lock (lockActions)\n {\n lock (lockStatus)\n {\n PauseOnQueueFull = false;\n\n if (Disposed || thread == null || !thread.IsAlive || Status == Status.Stopping || Status == Status.Stopped || Status == Status.Ended || Status == Status.Pausing || Status == Status.Paused) return;\n Status = Status.Pausing;\n }\n while (Status == Status.Pausing) Thread.Sleep(5);\n }\n }\n public void Start()\n {\n lock (lockActions)\n {\n int retries = 1;\n while (thread != null && thread.IsAlive && CriticalArea)\n {\n Thread.Sleep(5); // use small steps to re-check CriticalArea (demuxer can have 0 packets again after processing the received ones)\n retries++;\n if (retries > 16)\n {\n if (CanTrace) Log.Trace($\"Start() exhausted\");\n return;\n }\n }\n\n lock (lockStatus)\n {\n if (Disposed) return;\n\n PauseOnQueueFull = false;\n\n if (Status == Status.Draining) while (Status != Status.Draining) Thread.Sleep(3);\n if (Status == Status.Stopping) while (Status != Status.Stopping) Thread.Sleep(3);\n if (Status == Status.Pausing) while (Status != Status.Pausing) Thread.Sleep(3);\n\n if (Status == Status.Ended) return;\n\n if (Status == Status.Paused)\n {\n threadARE.Set();\n while (Status == Status.Paused) Thread.Sleep(3);\n return;\n }\n\n if (thread != null && thread.IsAlive) return; // might re-check CriticalArea\n\n thread = new Thread(() => Run());\n Status = Status.Running;\n\n thread.Name = $\"[#{UniqueId}] [{threadName}]\"; thread.IsBackground= true; thread.Start();\n while (!thread.IsAlive) { if (CanTrace) Log.Trace(\"Waiting thread to come up\"); Thread.Sleep(3); }\n }\n }\n }\n public void Stop()\n {\n lock (lockActions)\n {\n lock (lockStatus)\n {\n PauseOnQueueFull = false;\n\n if (Disposed || thread == null || !thread.IsAlive || Status == Status.Stopping || Status == Status.Stopped || Status == Status.Ended) return;\n if (Status == Status.Pausing) while (Status != Status.Pausing) Thread.Sleep(3);\n Status = Status.Stopping;\n threadARE.Set();\n }\n\n while (Status == Status.Stopping && thread != null && thread.IsAlive) Thread.Sleep(5);\n }\n }\n\n protected void Run()\n {\n if (CanDebug) Log.Debug($\"Thread started ({Status})\");\n\n do\n {\n RunInternal();\n\n if (Status == Status.Pausing)\n {\n threadARE.Reset();\n Status = Status.Paused;\n threadARE.WaitOne();\n if (Status == Status.Paused)\n {\n if (CanDebug) Log.Debug($\"{_Status} -> {Status.Running}\");\n _Status = Status.Running;\n }\n }\n\n } while (Status == Status.Running);\n\n if (Status != Status.Ended) Status = Status.Stopped;\n\n if (CanDebug) Log.Debug($\"Thread stopped ({Status})\");\n }\n protected abstract void RunInternal();\n}\n\npublic enum Status\n{\n Opening,\n\n Stopping,\n Stopped,\n\n Pausing,\n Paused,\n\n Running,\n QueueFull,\n QueueEmpty,\n Draining,\n\n Ended\n}\n"], ["/LLPlayer/LLPlayer/ViewModels/ErrorDialogVM.cs", "using System.Collections;\nusing System.Diagnostics.CodeAnalysis;\nusing System.Media;\nusing System.Text;\nusing System.Windows;\nusing LLPlayer.Extensions;\nusing LLPlayer.Services;\n\nnamespace LLPlayer.ViewModels;\n\npublic class ErrorDialogVM : Bindable, IDialogAware\n{\n public FlyleafManager FL { get; }\n\n public ErrorDialogVM(FlyleafManager fl)\n {\n FL = fl;\n }\n\n public string Message { get; set => Set(ref field, value); } = \"\";\n\n public Exception? Exception\n {\n get;\n set\n {\n if (Set(ref field, value))\n {\n OnPropertyChanged(nameof(HasException));\n ExceptionDetail = value == null ? \"\" : GetExceptionWithAllData(value);\n }\n }\n }\n public bool HasException => Exception != null;\n\n public string ExceptionDetail { get; set => Set(ref field, value); } = \"\";\n\n public bool IsUnknown\n {\n get;\n set\n {\n if (Set(ref field, value))\n {\n OnPropertyChanged(nameof(ErrorTitle));\n }\n }\n }\n\n public string ErrorType\n {\n get;\n set\n {\n if (Set(ref field, value))\n {\n OnPropertyChanged(nameof(ErrorTitle));\n }\n }\n } = \"\";\n\n public string ErrorTitle => IsUnknown ? $\"{ErrorType} Unknown Error\" : $\"{ErrorType} Error\";\n\n [field: AllowNull, MaybeNull]\n public DelegateCommand CmdCopyMessage => field ??= new(() =>\n {\n string text = $\"\"\"\n [{ErrorTitle}]\n {Message}\n \"\"\";\n\n if (Exception != null)\n {\n text += $\"\"\"\n\n\n ```\n {ExceptionDetail}\n ```\n \"\"\";\n }\n\n text += $\"\"\"\n\n\n Version: {App.Version}, CommitHash: {App.CommitHash}\n OS Architecture: {App.OSArchitecture}, Process Architecture: {App.ProcessArchitecture}\n \"\"\";\n Clipboard.SetText(text);\n });\n\n [field: AllowNull, MaybeNull]\n public DelegateCommand CmdCloseDialog => field ??= new(() =>\n {\n RequestClose.Invoke(ButtonResult.OK);\n });\n\n private static string GetExceptionWithAllData(Exception ex)\n {\n string exceptionInfo = ex.ToString();\n\n // Collect all Exception.Data to dictionary\n Dictionary allData = new();\n CollectExceptionData(ex, allData);\n\n if (allData.Count == 0)\n {\n // not found Exception.Data\n return exceptionInfo;\n }\n\n // found Exception.Data\n StringBuilder sb = new();\n sb.Append(exceptionInfo);\n\n sb.AppendLine();\n sb.AppendLine();\n sb.AppendLine(\"---------------------- All Exception Data ----------------------\");\n foreach (var (i, entry) in allData.Index())\n {\n sb.AppendLine($\" [{entry.Key}]: {entry.Value}\");\n if (i != allData.Count - 1)\n {\n sb.AppendLine();\n }\n }\n\n return sb.ToString();\n }\n\n private static void CollectExceptionData(Exception? ex, Dictionary allData)\n {\n if (ex == null) return;\n\n foreach (DictionaryEntry entry in ex.Data)\n {\n if (entry.Value != null)\n {\n allData.TryAdd(entry.Key, entry.Value);\n }\n }\n\n if (ex.InnerException != null)\n {\n CollectExceptionData(ex.InnerException, allData);\n }\n\n if (ex is AggregateException aggregateEx)\n {\n foreach (var innerEx in aggregateEx.InnerExceptions)\n {\n CollectExceptionData(innerEx, allData);\n }\n }\n }\n\n #region IDialogAware\n public string Title => \"Error Occured\";\n public double WindowWidth { get; set => Set(ref field, value); } = 450;\n public double WindowHeight { get; set => Set(ref field, value); } = 250;\n\n public bool CanCloseDialog() => true;\n\n public void OnDialogClosed()\n {\n FL.Player.Activity.Timeout = _prevTimeout;\n FL.Player.Activity.IsEnabled = true;\n }\n\n private int _prevTimeout;\n\n public void OnDialogOpened(IDialogParameters parameters)\n {\n _prevTimeout = FL.Player.Activity.Timeout;\n FL.Player.Activity.Timeout = 0;\n FL.Player.Activity.IsEnabled = false;\n\n switch (parameters.GetValue(\"type\"))\n {\n case \"known\":\n Message = parameters.GetValue(\"message\");\n ErrorType = parameters.GetValue(\"errorType\");\n IsUnknown = false;\n\n break;\n case \"unknown\":\n Message = parameters.GetValue(\"message\");\n ErrorType = parameters.GetValue(\"errorType\");\n IsUnknown = true;\n\n if (parameters.ContainsKey(\"exception\"))\n {\n Exception = parameters.GetValue(\"exception\");\n }\n\n WindowHeight += 100;\n WindowWidth += 20;\n\n // Play alert sound\n SystemSounds.Hand.Play();\n\n break;\n }\n }\n\n public DialogCloseListener RequestClose { get; }\n #endregion IDialogAware\n}\n"], ["/LLPlayer/LLPlayer/Services/FlyleafManager.cs", "using System.IO;\nusing System.Windows;\nusing FlyleafLib;\nusing FlyleafLib.Controls.WPF;\nusing FlyleafLib.MediaPlayer;\n\nnamespace LLPlayer.Services;\n\npublic class FlyleafManager\n{\n public Player Player { get; }\n public Config PlayerConfig => Player.Config;\n public FlyleafHost? FlyleafHost => Player.Host as FlyleafHost;\n public AppConfig Config { get; }\n public AppActions Action { get; }\n\n public AudioEngine AudioEngine => Engine.Audio;\n public EngineConfig ConfigEngine => Engine.Config;\n\n public FlyleafManager(Player player, IDialogService dialogService)\n {\n Player = player;\n\n // Load app configuration at this time\n Config = LoadAppConfig();\n Action = new AppActions(Player, Config, dialogService);\n }\n\n private AppConfig LoadAppConfig()\n {\n AppConfig? config = null;\n\n if (File.Exists(App.AppConfigPath))\n {\n try\n {\n config = AppConfig.Load(App.AppConfigPath);\n\n if (config.Version != App.Version)\n {\n config.Version = App.Version;\n config.Save(App.AppConfigPath);\n }\n }\n catch (Exception ex)\n {\n MessageBox.Show($\"Cannot load AppConfig from {Path.GetFileName(App.AppConfigPath)}, Please review the settings or delete the config file. Error details are recorded in {Path.GetFileName(App.CrashLogPath)}.\");\n try\n {\n File.WriteAllText(App.CrashLogPath, \"AppConfig Loading Error: \" + ex);\n }\n catch\n {\n // ignored\n }\n\n Application.Current.Shutdown();\n }\n }\n\n if (config == null)\n {\n config = new AppConfig();\n }\n config.Initialize(this);\n\n return config;\n }\n}\n"], ["/LLPlayer/FlyleafLib/Utils/ZOrderHandler.cs", "using System;\nusing System.Collections.Generic;\nusing System.Diagnostics;\nusing System.Linq;\nusing System.Runtime.InteropServices;\nusing System.Threading.Tasks;\nusing System.Windows.Interop;\nusing System.Windows;\n\nnamespace FlyleafLib;\n\npublic static partial class Utils\n{\n public static class ZOrderHandler\n {\n [DllImport(\"user32.dll\", SetLastError = true)]\n public static extern IntPtr GetWindow(IntPtr hWnd, uint uCmd);\n\n enum GetWindow_Cmd : uint {\n GW_HWNDFIRST = 0,\n GW_HWNDLAST = 1,\n GW_HWNDNEXT = 2,\n GW_HWNDPREV = 3,\n GW_OWNER = 4,\n GW_CHILD = 5,\n GW_ENABLEDPOPUP = 6\n }\n\n public class ZOrder\n {\n public string window;\n public int order;\n }\n\n public class Owner\n {\n static int uniqueNameId = 0;\n\n public List CurZOrder = null;\n public List SavedZOrder = null;\n\n public Window Window;\n public IntPtr WindowHwnd;\n\n Dictionary WindowNamesHandles = new();\n Dictionary WindowNamesWindows = new();\n\n public Owner(Window window, IntPtr windowHwnd)\n {\n Window = window;\n WindowHwnd = windowHwnd;\n\n // TBR: Stand alone\n //if (Window.Owner != null)\n // Window.Owner.StateChanged += Window_StateChanged;\n //else\n\n Window.StateChanged += Window_StateChanged;\n lastState = Window.WindowState;\n\n // TBR: Minimize with WindowsKey + D for example will not fire (none of those)\n //HwndSource source = HwndSource.FromHwnd(WindowHwnd);\n //source.AddHook(new HwndSourceHook(WndProc));\n }\n\n public const Int32 WM_SYSCOMMAND = 0x112;\n public const Int32 SC_MAXIMIZE = 0xF030;\n private const int SC_MINIMIZE = 0xF020;\n private IntPtr WndProc(IntPtr hwnd, int msg, IntPtr wParam, IntPtr lParam, ref bool handled)\n {\n if (msg == WM_SYSCOMMAND)\n {\n if (wParam.ToInt32() == SC_MINIMIZE)\n {\n Save();\n //handled = true;\n }\n }\n return IntPtr.Zero;\n }\n\n private IntPtr GetHandle(Window window)\n {\n IntPtr hwnd = IntPtr.Zero;\n\n if (string.IsNullOrEmpty(window.Name))\n {\n hwnd = new WindowInteropHelper(window).Handle;\n window.Name = \"Zorder\" + uniqueNameId++.ToString();\n WindowNamesHandles.Add(window.Name, hwnd);\n WindowNamesWindows.Add(window.Name, window);\n }\n else if (!WindowNamesHandles.ContainsKey(window.Name))\n {\n hwnd = new WindowInteropHelper(window).Handle;\n WindowNamesHandles.Add(window.Name, hwnd);\n WindowNamesWindows.Add(window.Name, window);\n }\n else\n hwnd = WindowNamesHandles[window.Name];\n\n return hwnd;\n }\n\n WindowState lastState = WindowState.Normal;\n\n private void Window_StateChanged(object sender, EventArgs e)\n {\n if (Window.OwnedWindows.Count < 2)\n return;\n\n if (lastState == WindowState.Minimized)\n Restore();\n else if (Window.WindowState == WindowState.Minimized)\n Save();\n\n lastState = Window.WindowState;\n }\n\n public void Save()\n {\n SavedZOrder = GetZOrder();\n Debug.WriteLine(\"Saved\");\n DumpZOrder(SavedZOrder);\n }\n\n public void Restore()\n {\n if (SavedZOrder == null)\n return;\n\n Task.Run(() =>\n {\n System.Threading.Thread.Sleep(50);\n\n Application.Current.Dispatcher.Invoke(() =>\n {\n for (int i=0; i GetZOrder()\n {\n List zorders = new();\n\n foreach(Window window in Window.OwnedWindows)\n {\n ZOrder zorder = new();\n IntPtr curHwnd = GetHandle(window);\n if (curHwnd == IntPtr.Zero)\n continue;\n\n zorder.window = window.Name;\n\n while ((curHwnd = GetWindow(curHwnd, (uint)GetWindow_Cmd.GW_HWNDNEXT)) != WindowHwnd && curHwnd != IntPtr.Zero)\n zorder.order++;\n\n zorders.Add(zorder);\n }\n\n return zorders.OrderBy((o) => o.order).ToList();\n }\n\n public void DumpZOrder(List zorders)\n {\n for (int i=0; i Owners = new();\n\n public static void Register(Window window)\n {\n IntPtr hwnd = new WindowInteropHelper(window).Handle;\n if (Owners.ContainsKey(hwnd))\n return;\n\n Owners.Add(hwnd, new Owner(window, hwnd));\n }\n }\n}\n"], ["/LLPlayer/FlyleafLib/MediaFramework/MediaRenderer/Renderer.PixelShader.cs", "using System.Collections.Generic;\nusing System.Threading;\n\nusing Vortice.Direct3D;\nusing Vortice.Direct3D11;\nusing Vortice.DXGI;\nusing Vortice.Mathematics;\nusing Vortice;\n\nusing FlyleafLib.MediaFramework.MediaDecoder;\nusing FlyleafLib.MediaFramework.MediaFrame;\n\nusing static FlyleafLib.Logger;\n\nusing ID3D11Texture2D = Vortice.Direct3D11.ID3D11Texture2D;\n\nnamespace FlyleafLib.MediaFramework.MediaRenderer;\n\nunsafe public partial class Renderer\n{\n static string[] pixelOffsets = new[] { \"r\", \"g\", \"b\", \"a\" };\n enum PSDefines { HDR, HLG, YUV }\n enum PSCase : int\n {\n None,\n HWD3D11VP,\n HWD3D11VPZeroCopy,\n HW,\n HWZeroCopy,\n\n RGBPacked,\n RGBPacked2,\n RGBPlanar,\n\n YUVPacked,\n YUVSemiPlanar,\n YUVPlanar,\n SwsScale\n }\n\n bool checkHDR;\n PSCase curPSCase;\n string curPSUniqueId;\n float curRatio = 1.0f;\n string prevPSUniqueId;\n internal bool forceNotExtractor; // TBR: workaround until we separate the Extractor?\n\n Texture2DDescription[] textDesc= new Texture2DDescription[4];\n ShaderResourceViewDescription[] srvDesc = new ShaderResourceViewDescription[4];\n SubresourceData[] subData = new SubresourceData[1];\n Box cropBox = new(0, 0, 0, 0, 0, 1);\n\n void InitPS()\n {\n for (int i=0; iflags & PixFmtFlags.Be) == 0) // We currently force SwsScale for BE (RGBA64/BGRA64 BE noted that could work as is?*)\n {\n if (videoProcessor == VideoProcessors.D3D11)\n {\n if (oldVP != videoProcessor)\n {\n VideoDecoder.DisposeFrames();\n Config.Video.Filters[VideoFilters.Brightness].Value = Config.Video.Filters[VideoFilters.Brightness].DefaultValue;\n Config.Video.Filters[VideoFilters.Contrast].Value = Config.Video.Filters[VideoFilters.Contrast].DefaultValue;\n }\n\n inputColorSpace = new()\n {\n Usage = 0,\n RGB_Range = VideoStream.AVStream->codecpar->color_range == AVColorRange.Jpeg ? (uint) 0 : 1,\n YCbCr_Matrix = VideoStream.ColorSpace != ColorSpace.BT601 ? (uint) 1 : 0,\n YCbCr_xvYCC = 0,\n Nominal_Range = VideoStream.AVStream->codecpar->color_range == AVColorRange.Jpeg ? (uint) 2 : 1\n };\n\n vpov?.Dispose();\n vd1.CreateVideoProcessorOutputView(backBuffer, vpe, vpovd, out vpov);\n vc.VideoProcessorSetStreamColorSpace(vp, 0, inputColorSpace);\n vc.VideoProcessorSetOutputColorSpace(vp, outputColorSpace);\n\n if (child != null)\n {\n child.vpov?.Dispose();\n vd1.CreateVideoProcessorOutputView(child.backBuffer, vpe, vpovd, out child.vpov);\n }\n\n if (VideoDecoder.ZeroCopy)\n curPSCase = PSCase.HWD3D11VPZeroCopy;\n else\n {\n curPSCase = PSCase.HWD3D11VP;\n\n textDesc[0].BindFlags |= BindFlags.RenderTarget;\n\n cropBox.Right = (int)VideoStream.Width;\n textDesc[0].Width = VideoStream.Width;\n cropBox.Bottom = (int)VideoStream.Height;\n textDesc[0].Height = VideoStream.Height;\n textDesc[0].Format = VideoDecoder.textureFFmpeg.Description.Format;\n }\n }\n else if (!Config.Video.SwsForce || VideoDecoder.VideoAccelerated) // FlyleafVP\n {\n List defines = new();\n\n if (oldVP != videoProcessor)\n {\n VideoDecoder.DisposeFrames();\n Config.Video.Filters[VideoFilters.Brightness].Value = Config.Video.Filters[VideoFilters.Brightness].Minimum + ((Config.Video.Filters[VideoFilters.Brightness].Maximum - Config.Video.Filters[VideoFilters.Brightness].Minimum) / 2);\n Config.Video.Filters[VideoFilters.Contrast].Value = Config.Video.Filters[VideoFilters.Contrast].Minimum + ((Config.Video.Filters[VideoFilters.Contrast].Maximum - Config.Video.Filters[VideoFilters.Contrast].Minimum) / 2);\n }\n\n if (IsHDR)\n {\n // TBR: It currently works better without it\n //if (VideoStream.ColorTransfer == AVColorTransferCharacteristic.AVCOL_TRC_ARIB_STD_B67)\n //{\n // defines.Add(PSDefines.HLG.ToString());\n // curPSUniqueId += \"g\";\n //}\n\n curPSUniqueId += \"h\";\n defines.Add(PSDefines.HDR.ToString());\n psBufferData.coefsIndex = 0;\n UpdateHDRtoSDR(false);\n }\n else\n psBufferData.coefsIndex = VideoStream.ColorSpace == ColorSpace.BT709 ? 1 : 2;\n\n for (int i=0; i 8)\n {\n srvDesc[0].Format = Format.R16_UNorm;\n srvDesc[1].Format = Format.R16G16_UNorm;\n }\n else\n {\n srvDesc[0].Format = Format.R8_UNorm;\n srvDesc[1].Format = Format.R8G8_UNorm;\n }\n\n if (VideoDecoder.ZeroCopy)\n {\n curPSCase = PSCase.HWZeroCopy;\n curPSUniqueId += ((int)curPSCase).ToString();\n\n for (int i=0; i 8)\n {\n curPSUniqueId += \"x\";\n textDesc[0].Format = srvDesc[0].Format = Format.R16G16B16A16_UNorm;\n }\n else if (VideoStream.PixelComp0Depth > 4)\n textDesc[0].Format = srvDesc[0].Format = Format.R8G8B8A8_UNorm; // B8G8R8X8_UNorm for 0[rgb]?\n\n string offsets = \"\";\n for (int i = 0; i < VideoStream.PixelComps.Length; i++)\n offsets += pixelOffsets[(int) (VideoStream.PixelComps[i].offset / Math.Ceiling(VideoStream.PixelComp0Depth / 8.0))];\n\n curPSUniqueId += offsets;\n\n if (VideoStream.PixelComps.Length > 3)\n SetPS(curPSUniqueId, $\"color = Texture1.Sample(Sampler, input.Texture).{offsets};\");\n else\n SetPS(curPSUniqueId, $\"color = float4(Texture1.Sample(Sampler, input.Texture).{offsets}, 1.0);\");\n }\n\n // [BGR/RGB]16\n else if (VideoStream.PixelPlanes == 1 && (\n VideoStream.PixelFormat == AVPixelFormat.Rgb444le||\n VideoStream.PixelFormat == AVPixelFormat.Bgr444le))\n {\n curPSCase = PSCase.RGBPacked2;\n curPSUniqueId += ((int)curPSCase).ToString();\n\n textDesc[0].Width = VideoStream.Width;\n textDesc[0].Height = VideoStream.Height;\n\n textDesc[0].Format = srvDesc[0].Format = Format.B4G4R4A4_UNorm;\n\n if (VideoStream.PixelFormat == AVPixelFormat.Rgb444le)\n {\n curPSUniqueId += \"a\";\n SetPS(curPSUniqueId, $\"color = float4(Texture1.Sample(Sampler, input.Texture).rgb, 1.0);\");\n }\n else\n {\n curPSUniqueId += \"b\";\n SetPS(curPSUniqueId, $\"color = float4(Texture1.Sample(Sampler, input.Texture).bgr, 1.0);\");\n }\n }\n\n // GBR(A) <=16\n else if (VideoStream.PixelPlanes > 2 && VideoStream.PixelComp0Depth <= 16)\n {\n curPSCase = PSCase.RGBPlanar;\n curPSUniqueId += ((int)curPSCase).ToString();\n\n for (int i=0; i 8)\n {\n curPSUniqueId += VideoStream.PixelComp0Depth;\n\n for (int i=0; i> 1);\n textDesc[0].Width = VideoStream.Width;\n textDesc[0].Height = VideoStream.Height;\n\n if (VideoStream.PixelComp0Depth > 8)\n {\n curPSUniqueId += $\"{VideoStream.Width}_\";\n textDesc[0].Format = Format.Y210;\n srvDesc[0].Format = Format.R16G16B16A16_UNorm;\n }\n else\n {\n curPSUniqueId += $\"{VideoStream.Width}\";\n textDesc[0].Format = Format.YUY2;\n srvDesc[0].Format = Format.R8G8B8A8_UNorm;\n }\n\n string header = @\"\n float posx = input.Texture.x - (texWidth * 0.25);\n float fx = frac(posx / texWidth);\n float pos1 = posx + ((0.5 - fx) * texWidth);\n float pos2 = posx + ((1.5 - fx) * texWidth);\n\n float4 c1 = Texture1.Sample(Sampler, float2(pos1, input.Texture.y));\n float4 c2 = Texture1.Sample(Sampler, float2(pos2, input.Texture.y));\n\n \";\n if (VideoStream.PixelFormat == AVPixelFormat.Yuyv422 ||\n VideoStream.PixelFormat == AVPixelFormat.Y210le)\n {\n curPSUniqueId += $\"a\";\n\n SetPS(curPSUniqueId, header + @\"\n float leftY = lerp(c1.r, c1.b, fx * 2);\n float rightY = lerp(c1.b, c2.r, fx * 2 - 1);\n float2 outUV = lerp(c1.ga, c2.ga, fx);\n float outY = lerp(leftY, rightY, step(0.5, fx));\n color = float4(outY, outUV, 1.0);\n \", defines);\n } else if (VideoStream.PixelFormat == AVPixelFormat.Yvyu422)\n {\n curPSUniqueId += $\"b\";\n\n SetPS(curPSUniqueId, header + @\"\n float leftY = lerp(c1.r, c1.b, fx * 2);\n float rightY = lerp(c1.b, c2.r, fx * 2 - 1);\n float2 outUV = lerp(c1.ag, c2.ag, fx);\n float outY = lerp(leftY, rightY, step(0.5, fx));\n color = float4(outY, outUV, 1.0);\n \", defines);\n } else if (VideoStream.PixelFormat == AVPixelFormat.Uyvy422)\n {\n curPSUniqueId += $\"c\";\n\n SetPS(curPSUniqueId, header + @\"\n float leftY = lerp(c1.g, c1.a, fx * 2);\n float rightY = lerp(c1.a, c2.g, fx * 2 - 1);\n float2 outUV = lerp(c1.rb, c2.rb, fx);\n float outY = lerp(leftY, rightY, step(0.5, fx));\n color = float4(outY, outUV, 1.0);\n \", defines);\n }\n }\n\n // Y_UV | nv12,nv21,nv24,nv42,p010le,p016le,p410le,p416le | (log2_chroma_w != log2_chroma_h / Interleaved) (? nv16,nv20le,p210le,p216le)\n // This covers all planes == 2 YUV (Semi-Planar)\n else if (VideoStream.PixelPlanes == 2) // && VideoStream.PixelSameDepth) && !VideoStream.PixelInterleaved)\n {\n curPSCase = PSCase.YUVSemiPlanar;\n curPSUniqueId += ((int)curPSCase).ToString();\n\n textDesc[0].Width = VideoStream.Width;\n textDesc[0].Height = VideoStream.Height;\n textDesc[1].Width = VideoStream.PixelFormatDesc->log2_chroma_w > 0 ? (VideoStream.Width + 1) >> VideoStream.PixelFormatDesc->log2_chroma_w : VideoStream.Width >> VideoStream.PixelFormatDesc->log2_chroma_w;\n textDesc[1].Height = VideoStream.PixelFormatDesc->log2_chroma_h > 0 ? (VideoStream.Height + 1) >> VideoStream.PixelFormatDesc->log2_chroma_h : VideoStream.Height >> VideoStream.PixelFormatDesc->log2_chroma_h;\n\n string offsets = VideoStream.PixelComps[1].offset > VideoStream.PixelComps[2].offset ? \"gr\" : \"rg\";\n\n if (VideoStream.PixelComp0Depth > 8)\n {\n curPSUniqueId += \"x\";\n textDesc[0].Format = srvDesc[0].Format = Format.R16_UNorm;\n textDesc[1].Format = srvDesc[1].Format = Format.R16G16_UNorm;\n }\n else\n {\n textDesc[0].Format = srvDesc[0].Format = Format.R8_UNorm;\n textDesc[1].Format = srvDesc[1].Format = Format.R8G8_UNorm;\n }\n\n SetPS(curPSUniqueId, @\"\n color = float4(\n Texture1.Sample(Sampler, input.Texture).r,\n Texture2.Sample(Sampler, input.Texture).\" + offsets + @\",\n 1.0);\n \", defines);\n }\n\n // Y_U_V\n else if (VideoStream.PixelPlanes > 2)\n {\n curPSCase = PSCase.YUVPlanar;\n curPSUniqueId += ((int)curPSCase).ToString();\n\n textDesc[0].Width = textDesc[3].Width = VideoStream.Width;\n textDesc[0].Height = textDesc[3].Height= VideoStream.Height;\n textDesc[1].Width = textDesc[2].Width = VideoStream.PixelFormatDesc->log2_chroma_w > 0 ? (VideoStream.Width + 1) >> VideoStream.PixelFormatDesc->log2_chroma_w : VideoStream.Width >> VideoStream.PixelFormatDesc->log2_chroma_w;\n textDesc[1].Height = textDesc[2].Height= VideoStream.PixelFormatDesc->log2_chroma_h > 0 ? (VideoStream.Height + 1) >> VideoStream.PixelFormatDesc->log2_chroma_h : VideoStream.Height >> VideoStream.PixelFormatDesc->log2_chroma_h;\n\n string shader = @\"\n color.r = Texture1.Sample(Sampler, input.Texture).r;\n color.g = Texture2.Sample(Sampler, input.Texture).r;\n color.b = Texture3.Sample(Sampler, input.Texture).r;\n \";\n\n if (VideoStream.PixelPlanes == 4)\n {\n curPSUniqueId += \"x\";\n\n shader += @\"\n color.a = Texture4.Sample(Sampler, input.Texture).r;\n \";\n }\n\n if (VideoStream.PixelComp0Depth > 8)\n {\n curPSUniqueId += VideoStream.PixelComp0Depth;\n\n for (int i=0; ipts * VideoStream.Timebase) - VideoDecoder.Demuxer.StartTime;\n if (CanTrace) Log.Trace($\"Processes {Utils.TicksToTime(mFrame.timestamp)}\");\n\n if (checkHDR)\n {\n // TODO Dolpy Vision / Vivid\n //var hdrSideDolpyDynamic = av_frame_get_side_data(frame, AVFrameSideDataType.AV_FRAME_DATA_DOVI_METADATA);\n\n var hdrSideDynamic = av_frame_get_side_data(frame, AVFrameSideDataType.DynamicHdrPlus);\n\n if (hdrSideDynamic != null && hdrSideDynamic->data != null)\n {\n hdrPlusData = (AVDynamicHDRPlus*) hdrSideDynamic->data;\n UpdateHDRtoSDR();\n }\n else\n {\n var lightSide = av_frame_get_side_data(frame, AVFrameSideDataType.ContentLightLevel);\n var displaySide = av_frame_get_side_data(frame, AVFrameSideDataType.MasteringDisplayMetadata);\n\n if (lightSide != null && lightSide->data != null && ((AVContentLightMetadata*)lightSide->data)->MaxCLL != 0)\n {\n lightData = *((AVContentLightMetadata*) lightSide->data);\n checkHDR = false;\n UpdateHDRtoSDR();\n }\n\n if (displaySide != null && displaySide->data != null && ((AVMasteringDisplayMetadata*)displaySide->data)->has_luminance != 0)\n {\n displayData = *((AVMasteringDisplayMetadata*) displaySide->data);\n checkHDR = false;\n UpdateHDRtoSDR();\n }\n }\n }\n\n if (curPSCase == PSCase.HWZeroCopy)\n {\n mFrame.srvs = new ID3D11ShaderResourceView[2];\n srvDesc[0].Texture2DArray.FirstArraySlice = srvDesc[1].Texture2DArray.FirstArraySlice = (uint) frame->data[1];\n\n mFrame.srvs[0] = Device.CreateShaderResourceView(VideoDecoder.textureFFmpeg, srvDesc[0]);\n mFrame.srvs[1] = Device.CreateShaderResourceView(VideoDecoder.textureFFmpeg, srvDesc[1]);\n\n mFrame.avFrame = av_frame_alloc();\n av_frame_move_ref(mFrame.avFrame, frame);\n return mFrame;\n }\n\n else if (curPSCase == PSCase.HW)\n {\n mFrame.textures = new ID3D11Texture2D[1];\n mFrame.srvs = new ID3D11ShaderResourceView[2];\n\n mFrame.textures[0] = Device.CreateTexture2D(textDesc[0]);\n context.CopySubresourceRegion(\n mFrame.textures[0], 0, 0, 0, 0, // dst\n VideoDecoder.textureFFmpeg, (uint) frame->data[1], // src\n cropBox); // crop decoder's padding\n\n mFrame.srvs[0] = Device.CreateShaderResourceView(mFrame.textures[0], srvDesc[0]);\n mFrame.srvs[1] = Device.CreateShaderResourceView(mFrame.textures[0], srvDesc[1]);\n }\n\n else if (curPSCase == PSCase.HWD3D11VPZeroCopy)\n {\n mFrame.avFrame = av_frame_alloc();\n av_frame_move_ref(mFrame.avFrame, frame);\n return mFrame;\n }\n\n else if (curPSCase == PSCase.HWD3D11VP)\n {\n mFrame.textures = new ID3D11Texture2D[1];\n mFrame.textures[0] = Device.CreateTexture2D(textDesc[0]);\n context.CopySubresourceRegion(\n mFrame.textures[0], 0, 0, 0, 0, // dst\n VideoDecoder.textureFFmpeg, (uint) frame->data[1], // src\n cropBox); // crop decoder's padding\n }\n\n else if (curPSCase == PSCase.SwsScale)\n {\n mFrame.textures = new ID3D11Texture2D[1];\n mFrame.srvs = new ID3D11ShaderResourceView[1];\n\n sws_scale(VideoDecoder.swsCtx, frame->data.ToRawArray(), frame->linesize.ToArray(), 0, frame->height, VideoDecoder.swsData.ToRawArray(), VideoDecoder.swsLineSize.ToArray());\n\n subData[0].DataPointer = VideoDecoder.swsData[0];\n subData[0].RowPitch = (uint)VideoDecoder.swsLineSize[0];\n\n mFrame.textures[0] = Device.CreateTexture2D(textDesc[0], subData);\n mFrame.srvs[0] = Device.CreateShaderResourceView(mFrame.textures[0], srvDesc[0]);\n }\n\n else\n {\n mFrame.textures = new ID3D11Texture2D[VideoStream.PixelPlanes];\n mFrame.srvs = new ID3D11ShaderResourceView[VideoStream.PixelPlanes];\n\n bool newRotationLinesize = false;\n for (int i = 0; i < VideoStream.PixelPlanes; i++)\n {\n if (frame->linesize[i] < 0)\n {\n // Negative linesize for vertical flipping [TBR: might required for HW as well? (SwsScale does that)] http://ffmpeg.org/doxygen/trunk/structAVFrame.html#aa52bfc6605f6a3059a0c3226cc0f6567\n newRotationLinesize = true;\n subData[0].RowPitch = (uint)(-1 * frame->linesize[i]);\n subData[0].DataPointer = frame->data[i];\n subData[0].DataPointer -= (nint)((subData[0].RowPitch * (VideoStream.Height - 1)));\n }\n else\n {\n newRotationLinesize = false;\n subData[0].RowPitch = (uint)frame->linesize[i];\n subData[0].DataPointer = frame->data[i];\n }\n\n if (subData[0].RowPitch < textDesc[i].Width) // Prevent reading more than the actual data (Access Violation #424)\n {\n av_frame_unref(frame);\n return null;\n }\n\n mFrame.textures[i] = Device.CreateTexture2D(textDesc[i], subData);\n mFrame.srvs[i] = Device.CreateShaderResourceView(mFrame.textures[i], srvDesc[i]);\n }\n\n if (newRotationLinesize != rotationLinesize)\n {\n rotationLinesize = newRotationLinesize;\n UpdateRotation(_RotationAngle);\n }\n }\n\n av_frame_unref(frame);\n return mFrame;\n }\n catch (Exception e)\n {\n av_frame_unref(frame);\n Log.Error($\"Failed to process frame ({e.Message})\");\n return null;\n }\n }\n\n void SetPS(string uniqueId, string sampleHLSL, List defines = null)\n {\n if (curPSUniqueId == prevPSUniqueId)\n return;\n\n ShaderPS?.Dispose();\n ShaderPS = ShaderCompiler.CompilePS(Device, uniqueId, sampleHLSL, defines);\n context.PSSetShader(ShaderPS);\n }\n}\n"], ["/LLPlayer/FlyleafLib/MediaFramework/MediaRenderer/Renderer.cs", "using System.Collections.Generic;\nusing System.Runtime.InteropServices;\nusing System.Windows;\n\nusing Vortice;\nusing Vortice.DXGI;\nusing Vortice.Direct3D11;\nusing Vortice.Mathematics;\n\nusing FlyleafLib.MediaFramework.MediaDecoder;\nusing FlyleafLib.MediaFramework.MediaFrame;\nusing FlyleafLib.MediaFramework.MediaStream;\n\nusing ID3D11Device = Vortice.Direct3D11.ID3D11Device;\n\nnamespace FlyleafLib.MediaFramework.MediaRenderer;\n\n/* TODO\n * 1) Attach on every frame video output configuration so we will not have to worry for video codec change etc.\n * this will fix also dynamic video stream change\n * we might have issue with bufRef / ffmpeg texture array on zero copy\n *\n * 2) Use different context/video processor for off rendering so we dont have to reset pixel shaders/viewports etc (review also rtvs for extractor)\n *\n * 3) Add Crop (Left/Right/Top/Bottom) -on Source- support per pixels (easy implemantation with D3D11VP, FlyleafVP requires more research)\n *\n * 4) Improve A/V Sync\n *\n * a. vsync / vblack\n * b. Present can cause a delay (based on device load), consider using more buffers for high frame rates that could minimize the delay\n * c. display refresh rate vs input rate, consider using max latency > 1 ?\n * d. frame drops\n *\n * swapChain.GetFrameStatistics(out var stats);\n * swapChain.LastPresentCount - stats.PresentCount;\n */\n\npublic partial class Renderer : NotifyPropertyChanged, IDisposable\n{\n public Config Config { get; private set;}\n public int ControlWidth { get; private set; }\n public int ControlHeight { get; private set; }\n internal IntPtr ControlHandle;\n\n internal Action\n SwapChainWinUIClbk;\n\n public ID3D11Device Device { get; private set; }\n public bool D3D11VPFailed => vc == null;\n public GPUAdapter GPUAdapter { get; private set; }\n public bool Disposed { get; private set; } = true;\n public bool SCDisposed { get; private set; } = true;\n public int MaxOffScreenTextures\n { get; set; } = 20;\n public VideoDecoder VideoDecoder { get; internal set; }\n public VideoStream VideoStream => VideoDecoder.VideoStream;\n\n public Viewport GetViewport { get; private set; }\n public event EventHandler ViewportChanged;\n\n public CornerRadius CornerRadius { get => cornerRadius; set { if (cornerRadius == value) return; cornerRadius = value; UpdateCornerRadius(); } }\n CornerRadius cornerRadius = new(0);\n CornerRadius zeroCornerRadius = new(0);\n\n public bool IsHDR { get => isHDR; private set { SetUI(ref _IsHDR, value); isHDR = value; } }\n bool _IsHDR, isHDR;\n\n public int SideXPixels { get; private set; }\n public int SideYPixels { get; private set; }\n\n public int PanXOffset { get => panXOffset; set => SetPanX(value); }\n int panXOffset;\n public void SetPanX(int panX, bool refresh = true)\n {\n lock(lockDevice)\n {\n panXOffset = panX;\n\n if (Disposed)\n return;\n\n SetViewport(refresh);\n }\n }\n\n public int PanYOffset { get => panYOffset; set => SetPanY(value); }\n int panYOffset;\n public void SetPanY(int panY, bool refresh = true)\n {\n lock(lockDevice)\n {\n panYOffset = panY;\n\n if (Disposed)\n return;\n\n SetViewport(refresh);\n }\n }\n\n public uint Rotation { get => _RotationAngle;set { lock (lockDevice) UpdateRotation(value); } }\n uint _RotationAngle;\n VideoProcessorRotation _d3d11vpRotation = VideoProcessorRotation.Identity;\n bool rotationLinesize; // if negative should be vertically flipped\n\n public bool HFlip { get => _HFlip;set { _HFlip = value; lock (lockDevice) UpdateRotation(_RotationAngle); } }\n bool _HFlip;\n\n public bool VFlip { get => _VFlip;set { _VFlip = value; lock (lockDevice) UpdateRotation(_RotationAngle); } }\n bool _VFlip;\n\n public VideoProcessors VideoProcessor { get => videoProcessor; private set => SetUI(ref videoProcessor, value); }\n VideoProcessors videoProcessor = VideoProcessors.Flyleaf;\n\n /// \n /// Zoom percentage (100% equals to 1.0)\n /// \n public double Zoom { get => zoom; set => SetZoom(value); }\n double zoom = 1;\n public void SetZoom(double zoom, bool refresh = true)\n {\n lock(lockDevice)\n {\n this.zoom = zoom;\n\n if (Disposed)\n return;\n\n SetViewport(refresh);\n }\n }\n\n public Point ZoomCenter { get => zoomCenter; set => SetZoomCenter(value); }\n Point zoomCenter = ZoomCenterPoint;\n public static Point ZoomCenterPoint = new(0.5, 0.5);\n public void SetZoomCenter(Point p, bool refresh = true)\n {\n lock(lockDevice)\n {\n zoomCenter = p;\n\n if (Disposed)\n return;\n\n if (refresh)\n SetViewport();\n }\n }\n public void SetZoomAndCenter(double zoom, Point p, bool refresh = true)\n {\n lock(lockDevice)\n {\n this.zoom = zoom;\n zoomCenter = p;\n\n if (Disposed)\n return;\n\n if (refresh)\n SetViewport();\n }\n }\n public void SetPanAll(int panX, int panY, uint rotation, double zoom, Point p, bool refresh = true)\n {\n lock(lockDevice)\n {\n panXOffset = panX;\n panYOffset = panY;\n this.zoom = zoom;\n zoomCenter = p;\n UpdateRotation(rotation, false);\n\n if (Disposed)\n return;\n\n if (refresh)\n SetViewport();\n }\n }\n\n public int UniqueId { get; private set; }\n\n public Dictionary\n Filters { get; set; }\n public VideoFrame LastFrame { get; set; }\n public RawRect VideoRect { get; set; }\n\n LogHandler Log;\n\n public Renderer(VideoDecoder videoDecoder, IntPtr handle = new IntPtr(), int uniqueId = -1)\n {\n UniqueId = uniqueId == -1 ? Utils.GetUniqueId() : uniqueId;\n VideoDecoder= videoDecoder;\n Config = videoDecoder.Config;\n Log = new LogHandler((\"[#\" + UniqueId + \"]\").PadRight(8, ' ') + \" [Renderer ] \");\n\n overlayTextureDesc = new()\n {\n Usage = ResourceUsage.Default,\n Width = 0,\n Height = 0,\n Format = Format.B8G8R8A8_UNorm,\n ArraySize = 1,\n MipLevels = 1,\n BindFlags = BindFlags.ShaderResource,\n SampleDescription = new SampleDescription(1, 0)\n };\n\n singleStageDesc = new Texture2DDescription()\n {\n Usage = ResourceUsage.Staging,\n Format = Format.B8G8R8A8_UNorm,\n ArraySize = 1,\n MipLevels = 1,\n BindFlags = BindFlags.None,\n CPUAccessFlags = CpuAccessFlags.Read,\n SampleDescription = new SampleDescription(1, 0),\n\n Width = 0,\n Height = 0\n };\n\n singleGpuDesc = new Texture2DDescription()\n {\n Usage = ResourceUsage.Default,\n Format = Format.B8G8R8A8_UNorm,\n ArraySize = 1,\n MipLevels = 1,\n BindFlags = BindFlags.RenderTarget | BindFlags.ShaderResource,\n SampleDescription = new SampleDescription(1, 0)\n };\n\n wndProcDelegate = new(WndProc);\n wndProcDelegatePtr = Marshal.GetFunctionPointerForDelegate(wndProcDelegate);\n ControlHandle = handle;\n Initialize();\n }\n\n #region Replica Renderer (Expiremental)\n public Renderer child; // allow access to child renderer (not safe)\n Renderer parent;\n public Renderer(Renderer renderer, IntPtr handle, int uniqueId = -1)\n {\n UniqueId = uniqueId == -1 ? Utils.GetUniqueId() : uniqueId;\n Log = new LogHandler((\"[#\" + UniqueId + \"]\").PadRight(8, ' ') + \" [Renderer Repl] \");\n\n renderer.child = this;\n parent = renderer;\n Config = renderer.Config;\n wndProcDelegate = new(WndProc);\n wndProcDelegatePtr = Marshal.GetFunctionPointerForDelegate(wndProcDelegate);\n ControlHandle = handle;\n }\n\n public void SetChildHandle(IntPtr handle)\n {\n lock (lockDevice)\n {\n if (child != null)\n DisposeChild();\n\n if (handle == IntPtr.Zero)\n return;\n\n child = new(this, handle, UniqueId);\n InitializeChildSwapChain();\n }\n }\n #endregion\n}\n"], ["/LLPlayer/LLPlayer/Extensions/FileHelper.cs", "using System.IO;\nusing static FlyleafLib.Utils;\n\nnamespace LLPlayer.Extensions;\n\npublic static class FileHelper\n{\n /// \n /// Retrieves the next and previous file from the specified file path.\n /// Select files with the same extension in the same folder, sorted in natural alphabetical order.\n /// Returns null if the next or previous file does not exist.\n /// \n /// \n /// \n /// \n /// \n /// \n public static (string? prev, string? next) GetNextAndPreviousFile(string filePath)\n {\n if (!File.Exists(filePath))\n {\n throw new FileNotFoundException(\"file does not exist\", filePath);\n }\n\n string? directory = Path.GetDirectoryName(filePath);\n string? extension = Path.GetExtension(filePath);\n\n if (string.IsNullOrEmpty(directory) || string.IsNullOrEmpty(extension))\n {\n throw new InvalidOperationException($\"filePath is invalid: {filePath}\");\n }\n\n // Get files with the same extension, ignoring case\n List foundFiles = Directory.GetFiles(directory, $\"*{extension}\")\n .Where(f => string.Equals(Path.GetExtension(f), extension, StringComparison.OrdinalIgnoreCase))\n .OrderBy(f => Path.GetFileName(f), new NaturalStringComparer())\n .ToList();\n\n if (foundFiles.Count == 0)\n {\n throw new InvalidOperationException($\"same extension file does not exist: {filePath}\");\n }\n\n int currentIndex = foundFiles.FindIndex(f => string.Equals(f, filePath, StringComparison.OrdinalIgnoreCase));\n if (currentIndex == -1)\n {\n throw new InvalidOperationException($\"current file does not exist: {filePath}\");\n }\n\n string? next = (currentIndex < foundFiles.Count - 1) ? foundFiles[currentIndex + 1] : null;\n string? prev = (currentIndex > 0) ? foundFiles[currentIndex - 1] : null;\n\n return (prev, next);\n }\n}\n"], ["/LLPlayer/LLPlayer/Controls/FlyleafBar.xaml.cs", "using System.Windows;\nusing System.Windows.Controls;\nusing System.Windows.Controls.Primitives;\nusing System.Windows.Documents;\nusing System.Windows.Input;\nusing System.Windows.Media;\nusing System.Windows.Media.Animation;\nusing FlyleafLib;\nusing FlyleafLib.MediaFramework.MediaDemuxer;\nusing FlyleafLib.MediaPlayer;\nusing LLPlayer.Services;\nusing Microsoft.Xaml.Behaviors;\n\nnamespace LLPlayer.Controls;\n\npublic partial class FlyleafBar : UserControl\n{\n public FlyleafManager FL { get; }\n\n public FlyleafBar()\n {\n InitializeComponent();\n\n FL = ((App)Application.Current).Container.Resolve();\n\n DataContext = this;\n\n // Do not hide the cursor when it is on the seek bar\n MouseEnter += OnMouseEnter;\n LostFocus += OnMouseLeave;\n MouseLeave += OnMouseLeave;\n\n FL.Config.PropertyChanged += (sender, args) =>\n {\n if (args.PropertyName == nameof(FL.Config.SeekBarShowOnlyMouseOver))\n {\n // Avoided a problem in which Opacity was set to 0 when switching settings and was not displayed.\n FL.Player.Activity.ForceFullActive();\n IsShowing = true;\n\n if (FL.Config.SeekBarShowOnlyMouseOver && !MyCard.IsMouseOver)\n {\n IsShowing = false;\n }\n }\n };\n\n FL.Player.Activity.PropertyChanged += (sender, args) =>\n {\n switch (args.PropertyName)\n {\n case nameof(FL.Player.Activity.IsEnabled):\n if (FL.Config.SeekBarShowOnlyMouseOver)\n {\n IsShowing = !FL.Player.Activity.IsEnabled || MyCard.IsMouseOver;\n }\n break;\n\n case nameof(FL.Player.Activity.Mode):\n if (!FL.Config.SeekBarShowOnlyMouseOver)\n {\n IsShowing = FL.Player.Activity.Mode == ActivityMode.FullActive;\n }\n break;\n }\n };\n\n if (FL.Config.SeekBarShowOnlyMouseOver)\n {\n // start in hide\n MyCard.Opacity = 0.01;\n }\n else\n {\n // start in show\n IsShowing = true;\n }\n }\n\n public bool IsShowing\n {\n get;\n set\n {\n if (field == value)\n return;\n\n field = value;\n if (value)\n {\n // Fade In\n MyCard.BeginAnimation(OpacityProperty, new DoubleAnimation()\n {\n BeginTime = TimeSpan.Zero,\n To = 1,\n Duration = new Duration(TimeSpan.FromMilliseconds(FL.Config.SeekBarFadeInTimeMs))\n });\n }\n else\n {\n // Fade Out\n MyCard.BeginAnimation(OpacityProperty, new DoubleAnimation()\n {\n BeginTime = TimeSpan.Zero,\n // TODO: L: needs to be almost transparent to receive MouseEnter events\n To = FL.Config.SeekBarShowOnlyMouseOver ? 0.01 : 0,\n Duration = new Duration(TimeSpan.FromMilliseconds(FL.Config.SeekBarFadeOutTimeMs))\n });\n }\n }\n }\n\n private void OnMouseLeave(object sender, RoutedEventArgs e)\n {\n if (FL.Config.SeekBarShowOnlyMouseOver && FL.Player.Activity.IsEnabled)\n {\n IsShowing = false;\n }\n else\n {\n SetActivity(true);\n }\n }\n\n private void OnMouseEnter(object sender, MouseEventArgs e)\n {\n if (FL.Config.SeekBarShowOnlyMouseOver && FL.Player.Activity.IsEnabled)\n {\n IsShowing = true;\n }\n else\n {\n SetActivity(false);\n }\n }\n\n private void SetActivity(bool isActive)\n {\n FL.Player.Activity.IsEnabled = isActive;\n }\n\n // Left-click on button to open context menu\n private void ButtonBase_OnClick(object sender, RoutedEventArgs e)\n {\n if (sender is not Button btn)\n {\n return;\n }\n\n if (btn.ContextMenu == null)\n {\n return;\n }\n\n if (btn.ContextMenu.PlacementTarget == null)\n {\n // Do not hide seek bar when context menu is displayed (register once)\n btn.ContextMenu.Opened += OnContextMenuOnOpened;\n btn.ContextMenu.Closed += OnContextMenuOnClosed;\n btn.ContextMenu.MouseMove += OnContextMenuOnMouseMove;\n btn.ContextMenu.PlacementTarget = btn;\n }\n btn.ContextMenu.IsOpen = true;\n }\n\n private void OnContextMenuOnOpened(object o, RoutedEventArgs args)\n {\n SetActivity(false);\n }\n\n private void OnContextMenuOnClosed(object o, RoutedEventArgs args)\n {\n SetActivity(true);\n }\n\n private void OnContextMenuOnMouseMove(object o, MouseEventArgs args)\n {\n // this is necessary to keep PopupMenu visible when opened in succession when SeekBarShowOnlyMouseOver\n SetActivity(false);\n }\n}\n\npublic class SliderToolTipBehavior : Behavior\n{\n private const int PaddingSize = 5;\n private Popup? _valuePopup;\n private TextBlock? _tooltipText;\n private Border? _tooltipBorder;\n private Track? _track;\n\n public static readonly DependencyProperty ChaptersProperty =\n DependencyProperty.Register(nameof(Chapters), typeof(IList), typeof(SliderToolTipBehavior), new PropertyMetadata(null));\n\n public IList? Chapters\n {\n get => (IList)GetValue(ChaptersProperty);\n set => SetValue(ChaptersProperty, value);\n }\n\n protected override void OnAttached()\n {\n base.OnAttached();\n\n _tooltipText = new TextBlock\n {\n Foreground = Brushes.White,\n FontSize = 12,\n TextAlignment = TextAlignment.Center\n };\n\n _tooltipBorder = new Border\n {\n Background = new SolidColorBrush(Colors.Black) { Opacity = 0.7 },\n CornerRadius = new CornerRadius(4),\n Padding = new Thickness(PaddingSize),\n Child = _tooltipText\n };\n\n _valuePopup = new Popup\n {\n AllowsTransparency = true,\n Placement = PlacementMode.Absolute,\n PlacementTarget = AssociatedObject,\n Child = _tooltipBorder\n };\n\n AssociatedObject.MouseMove += Slider_MouseMove;\n AssociatedObject.MouseLeave += Slider_MouseLeave;\n }\n\n protected override void OnDetaching()\n {\n base.OnDetaching();\n\n AssociatedObject.MouseMove -= Slider_MouseMove;\n AssociatedObject.MouseLeave -= Slider_MouseLeave;\n }\n\n private void Slider_MouseMove(object sender, MouseEventArgs e)\n {\n _track ??= (Track)AssociatedObject.Template.FindName(\"PART_Track\", AssociatedObject);\n Point pos = e.GetPosition(_track);\n double value = _track.ValueFromPoint(pos);\n TimeSpan hoverTime = TimeSpan.FromSeconds(value);\n\n string dateFormat = hoverTime.Hours >= 1 ? @\"hh\\:mm\\:ss\" : @\"mm\\:ss\";\n string timestamp = hoverTime.ToString(dateFormat);\n\n // TODO: L: Allow customizable chapter display functionality\n string? chapterTitle = GetChapterTitleAtTime(hoverTime);\n\n _tooltipText!.Inlines.Clear();\n if (chapterTitle != null)\n {\n _tooltipText.Inlines.Add(chapterTitle);\n _tooltipText.Inlines.Add(new LineBreak());\n }\n\n _tooltipText.Inlines.Add(timestamp);\n\n Window window = Window.GetWindow(AssociatedObject)!;\n Point cursorPoint = window.PointToScreen(e.GetPosition(window));\n Point sliderPoint = AssociatedObject.PointToScreen(default);\n\n // Fix for high dpi because PointToScreen returns physical coords\n cursorPoint.X /= Utils.NativeMethods.DpiX;\n cursorPoint.Y /= Utils.NativeMethods.DpiY;\n\n sliderPoint.X /= Utils.NativeMethods.DpiX;\n sliderPoint.Y /= Utils.NativeMethods.DpiY;\n\n // Display on top of slider near mouse\n _valuePopup!.HorizontalOffset = cursorPoint.X - (_tooltipText.ActualWidth + PaddingSize * 2) / 2;\n _valuePopup!.VerticalOffset = sliderPoint.Y - _tooltipBorder!.ActualHeight - 5;\n\n // display popup\n _valuePopup.IsOpen = true;\n }\n\n private void Slider_MouseLeave(object sender, MouseEventArgs e)\n {\n _valuePopup!.IsOpen = false;\n }\n\n private string? GetChapterTitleAtTime(TimeSpan time)\n {\n if (Chapters == null || Chapters.Count <= 1)\n {\n return null;\n }\n\n var chapter = Chapters.FirstOrDefault(c => c.StartTime <= time.Ticks && time.Ticks <= c.EndTime);\n return chapter?.Title;\n }\n}\n"], ["/LLPlayer/LLPlayer/Controls/Settings/SettingsSubtitlesOCR.xaml.cs", "using System.Collections.ObjectModel;\nusing System.ComponentModel;\nusing System.Diagnostics.CodeAnalysis;\nusing System.Windows;\nusing System.Windows.Controls;\nusing Windows.Media.Ocr;\nusing FlyleafLib;\nusing LLPlayer.Extensions;\nusing LLPlayer.Services;\nusing LLPlayer.Views;\n\nnamespace LLPlayer.Controls.Settings;\n\npublic partial class SettingsSubtitlesOCR : UserControl\n{\n public SettingsSubtitlesOCR()\n {\n InitializeComponent();\n\n DataContext = ((App)Application.Current).Container.Resolve();\n }\n}\n\npublic class SettingsSubtitlesOCRVM : Bindable\n{\n public FlyleafManager FL { get; }\n private readonly IDialogService _dialogService;\n\n public SettingsSubtitlesOCRVM(FlyleafManager fl, IDialogService dialogService)\n {\n FL = fl;\n _dialogService = dialogService;\n\n LoadDownloadedTessModels();\n LoadAvailableMsModels();\n }\n\n public ObservableCollection DownloadedTessLanguages { get; } = new();\n public ObservableCollection TessLanguageGroups { get; } = new();\n\n public ObservableCollection AvailableMsOcrLanguages { get; } = new();\n public ObservableCollection MsLanguageGroups { get; } = new();\n\n [field: AllowNull, MaybeNull]\n public DelegateCommand CmdDownloadTessModel => field ??= new(() =>\n {\n _dialogService.ShowDialog(nameof(TesseractDownloadDialog));\n\n // reload\n LoadDownloadedTessModels();\n });\n\n private void LoadDownloadedTessModels()\n {\n DownloadedTessLanguages.Clear();\n\n List langs = TesseractModelLoader.LoadDownloadedModels().ToList();\n foreach (var lang in langs)\n {\n DownloadedTessLanguages.Add(lang);\n }\n\n TessLanguageGroups.Clear();\n\n List langGroups = langs\n .GroupBy(l => l.ISO6391)\n .Where(lg => lg.Count() >= 2)\n .Select(lg => new TessOcrLanguageGroup\n {\n ISO6391 = lg.Key,\n Members = new ObservableCollection(\n lg.Select(m => new TessOcrLanguageGroupMember()\n {\n DisplayName = m.Lang.ToString(),\n LangCode = m.LangCode\n })\n )\n }).ToList();\n\n Dictionary? regionConfig = FL.PlayerConfig.Subtitles.TesseractOcrRegions;\n foreach (TessOcrLanguageGroup group in langGroups)\n {\n // Load preferred region settings from config\n if (regionConfig != null && regionConfig.TryGetValue(group.ISO6391, out string? code))\n {\n group.SelectedMember = group.Members.FirstOrDefault(m => m.LangCode == code);\n }\n group.PropertyChanged += TessLanguageGroup_OnPropertyChanged;\n\n TessLanguageGroups.Add(group);\n }\n }\n\n private void LoadAvailableMsModels()\n {\n var langs = OcrEngine.AvailableRecognizerLanguages.ToList();\n foreach (var lang in langs)\n {\n AvailableMsOcrLanguages.Add(lang);\n }\n\n List langGroups = langs\n .GroupBy(l => l.LanguageTag.Split('-').First())\n .Where(lg => lg.Count() >= 2)\n .Select(lg => new MsOcrLanguageGroup\n {\n ISO6391 = lg.Key,\n Members = new ObservableCollection(\n lg.Select(m => new MsOcrLanguageGroupMember()\n {\n DisplayName = m.DisplayName,\n LanguageTag = m.LanguageTag,\n NativeName = m.NativeName\n })\n )\n }).ToList();\n\n Dictionary? regionConfig = FL.PlayerConfig.Subtitles.MsOcrRegions;\n foreach (MsOcrLanguageGroup group in langGroups)\n {\n // Load preferred region settings from config\n if (regionConfig != null && regionConfig.TryGetValue(group.ISO6391, out string? tag))\n {\n group.SelectedMember = group.Members.FirstOrDefault(m => m.LanguageTag == tag);\n }\n group.PropertyChanged += MsLanguageGroup_OnPropertyChanged;\n\n MsLanguageGroups.Add(group);\n }\n }\n\n private void MsLanguageGroup_OnPropertyChanged(object? sender, PropertyChangedEventArgs e)\n {\n if (e.PropertyName == nameof(MsOcrLanguageGroup.SelectedMember))\n {\n Dictionary iso6391ToTag = new();\n\n foreach (MsOcrLanguageGroup group in MsLanguageGroups)\n {\n if (group.SelectedMember != null)\n {\n iso6391ToTag.Add(group.ISO6391, group.SelectedMember.LanguageTag);\n }\n }\n\n FL.PlayerConfig.Subtitles.MsOcrRegions = iso6391ToTag;\n }\n }\n\n private void TessLanguageGroup_OnPropertyChanged(object? sender, PropertyChangedEventArgs e)\n {\n if (e.PropertyName == nameof(TessOcrLanguageGroup.SelectedMember))\n {\n Dictionary iso6391ToCode = new();\n\n foreach (TessOcrLanguageGroup group in TessLanguageGroups)\n {\n if (group.SelectedMember != null)\n {\n iso6391ToCode.Add(group.ISO6391, group.SelectedMember.LangCode);\n }\n }\n\n FL.PlayerConfig.Subtitles.TesseractOcrRegions = iso6391ToCode;\n }\n }\n}\n\n#region Tesseract\npublic class TessOcrLanguageGroupMember : Bindable\n{\n public required string LangCode { get; init; }\n public required string DisplayName { get; init; }\n}\n\npublic class TessOcrLanguageGroup : Bindable\n{\n public required string ISO6391 { get; init; }\n\n public string DisplayName\n {\n get\n {\n var lang = Language.Get(ISO6391);\n return lang.TopEnglishName;\n }\n }\n\n public required ObservableCollection Members { get; init; }\n public TessOcrLanguageGroupMember? SelectedMember { get; set => Set(ref field, value); }\n}\n#endregion\n\n#region Microsoft OCR\npublic class MsOcrLanguageGroupMember : Bindable\n{\n public required string LanguageTag { get; init; }\n public required string DisplayName { get; init; }\n public required string NativeName { get; init; }\n}\n\npublic class MsOcrLanguageGroup : Bindable\n{\n public required string ISO6391 { get; init; }\n\n public string DisplayName\n {\n get\n {\n var lang = Language.Get(ISO6391);\n return lang.TopEnglishName;\n }\n }\n\n public required ObservableCollection Members { get; init; }\n public MsOcrLanguageGroupMember? SelectedMember { get; set => Set(ref field, value); }\n}\n#endregion\n"], ["/LLPlayer/FlyleafLib/Engine/WhisperConfig.cs", "using System.Collections.Generic;\nusing System.Diagnostics;\nusing System.IO;\nusing System.Text.Json.Serialization;\nusing Whisper.net;\nusing Whisper.net.LibraryLoader;\n\nnamespace FlyleafLib;\n\n#nullable enable\n\n// Whisper Common Config (whisper.cpp, faster-whisper)\npublic class WhisperConfig : NotifyPropertyChanged\n{\n public static string ModelsDirectory { get; } = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, \"whispermodels\");\n public static string EnginesDirectory { get; } = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, \"Whisper\");\n\n // For UI\n public string LanguageName\n {\n get\n {\n string translate = Translate ? \", Trans\" : \"\";\n\n if (LanguageDetection)\n {\n return \"Auto\" + translate;\n }\n\n var lang = FlyleafLib.Language.Get(Language);\n\n if (lang != null)\n {\n return lang.TopEnglishName + translate;\n }\n\n return Language + translate;\n }\n }\n\n public string Language\n {\n get;\n set\n {\n if (Set(ref field, value))\n {\n Raise(LanguageName);\n }\n }\n } = \"en\";\n\n public bool LanguageDetection\n {\n get;\n set\n {\n if (Set(ref field, value))\n {\n Raise(LanguageName);\n }\n }\n } = true;\n\n public bool Translate\n {\n get;\n set\n {\n if (Set(ref field, value))\n {\n Raise(LanguageName);\n }\n }\n }\n\n public static void EnsureModelsDirectory()\n {\n if (!Directory.Exists(ModelsDirectory))\n {\n Directory.CreateDirectory(ModelsDirectory);\n }\n }\n\n public static void EnsureEnginesDirectory()\n {\n if (!Directory.Exists(EnginesDirectory))\n {\n Directory.CreateDirectory(EnginesDirectory);\n }\n }\n}\n\n// TODO: L: Add other options\npublic class WhisperCppConfig : NotifyPropertyChanged\n{\n public WhisperCppModel? Model\n {\n get;\n set\n {\n if (Set(ref field, value))\n {\n Raise(nameof(IsEnglishModel));\n }\n }\n }\n\n [JsonIgnore]\n public bool IsEnglishModel => Model != null && Model.Model.ToString().EndsWith(\"En\");\n\n public List RuntimeLibraries { get; set => Set(ref field, value); } = [RuntimeLibrary.Cpu, RuntimeLibrary.CpuNoAvx];\n public RuntimeLibrary? LoadedLibrary => RuntimeOptions.LoadedLibrary;\n\n public int? GpuDevice { get; set => Set(ref field, value); }\n\n public int? Threads { get; set => Set(ref field, value); }\n public int? MaxSegmentLength { get; set => Set(ref field, value); }\n public int? MaxTokensPerSegment { get; set => Set(ref field, value); }\n public bool SplitOnWord { get; set => Set(ref field, value); }\n public float? NoSpeechThreshold { get; set => Set(ref field, value); }\n public bool NoContext { get; set => Set(ref field, value); }\n public int? AudioContextSize { get; set => Set(ref field, value); }\n public string Prompt { get; set => Set(ref field, value); } = string.Empty;\n\n public WhisperFactoryOptions GetFactoryOptions()\n {\n WhisperFactoryOptions opts = WhisperFactoryOptions.Default;\n\n if (GpuDevice.HasValue)\n opts.GpuDevice = GpuDevice.Value;\n\n return opts;\n }\n\n public WhisperProcessorBuilder ConfigureBuilder(WhisperConfig whisperConfig, WhisperProcessorBuilder builder)\n {\n if (IsEnglishModel)\n {\n // set English forcefully if English-only models\n builder.WithLanguage(\"en\");\n }\n else\n {\n if (!string.IsNullOrEmpty(whisperConfig.Language))\n builder.WithLanguage(whisperConfig.Language);\n\n // prefer auto\n if (whisperConfig.LanguageDetection)\n builder.WithLanguageDetection();\n\n if (whisperConfig.Translate)\n builder.WithTranslate();\n }\n\n if (Threads is > 0)\n builder.WithThreads(Threads.Value);\n\n if (MaxSegmentLength is > 0)\n builder.WithMaxSegmentLength(MaxSegmentLength.Value);\n\n if (MaxTokensPerSegment is > 0)\n builder.WithMaxTokensPerSegment(MaxTokensPerSegment.Value);\n\n if (SplitOnWord)\n builder.SplitOnWord();\n\n if (NoSpeechThreshold is > 0)\n builder.WithNoSpeechThreshold(NoSpeechThreshold.Value);\n\n if (NoContext)\n builder.WithNoContext();\n\n if (AudioContextSize is > 0)\n builder.WithAudioContextSize(AudioContextSize.Value);\n\n if (!string.IsNullOrWhiteSpace(Prompt))\n builder.WithPrompt(Prompt);\n\n // auto set\n if (MaxSegmentLength is > 0 || MaxSegmentLength is > 0)\n builder.WithTokenTimestamps();\n\n return builder;\n }\n}\n\npublic class FasterWhisperConfig : NotifyPropertyChanged\n{\n public static string DefaultEnginePath { get; } = Path.Combine(WhisperConfig.EnginesDirectory, \"Faster-Whisper-XXL\", \"faster-whisper-xxl.exe\");\n\n // can get by faster-whisper-xxl.exe --model foo bar.wav\n public static List ModelOptions { get; } = [\n \"tiny\",\n \"tiny.en\",\n \"base\",\n \"base.en\",\n \"small\",\n \"small.en\",\n \"medium\",\n \"medium.en\",\n \"large-v1\",\n \"large-v2\",\n \"large-v3\",\n //\"large\", // = large-v3\n \"large-v3-turbo\",\n //\"turbo\", // = large-v3-turbo\n \"distil-large-v2\",\n \"distil-medium.en\",\n \"distil-small.en\",\n \"distil-large-v3\",\n \"distil-large-v3.5\"\n ];\n\n public bool UseManualEngine { get; set => Set(ref field, value); }\n public string? ManualEnginePath { get; set => Set(ref field, value); }\n public bool UseManualModel { get; set => Set(ref field, value); }\n public string? ManualModelDir { get; set => Set(ref field, value); }\n public string Model\n {\n get;\n set\n {\n if (Set(ref field, value))\n {\n Raise(nameof(IsEnglishModel));\n }\n }\n } = \"tiny\";\n [JsonIgnore]\n public bool IsEnglishModel => Model.EndsWith(\".en\") ||\n Model is \"distil-large-v2\"\n or \"distil-large-v3\"\n or \"distil-large-v3.5\";\n public string ExtraArguments { get; set => Set(ref field, value); } = string.Empty;\n\n public ProcessPriorityClass ProcessPriority { get; set => Set(ref field, value); } = ProcessPriorityClass.Normal;\n}\n"], ["/LLPlayer/LLPlayer/ViewModels/FlyleafOverlayVM.cs", "using System.Diagnostics;\nusing System.Windows;\nusing System.Windows.Controls;\nusing System.Windows.Input;\nusing FlyleafLib;\nusing FlyleafLib.MediaPlayer;\nusing LLPlayer.Extensions;\nusing LLPlayer.Services;\nusing MaterialDesignThemes.Wpf;\nusing static FlyleafLib.Utils.NativeMethods;\n\nnamespace LLPlayer.ViewModels;\n\npublic class FlyleafOverlayVM : Bindable\n{\n public FlyleafManager FL { get; }\n\n public FlyleafOverlayVM(FlyleafManager fl)\n {\n FL = fl;\n }\n\n public DelegateCommand? CmdOnLoaded => field ??= new(() =>\n {\n SetupOSDStatus();\n SetupFlyleafContextMenu();\n SetupFlyleafKeybindings();\n\n FL.Config.FlyleafHostLoaded();\n });\n\n private void SetupFlyleafContextMenu()\n {\n // When a context menu is opened using the Overlay.MouseRightButtonUp event,\n // it is a bubble event and therefore has priority over the ContextMenu of the child controls.\n // so set ContextMenu directly to each of the controls in order to give priority to the child contextmenu.\n ContextMenu menu = (ContextMenu)Application.Current.FindResource(\"PopUpMenu\")!;\n menu.DataContext = this;\n menu.PlacementTarget = FL.FlyleafHost!.Overlay;\n\n FL.FlyleafHost!.Overlay.ContextMenu = menu;\n FL.FlyleafHost!.Surface.ContextMenu = menu;\n }\n\n #region Flyleaf Keybindings\n // TODO: L: Make it fully customizable like PotPlayer\n private void SetupFlyleafKeybindings()\n {\n // Subscribe to the same event to the following two\n // Surface: On Video Screen\n // Overlay: Content of FlyleafHost = FlyleafOverlay\n foreach (var window in (Window[])[FL.FlyleafHost!.Surface, FL.FlyleafHost!.Overlay])\n {\n window.MouseWheel += FlyleafOnMouseWheel;\n }\n FL.FlyleafHost.Surface.MouseUp += SurfaceOnMouseUp;\n FL.FlyleafHost.Surface.MouseDoubleClick += SurfaceOnMouseDoubleClick;\n FL.FlyleafHost.Surface.MouseLeftButtonDown += SurfaceOnMouseLeftButtonDown;\n FL.FlyleafHost.Surface.MouseLeftButtonUp += SurfaceOnMouseLeftButtonUp;\n FL.FlyleafHost.Surface.MouseMove += SurfaceOnMouseMove;\n FL.FlyleafHost.Surface.LostMouseCapture += SurfaceOnLostMouseCapture;\n }\n\n private void SurfaceOnMouseUp(object sender, MouseButtonEventArgs e)\n {\n switch (e.ChangedButton)\n {\n // Middle click: seek to current subtitle\n case MouseButton.Middle:\n bool ctrlDown = Keyboard.IsKeyDown(Key.LeftCtrl) || Keyboard.IsKeyDown(Key.RightCtrl);\n if (ctrlDown)\n {\n // CTRL + Middle click: Reset zoom\n FL.Player.ResetZoom();\n e.Handled = true;\n return;\n }\n\n if (FL.Player.Subtitles[0].Enabled)\n {\n FL.Player.Subtitles.CurSeek();\n }\n e.Handled = true;\n break;\n\n // X1 click: subtitles prev seek with fallback\n case MouseButton.XButton1:\n FL.Player.Subtitles.PrevSeekFallback();\n e.Handled = true;\n break;\n\n // X2 click: subtitles next seek with fallback\n case MouseButton.XButton2:\n FL.Player.Subtitles.NextSeekFallback();\n e.Handled = true;\n break;\n }\n }\n\n private void SurfaceOnMouseDoubleClick(object sender, MouseButtonEventArgs e)\n {\n if (FL.Config.MouseDoubleClickToFullScreen && e.ChangedButton == MouseButton.Left)\n {\n FL.Player.ToggleFullScreen();\n\n // Double and single clicks are not currently distinguished, so need to be re-fired\n // Timers need to be added to distinguish between the two,\n // but this is controversial because it delays a single click action\n SingleClickAction();\n\n e.Handled = true;\n }\n }\n\n private bool _isLeftDragging;\n private Point _downPoint;\n private Point _downCursorPoint;\n private long _downTick;\n\n private void SurfaceOnMouseLeftButtonDown(object sender, MouseButtonEventArgs e)\n {\n // Support window dragging & play / pause toggle\n if (Keyboard.Modifiers != ModifierKeys.None)\n return;\n\n if (FL.FlyleafHost is not { IsResizing: false, IsPanMoving: false, IsDragMoving: false })\n return;\n\n Point downPoint = FL.FlyleafHost!.Surface.PointToScreen(default);\n long downTick = Stopwatch.GetTimestamp();\n\n if (!FL.FlyleafHost.IsFullScreen && FL.FlyleafHost.Owner.WindowState == WindowState.Normal)\n {\n // normal window: window dragging\n DragMoveOwner();\n\n MouseLeftButtonUpAction(downPoint, downTick);\n }\n else\n {\n // fullscreen or maximized window: do action in KeyUp event\n _isLeftDragging = true;\n _downPoint = downPoint;\n _downTick = downTick;\n\n _downCursorPoint = e.GetPosition((IInputElement)sender);\n }\n }\n\n // When left dragging while maximized, move window back to normal and move window\n private void SurfaceOnMouseMove(object sender, MouseEventArgs e)\n {\n if (!_isLeftDragging || e.LeftButton != MouseButtonState.Pressed)\n return;\n\n if (FL.FlyleafHost!.IsFullScreen || FL.FlyleafHost.Owner.WindowState != WindowState.Maximized)\n return;\n\n Point curPoint = e.GetPosition((IInputElement)sender);\n\n // distinguish between mouse click and dragging (to prevent misfire)\n if (Math.Abs(curPoint.X - _downCursorPoint.X) >= 60 ||\n Math.Abs(curPoint.Y - _downCursorPoint.Y) >= 60)\n {\n _isLeftDragging = false;\n\n // change to normal window\n FL.FlyleafHost.Owner.WindowState = WindowState.Normal;\n\n // start dragging\n DragMoveOwner();\n }\n }\n\n private void DragMoveOwner()\n {\n // (!SeekBarShowOnlyMouseOver) always show cursor when moving\n // (SeekBarShowOnlyMouseOver) prevent to activate seek bar\n if (!FL.Config.SeekBarShowOnlyMouseOver)\n {\n FL.Player.Activity.IsEnabled = false;\n }\n\n FL.FlyleafHost!.Owner.DragMove();\n\n if (!FL.Config.SeekBarShowOnlyMouseOver)\n {\n FL.Player.Activity.IsEnabled = true;\n }\n }\n\n private void SurfaceOnMouseLeftButtonUp(object sender, MouseButtonEventArgs e)\n {\n if (!_isLeftDragging)\n return;\n\n _isLeftDragging = false;\n\n MouseLeftButtonUpAction(_downPoint, _downTick);\n }\n\n private void SurfaceOnLostMouseCapture(object sender, MouseEventArgs e)\n {\n _isLeftDragging = false;\n }\n\n private void MouseLeftButtonUpAction(Point downPoint, long downTick)\n {\n Point upPoint = FL.FlyleafHost!.Surface.PointToScreen(default);\n\n if (downPoint == upPoint // if not moved at all\n ||\n Stopwatch.GetElapsedTime(downTick) <= TimeSpan.FromMilliseconds(200)\n && // if click within 200ms and not so much moved\n Math.Abs(upPoint.X - downPoint.X) < 60 && Math.Abs(upPoint.Y - downPoint.Y) < 60)\n {\n SingleClickAction();\n }\n }\n\n private void SingleClickAction()\n {\n // Toggle play/pause on left click\n if (FL.Config.MouseSingleClickToPlay && FL.Player.CanPlay)\n FL.Player.TogglePlayPause();\n }\n\n private void FlyleafOnMouseWheel(object sender, MouseWheelEventArgs e)\n {\n // CTRL + Wheel : Zoom in / out\n // SHIFT + Wheel : Subtitles Up / Down\n // CTRL + SHIFT + Wheel : Subtitles Size Increase / Decrease\n if (e.Delta == 0)\n {\n return;\n }\n\n Window surface = FL.FlyleafHost!.Surface;\n\n bool ctrlDown = Keyboard.IsKeyDown(Key.LeftCtrl) || Keyboard.IsKeyDown(Key.RightCtrl);\n bool shiftDown = Keyboard.IsKeyDown(Key.LeftShift) || Keyboard.IsKeyDown(Key.RightShift);\n\n if (ctrlDown && shiftDown)\n {\n if (e.Delta > 0)\n {\n FL.Action.CmdSubsSizeIncrease.Execute();\n }\n else\n {\n FL.Action.CmdSubsSizeDecrease.Execute();\n }\n }\n else if (ctrlDown)\n {\n Point cur = e.GetPosition(surface);\n Point curDpi = new(cur.X * DpiX, cur.Y * DpiY);\n if (e.Delta > 0)\n {\n FL.Player.ZoomIn(curDpi);\n }\n else\n {\n FL.Player.ZoomOut(curDpi);\n }\n }\n else if (shiftDown)\n {\n if (e.Delta > 0)\n {\n FL.Action.CmdSubsPositionUp.Execute();\n }\n else\n {\n FL.Action.CmdSubsPositionDown.Execute();\n }\n }\n else\n {\n if (FL.Config.MouseWheelToVolumeUpDown)\n {\n if (e.Delta > 0)\n {\n FL.Player.Audio.VolumeUp();\n }\n else\n {\n FL.Player.Audio.VolumeDown();\n }\n }\n }\n\n e.Handled = true;\n }\n #endregion\n\n #region OSD\n private void SetupOSDStatus()\n {\n var player = FL.Player;\n\n player.PropertyChanged += (o, e) =>\n {\n switch (e.PropertyName)\n {\n case nameof(player.OSDMessage):\n OSDMessage = player.OSDMessage;\n break;\n case nameof(player.ReversePlayback):\n OSDMessage = $\"Reverse Playback {(player.ReversePlayback ? \"On\" : \"Off\")}\";\n break;\n case nameof(player.LoopPlayback):\n OSDMessage = $\"Loop Playback {(player.LoopPlayback ? \"On\" : \"Off\")}\";\n break;\n case nameof(player.Rotation):\n OSDMessage = $\"Rotation {player.Rotation}°\";\n break;\n case nameof(player.Speed):\n OSDMessage = $\"Speed x{player.Speed}\";\n break;\n case nameof(player.Zoom):\n OSDMessage = $\"Zoom {player.Zoom}%\";\n break;\n case nameof(player.Status):\n // Change only Play and Pause to icon\n switch (player.Status)\n {\n case Status.Paused:\n OSDIcon = PackIconKind.Pause;\n return;\n case Status.Playing:\n OSDIcon = PackIconKind.Play;\n return;\n }\n OSDMessage = $\"{player.Status.ToString()}\";\n break;\n }\n };\n\n player.Audio.PropertyChanged += (o, e) =>\n {\n switch (e.PropertyName)\n {\n case nameof(player.Audio.Volume):\n OSDMessage = $\"Volume {player.Audio.Volume}%\";\n break;\n case nameof(player.Audio.Mute):\n OSDIcon = player.Audio.Mute ? PackIconKind.VolumeOff : PackIconKind.VolumeHigh;\n break;\n }\n };\n\n player.Config.Player.PropertyChanged += (o, e) =>\n {\n switch (e.PropertyName)\n {\n case nameof(player.Config.Player.SeekAccurate):\n OSDMessage = $\"Always Seek Accurate {(player.Config.Player.SeekAccurate ? \"On\" : \"Off\")}\";\n break;\n }\n };\n\n player.Config.Audio.PropertyChanged += (o, e) =>\n {\n switch (e.PropertyName)\n {\n case nameof(player.Config.Audio.Enabled):\n OSDMessage = $\"Audio {(player.Config.Audio.Enabled ? \"Enabled\" : \"Disabled\")}\";\n break;\n case nameof(player.Config.Audio.Delay):\n OSDMessage = $\"Audio Delay {player.Config.Audio.Delay / 10000}ms\";\n break;\n }\n };\n\n player.Config.Video.PropertyChanged += (o, e) =>\n {\n switch (e.PropertyName)\n {\n case nameof(player.Config.Video.Enabled):\n OSDMessage = $\"Video {(player.Config.Video.Enabled ? \"Enabled\" : \"Disabled\")}\";\n break;\n case nameof(player.Config.Video.AspectRatio):\n OSDMessage = $\"Aspect Ratio {player.Config.Video.AspectRatio.ToString()}\";\n break;\n case nameof(player.Config.Video.VideoAcceleration):\n OSDMessage = $\"Video Acceleration {(player.Config.Video.VideoAcceleration ? \"On\" : \"Off\")}\";\n break;\n }\n };\n\n foreach (var (i, config) in player.Config.Subtitles.SubConfigs.Index())\n {\n config.PropertyChanged += (o, e) =>\n {\n switch (e.PropertyName)\n {\n case nameof(config.Delay):\n OSDMessage = $\"{(i == 0 ? \"Primary\" : \"Secondary\")} Subs Delay {config.Delay / 10000}ms\";\n break;\n case nameof(config.Visible):\n var primary = player.Config.Subtitles[0].Visible ? \"visible\" : \"hidden\";\n var secondary = player.Config.Subtitles[1].Visible ? \"visible\" : \"hidden\";\n\n if (player.Subtitles[1].Enabled)\n {\n OSDMessage = $\"Subs {primary} / {secondary}\";\n }\n else\n {\n OSDMessage = $\"Subs {primary}\";\n }\n break;\n }\n };\n }\n\n // app config\n FL.Config.PropertyChanged += (o, e) =>\n {\n switch (e.PropertyName)\n {\n case nameof(FL.Config.AlwaysOnTop):\n OSDMessage = $\"Always on Top {(FL.Config.AlwaysOnTop ? \"On\" : \"Off\")}\";\n break;\n }\n };\n\n FL.Config.Subs.PropertyChanged += (o, e) =>\n {\n switch (e.PropertyName)\n {\n case nameof(FL.Config.Subs.SubsAutoTextCopy):\n OSDMessage = $\"Subs Auto Text Copy {(FL.Config.Subs.SubsAutoTextCopy ? \"On\" : \"Off\")}\";\n break;\n }\n };\n }\n\n private CancellationTokenSource? _cancelMsgToken;\n\n public string OSDMessage\n {\n get => _osdMessage;\n set\n {\n if (Set(ref _osdMessage, value))\n {\n if (_cancelMsgToken != null)\n {\n _cancelMsgToken.Cancel();\n _cancelMsgToken.Dispose();\n _cancelMsgToken = null;\n }\n\n if (Set(ref _osdIcon, null, nameof(OSDIcon)))\n {\n OnPropertyChanged(nameof(IsOSDIcon));\n }\n\n _cancelMsgToken = new();\n\n var token = _cancelMsgToken.Token;\n _ = Task.Run(() => ClearOSD(3000, token));\n }\n }\n }\n private string _osdMessage = \"\";\n\n public PackIconKind? OSDIcon\n {\n get => _osdIcon;\n set\n {\n if (Set(ref _osdIcon, value))\n {\n OnPropertyChanged(nameof(IsOSDIcon));\n\n if (_cancelMsgToken != null)\n {\n _cancelMsgToken.Cancel();\n _cancelMsgToken.Dispose();\n _cancelMsgToken = null;\n }\n\n Set(ref _osdMessage, \"\", nameof(OSDMessage));\n\n _cancelMsgToken = new();\n\n var token = _cancelMsgToken.Token;\n _ = Task.Run(() => ClearOSD(500, token));\n }\n }\n }\n private PackIconKind? _osdIcon;\n\n public bool IsOSDIcon => OSDIcon != null;\n\n private async Task ClearOSD(int timeoutMs, CancellationToken token)\n {\n await Task.Delay(timeoutMs, token);\n\n if (token.IsCancellationRequested)\n return;\n\n Utils.UI(() =>\n {\n Set(ref _osdMessage, \"\", nameof(OSDMessage));\n if (Set(ref _osdIcon, null, nameof(OSDIcon)))\n {\n OnPropertyChanged(nameof(IsOSDIcon));\n }\n });\n }\n #endregion\n}\n"], ["/LLPlayer/LLPlayer/Controls/Settings/SettingsSubtitlesTrans.xaml.cs", "using System.Globalization;\nusing System.Windows;\nusing System.Windows.Controls;\nusing System.Windows.Data;\nusing FlyleafLib.MediaPlayer.Translation;\nusing FlyleafLib.MediaPlayer.Translation.Services;\nusing LLPlayer.Extensions;\nusing LLPlayer.Services;\n\nnamespace LLPlayer.Controls.Settings;\n\npublic partial class SettingsSubtitlesTrans : UserControl\n{\n public SettingsSubtitlesTrans()\n {\n InitializeComponent();\n\n DataContext = ((App)Application.Current).Container.Resolve();\n }\n}\n\npublic class SettingsSubtitlesTransVM : Bindable\n{\n public FlyleafManager FL { get; }\n\n public SettingsSubtitlesTransVM(FlyleafManager fl)\n {\n FL = fl;\n\n SelectedTranslateServiceType = FL.PlayerConfig.Subtitles.TranslateServiceType;\n }\n\n public TranslateServiceType SelectedTranslateServiceType\n {\n get;\n set\n {\n Set(ref field, value);\n\n FL.PlayerConfig.Subtitles.TranslateServiceType = value;\n\n if (FL.PlayerConfig.Subtitles.TranslateServiceSettings.TryGetValue(value, out var settings))\n {\n // It points to an instance of the same class, so change this will be reflected in the config.\n SelectedServiceSettings = settings;\n }\n else\n {\n ITranslateSettings? defaultSettings = value.DefaultSettings();\n FL.PlayerConfig.Subtitles.TranslateServiceSettings.Add(value, defaultSettings);\n\n SelectedServiceSettings = defaultSettings;\n }\n }\n }\n\n public ITranslateSettings? SelectedServiceSettings { get; set => Set(ref field, value); }\n\n public DelegateCommand? CmdSetDefaultPromptKeepContext => field ??= new(() =>\n {\n FL.PlayerConfig.Subtitles.TranslateChatConfig.PromptKeepContext = TranslateChatConfig.DefaultPromptKeepContext.ReplaceLineEndings(\"\\n\");\n });\n\n public DelegateCommand? CmdSetDefaultPromptOneByOne => field ??= new(() =>\n {\n FL.PlayerConfig.Subtitles.TranslateChatConfig.PromptOneByOne = TranslateChatConfig.DefaultPromptOneByOne.ReplaceLineEndings(\"\\n\");\n });\n}\n\n[ValueConversion(typeof(TargetLanguage), typeof(string))]\ninternal class TargetLanguageEnumToStringConverter : IValueConverter\n{\n public object Convert(object value, Type targetType, object parameter, CultureInfo culture)\n {\n if (value is TargetLanguage enumValue)\n {\n return enumValue.DisplayName();\n }\n return value?.ToString() ?? string.Empty;\n }\n\n public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)\n {\n throw new NotImplementedException();\n }\n}\n\n[ValueConversion(typeof(TranslateServiceType), typeof(string))]\ninternal class TranslateServiceTypeEnumToStringConverter : IValueConverter\n{\n public object Convert(object value, Type targetType, object parameter, CultureInfo culture)\n {\n if (value is TranslateServiceType enumValue)\n {\n string displayName = enumValue.GetDescription();\n\n if (enumValue.IsLLM())\n {\n return $\"{displayName} (LLM)\";\n }\n\n return $\"{displayName}\";\n }\n\n return value?.ToString() ?? string.Empty;\n }\n\n public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)\n {\n throw new NotImplementedException();\n }\n}\n\n[ValueConversion(typeof(TranslateServiceType), typeof(string))]\ninternal class TranslateServiceTypeEnumToUrlConverter : IValueConverter\n{\n private const string BaseUrl = \"https://github.com/umlx5h/LLPlayer/wiki/Translation-Engine\";\n public object Convert(object value, Type targetType, object parameter, CultureInfo culture)\n {\n if (value is TranslateServiceType enumValue)\n {\n string displayName = enumValue.GetDescription();\n\n return $\"{BaseUrl}#{displayName.ToLower().Replace(' ', '-')}\";\n }\n return BaseUrl;\n }\n\n public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)\n {\n throw new NotImplementedException();\n }\n}\n\n[ValueConversion(typeof(TargetLanguage), typeof(string))]\ninternal class TargetLanguageEnumToNoSupportedTranslateServiceConverter : IValueConverter\n{\n public object Convert(object value, Type targetType, object parameter, CultureInfo culture)\n {\n if (value is TargetLanguage enumValue)\n {\n TranslateServiceType supported = enumValue.SupportedServiceType();\n\n // DeepL = DeepLX\n List notSupported =\n Enum.GetValues()\n .Where(t => t != TranslateServiceType.DeepLX)\n .Where(t => !supported.HasFlag(t))\n .ToList();\n\n if (notSupported.Count == 0)\n {\n return \"[All supported]\";\n }\n\n return string.Join(',', notSupported.Select(t => t.ToString()));\n }\n return value?.ToString() ?? string.Empty;\n }\n\n public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)\n {\n throw new NotImplementedException();\n }\n}\n"], ["/LLPlayer/LLPlayer/Controls/SelectableSubtitleText.xaml.cs", "using System.Diagnostics;\nusing System.Text.RegularExpressions;\nusing System.Windows;\nusing System.Windows.Controls;\nusing System.Windows.Data;\nusing System.Windows.Input;\nusing System.Windows.Media;\nusing FlyleafLib;\nusing LLPlayer.Extensions;\nusing NMeCab.Specialized;\n\nnamespace LLPlayer.Controls;\n\npublic partial class SelectableSubtitleText : UserControl\n{\n private readonly Binding _bindFontSize;\n private readonly Binding _bindFontWeight;\n private readonly Binding _bindFontFamily;\n private readonly Binding _bindFontStyle;\n private readonly Binding _bindFill;\n private readonly Binding _bindStroke;\n private readonly Binding _bindStrokeThicknessInitial;\n\n private OutlinedTextBlock? _wordStart;\n\n public SelectableSubtitleText()\n {\n InitializeComponent();\n\n // DataContext is set in WrapPanel, so there is no need to use ElementName.\n //_bindFontSize = new Binding(nameof(FontSize))\n //{\n // //ElementName = nameof(Root),\n // Mode = BindingMode.OneWay\n //};\n _bindFontSize = new Binding(nameof(FontSize));\n _bindFontWeight = new Binding(nameof(FontWeight));\n _bindFontFamily = new Binding(nameof(FontFamily));\n _bindFontStyle = new Binding(nameof(FontStyle));\n _bindFill = new Binding(nameof(Fill));\n _bindStroke = new Binding(nameof(Stroke));\n _bindStrokeThicknessInitial = new Binding(nameof(StrokeThicknessInitial));\n }\n\n public static readonly RoutedEvent WordClickedEvent =\n EventManager.RegisterRoutedEvent(nameof(WordClicked), RoutingStrategy.Bubble, typeof(WordClickedEventHandler), typeof(SelectableSubtitleText));\n\n public event WordClickedEventHandler WordClicked\n {\n add => AddHandler(WordClickedEvent, value);\n remove => RemoveHandler(WordClickedEvent, value);\n }\n\n public event EventHandler? WordClickedDown;\n\n public static readonly DependencyProperty TextProperty =\n DependencyProperty.Register(nameof(Text), typeof(string), typeof(SelectableSubtitleText), new FrameworkPropertyMetadata(string.Empty, OnTextChanged));\n\n public string Text\n {\n get => (string)GetValue(TextProperty);\n set => SetValue(TextProperty, value);\n }\n\n private string _textFix = string.Empty;\n\n public static readonly DependencyProperty IsTranslatedProperty =\n DependencyProperty.Register(nameof(IsTranslated), typeof(bool), typeof(SelectableSubtitleText), new FrameworkPropertyMetadata(false));\n\n public bool IsTranslated\n {\n get => (bool)GetValue(IsTranslatedProperty);\n set => SetValue(IsTranslatedProperty, value);\n }\n\n public static readonly DependencyProperty TextLanguageProperty =\n DependencyProperty.Register(nameof(TextLanguage), typeof(Language), typeof(SelectableSubtitleText), new FrameworkPropertyMetadata(null, OnTextLanguageChanged));\n\n public Language? TextLanguage\n {\n get => (Language)GetValue(TextLanguageProperty);\n set => SetValue(TextLanguageProperty, value);\n }\n\n public static readonly DependencyProperty SubIndexProperty =\n DependencyProperty.Register(nameof(SubIndex), typeof(int), typeof(SelectableSubtitleText), new FrameworkPropertyMetadata(0));\n\n public int SubIndex\n {\n get => (int)GetValue(SubIndexProperty);\n set => SetValue(SubIndexProperty, value);\n }\n\n public static readonly DependencyProperty FillProperty =\n OutlinedTextBlock.FillProperty.AddOwner(typeof(SelectableSubtitleText));\n\n public Brush Fill\n {\n get => (Brush)GetValue(FillProperty);\n set => SetValue(FillProperty, value);\n }\n\n public static readonly DependencyProperty StrokeProperty =\n OutlinedTextBlock.StrokeProperty.AddOwner(typeof(SelectableSubtitleText));\n\n public Brush Stroke\n {\n get => (Brush)GetValue(StrokeProperty);\n set => SetValue(StrokeProperty, value);\n }\n\n public static readonly DependencyProperty WidthPercentageProperty =\n DependencyProperty.Register(nameof(WidthPercentage), typeof(double), typeof(SelectableSubtitleText), new FrameworkPropertyMetadata(60.0, OnWidthPercentageChanged));\n\n public double WidthPercentage\n {\n get => (double)GetValue(WidthPercentageProperty);\n set => SetValue(WidthPercentageProperty, value);\n }\n\n public static readonly DependencyProperty WidthPercentageFixProperty =\n DependencyProperty.Register(nameof(WidthPercentageFix), typeof(double), typeof(SelectableSubtitleText), new FrameworkPropertyMetadata(60.0));\n\n public double WidthPercentageFix\n {\n get => (double)GetValue(WidthPercentageFixProperty);\n set => SetValue(WidthPercentageFixProperty, value);\n }\n\n public static readonly DependencyProperty IgnoreLineBreakProperty =\n DependencyProperty.Register(nameof(IgnoreLineBreak), typeof(bool), typeof(SelectableSubtitleText), new FrameworkPropertyMetadata(false));\n\n public double MaxFixedWidth\n {\n get => (double)GetValue(MaxFixedWidthProperty);\n set => SetValue(MaxFixedWidthProperty, value);\n }\n\n public static readonly DependencyProperty MaxFixedWidthProperty =\n DependencyProperty.Register(nameof(MaxFixedWidth), typeof(double), typeof(SelectableSubtitleText), new FrameworkPropertyMetadata(0.0));\n\n public bool IgnoreLineBreak\n {\n get => (bool)GetValue(IgnoreLineBreakProperty);\n set => SetValue(IgnoreLineBreakProperty, value);\n }\n\n public static readonly DependencyProperty StrokeThicknessInitialProperty =\n DependencyProperty.Register(nameof(StrokeThicknessInitial), typeof(double), typeof(SelectableSubtitleText), new FrameworkPropertyMetadata(3.0));\n\n public double StrokeThicknessInitial\n {\n get => (double)GetValue(StrokeThicknessInitialProperty);\n set => SetValue(StrokeThicknessInitialProperty, value);\n }\n\n public static readonly DependencyProperty WordHoverBorderBrushProperty =\n DependencyProperty.Register(nameof(WordHoverBorderBrush), typeof(Brush), typeof(SelectableSubtitleText), new FrameworkPropertyMetadata(Brushes.Cyan));\n\n public Brush WordHoverBorderBrush\n {\n get => (Brush)GetValue(WordHoverBorderBrushProperty);\n set => SetValue(WordHoverBorderBrushProperty, value);\n }\n\n private static void OnWidthPercentageChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)\n {\n var ctl = (SelectableSubtitleText)d;\n ctl.WidthPercentageFix = (double)e.NewValue;\n }\n\n private static void OnTextChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)\n {\n var ctl = (SelectableSubtitleText)d;\n ctl.SetText((string)e.NewValue);\n }\n\n private static void OnTextLanguageChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)\n {\n var ctl = (SelectableSubtitleText)d;\n if (ctl.TextLanguage != null && ctl.TextLanguage.IsRTL)\n {\n ctl.wrapPanel.FlowDirection = FlowDirection.RightToLeft;\n }\n else\n {\n ctl.wrapPanel.FlowDirection = FlowDirection.LeftToRight;\n }\n }\n\n // SelectableTextBox uses char.IsPunctuation(), so use a regular expression for it.\n // TODO: L: Sharing the code with TextBox\n [GeneratedRegex(@\"((?:[^\\P{P}'-]+|\\s))\")]\n private static partial Regex WordSplitReg { get; }\n\n [GeneratedRegex(@\"^(?:[^\\P{P}'-]+|\\s)$\")]\n private static partial Regex WordSplitFullReg { get; }\n\n [GeneratedRegex(@\"((?:[^\\P{P}'-]+|\\s|[\\p{IsCJKUnifiedIdeographs}\\p{IsCJKUnifiedIdeographsExtensionA}]))\")]\n private static partial Regex ChineseWordSplitReg { get; }\n\n\n private static readonly Lazy MeCabTagger = new(() => MeCabIpaDicTagger.Create(), true);\n\n private void SetText(string text)\n {\n if (text == null)\n {\n return;\n }\n\n if (IgnoreLineBreak)\n {\n text = SubtitleTextUtil.FlattenText(text);\n }\n\n _textFix = text;\n\n bool containLineBreak = text.AsSpan().ContainsAny('\\r', '\\n');\n\n // If it contains line feeds, expand them to the full screen width (respecting the formatting in the SRT subtitle)\n WidthPercentageFix = containLineBreak ? 100.0 : WidthPercentage;\n\n wrapPanel.Children.Clear();\n _wordStart = null;\n\n string[] lines = text.SplitToLines().ToArray();\n\n var wordOffset = 0;\n\n // Use an OutlinedTextBlock for each word to display the border Text and enclose it in a WrapPanel\n for (int i = 0; i < lines.Length; i++)\n {\n IEnumerable words;\n\n if (TextLanguage != null && TextLanguage.ISO6391 == \"ja\")\n {\n // word segmentation for Japanese\n // TODO: L: Also do word segmentation in sidebar\n var nodes = MeCabTagger.Value.Parse(lines[i]);\n List wordsList = new(nodes.Length);\n foreach (var node in nodes)\n {\n // If there are space-separated characters, such as English, add them manually since they are not on the Surface\n if (char.IsWhiteSpace(lines[i][node.BPos]))\n {\n wordsList.Add(\" \");\n }\n wordsList.Add(node.Surface);\n }\n\n words = wordsList;\n }\n else if (TextLanguage != null && TextLanguage.ISO6391 == \"zh\")\n {\n words = ChineseWordSplitReg.Split(lines[i]);\n }\n else\n {\n words = WordSplitReg.Split(lines[i]);\n }\n\n foreach (string word in words)\n {\n // skip empty string because Split includes\n if (word.Length == 0)\n {\n continue;\n }\n\n if (string.IsNullOrWhiteSpace(word))\n {\n // Blanks are inserted with TextBlock.\n TextBlock space = new()\n {\n Text = word,\n // Created a click judgment to prevent playback toggling when clicking between words.\n Background = new SolidColorBrush(Color.FromArgb(1, 0, 0, 0)),\n };\n space.SetBinding(TextBlock.FontSizeProperty, _bindFontSize);\n space.SetBinding(TextBlock.FontWeightProperty, _bindFontWeight);\n space.SetBinding(TextBlock.FontStyleProperty, _bindFontStyle);\n space.SetBinding(TextBlock.FontFamilyProperty, _bindFontFamily);\n wrapPanel.Children.Add(space);\n wordOffset += word.Length;\n continue;\n }\n\n bool isSplitChar = WordSplitFullReg.IsMatch(word);\n\n OutlinedTextBlock textBlock = new()\n {\n Text = word,\n ClipToBounds = false,\n TextWrapping = TextWrapping.Wrap,\n StrokePosition = StrokePosition.Outside,\n IsHitTestVisible = false,\n WordOffset = wordOffset,\n // Fixed because the word itself is inverted\n FlowDirection = FlowDirection.LeftToRight\n };\n\n wordOffset += word.Length;\n\n textBlock.SetBinding(OutlinedTextBlock.FontSizeProperty, _bindFontSize);\n textBlock.SetBinding(OutlinedTextBlock.FontWeightProperty, _bindFontWeight);\n textBlock.SetBinding(OutlinedTextBlock.FontStyleProperty, _bindFontStyle);\n textBlock.SetBinding(OutlinedTextBlock.FontFamilyProperty, _bindFontFamily);\n textBlock.SetBinding(OutlinedTextBlock.FillProperty, _bindFill);\n textBlock.SetBinding(OutlinedTextBlock.StrokeProperty, _bindStroke);\n textBlock.SetBinding(OutlinedTextBlock.StrokeThicknessInitialProperty, _bindStrokeThicknessInitial);\n\n if (isSplitChar)\n {\n wrapPanel.Children.Add(textBlock);\n }\n else\n {\n Border border = new()\n {\n // Set brush to Border because OutlinedTextBlock's character click judgment is only on the character.\n //ref: https://stackoverflow.com/questions/50653308/hit-testing-a-transparent-element-in-a-transparent-window\n Background = new SolidColorBrush(Color.FromArgb(1, 0, 0, 0)),\n BorderThickness = new Thickness(1),\n IsHitTestVisible = true,\n Child = textBlock,\n Cursor = Cursors.Hand,\n };\n\n border.MouseLeftButtonDown += WordMouseLeftButtonDown;\n border.MouseLeftButtonUp += WordMouseLeftButtonUp;\n border.MouseRightButtonUp += WordMouseRightButtonUp;\n border.MouseUp += WordMouseMiddleButtonUp;\n\n // Change background color on mouse over\n border.MouseEnter += (_, _) =>\n {\n border.BorderBrush = WordHoverBorderBrush;\n border.Background = new SolidColorBrush(Color.FromArgb(80, 127, 127, 127));\n };\n border.MouseLeave += (_, _) =>\n {\n border.BorderBrush = null;\n border.Background = new SolidColorBrush(Color.FromArgb(1, 0, 0, 0));\n };\n\n wrapPanel.Children.Add(border);\n }\n }\n\n if (containLineBreak && i != lines.Length - 1)\n {\n // Add line breaks except at the end when there are two or more lines\n wrapPanel.Children.Add(new NewLine());\n }\n }\n }\n\n private void WordMouseLeftButtonDown(object sender, MouseButtonEventArgs e)\n {\n if (sender is Border { Child: OutlinedTextBlock word })\n {\n _wordStart = word;\n WordClickedDown?.Invoke(this, EventArgs.Empty);\n\n e.Handled = true;\n }\n }\n\n private void WordMouseLeftButtonUp(object sender, MouseButtonEventArgs e)\n {\n if (sender is Border { Child: OutlinedTextBlock word })\n {\n if (_wordStart == word)\n {\n // word clicked\n Point wordPoint = word.TranslatePoint(default, Root);\n\n WordClickedEventArgs args = new(WordClickedEvent)\n {\n Mouse = MouseClick.Left,\n Words = word.Text,\n IsWord = true,\n Text = _textFix,\n IsTranslated = IsTranslated,\n SubIndex = SubIndex,\n WordOffset = word.WordOffset,\n WordsX = wordPoint.X,\n WordsWidth = word.ActualWidth\n };\n RaiseEvent(args);\n }\n else if (_wordStart != null)\n {\n // phrase selected\n var wordStart = _wordStart!;\n var wordEnd = word;\n\n // support right to left drag\n if (wordStart.WordOffset > wordEnd.WordOffset)\n {\n (wordStart, wordEnd) = (wordEnd, wordStart);\n }\n\n List elements = wrapPanel.Children.OfType().ToList();\n\n int startIndex = elements.IndexOf((FrameworkElement)wordStart.Parent);\n int endIndex = elements.IndexOf((FrameworkElement)wordEnd.Parent);\n\n if (startIndex == -1 || endIndex == -1)\n {\n Debug.Assert(startIndex >= 0);\n Debug.Assert(endIndex >= 0);\n return;\n }\n\n var selectedElements = elements[startIndex..(endIndex + 1)];\n var selectedWords = selectedElements.Select(fe =>\n {\n switch (fe)\n {\n case Border { Child: OutlinedTextBlock word }:\n return word.Text;\n case OutlinedTextBlock splitter:\n return splitter.Text;\n case TextBlock space:\n return space.Text;\n case NewLine:\n // convert to space\n return \" \";\n default:\n throw new InvalidOperationException();\n }\n }).ToList();\n string selectedText = string.Join(string.Empty, selectedWords);\n\n Point startPoint = wordStart.TranslatePoint(default, Root);\n Point endPoint = wordEnd.TranslatePoint(default, Root);\n\n // if different Y axis, then line break or text wrapping\n double wordsX = 0;\n double wordsWidth = wrapPanel.ActualWidth;\n\n if (startPoint.Y == endPoint.Y)\n {\n // selection in one line\n\n if (wrapPanel.FlowDirection == FlowDirection.LeftToRight)\n {\n wordsX = startPoint.X;\n wordsWidth = endPoint.X + wordEnd.ActualWidth - startPoint.X;\n }\n else\n {\n wordsX = endPoint.X;\n wordsWidth = startPoint.X + wordStart.ActualWidth - endPoint.X;\n }\n }\n\n WordClickedEventArgs args = new(WordClickedEvent)\n {\n Mouse = MouseClick.Left,\n Words = selectedText,\n IsWord = false,\n Text = _textFix,\n IsTranslated = IsTranslated,\n SubIndex = SubIndex,\n WordOffset = wordStart.WordOffset,\n WordsX = wordsX,\n WordsWidth = wordsWidth\n };\n RaiseEvent(args);\n }\n\n _wordStart = null;\n e.Handled = true;\n }\n }\n\n private void WordMouseRightButtonUp(object sender, MouseButtonEventArgs e)\n {\n if (sender is Border { Child: OutlinedTextBlock word })\n {\n Point wordPoint = word.TranslatePoint(default, Root);\n\n WordClickedEventArgs args = new(WordClickedEvent)\n {\n Mouse = MouseClick.Right,\n Words = word.Text,\n IsWord = true,\n Text = _textFix,\n IsTranslated = IsTranslated,\n SubIndex = SubIndex,\n WordOffset = word.WordOffset,\n WordsX = wordPoint.X,\n WordsWidth = word.ActualWidth\n };\n RaiseEvent(args);\n e.Handled = true;\n }\n }\n\n private void WordMouseMiddleButtonUp(object sender, MouseButtonEventArgs e)\n {\n if (e.ChangedButton == MouseButton.Middle)\n {\n WordClickedEventArgs args = new(WordClickedEvent)\n {\n Mouse = MouseClick.Middle,\n Words = _textFix,\n IsWord = false,\n Text = _textFix,\n IsTranslated = IsTranslated,\n SubIndex = SubIndex,\n WordOffset = 0,\n WordsX = 0,\n WordsWidth = wrapPanel.ActualWidth\n };\n RaiseEvent(args);\n e.Handled = true;\n }\n }\n}\n\npublic class NewLine : FrameworkElement\n{\n}\n"], ["/LLPlayer/FlyleafLib/MediaFramework/MediaStream/VideoStream.cs", "using System.Runtime.InteropServices;\n\nusing FlyleafLib.MediaFramework.MediaDemuxer;\n\nnamespace FlyleafLib.MediaFramework.MediaStream;\n\npublic unsafe class VideoStream : StreamBase\n{\n public AspectRatio AspectRatio { get; set; }\n public ColorRange ColorRange { get; set; }\n public ColorSpace ColorSpace { get; set; }\n public AVColorTransferCharacteristic\n ColorTransfer { get; set; }\n public double Rotation { get; set; }\n public double FPS { get; set; }\n public long FrameDuration { get ;set; }\n public uint Height { get; set; }\n public bool IsRGB { get; set; }\n public AVComponentDescriptor[] PixelComps { get; set; }\n public int PixelComp0Depth { get; set; }\n public AVPixelFormat PixelFormat { get; set; }\n public AVPixFmtDescriptor* PixelFormatDesc { get; set; }\n public string PixelFormatStr { get; set; }\n public int PixelPlanes { get; set; }\n public bool PixelSameDepth { get; set; }\n public bool PixelInterleaved { get; set; }\n public int TotalFrames { get; set; }\n public uint Width { get; set; }\n public bool FixTimestamps { get; set; } // TBR: For formats such as h264/hevc that have no or invalid pts values\n\n public override string GetDump()\n => $\"[{Type} #{StreamIndex}] {Codec} {PixelFormatStr} {Width}x{Height} @ {FPS:#.###} | [Color: {ColorSpace}] [BR: {BitRate}] | {Utils.TicksToTime((long)(AVStream->start_time * Timebase))}/{Utils.TicksToTime((long)(AVStream->duration * Timebase))} | {Utils.TicksToTime(StartTime)}/{Utils.TicksToTime(Duration)}\";\n\n public VideoStream() { }\n public VideoStream(Demuxer demuxer, AVStream* st) : base(demuxer, st)\n {\n Demuxer = demuxer;\n AVStream = st;\n Refresh();\n }\n\n public void Refresh(AVPixelFormat format = AVPixelFormat.None, AVFrame* frame = null)\n {\n base.Refresh();\n\n PixelFormat = format == AVPixelFormat.None ? (AVPixelFormat)AVStream->codecpar->format : format;\n PixelFormatStr = PixelFormat.ToString().Replace(\"AV_PIX_FMT_\",\"\").ToLower();\n Width = (uint)AVStream->codecpar->width;\n Height = (uint)AVStream->codecpar->height;\n\n // TBR: Maybe required also for input formats with AVFMT_NOTIMESTAMPS (and audio/subs)\n // Possible FFmpeg.Autogen bug with Demuxer.FormatContext->iformat->flags (should be uint?) does not contain AVFMT_NOTIMESTAMPS (256 instead of 384)\n if (Demuxer.Name == \"h264\" || Demuxer.Name == \"hevc\")\n {\n FixTimestamps = true;\n\n if (Demuxer.Config.ForceFPS > 0)\n FPS = Demuxer.Config.ForceFPS;\n else\n FPS = av_q2d(av_guess_frame_rate(Demuxer.FormatContext, AVStream, frame));\n\n if (FPS == 0)\n FPS = 25;\n }\n else\n {\n FixTimestamps = false;\n FPS = av_q2d(av_guess_frame_rate(Demuxer.FormatContext, AVStream, frame));\n }\n\n FrameDuration = FPS > 0 ? (long) (10000000 / FPS) : 0;\n TotalFrames = AVStream->duration > 0 && FrameDuration > 0 ? (int) (AVStream->duration * Timebase / FrameDuration) : (FrameDuration > 0 ? (int) (Demuxer.Duration / FrameDuration) : 0);\n\n int x, y;\n AVRational sar = av_guess_sample_aspect_ratio(null, AVStream, null);\n if (av_cmp_q(sar, av_make_q(0, 1)) <= 0)\n sar = av_make_q(1, 1);\n\n av_reduce(&x, &y, Width * sar.Num, Height * sar.Den, 1024 * 1024);\n AspectRatio = new AspectRatio(x, y);\n\n if (PixelFormat != AVPixelFormat.None)\n {\n ColorRange = AVStream->codecpar->color_range == AVColorRange.Jpeg ? ColorRange.Full : ColorRange.Limited;\n\n if (AVStream->codecpar->color_space == AVColorSpace.Bt470bg)\n ColorSpace = ColorSpace.BT601;\n else if (AVStream->codecpar->color_space == AVColorSpace.Bt709)\n ColorSpace = ColorSpace.BT709;\n else ColorSpace = AVStream->codecpar->color_space == AVColorSpace.Bt2020Cl || AVStream->codecpar->color_space == AVColorSpace.Bt2020Ncl\n ? ColorSpace.BT2020\n : Height > 576 ? ColorSpace.BT709 : ColorSpace.BT601;\n\n // This causes issues\n //if (AVStream->codecpar->color_space == AVColorSpace.AVCOL_SPC_UNSPECIFIED && AVStream->codecpar->color_trc == AVColorTransferCharacteristic.AVCOL_TRC_UNSPECIFIED && Height > 1080)\n //{ // TBR: Handle Dolphy Vision?\n // ColorSpace = ColorSpace.BT2020;\n // ColorTransfer = AVColorTransferCharacteristic.AVCOL_TRC_SMPTE2084;\n //}\n //else\n ColorTransfer = AVStream->codecpar->color_trc;\n\n // We get rotation from frame side data only from 1st frame in case of exif orientation (mainly for jpeg) - TBR if required to check for each frame\n AVFrameSideData* frameSideData;\n AVPacketSideData* pktSideData;\n double rotation = 0;\n if (frame != null && (frameSideData = av_frame_get_side_data(frame, AVFrameSideDataType.Displaymatrix)) != null && frameSideData->data != null)\n rotation = -Math.Round(av_display_rotation_get((int*)frameSideData->data)); //int_array9 displayMatrix = Marshal.PtrToStructure((nint)frameSideData->data); TBR: NaN why?\n else if ((pktSideData = av_packet_side_data_get(AVStream->codecpar->coded_side_data, AVStream->codecpar->nb_coded_side_data, AVPacketSideDataType.Displaymatrix)) != null && pktSideData->data != null)\n rotation = -Math.Round(av_display_rotation_get((int*)pktSideData->data));\n\n Rotation = rotation - (360*Math.Floor(rotation/360 + 0.9/360));\n\n PixelFormatDesc = av_pix_fmt_desc_get(PixelFormat);\n var comps = PixelFormatDesc->comp.ToArray();\n PixelComps = new AVComponentDescriptor[PixelFormatDesc->nb_components];\n for (int i=0; ilog2_chroma_w != PixelFormatDesc->log2_chroma_h;\n IsRGB = (PixelFormatDesc->flags & PixFmtFlags.Rgb) != 0;\n\n PixelSameDepth = true;\n PixelPlanes = 0;\n if (PixelComps.Length > 0)\n {\n PixelComp0Depth = PixelComps[0].depth;\n int prevBit = PixelComp0Depth;\n for (int i=0; i PixelPlanes)\n PixelPlanes = PixelComps[i].plane;\n\n if (prevBit != PixelComps[i].depth)\n PixelSameDepth = false;\n }\n\n PixelPlanes++;\n }\n }\n }\n}\n"], ["/LLPlayer/FlyleafLib/MediaPlayer/Translation/Services/ITranslateService.cs", "using System.ComponentModel;\nusing System.Threading;\nusing System.Threading.Tasks;\n\nnamespace FlyleafLib.MediaPlayer.Translation.Services;\n\npublic interface ITranslateService : IDisposable\n{\n TranslateServiceType ServiceType { get; }\n\n /// \n /// Initialize\n /// \n /// \n /// \n /// when language is not supported or configured properly\n void Initialize(Language src, TargetLanguage target);\n\n /// \n /// TranslateAsync\n /// \n /// \n /// \n /// \n /// \n /// when translation is failed\n /// \n Task TranslateAsync(string text, CancellationToken token);\n}\n\n[Flags]\npublic enum TranslateServiceType\n{\n /// \n /// Google V1.\n /// \n [Description(\"Google V1\")]\n GoogleV1 = 1 << 0,\n\n /// \n /// DeepL\n /// \n [Description(nameof(DeepL))]\n DeepL = 1 << 1,\n\n /// \n /// DeepLX\n /// https://github.com/OwO-Network/DeepLX\n /// \n [Description(nameof(DeepLX))]\n DeepLX = 1 << 2,\n\n /// \n /// Ollama\n /// \n [Description(nameof(Ollama))]\n Ollama = 1 << 3,\n\n /// \n /// LM Studio\n /// \n [Description(\"LM Studio\")]\n LMStudio = 1 << 4,\n\n /// \n /// KoboldCpp\n /// \n [Description(nameof(KoboldCpp))]\n KoboldCpp = 1 << 5,\n\n /// \n /// OpenAI (ChatGPT)\n /// \n [Description(nameof(OpenAI))]\n OpenAI = 1 << 6,\n\n /// \n /// OpenAI compatible\n /// \n [Description(\"OpenAI Like\")]\n OpenAILike = 1 << 7,\n\n /// \n /// Anthropic Claude\n /// \n [Description(nameof(Claude))]\n Claude = 1 << 8,\n\n /// \n /// LiteLLM\n /// \n [Description(nameof(LiteLLM))]\n LiteLLM = 1 << 9,\n}\n\npublic static class TranslateServiceTypeExtensions\n{\n public static TranslateServiceType LLMServices =>\n TranslateServiceType.Ollama |\n TranslateServiceType.LMStudio |\n TranslateServiceType.KoboldCpp |\n TranslateServiceType.OpenAI |\n TranslateServiceType.OpenAILike |\n TranslateServiceType.Claude |\n TranslateServiceType.LiteLLM;\n\n public static bool IsLLM(this TranslateServiceType serviceType)\n {\n return LLMServices.HasFlag(serviceType);\n }\n\n public static ITranslateSettings DefaultSettings(this TranslateServiceType serviceType)\n {\n switch (serviceType)\n {\n case TranslateServiceType.GoogleV1:\n return new GoogleV1TranslateSettings();\n case TranslateServiceType.DeepL:\n return new DeepLTranslateSettings();\n case TranslateServiceType.DeepLX:\n return new DeepLXTranslateSettings();\n case TranslateServiceType.Ollama:\n return new OllamaTranslateSettings();\n case TranslateServiceType.LMStudio:\n return new LMStudioTranslateSettings();\n case TranslateServiceType.KoboldCpp:\n return new KoboldCppTranslateSettings();\n case TranslateServiceType.OpenAI:\n return new OpenAITranslateSettings();\n case TranslateServiceType.OpenAILike:\n return new OpenAILikeTranslateSettings();\n case TranslateServiceType.Claude:\n return new ClaudeTranslateSettings();\n case TranslateServiceType.LiteLLM:\n return new LiteLLMTranslateSettings();\n }\n\n throw new InvalidOperationException();\n }\n}\n\npublic static class TranslateServiceHelper\n{\n /// \n /// TryGetLanguage\n /// \n /// \n /// \n /// \n /// \n /// \n public static (TranslateLanguage srcLang, TranslateLanguage targetLang) TryGetLanguage(this ITranslateService service, Language src, TargetLanguage target)\n {\n string iso6391 = src.ISO6391;\n\n // TODO: L: Allow the user to choose auto-detection by translation provider?\n if (src == Language.Unknown)\n {\n throw new TranslationConfigException(\"source language are unknown\");\n }\n\n if (src.ISO6391 == target.ToISO6391())\n {\n // Only chinese allow translation between regions (Simplified <-> Traditional)\n // Portuguese, French, and English are not permitted.\n // TODO: L: review this validation?\n if (target is not (TargetLanguage.ChineseSimplified or TargetLanguage.ChineseTraditional))\n {\n throw new TranslationConfigException(\"source and target language are same\");\n }\n }\n\n if (!TranslateLanguage.Langs.TryGetValue(iso6391, out TranslateLanguage srcLang))\n {\n throw new TranslationConfigException($\"source language is not supported: {src.TopEnglishName}\");\n }\n\n if (!srcLang.SupportedServices.HasFlag(service.ServiceType))\n {\n throw new TranslationConfigException($\"source language is not supported by {service.ServiceType}: {src.TopEnglishName}\");\n }\n\n if (!TranslateLanguage.Langs.TryGetValue(target.ToISO6391(), out TranslateLanguage targetLang))\n {\n throw new TranslationConfigException($\"target language is not supported: {target.ToString()}\");\n }\n\n if (!targetLang.SupportedServices.HasFlag(service.ServiceType))\n {\n throw new TranslationConfigException($\"target language is not supported by {service.ServiceType}: {src.TopEnglishName}\");\n }\n\n return (srcLang, targetLang);\n }\n}\n\npublic class TranslationException : Exception\n{\n public TranslationException()\n {\n }\n\n public TranslationException(string message)\n : base(message)\n {\n }\n\n public TranslationException(string message, Exception inner)\n : base(message, inner)\n {\n }\n}\n\npublic class TranslationConfigException : Exception\n{\n public TranslationConfigException()\n {\n }\n\n public TranslationConfigException(string message)\n : base(message)\n {\n }\n\n public TranslationConfigException(string message, Exception inner)\n : base(message, inner)\n {\n }\n}\n"], ["/LLPlayer/FlyleafLib/Engine/TesseractModel.cs", "using System.Collections.Generic;\nusing System.IO;\nusing System.Linq;\n\nnamespace FlyleafLib;\n\n#nullable enable\n\npublic class TesseractModel : NotifyPropertyChanged, IEquatable\n{\n public static Dictionary TesseractLangToISO6391 { get; } = new()\n {\n {TesseractOCR.Enums.Language.Afrikaans, \"af\"},\n {TesseractOCR.Enums.Language.Amharic, \"am\"},\n {TesseractOCR.Enums.Language.Arabic, \"ar\"},\n {TesseractOCR.Enums.Language.Assamese, \"as\"},\n {TesseractOCR.Enums.Language.Azerbaijani, \"az\"},\n //{TesseractOCR.Enums.Language.AzerbaijaniCyrilic, \"\"},\n {TesseractOCR.Enums.Language.Belarusian, \"be\"},\n {TesseractOCR.Enums.Language.Bengali, \"bn\"},\n {TesseractOCR.Enums.Language.Tibetan, \"bo\"},\n {TesseractOCR.Enums.Language.Bosnian, \"bs\"},\n {TesseractOCR.Enums.Language.Breton, \"br\"},\n {TesseractOCR.Enums.Language.Bulgarian, \"bg\"},\n {TesseractOCR.Enums.Language.CatalanValencian, \"ca\"},\n //{TesseractOCR.Enums.Language.Cebuano, \"\"},\n {TesseractOCR.Enums.Language.Czech, \"cs\"},\n {TesseractOCR.Enums.Language.ChineseSimplified, \"zh\"}, // do special handling\n {TesseractOCR.Enums.Language.ChineseTraditional, \"zh\"},\n //{TesseractOCR.Enums.Language.Cherokee, \"\"},\n {TesseractOCR.Enums.Language.Corsican, \"co\"},\n {TesseractOCR.Enums.Language.Welsh, \"cy\"},\n {TesseractOCR.Enums.Language.Danish, \"da\"},\n //{TesseractOCR.Enums.Language.DanishFraktur, \"\"},\n {TesseractOCR.Enums.Language.German, \"de\"},\n //{TesseractOCR.Enums.Language.GermanFrakturContrib, \"\"},\n {TesseractOCR.Enums.Language.Dzongkha, \"dz\"},\n {TesseractOCR.Enums.Language.GreekModern, \"el\"},\n {TesseractOCR.Enums.Language.English, \"en\"},\n //{TesseractOCR.Enums.Language.EnglishMiddle, \"\"},\n {TesseractOCR.Enums.Language.Esperanto, \"eo\"},\n //{TesseractOCR.Enums.Language.Math, \"zz\"},\n {TesseractOCR.Enums.Language.Estonian, \"et\"},\n {TesseractOCR.Enums.Language.Basque, \"eu\"},\n {TesseractOCR.Enums.Language.Faroese, \"fo\"},\n {TesseractOCR.Enums.Language.Persian, \"fa\"},\n //{TesseractOCR.Enums.Language.Filipino, \"\"},\n {TesseractOCR.Enums.Language.Finnish, \"fi\"},\n {TesseractOCR.Enums.Language.French, \"fr\"},\n //{TesseractOCR.Enums.Language.GermanFraktur, \"\"},\n {TesseractOCR.Enums.Language.FrenchMiddle, \"zz\"},\n //{TesseractOCR.Enums.Language.WesternFrisian, \"\"},\n {TesseractOCR.Enums.Language.ScottishGaelic, \"gd\"},\n {TesseractOCR.Enums.Language.Irish, \"ga\"},\n {TesseractOCR.Enums.Language.Galician, \"gl\"},\n //{TesseractOCR.Enums.Language.GreekAncientContrib, \"\"},\n {TesseractOCR.Enums.Language.Gujarati, \"gu\"},\n {TesseractOCR.Enums.Language.Haitian, \"ht\"},\n {TesseractOCR.Enums.Language.Hebrew, \"he\"},\n {TesseractOCR.Enums.Language.Hindi, \"hi\"},\n {TesseractOCR.Enums.Language.Croatian, \"hr\"},\n {TesseractOCR.Enums.Language.Hungarian, \"hu\"},\n {TesseractOCR.Enums.Language.Armenian, \"hy\"},\n {TesseractOCR.Enums.Language.Inuktitut, \"iu\"},\n {TesseractOCR.Enums.Language.Indonesian, \"id\"},\n {TesseractOCR.Enums.Language.Icelandic, \"is\"},\n {TesseractOCR.Enums.Language.Italian, \"it\"},\n //{TesseractOCR.Enums.Language.ItalianOld, \"\"},\n {TesseractOCR.Enums.Language.Javanese, \"jv\"},\n {TesseractOCR.Enums.Language.Japanese, \"ja\"},\n //{TesseractOCR.Enums.Language.JapaneseVertical, \"\"},\n {TesseractOCR.Enums.Language.Kannada, \"kn\"},\n {TesseractOCR.Enums.Language.Georgian, \"ka\"},\n //{TesseractOCR.Enums.Language.GeorgianOld, \"\"},\n {TesseractOCR.Enums.Language.Kazakh, \"kk\"},\n {TesseractOCR.Enums.Language.CentralKhmer, \"km\"},\n {TesseractOCR.Enums.Language.KirghizKyrgyz, \"ky\"},\n {TesseractOCR.Enums.Language.Kurmanji, \"ku\"},\n {TesseractOCR.Enums.Language.Korean, \"ko\"},\n //{TesseractOCR.Enums.Language.KoreanVertical, \"\"},\n //{TesseractOCR.Enums.Language.KurdishArabicScript, \"\"},\n {TesseractOCR.Enums.Language.Lao, \"lo\"},\n {TesseractOCR.Enums.Language.Latin, \"la\"},\n {TesseractOCR.Enums.Language.Latvian, \"lv\"},\n {TesseractOCR.Enums.Language.Lithuanian, \"lt\"},\n {TesseractOCR.Enums.Language.Luxembourgish, \"lb\"},\n {TesseractOCR.Enums.Language.Malayalam, \"ml\"},\n {TesseractOCR.Enums.Language.Marathi, \"mr\"},\n {TesseractOCR.Enums.Language.Macedonian, \"mk\"},\n {TesseractOCR.Enums.Language.Maltese, \"mt\"},\n {TesseractOCR.Enums.Language.Mongolian, \"mn\"},\n {TesseractOCR.Enums.Language.Maori, \"mi\"},\n {TesseractOCR.Enums.Language.Malay, \"ms\"},\n {TesseractOCR.Enums.Language.Burmese, \"my\"},\n {TesseractOCR.Enums.Language.Nepali, \"ne\"},\n {TesseractOCR.Enums.Language.Dutch, \"nl\"},\n {TesseractOCR.Enums.Language.Norwegian, \"no\"},\n {TesseractOCR.Enums.Language.Occitan, \"oc\"},\n {TesseractOCR.Enums.Language.Oriya, \"or\"},\n //{TesseractOCR.Enums.Language.Osd, \"\"},\n {TesseractOCR.Enums.Language.Panjabi, \"pa\"},\n {TesseractOCR.Enums.Language.Polish, \"pl\"},\n {TesseractOCR.Enums.Language.Portuguese, \"pt\"},\n {TesseractOCR.Enums.Language.Pushto, \"ps\"},\n {TesseractOCR.Enums.Language.Quechua, \"qu\"},\n {TesseractOCR.Enums.Language.Romanian, \"ro\"},\n {TesseractOCR.Enums.Language.Russian, \"ru\"},\n {TesseractOCR.Enums.Language.Sanskrit, \"sa\"},\n {TesseractOCR.Enums.Language.Sinhala, \"si\"},\n {TesseractOCR.Enums.Language.Slovak, \"sk\"},\n //{TesseractOCR.Enums.Language.SlovakFrakturContrib, \"\"},\n {TesseractOCR.Enums.Language.Slovenian, \"sl\"},\n {TesseractOCR.Enums.Language.Sindhi, \"sd\"},\n {TesseractOCR.Enums.Language.SpanishCastilian, \"es\"},\n //{TesseractOCR.Enums.Language.SpanishCastilianOld, \"\"},\n {TesseractOCR.Enums.Language.Albanian, \"sq\"},\n {TesseractOCR.Enums.Language.Serbian, \"sr\"},\n //{TesseractOCR.Enums.Language.SerbianLatin, \"\"},\n {TesseractOCR.Enums.Language.Sundanese, \"su\"},\n {TesseractOCR.Enums.Language.Swahili, \"sw\"},\n {TesseractOCR.Enums.Language.Swedish, \"sv\"},\n //{TesseractOCR.Enums.Language.Syriac, \"\"},\n {TesseractOCR.Enums.Language.Tamil, \"ta\"},\n {TesseractOCR.Enums.Language.Tatar, \"tt\"},\n {TesseractOCR.Enums.Language.Telugu, \"te\"},\n {TesseractOCR.Enums.Language.Tajik, \"tg\"},\n {TesseractOCR.Enums.Language.Tagalog, \"tl\"},\n {TesseractOCR.Enums.Language.Thai, \"th\"},\n {TesseractOCR.Enums.Language.Tigrinya, \"ti\"},\n {TesseractOCR.Enums.Language.Tonga, \"to\"},\n {TesseractOCR.Enums.Language.Turkish, \"tr\"},\n {TesseractOCR.Enums.Language.Uighur, \"ug\"},\n {TesseractOCR.Enums.Language.Ukrainian, \"uk\"},\n {TesseractOCR.Enums.Language.Urdu, \"ur\"},\n {TesseractOCR.Enums.Language.Uzbek, \"uz\"},\n //{TesseractOCR.Enums.Language.UzbekCyrilic, \"\"},\n {TesseractOCR.Enums.Language.Vietnamese, \"vi\"},\n {TesseractOCR.Enums.Language.Yiddish, \"yi\"},\n {TesseractOCR.Enums.Language.Yoruba, \"yo\"},\n };\n\n public static string ModelsDirectory { get; } = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, \"tesseractmodels\", \"tessdata\");\n\n public TesseractOCR.Enums.Language Lang { get; set; }\n\n public string ISO6391 => TesseractLangToISO6391[Lang];\n\n public string LangCode =>\n TesseractOCR.Enums.LanguageHelper.EnumToString(Lang);\n\n public long Size\n {\n get;\n set\n {\n if (Set(ref field, value))\n {\n Raise(nameof(Downloaded));\n }\n }\n }\n\n public string ModelFileName => $\"{LangCode}.traineddata\";\n\n public string ModelFilePath => Path.Combine(ModelsDirectory, ModelFileName);\n\n public bool Downloaded => Size > 0;\n\n public override string ToString() => LangCode;\n\n public bool Equals(TesseractModel? other)\n {\n if (other is null) return false;\n if (ReferenceEquals(this, other)) return true;\n return Lang == other.Lang;\n }\n\n public override bool Equals(object? obj) => obj is TesseractModel o && Equals(o);\n\n public override int GetHashCode()\n {\n return (int)Lang;\n }\n}\n\npublic class TesseractModelLoader\n{\n /// \n /// key: ISO6391, value: TesseractModel\n /// Chinese has multiple models for one ISO6391 key\n /// \n /// \n internal static Dictionary> GetAvailableModels()\n {\n List models = LoadDownloadedModels();\n\n Dictionary> dict = new();\n\n foreach (TesseractModel model in models)\n {\n if (TesseractModel.TesseractLangToISO6391.TryGetValue(model.Lang, out string? iso6391))\n {\n if (dict.ContainsKey(iso6391))\n {\n // for chinese (zh-CN, zh-TW)\n dict[iso6391].Add(model);\n }\n else\n {\n dict.Add(iso6391, [model]);\n }\n }\n }\n\n return dict;\n }\n\n public static List LoadAllModels()\n {\n EnsureModelsDirectory();\n\n List models = Enum.GetValues()\n .Where(l => TesseractModel.TesseractLangToISO6391.ContainsKey(l))\n .Select(l => new TesseractModel { Lang = l })\n .OrderBy(m => m.Lang.ToString())\n .ToList();\n\n foreach (TesseractModel model in models)\n {\n // Initialize download status of each model\n string path = model.ModelFilePath;\n if (File.Exists(path))\n {\n model.Size = new FileInfo(path).Length;\n }\n }\n\n return models;\n }\n\n public static List LoadDownloadedModels()\n {\n return LoadAllModels()\n .Where(m => m.Downloaded)\n .ToList();\n }\n\n private static void EnsureModelsDirectory()\n {\n if (!Directory.Exists(TesseractModel.ModelsDirectory))\n {\n Directory.CreateDirectory(TesseractModel.ModelsDirectory);\n }\n }\n}\n"], ["/LLPlayer/FlyleafLib/MediaFramework/MediaRenderer/Renderer.Present.cs", "using System;\nusing System.Threading;\nusing System.Threading.Tasks;\n\nusing Vortice.DXGI;\nusing Vortice.Direct3D11;\n\nusing FlyleafLib.MediaFramework.MediaDecoder;\nusing FlyleafLib.MediaFramework.MediaFrame;\n\nusing static FlyleafLib.Logger;\n\nnamespace FlyleafLib.MediaFramework.MediaRenderer;\n\npublic unsafe partial class Renderer\n{\n bool isPresenting;\n long lastPresentAt = 0;\n long lastPresentRequestAt= 0;\n object lockPresentTask = new();\n\n public bool Present(VideoFrame frame, bool forceWait = true)\n {\n if (Monitor.TryEnter(lockDevice, frame.timestamp == 0 ? 100 : 5)) // Allow more time for first frame\n {\n try\n {\n PresentInternal(frame, forceWait);\n VideoDecoder.DisposeFrame(LastFrame);\n LastFrame = frame;\n\n if (child != null)\n child.LastFrame = frame;\n\n return true;\n\n }\n catch (Exception e)\n {\n if (CanWarn) Log.Warn($\"Present frame failed {e.Message} | {Device?.DeviceRemovedReason}\");\n VideoDecoder.DisposeFrame(frame);\n\n vpiv?.Dispose();\n\n return false;\n\n }\n finally\n {\n Monitor.Exit(lockDevice);\n }\n }\n\n if (CanDebug) Log.Debug(\"Dropped Frame - Lock timeout \" + (frame != null ? Utils.TicksToTime(frame.timestamp) : \"\"));\n VideoDecoder.DisposeFrame(frame);\n\n return false;\n }\n public void Present()\n {\n if (SCDisposed)\n return;\n\n // NOTE: We don't have TimeBeginPeriod, FpsForIdle will not be accurate\n lock (lockPresentTask)\n {\n if ((Config.Player.player == null || !Config.Player.player.requiresBuffering) && VideoDecoder.IsRunning && (VideoStream == null || VideoStream.FPS > 10)) // With slow FPS we need to refresh as fast as possible\n return;\n\n if (isPresenting)\n {\n lastPresentRequestAt = DateTime.UtcNow.Ticks;\n return;\n }\n\n isPresenting = true;\n }\n\n Task.Run(() =>\n {\n long presentingAt;\n do\n {\n long sleepMs = DateTime.UtcNow.Ticks - lastPresentAt;\n sleepMs = sleepMs < (long)(1.0 / Config.Player.IdleFps * 1000 * 10000) ? (long) (1.0 / Config.Player.IdleFps * 1000) : 0;\n if (sleepMs > 2)\n Thread.Sleep((int)sleepMs);\n\n presentingAt = DateTime.UtcNow.Ticks;\n RefreshLayout();\n lastPresentAt = DateTime.UtcNow.Ticks;\n\n } while (lastPresentRequestAt > presentingAt);\n\n isPresenting = false;\n });\n }\n internal void PresentInternal(VideoFrame frame, bool forceWait = true)\n {\n if (SCDisposed)\n return;\n\n // TBR: Replica performance issue with D3D11 (more zoom more gpu overload)\n if (frame.srvs == null) // videoProcessor can be FlyleafVP but the player can send us a cached frame from prev videoProcessor D3D11VP (check frame.srv instead of videoProcessor)\n {\n if (frame.avFrame != null)\n {\n vpivd.Texture2D.ArraySlice = (uint) frame.avFrame->data[1];\n vd1.CreateVideoProcessorInputView(VideoDecoder.textureFFmpeg, vpe, vpivd, out vpiv);\n }\n else\n {\n vpivd.Texture2D.ArraySlice = 0;\n vd1.CreateVideoProcessorInputView(frame.textures[0], vpe, vpivd, out vpiv);\n }\n\n vpsa[0].InputSurface = vpiv;\n vc.VideoProcessorBlt(vp, vpov, 0, 1, vpsa);\n swapChain.Present(Config.Video.VSync, forceWait ? PresentFlags.None : Config.Video.PresentFlags);\n\n vpiv.Dispose();\n }\n else\n {\n context.OMSetRenderTargets(backBufferRtv);\n context.ClearRenderTargetView(backBufferRtv, Config.Video._BackgroundColor);\n context.RSSetViewport(GetViewport);\n context.PSSetShaderResources(0, frame.srvs);\n context.Draw(6, 0);\n\n if (overlayTexture != null)\n {\n // Don't stretch the overlay (reduce height based on ratiox) | Sub's stream size might be different from video size (fix y based on percentage)\n var ratiox = (double)GetViewport.Width / overlayTextureOriginalWidth;\n var ratioy = (double)overlayTextureOriginalPosY / overlayTextureOriginalHeight;\n\n context.OMSetBlendState(blendStateAlpha);\n context.PSSetShaderResources(0, overlayTextureSRVs);\n context.RSSetViewport((float) (GetViewport.X + (overlayTextureOriginalPosX * ratiox)), (float) (GetViewport.Y + (GetViewport.Height * ratioy)), (float) (overlayTexture.Description.Width * ratiox), (float) (overlayTexture.Description.Height * ratiox));\n context.PSSetShader(ShaderBGRA);\n context.Draw(6, 0);\n\n // restore context\n context.PSSetShader(ShaderPS);\n context.OMSetBlendState(curPSCase == PSCase.RGBPacked ? blendStateAlpha : null);\n }\n\n swapChain.Present(Config.Video.VSync, forceWait ? PresentFlags.None : Config.Video.PresentFlags);\n }\n\n child?.PresentInternal(frame);\n }\n\n public void ClearOverlayTexture()\n {\n if (overlayTexture == null)\n return;\n\n overlayTexture?.Dispose();\n overlayTextureSrv?.Dispose();\n overlayTexture = null;\n overlayTextureSrv = null;\n }\n\n internal void CreateOverlayTexture(SubtitlesFrame frame, int streamWidth, int streamHeight)\n {\n var rect = frame.sub.rects[0];\n var stride = rect->linesize[0] * 4;\n\n overlayTextureOriginalWidth = streamWidth;\n overlayTextureOriginalHeight= streamHeight;\n overlayTextureOriginalPosX = rect->x;\n overlayTextureOriginalPosY = rect->y;\n overlayTextureDesc.Width = (uint)rect->w;\n overlayTextureDesc.Height = (uint)rect->h;\n\n byte[] data = ConvertBitmapSub(frame.sub, false);\n\n fixed(byte* ptr = data)\n {\n SubresourceData subData = new()\n {\n DataPointer = (nint)ptr,\n RowPitch = (uint)stride\n };\n\n overlayTexture?.Dispose();\n overlayTextureSrv?.Dispose();\n overlayTexture = Device.CreateTexture2D(overlayTextureDesc, new SubresourceData[] { subData });\n overlayTextureSrv = Device.CreateShaderResourceView(overlayTexture);\n overlayTextureSRVs[0] = overlayTextureSrv;\n }\n }\n\n public static byte[] ConvertBitmapSub(AVSubtitle sub, bool grey)\n {\n var rect = sub.rects[0];\n var stride = rect->linesize[0] * 4;\n\n byte[] data = new byte[rect->w * rect->h * 4];\n Span colors = stackalloc uint[256];\n\n fixed(byte* ptr = data)\n {\n var colorsData = new Span((byte*)rect->data[1], rect->nb_colors);\n\n for (int i = 0; i < colorsData.Length; i++)\n colors[i] = colorsData[i];\n\n ConvertPal(colors, 256, grey);\n\n for (int y = 0; y < rect->h; y++)\n {\n uint* xout =(uint*) (ptr + y * stride);\n byte* xin = ((byte*)rect->data[0]) + y * rect->linesize[0];\n\n for (int x = 0; x < rect->w; x++)\n *xout++ = colors[*xin++];\n }\n }\n\n return data;\n }\n\n static void ConvertPal(Span colors, int count, bool gray) // subs bitmap (source: mpv)\n {\n for (int n = 0; n < count; n++)\n {\n uint c = colors[n];\n uint b = c & 0xFF;\n uint g = (c >> 8) & 0xFF;\n uint r = (c >> 16) & 0xFF;\n uint a = (c >> 24) & 0xFF;\n\n if (gray)\n r = g = b = (r + g + b) / 3;\n\n // from straight to pre-multiplied alpha\n b = b * a / 255;\n g = g * a / 255;\n r = r * a / 255;\n colors[n] = b | (g << 8) | (r << 16) | (a << 24);\n }\n }\n\n public void RefreshLayout()\n {\n if (Monitor.TryEnter(lockDevice, 5))\n {\n try\n {\n if (SCDisposed)\n return;\n\n if (LastFrame != null && (LastFrame.textures != null || LastFrame.avFrame != null))\n PresentInternal(LastFrame);\n else if (Config.Video.ClearScreen)\n {\n context.ClearRenderTargetView(backBufferRtv, Config.Video._BackgroundColor);\n swapChain.Present(Config.Video.VSync, PresentFlags.None);\n }\n }\n catch (Exception e)\n {\n if (CanWarn) Log.Warn($\"Present idle failed {e.Message} | {Device.DeviceRemovedReason}\");\n }\n finally\n {\n Monitor.Exit(lockDevice);\n }\n }\n }\n public void ClearScreen()\n {\n ClearOverlayTexture();\n VideoDecoder.DisposeFrame(LastFrame);\n Present();\n }\n}\n"], ["/LLPlayer/FlyleafLib/MediaFramework/MediaRemuxer/Remuxer.cs", "using System.Collections.Generic;\nusing System.Diagnostics;\n\nnamespace FlyleafLib.MediaFramework.MediaRemuxer;\n\npublic unsafe class Remuxer\n{\n public int UniqueId { get; set; }\n public bool Disposed { get; private set; } = true;\n public string Filename { get; private set; }\n public bool HasStreams => mapInOutStreams2.Count > 0 || mapInOutStreams.Count > 0;\n public bool HeaderWritten { get; private set; }\n\n Dictionary mapInOutStreams = new();\n Dictionary mapInInStream = new();\n Dictionary mapInStreamToDts = new();\n Dictionary mapInOutStreams2 = new();\n Dictionary mapInInStream2 = new();\n Dictionary mapInStreamToDts2 = new();\n\n AVFormatContext* fmtCtx;\n AVOutputFormat* fmt;\n\n public Remuxer(int uniqueId = -1)\n => UniqueId = uniqueId == -1 ? Utils.GetUniqueId() : uniqueId;\n\n public int Open(string filename)\n {\n int ret;\n Filename = filename;\n\n fixed (AVFormatContext** ptr = &fmtCtx)\n ret = avformat_alloc_output_context2(ptr, null, null, Filename);\n\n if (ret < 0) return ret;\n\n fmt = fmtCtx->oformat;\n mapInStreamToDts = new Dictionary();\n Disposed = false;\n\n return 0;\n }\n\n public int AddStream(AVStream* in_stream, bool isAudioDemuxer = false)\n {\n int ret = -1;\n\n if (in_stream == null || (in_stream->codecpar->codec_type != AVMediaType.Video && in_stream->codecpar->codec_type != AVMediaType.Audio)) return ret;\n\n AVStream *out_stream;\n var in_codecpar = in_stream->codecpar;\n\n out_stream = avformat_new_stream(fmtCtx, null);\n if (out_stream == null) return -1;\n\n ret = avcodec_parameters_copy(out_stream->codecpar, in_codecpar);\n if (ret < 0) return ret;\n\n // Copy metadata (currently only language)\n AVDictionaryEntry* b = null;\n while (true)\n {\n b = av_dict_get(in_stream->metadata, \"\", b, DictReadFlags.IgnoreSuffix);\n if (b == null) break;\n\n if (Utils.BytePtrToStringUTF8(b->key).ToLower() == \"language\" || Utils.BytePtrToStringUTF8(b->key).ToLower() == \"lang\")\n av_dict_set(&out_stream->metadata, Utils.BytePtrToStringUTF8(b->key), Utils.BytePtrToStringUTF8(b->value), 0);\n }\n\n out_stream->codecpar->codec_tag = 0;\n\n // TODO:\n // validate that the output format container supports the codecs (if not change the container?)\n // check whether we remux from mp4 to mpegts (requires bitstream filter h264_mp4toannexb)\n\n //if (av_codec_get_tag(fmtCtx->oformat->codec_tag, in_stream->codecpar->codec_id) == 0)\n // Log(\"Not Found\");\n //else\n // Log(\"Found\");\n\n if (isAudioDemuxer)\n {\n mapInOutStreams2.Add((IntPtr)in_stream, (IntPtr)out_stream);\n mapInInStream2.Add(in_stream->index, (IntPtr)in_stream);\n }\n else\n {\n mapInOutStreams.Add((IntPtr)in_stream, (IntPtr)out_stream);\n mapInInStream.Add(in_stream->index, (IntPtr)in_stream);\n }\n\n return 0;\n }\n\n public int WriteHeader()\n {\n if (!HasStreams) throw new Exception(\"No streams have been configured for the remuxer\");\n\n int ret;\n\n ret = avio_open(&fmtCtx->pb, Filename, IOFlags.Write);\n if (ret < 0) { Dispose(); return ret; }\n\n ret = avformat_write_header(fmtCtx, null);\n\n if (ret < 0) { Dispose(); return ret; }\n\n HeaderWritten = true;\n\n return 0;\n }\n\n public int Write(AVPacket* packet, bool isAudioDemuxer = false)\n {\n lock (this)\n {\n var mapInInStream = !isAudioDemuxer? this.mapInInStream : mapInInStream2;\n var mapInOutStreams = !isAudioDemuxer? this.mapInOutStreams : mapInOutStreams2;\n var mapInStreamToDts = !isAudioDemuxer? this.mapInStreamToDts: mapInStreamToDts2;\n\n AVStream* in_stream = (AVStream*) mapInInStream[packet->stream_index];\n AVStream* out_stream = (AVStream*) mapInOutStreams[(IntPtr)in_stream];\n\n if (packet->dts != AV_NOPTS_VALUE)\n {\n\n if (!mapInStreamToDts.ContainsKey(in_stream->index))\n {\n // TODO: In case of AudioDemuxer calculate the diff with the VideoDemuxer and add it in one of them - all stream - (in a way to have positive)\n mapInStreamToDts.Add(in_stream->index, packet->dts);\n }\n\n packet->pts = packet->pts == AV_NOPTS_VALUE ? AV_NOPTS_VALUE : av_rescale_q_rnd(packet->pts - mapInStreamToDts[in_stream->index], in_stream->time_base, out_stream->time_base, AVRounding.NearInf | AVRounding.PassMinmax);\n packet->dts = av_rescale_q_rnd(packet->dts - mapInStreamToDts[in_stream->index], in_stream->time_base, out_stream->time_base, AVRounding.NearInf | AVRounding.PassMinmax);\n }\n else\n {\n packet->pts = packet->pts == AV_NOPTS_VALUE ? AV_NOPTS_VALUE : av_rescale_q_rnd(packet->pts, in_stream->time_base, out_stream->time_base, AVRounding.NearInf | AVRounding.PassMinmax);\n packet->dts = AV_NOPTS_VALUE;\n }\n\n packet->duration = av_rescale_q(packet->duration,in_stream->time_base, out_stream->time_base);\n packet->stream_index = out_stream->index;\n packet->pos = -1;\n\n int ret = av_interleaved_write_frame(fmtCtx, packet);\n av_packet_free(&packet);\n\n return ret;\n }\n }\n\n public int WriteTrailer() => Dispose();\n public int Dispose()\n {\n if (Disposed) return -1;\n\n int ret = 0;\n\n if (fmtCtx != null)\n {\n if (HeaderWritten)\n {\n ret = av_write_trailer(fmtCtx);\n avio_closep(&fmtCtx->pb);\n }\n\n avformat_free_context(fmtCtx);\n }\n\n fmtCtx = null;\n Filename = null;\n Disposed = true;\n HeaderWritten = false;\n mapInOutStreams.Clear();\n mapInInStream.Clear();\n mapInOutStreams2.Clear();\n mapInInStream2.Clear();\n\n return ret;\n }\n\n private void Log(string msg)\n => Debug.WriteLine($\"[{DateTime.Now:hh.mm.ss.fff}] [#{UniqueId}] [Remuxer] {msg}\");\n}\n"], ["/LLPlayer/FlyleafLib/MediaPlayer/Translation/Services/GoogleV1TranslateService.cs", "using System.Collections.Generic;\nusing System.Linq;\nusing System.Net.Http;\nusing System.Text.Json;\nusing System.Threading;\nusing System.Threading.Tasks;\n\nnamespace FlyleafLib.MediaPlayer.Translation.Services;\n\n#nullable enable\n\npublic class GoogleV1TranslateService : ITranslateService\n{\n internal static Dictionary DefaultRegions { get; } = new()\n {\n [\"zh\"] = \"zh-CN\",\n [\"pt\"] = \"pt-PT\",\n [\"fr\"] = \"fr-FR\",\n };\n\n private readonly HttpClient _httpClient;\n private string? _srcLang;\n private string? _targetLang;\n private readonly GoogleV1TranslateSettings _settings;\n\n public GoogleV1TranslateService(GoogleV1TranslateSettings settings)\n {\n if (string.IsNullOrWhiteSpace(settings.Endpoint))\n {\n throw new TranslationConfigException(\n $\"Endpoint for {ServiceType} is not configured.\");\n }\n\n _settings = settings;\n _httpClient = new HttpClient();\n _httpClient.BaseAddress = new Uri(settings.Endpoint);\n _httpClient.Timeout = TimeSpan.FromMilliseconds(settings.TimeoutMs);\n }\n\n public TranslateServiceType ServiceType => TranslateServiceType.GoogleV1;\n\n public void Dispose()\n {\n _httpClient.Dispose();\n }\n\n public void Initialize(Language src, TargetLanguage target)\n {\n (TranslateLanguage srcLang, _) = this.TryGetLanguage(src, target);\n\n _srcLang = ToSourceCode(srcLang.ISO6391);\n _targetLang = ToTargetCode(target);\n }\n\n private string ToSourceCode(string iso6391)\n {\n if (iso6391 == \"nb\")\n {\n // handle 'Norwegian Bokmål' as 'Norwegian'\n return \"no\";\n }\n\n // ref: https://cloud.google.com/translate/docs/languages?hl=en\n if (!DefaultRegions.TryGetValue(iso6391, out string? defaultRegion))\n {\n // no region languages\n return iso6391;\n }\n\n // has region languages\n return _settings.Regions.GetValueOrDefault(iso6391, defaultRegion);\n }\n\n private static string ToTargetCode(TargetLanguage target)\n {\n return target switch\n {\n TargetLanguage.ChineseSimplified => \"zh-CN\",\n TargetLanguage.ChineseTraditional => \"zh-TW\",\n TargetLanguage.French => \"fr-FR\",\n TargetLanguage.FrenchCanadian => \"fr-CA\",\n TargetLanguage.Portuguese => \"pt-PT\",\n TargetLanguage.PortugueseBrazilian => \"pt-BR\",\n _ => target.ToISO6391()\n };\n }\n\n public async Task TranslateAsync(string text, CancellationToken token)\n {\n string jsonResultString = \"\";\n int statusCode = -1;\n\n try\n {\n var url = $\"/translate_a/single?client=gtx&sl={_srcLang}&tl={_targetLang}&dt=t&q={Uri.EscapeDataString(text)}\";\n\n using var result = await _httpClient.GetAsync(url, token).ConfigureAwait(false);\n jsonResultString = await result.Content.ReadAsStringAsync(token).ConfigureAwait(false);\n\n statusCode = (int)result.StatusCode;\n result.EnsureSuccessStatusCode();\n\n List resultTexts = new();\n using JsonDocument doc = JsonDocument.Parse(jsonResultString);\n resultTexts.AddRange(doc.RootElement[0].EnumerateArray().Select(arr => arr[0].GetString()!.Trim()));\n\n return string.Join(Environment.NewLine, resultTexts);\n }\n // Distinguish between timeout and cancel errors\n catch (OperationCanceledException ex)\n when (!ex.Message.StartsWith(\"The request was canceled due to the configured HttpClient.Timeout\"))\n {\n // cancel\n throw;\n }\n catch (Exception ex)\n {\n // timeout and other error\n throw new TranslationException($\"Cannot request to {ServiceType}: {ex.Message}\", ex)\n {\n Data =\n {\n [\"status_code\"] = statusCode.ToString(),\n [\"response\"] = jsonResultString\n }\n };\n }\n }\n}\n"], ["/LLPlayer/FlyleafLib/MediaPlayer/Commands.cs", "using System.Threading.Tasks;\nusing System.Windows.Input;\n\nusing FlyleafLib.Controls.WPF;\nusing FlyleafLib.MediaFramework.MediaPlaylist;\nusing FlyleafLib.MediaFramework.MediaStream;\n\nnamespace FlyleafLib.MediaPlayer;\n\npublic class Commands\n{\n public ICommand AudioDelaySet { get; set; }\n public ICommand AudioDelaySet2 { get; set; }\n public ICommand AudioDelayAdd { get; set; }\n public ICommand AudioDelayAdd2 { get; set; }\n public ICommand AudioDelayRemove { get; set; }\n public ICommand AudioDelayRemove2 { get; set; }\n\n public ICommand SubtitlesDelaySetPrimary { get; set; }\n public ICommand SubtitlesDelaySet2Primary { get; set; }\n public ICommand SubtitlesDelayAddPrimary { get; set; }\n public ICommand SubtitlesDelayAdd2Primary { get; set; }\n public ICommand SubtitlesDelayRemovePrimary { get; set; }\n public ICommand SubtitlesDelayRemove2Primary { get; set; }\n\n public ICommand SubtitlesDelaySetSecondary { get; set; }\n public ICommand SubtitlesDelaySet2Secondary { get; set; }\n public ICommand SubtitlesDelayAddSecondary { get; set; }\n public ICommand SubtitlesDelayAdd2Secondary { get; set; }\n public ICommand SubtitlesDelayRemoveSecondary { get; set; }\n public ICommand SubtitlesDelayRemove2Secondary { get; set; }\n\n public ICommand OpenSubtitles { get; set; }\n public ICommand OpenSubtitlesASR { get; set; }\n public ICommand SubtitlesOff { get; set; }\n\n public ICommand Open { get; set; }\n public ICommand OpenFromClipboard { get; set; }\n public ICommand OpenFromFileDialog { get; set; }\n public ICommand Reopen { get; set; }\n public ICommand CopyToClipboard { get; set; }\n public ICommand CopyItemToClipboard { get; set; }\n\n public ICommand Play { get; set; }\n public ICommand Pause { get; set; }\n public ICommand Stop { get; set; }\n public ICommand TogglePlayPause { get; set; }\n\n public ICommand SeekBackward { get; set; }\n public ICommand SeekBackward2 { get; set; }\n public ICommand SeekBackward3 { get; set; }\n public ICommand SeekBackward4 { get; set; }\n public ICommand SeekForward { get; set; }\n public ICommand SeekForward2 { get; set; }\n public ICommand SeekForward3 { get; set; }\n public ICommand SeekForward4 { get; set; }\n public ICommand SeekToChapter { get; set; }\n\n public ICommand ShowFramePrev { get; set; }\n public ICommand ShowFrameNext { get; set; }\n\n public ICommand NormalScreen { get; set; }\n public ICommand FullScreen { get; set; }\n public ICommand ToggleFullScreen { get; set; }\n\n public ICommand ToggleReversePlayback { get; set; }\n public ICommand ToggleLoopPlayback { get; set; }\n public ICommand StartRecording { get; set; }\n public ICommand StopRecording { get; set; }\n public ICommand ToggleRecording { get; set; }\n\n public ICommand TakeSnapshot { get; set; }\n public ICommand ZoomIn { get; set; }\n public ICommand ZoomOut { get; set; }\n public ICommand RotationSet { get; set; }\n public ICommand RotateLeft { get; set; }\n public ICommand RotateRight { get; set; }\n public ICommand ResetAll { get; set; }\n public ICommand ResetSpeed { get; set; }\n public ICommand ResetRotation { get; set; }\n public ICommand ResetZoom { get; set; }\n\n public ICommand SpeedSet { get; set; }\n public ICommand SpeedUp { get; set; }\n public ICommand SpeedUp2 { get; set; }\n public ICommand SpeedDown { get; set; }\n public ICommand SpeedDown2 { get; set; }\n\n public ICommand VolumeUp { get; set; }\n public ICommand VolumeDown { get; set; }\n public ICommand ToggleMute { get; set; }\n\n public ICommand ForceIdle { get; set; }\n public ICommand ForceActive { get; set; }\n public ICommand ForceFullActive { get; set; }\n public ICommand RefreshActive { get; set; }\n public ICommand RefreshFullActive { get; set; }\n\n public ICommand ResetFilter { get; set; }\n\n Player player;\n\n public Commands(Player player)\n {\n this.player = player;\n\n Open = new RelayCommand(OpenAction);\n OpenFromClipboard = new RelayCommandSimple(player.OpenFromClipboard);\n OpenFromFileDialog = new RelayCommandSimple(player.OpenFromFileDialog);\n Reopen = new RelayCommand(ReopenAction);\n CopyToClipboard = new RelayCommandSimple(player.CopyToClipboard);\n CopyItemToClipboard = new RelayCommandSimple(player.CopyItemToClipboard);\n\n Play = new RelayCommandSimple(player.Play);\n Pause = new RelayCommandSimple(player.Pause);\n TogglePlayPause = new RelayCommandSimple(player.TogglePlayPause);\n Stop = new RelayCommandSimple(player.Stop);\n\n SeekBackward = new RelayCommandSimple(player.SeekBackward);\n SeekBackward2 = new RelayCommandSimple(player.SeekBackward2);\n SeekBackward3 = new RelayCommandSimple(player.SeekBackward3);\n SeekBackward4 = new RelayCommandSimple(player.SeekBackward4);\n SeekForward = new RelayCommandSimple(player.SeekForward);\n SeekForward2 = new RelayCommandSimple(player.SeekForward2);\n SeekForward3 = new RelayCommandSimple(player.SeekForward3);\n SeekForward4 = new RelayCommandSimple(player.SeekForward4);\n SeekToChapter = new RelayCommand(SeekToChapterAction);\n\n ShowFrameNext = new RelayCommandSimple(player.ShowFrameNext);\n ShowFramePrev = new RelayCommandSimple(player.ShowFramePrev);\n\n NormalScreen = new RelayCommandSimple(player.NormalScreen);\n FullScreen = new RelayCommandSimple(player.FullScreen);\n ToggleFullScreen = new RelayCommandSimple(player.ToggleFullScreen);\n\n ToggleReversePlayback = new RelayCommandSimple(player.ToggleReversePlayback);\n ToggleLoopPlayback = new RelayCommandSimple(player.ToggleLoopPlayback);\n StartRecording = new RelayCommandSimple(player.StartRecording);\n StopRecording = new RelayCommandSimple(player.StopRecording);\n ToggleRecording = new RelayCommandSimple(player.ToggleRecording);\n\n TakeSnapshot = new RelayCommandSimple(TakeSnapshotAction);\n ZoomIn = new RelayCommandSimple(player.ZoomIn);\n ZoomOut = new RelayCommandSimple(player.ZoomOut);\n RotationSet = new RelayCommand(RotationSetAction);\n RotateLeft = new RelayCommandSimple(player.RotateLeft);\n RotateRight = new RelayCommandSimple(player.RotateRight);\n ResetAll = new RelayCommandSimple(player.ResetAll);\n ResetSpeed = new RelayCommandSimple(player.ResetSpeed);\n ResetRotation = new RelayCommandSimple(player.ResetRotation);\n ResetZoom = new RelayCommandSimple(player.ResetZoom);\n\n SpeedSet = new RelayCommand(SpeedSetAction);\n SpeedUp = new RelayCommandSimple(player.SpeedUp);\n SpeedDown = new RelayCommandSimple(player.SpeedDown);\n SpeedUp2 = new RelayCommandSimple(player.SpeedUp2);\n SpeedDown2 = new RelayCommandSimple(player.SpeedDown2);\n\n VolumeUp = new RelayCommandSimple(player.Audio.VolumeUp);\n VolumeDown = new RelayCommandSimple(player.Audio.VolumeDown);\n ToggleMute = new RelayCommandSimple(player.Audio.ToggleMute);\n\n AudioDelaySet = new RelayCommand(AudioDelaySetAction);\n AudioDelaySet2 = new RelayCommand(AudioDelaySetAction2);\n AudioDelayAdd = new RelayCommandSimple(player.Audio.DelayAdd);\n AudioDelayAdd2 = new RelayCommandSimple(player.Audio.DelayAdd2);\n AudioDelayRemove = new RelayCommandSimple(player.Audio.DelayRemove);\n AudioDelayRemove2 = new RelayCommandSimple(player.Audio.DelayRemove2);\n\n SubtitlesDelaySetPrimary = new RelayCommand(SubtitlesDelaySetActionPrimary);\n SubtitlesDelaySet2Primary = new RelayCommand(SubtitlesDelaySetAction2Primary);\n SubtitlesDelayAddPrimary = new RelayCommandSimple(player.Subtitles.DelayAddPrimary);\n SubtitlesDelayAdd2Primary = new RelayCommandSimple(player.Subtitles.DelayAdd2Primary);\n SubtitlesDelayRemovePrimary = new RelayCommandSimple(player.Subtitles.DelayRemovePrimary);\n SubtitlesDelayRemove2Primary = new RelayCommandSimple(player.Subtitles.DelayRemove2Primary);\n\n SubtitlesDelaySetSecondary = new RelayCommand(SubtitlesDelaySetActionSecondary);\n SubtitlesDelaySet2Secondary = new RelayCommand(SubtitlesDelaySetAction2Secondary);\n SubtitlesDelayAddSecondary = new RelayCommandSimple(player.Subtitles.DelayAddSecondary);\n SubtitlesDelayAdd2Secondary = new RelayCommandSimple(player.Subtitles.DelayAdd2Secondary);\n SubtitlesDelayRemoveSecondary = new RelayCommandSimple(player.Subtitles.DelayRemoveSecondary);\n SubtitlesDelayRemove2Secondary = new RelayCommandSimple(player.Subtitles.DelayRemove2Secondary);\n\n OpenSubtitles = new RelayCommand(OpenSubtitlesAction);\n OpenSubtitlesASR = new RelayCommand(OpenSubtitlesASRAction);\n SubtitlesOff = new RelayCommand(SubtitlesOffAction);\n\n ForceIdle = new RelayCommandSimple(player.Activity.ForceIdle);\n ForceActive = new RelayCommandSimple(player.Activity.ForceActive);\n ForceFullActive = new RelayCommandSimple(player.Activity.ForceFullActive);\n RefreshActive = new RelayCommandSimple(player.Activity.RefreshActive);\n RefreshFullActive = new RelayCommandSimple(player.Activity.RefreshFullActive);\n\n ResetFilter = new RelayCommand(ResetFilterAction);\n }\n\n private void RotationSetAction(object obj)\n => player.Rotation = uint.Parse(obj.ToString());\n\n private void ResetFilterAction(object filter)\n => player.Config.Video.Filters[(VideoFilters)filter].Value = player.Config.Video.Filters[(VideoFilters)filter].DefaultValue;\n\n public void SpeedSetAction(object speed)\n {\n string speedstr = speed.ToString().Replace(',', '.');\n if (double.TryParse(speedstr, System.Globalization.NumberStyles.Any, System.Globalization.CultureInfo.InvariantCulture, out double value))\n player.Speed = value;\n }\n\n public void AudioDelaySetAction(object delay)\n => player.Config.Audio.Delay = int.Parse(delay.ToString()) * (long)10000;\n public void AudioDelaySetAction2(object delay)\n => player.Config.Audio.Delay += int.Parse(delay.ToString()) * (long)10000;\n\n public void SubtitlesDelaySetActionPrimary(object delay)\n => player.Config.Subtitles[0].Delay = int.Parse(delay.ToString()) * (long)10000;\n public void SubtitlesDelaySetAction2Primary(object delay)\n => player.Config.Subtitles[0].Delay += int.Parse(delay.ToString()) * (long)10000;\n\n // TODO: L: refactor\n public void SubtitlesDelaySetActionSecondary(object delay)\n => player.Config.Subtitles[1].Delay = int.Parse(delay.ToString()) * (long)10000;\n public void SubtitlesDelaySetAction2Secondary(object delay)\n => player.Config.Subtitles[1].Delay += int.Parse(delay.ToString()) * (long)10000;\n\n\n public void TakeSnapshotAction() => Task.Run(() => { try { player.TakeSnapshotToFile(); } catch { } });\n\n public void SeekToChapterAction(object chapter)\n {\n if (player.Chapters == null || player.Chapters.Count == 0)\n return;\n\n if (chapter is MediaFramework.MediaDemuxer.Demuxer.Chapter)\n player.SeekToChapter((MediaFramework.MediaDemuxer.Demuxer.Chapter)chapter);\n else if (int.TryParse(chapter.ToString(), out int chapterId) && chapterId < player.Chapters.Count)\n player.SeekToChapter(player.Chapters[chapterId]);\n }\n\n public void OpenSubtitlesAction(object input)\n {\n if (input is not ValueTuple tuple)\n {\n return;\n }\n\n if (tuple is { Item1: string, Item2: SubtitlesStream, Item3: SelectSubMethod })\n {\n var subIndex = int.Parse((string)tuple.Item1);\n var stream = (SubtitlesStream)tuple.Item2;\n var selectSubMethod = (SelectSubMethod)tuple.Item3;\n\n if (selectSubMethod == SelectSubMethod.OCR)\n {\n if (!TryInitializeOCR(subIndex, stream.Language))\n {\n return;\n }\n }\n\n SubtitlesSelectedHelper.Set(subIndex, (stream.StreamIndex, null));\n SubtitlesSelectedHelper.SetMethod(subIndex, selectSubMethod);\n SubtitlesSelectedHelper.CurIndex = subIndex;\n }\n else if (tuple is { Item1: string, Item2: ExternalSubtitlesStream, Item3: SelectSubMethod })\n {\n var subIndex = int.Parse((string)tuple.Item1);\n var stream = (ExternalSubtitlesStream)tuple.Item2;\n var selectSubMethod = (SelectSubMethod)tuple.Item3;\n\n if (selectSubMethod == SelectSubMethod.OCR)\n {\n if (!TryInitializeOCR(subIndex, stream.Language))\n {\n return;\n }\n }\n\n SubtitlesSelectedHelper.Set(subIndex, (null, stream));\n SubtitlesSelectedHelper.SetMethod(subIndex, selectSubMethod);\n SubtitlesSelectedHelper.CurIndex = subIndex;\n }\n\n OpenAction(tuple.Item2);\n return;\n\n bool TryInitializeOCR(int subIndex, Language lang)\n {\n if (!player.SubtitlesOCR.TryInitialize(subIndex, lang, out string err))\n {\n player.RaiseKnownErrorOccurred(err, KnownErrorType.Configuration);\n return false;\n }\n\n return true;\n }\n }\n\n public void OpenSubtitlesASRAction(object input)\n {\n if (!int.TryParse(input.ToString(), out var subIndex))\n {\n return;\n }\n\n if (!player.Audio.IsOpened)\n {\n // not opened\n return;\n }\n\n if (!player.SubtitlesASR.CanExecute(out string err))\n {\n player.RaiseKnownErrorOccurred(err, KnownErrorType.Configuration);\n return;\n }\n\n if (player.IsLive)\n {\n player.RaiseKnownErrorOccurred(\"Currently ASR is not available for live streams.\", KnownErrorType.ASR);\n return;\n }\n\n SubtitlesSelectedHelper.CurIndex = subIndex;\n\n // First, turn off existing subtitles (if not ASR)\n if (!player.Subtitles[subIndex].EnabledASR)\n {\n player.Subtitles[subIndex].Disable();\n }\n\n player.Subtitles[subIndex].EnableASR();\n }\n\n public void SubtitlesOffAction(object input)\n {\n if (int.TryParse(input.ToString(), out var subIndex))\n {\n SubtitlesSelectedHelper.CurIndex = subIndex;\n player.Subtitles[subIndex].Disable();\n }\n }\n\n public void OpenAction(object input)\n {\n if (input == null)\n return;\n\n if (input is StreamBase)\n player.OpenAsync((StreamBase)input);\n else if (input is PlaylistItem)\n player.OpenAsync((PlaylistItem)input);\n else if (input is ExternalStream)\n player.OpenAsync((ExternalStream)input);\n else if (input is System.IO.Stream)\n player.OpenAsync((System.IO.Stream)input);\n else\n player.OpenAsync(input.ToString());\n }\n\n public void ReopenAction(object playlistItem)\n {\n if (playlistItem == null)\n return;\n\n PlaylistItem item = (PlaylistItem)playlistItem;\n if (item.OpenedCounter > 0)\n {\n var session = player.GetSession(item);\n session.isReopen = true;\n session.CurTime = 0;\n\n // TBR: in case of disabled audio/video/subs it will save the session with them to be disabled\n\n // TBR: This can cause issues and it might not useful either\n //if (session.CurTime < 60 * (long)1000 * 10000)\n // session.CurTime = 0;\n\n player.OpenAsync(session);\n }\n else\n player.OpenAsync(item);\n }\n}\n"], ["/LLPlayer/LLPlayer/ViewModels/SubtitlesExportDialogVM.cs", "using System.Diagnostics;\nusing System.IO;\nusing System.Diagnostics.CodeAnalysis;\nusing System.Text;\nusing FlyleafLib.MediaPlayer;\nusing LLPlayer.Extensions;\nusing LLPlayer.Services;\nusing SaveFileDialog = Microsoft.Win32.SaveFileDialog;\n\nnamespace LLPlayer.ViewModels;\n\npublic class SubtitlesExportDialogVM : Bindable, IDialogAware\n{\n public FlyleafManager FL { get; }\n\n public SubtitlesExportDialogVM(FlyleafManager fl)\n {\n FL = fl;\n\n IsUtf8Bom = FL.Config.Subs.SubsExportUTF8WithBom;\n }\n\n public List SubIndexList { get; } = [0, 1];\n public int SelectedSubIndex\n {\n get;\n set\n {\n if (Set(ref field, value))\n {\n OnPropertyChanged(nameof(SubManager));\n }\n }\n }\n\n public SubManager SubManager => FL.Player.SubtitlesManager[SelectedSubIndex];\n\n public bool IsUtf8Bom { get; set => Set(ref field, value); }\n\n public TranslateExportOptions SelectedTranslateOpts { get; set => Set(ref field, value); }\n\n [field: AllowNull, MaybeNull]\n public DelegateCommand CmdExport => field ??= new(() =>\n {\n var playlist = FL.Player.Playlist.Selected;\n if (playlist == null)\n {\n return;\n }\n\n List lines = FL.Player.SubtitlesManager[SelectedSubIndex].Subs\n .Where(s =>\n {\n if (!s.IsText)\n {\n return false;\n }\n\n if (SelectedTranslateOpts == TranslateExportOptions.TranslatedOnly)\n {\n return s.IsTranslated;\n }\n\n return true;\n })\n .Select(s => new SubtitleLine()\n {\n Text = (SelectedTranslateOpts != TranslateExportOptions.Original\n ? s.DisplayText : s.Text)!,\n Start = s.StartTime,\n End = s.EndTime\n }).ToList();\n\n if (lines.Count == 0)\n {\n ErrorDialogHelper.ShowKnownErrorPopup(\"There were no subtitles to export.\", \"Export\");\n return;\n }\n\n string? initDir = null;\n string fileName;\n\n if (FL.Player.Playlist.Url != null && File.Exists(playlist.Url))\n {\n fileName = Path.GetFileNameWithoutExtension(playlist.Url);\n\n // If there is currently an open file, set that folder as the base folder\n initDir = Path.GetDirectoryName(playlist.Url);\n }\n else\n {\n // If live video, use title instead\n fileName = playlist.Title;\n }\n\n SaveFileDialog saveFileDialog = new()\n {\n Filter = \"SRT files (*.srt)|*.srt|All files (*.*)|*.*\",\n FileName = fileName + \".srt\",\n InitialDirectory = initDir\n };\n\n if (SelectedTranslateOpts != TranslateExportOptions.Original)\n {\n saveFileDialog.FileName = fileName + \".translated.srt\";\n }\n\n if (saveFileDialog.ShowDialog() == true)\n {\n SrtExporter.ExportSrt(lines, saveFileDialog.FileName, new UTF8Encoding(IsUtf8Bom));\n\n // open saved file in explorer\n Process.Start(\"explorer.exe\", $@\"/select,\"\"{saveFileDialog.FileName}\"\"\");\n }\n });\n\n #region IDialogAware\n public string Title { get; set => Set(ref field, value); }\n = $\"Subtitles Exporter - {App.Name}\";\n public double WindowWidth { get; set => Set(ref field, value); } = 350;\n public double WindowHeight { get; set => Set(ref field, value); } = 240;\n\n public DialogCloseListener RequestClose { get; }\n\n public bool CanCloseDialog()\n {\n return true;\n }\n public void OnDialogClosed() { }\n\n public void OnDialogOpened(IDialogParameters parameters) { }\n #endregion\n\n public enum TranslateExportOptions\n {\n Original,\n TranslatedOnly,\n TranslatedWithFallback\n }\n}\n"], ["/LLPlayer/FlyleafLib/MediaFramework/MediaPlaylist/M3UPlaylist.cs", "using System.Collections.Generic;\nusing System.IO;\nusing System.Text.RegularExpressions;\n\nnamespace FlyleafLib.MediaFramework.MediaPlaylist;\n\npublic class M3UPlaylistItem\n{\n public long Duration { get; set; }\n public string Title { get; set; }\n public string OriginalTitle\n { get; set; }\n public string Url { get; set; }\n public string UserAgent { get; set; }\n public string Referrer { get; set; }\n public bool GeoBlocked { get; set; }\n public bool Not_24_7 { get; set; }\n public int Height { get; set; }\n\n public Dictionary Tags { get; set; } = new Dictionary();\n}\n\npublic class M3UPlaylist\n{\n public static List ParseFromHttp(string url, int timeoutMs = 30000)\n {\n string downStr = Utils.DownloadToString(url, timeoutMs);\n if (downStr == null)\n return new();\n\n using StringReader reader = new(downStr);\n return Parse(reader);\n }\n\n public static List ParseFromString(string text)\n {\n using StringReader reader = new(text);\n return Parse(reader);\n }\n\n public static List Parse(string filename)\n {\n using StreamReader reader = new(filename);\n return Parse(reader);\n }\n private static List Parse(TextReader reader)\n {\n string line;\n List items = new();\n\n while ((line = reader.ReadLine()) != null)\n {\n if (line.StartsWith(\"#EXTINF\"))\n {\n M3UPlaylistItem item = new();\n var matches = Regex.Matches(line, \" ([^\\\\s=]+)=\\\"([^\\\\s\\\"]+)\\\"\");\n foreach (Match match in matches)\n {\n if (match.Groups.Count == 3 && !string.IsNullOrWhiteSpace(match.Groups[2].Value))\n item.Tags.Add(match.Groups[1].Value, match.Groups[2].Value);\n }\n\n item.Title = GetMatch(line, @\",\\s*(.*)$\");\n item.OriginalTitle = item.Title;\n\n if (item.Title.IndexOf(\" [Geo-blocked]\") >= 0)\n {\n item.GeoBlocked = true;\n item.Title = item.Title.Replace(\" [Geo-blocked]\", \"\");\n }\n\n if (item.Title.IndexOf(\" [Not 24/7]\") >= 0)\n {\n item.Not_24_7 = true;\n item.Title = item.Title.Replace(\" [Not 24/7]\", \"\");\n }\n\n var height = Regex.Match(item.Title, \" \\\\(([0-9]+)p\\\\)\");\n if (height.Groups.Count == 2)\n {\n item.Height = int.Parse(height.Groups[1].Value);\n item.Title = item.Title.Replace(height.Groups[0].Value, \"\");\n }\n\n while ((line = reader.ReadLine()) != null && line.StartsWith(\"#EXTVLCOPT\"))\n {\n if (item.UserAgent == null)\n {\n item.UserAgent = GetMatch(line, \"http-user-agent\\\\s*=\\\\s*\\\"*(.*)\\\"*\");\n if (item.UserAgent != null) continue;\n }\n\n if (item.Referrer == null)\n {\n item.Referrer = GetMatch(line, \"http-referrer\\\\s*=\\\\s*\\\"*(.*)\\\"*\");\n if (item.Referrer != null) continue;\n }\n }\n\n item.Url = line;\n items.Add(item);\n }\n\n // TODO: for m3u8 saved from windows media player\n //else if (!line.StartsWith(\"#\"))\n //{\n // M3UPlaylistItem item = new();\n // item.Url = line.Trim(); // this can be relative path (base path from the root m3u8) in case of http(s) this can be another m3u8*\n // if (item.Url.Length > 0)\n // {\n // item.Title = Path.GetFileName(item.Url);\n // items.Add(item);\n // }\n //}\n }\n\n return items;\n }\n\n private static string GetMatch(string text, string pattern)\n {\n var match = Regex.Match(text, pattern);\n return match.Success && match.Groups.Count > 1 ? match.Groups[1].Value : null;\n }\n}\n"], ["/LLPlayer/FlyleafLib/Utils/TextEncodings.cs", "using System.IO;\nusing System.Text;\nusing UtfUnknown;\n\nnamespace FlyleafLib;\n\n#nullable enable\n\npublic static class TextEncodings\n{\n private static Encoding? DetectEncodingInternal(byte[] data)\n {\n // 1. Check Unicode BOM\n Encoding? encoding = DetectEncodingWithBOM(data);\n if (encoding != null)\n {\n return encoding;\n }\n\n // 2. If no BOM, then check text is UTF-8 without BOM\n // Perform UTF-8 check first because automatic detection often results in false positives such as WINDOWS-1252.\n if (IsUtf8(data))\n {\n return Encoding.UTF8;\n }\n\n // 3. Auto detect encoding using library\n try\n {\n var result = CharsetDetector.DetectFromBytes(data);\n return result.Detected.Encoding;\n }\n catch\n {\n return null;\n }\n }\n\n /// \n /// Detect character encoding of text binary files\n /// \n /// text binary\n /// Bytes to read\n /// Detected Encoding or null\n public static Encoding? DetectEncoding(byte[] original, int maxBytes = 1 * 1024 * 1024)\n {\n if (maxBytes > original.Length)\n {\n maxBytes = original.Length;\n }\n\n byte[] data = new byte[maxBytes];\n Array.Copy(original, data, maxBytes);\n\n return DetectEncodingInternal(data);\n }\n\n /// \n /// Detect character encoding of text files\n /// \n /// file path\n /// Bytes to read\n /// Detected Encoding or null\n public static Encoding? DetectEncoding(string path, int maxBytes = 1 * 1024 * 1024)\n {\n byte[] data = new byte[maxBytes];\n\n try\n {\n using FileStream fs = new(path, FileMode.Open, FileAccess.Read);\n int bytesRead = fs.Read(data, 0, data.Length);\n Array.Resize(ref data, bytesRead);\n }\n catch\n {\n return null;\n }\n\n return DetectEncodingInternal(data);\n }\n\n /// \n /// Detect character encoding using BOM\n /// \n /// string raw data\n /// Detected Encoding or null\n private static Encoding? DetectEncodingWithBOM(byte[] bytes)\n {\n // UTF-8 BOM: EF BB BF\n if (bytes.Length >= 3 && bytes[0] == 0xEF && bytes[1] == 0xBB && bytes[2] == 0xBF)\n {\n return Encoding.UTF8;\n }\n\n // UTF-16 LE BOM: FF FE\n if (bytes.Length >= 2 && bytes[0] == 0xFF && bytes[1] == 0xFE)\n {\n return Encoding.Unicode; // UTF-16 LE\n }\n\n // UTF-16 BE BOM: FE FF\n if (bytes.Length >= 2 && bytes[0] == 0xFE && bytes[1] == 0xFF)\n {\n return Encoding.BigEndianUnicode; // UTF-16 BE\n }\n\n // UTF-32 LE BOM: FF FE 00 00\n if (bytes.Length >= 4 && bytes[0] == 0xFF && bytes[1] == 0xFE && bytes[2] == 0x00 && bytes[3] == 0x00)\n {\n return Encoding.UTF32;\n }\n\n // UTF-32 BE BOM: 00 00 FE FF\n if (bytes.Length >= 4 && bytes[0] == 0x00 && bytes[1] == 0x00 && bytes[2] == 0xFE && bytes[3] == 0xFF)\n {\n return new UTF32Encoding(bigEndian: true, byteOrderMark: true);\n }\n\n // No BOM\n return null;\n }\n\n private static bool IsUtf8(byte[] bytes)\n {\n // enable validation\n UTF8Encoding encoding = new(encoderShouldEmitUTF8Identifier: false, throwOnInvalidBytes: true);\n\n try\n {\n encoding.GetString(bytes);\n\n return true;\n }\n catch (DecoderFallbackException ex)\n {\n // Ignore when a trailing cut character causes a validation error.\n if (bytes.Length - ex.Index < 4)\n {\n return true;\n }\n\n return false;\n }\n }\n}\n"], ["/LLPlayer/FlyleafLib/MediaFramework/MediaStream/SubtitlesStream.cs", "using System.IO;\nusing System.Linq;\nusing FlyleafLib.MediaFramework.MediaDemuxer;\nusing FlyleafLib.MediaPlayer;\n\nnamespace FlyleafLib.MediaFramework.MediaStream;\n\npublic enum SelectSubMethod\n{\n Original,\n OCR\n}\n\n// Both external and internal subtitles implement this interface and use it with PopMenu.\npublic interface ISubtitlesStream\n{\n public bool EnabledPrimarySubtitle { get; }\n public bool EnabledSecondarySubtitle { get; }\n}\n\npublic class SelectedSubMethod\n{\n private readonly ISubtitlesStream _stream;\n\n public SelectedSubMethod(ISubtitlesStream stream, SelectSubMethod method)\n {\n _stream = stream;\n SelectSubMethod = method;\n }\n\n public SelectSubMethod SelectSubMethod { get; }\n\n public bool IsPrimaryEnabled => _stream.EnabledPrimarySubtitle\n && SelectSubMethod == SubtitlesSelectedHelper.PrimaryMethod;\n\n public bool IsSecondaryEnabled => _stream.EnabledSecondarySubtitle\n && SelectSubMethod == SubtitlesSelectedHelper.SecondaryMethod;\n}\n\npublic unsafe class SubtitlesStream : StreamBase, ISubtitlesStream\n{\n public bool IsBitmap { get; set; }\n\n public SelectedSubMethod[] SelectedSubMethods {\n get\n {\n var methods = (SelectSubMethod[])Enum.GetValues(typeof(SelectSubMethod));\n if (!IsBitmap)\n {\n // delete OCR if text sub\n methods = methods.Where(m => m != SelectSubMethod.OCR).ToArray();\n }\n\n return methods.\n Select(m => new SelectedSubMethod(this, m)).ToArray();\n }\n }\n\n public string DisplayMember => $\"[#{StreamIndex}] {Language} ({(IsBitmap ? \"BMP\" : \"TXT\")})\";\n\n public override string GetDump()\n => $\"[{Type} #{StreamIndex}-{Language.IdSubLanguage}{(Title != null ? \"(\" + Title + \")\" : \"\")}] {Codec} | [BR: {BitRate}] | {Utils.TicksToTime((long)(AVStream->start_time * Timebase))}/{Utils.TicksToTime((long)(AVStream->duration * Timebase))} | {Utils.TicksToTime(StartTime)}/{Utils.TicksToTime(Duration)}\";\n\n public SubtitlesStream() { }\n public SubtitlesStream(Demuxer demuxer, AVStream* st) : base(demuxer, st) => Refresh();\n\n public override void Refresh()\n {\n base.Refresh();\n\n var codecDescr = avcodec_descriptor_get(CodecID);\n IsBitmap = codecDescr != null && (codecDescr->props & CodecPropFlags.BitmapSub) != 0;\n\n if (Demuxer.FormatContext->nb_streams == 1) // External Streams (mainly for .sub will have as start time the first subs timestamp)\n StartTime = 0;\n }\n\n public void ExternalStreamAdded()\n {\n // VobSub (parse .idx data to extradata - based on .sub url)\n if (CodecID == AVCodecID.DvdSubtitle && ExternalStream != null && ExternalStream.Url.EndsWith(\".sub\", StringComparison.OrdinalIgnoreCase))\n {\n var idxFile = ExternalStream.Url.Substring(0, ExternalStream.Url.Length - 3) + \"idx\";\n if (File.Exists(idxFile))\n {\n var bytes = File.ReadAllBytes(idxFile);\n AVStream->codecpar->extradata = (byte*)av_malloc((nuint)bytes.Length);\n AVStream->codecpar->extradata_size = bytes.Length;\n Span src = new(bytes);\n Span dst = new(AVStream->codecpar->extradata, bytes.Length);\n src.CopyTo(dst);\n }\n }\n }\n}\n"], ["/LLPlayer/LLPlayer/Extensions/ExtendedDialogService.cs", "using System.Windows;\n\nnamespace LLPlayer.Extensions;\n\n/// \n/// Customize DialogService's Show(), which sets the Owner of the Window and sets it to always-on-top.\n/// ref: https://stackoverflow.com/questions/64420093/prism-idialogservice-show-non-modal-dialog-acts-as-modal\n/// \npublic class ExtendedDialogService(IContainerExtension containerExtension) : DialogService(containerExtension)\n{\n private bool _isOrphan;\n\n protected override void ConfigureDialogWindowContent(string dialogName, IDialogWindow window, IDialogParameters parameters)\n {\n base.ConfigureDialogWindowContent(dialogName, window, parameters);\n\n if (parameters != null &&\n parameters.ContainsKey(MyKnownDialogParameters.OrphanWindow))\n {\n _isOrphan = true;\n }\n }\n\n protected override void ShowDialogWindow(IDialogWindow dialogWindow, bool isModal)\n {\n base.ShowDialogWindow(dialogWindow, isModal);\n\n if (_isOrphan)\n {\n // Show and then clear Owner to place the window based on the parent window and then make it an orphan window.\n _isOrphan = false;\n dialogWindow.Owner = null;\n }\n }\n}\n\n// ref: https://github.com/PrismLibrary/Prism/blob/master/src/Wpf/Prism.Wpf/Dialogs/IDialogServiceCompatExtensions.cs\npublic static class ExtendedDialogServiceExtensions\n{\n /// \n /// Shows a non-modal and singleton dialog.\n /// \n /// The DialogService\n /// The name of the dialog to show.\n /// Whether to set owner to window\n public static void ShowSingleton(this IDialogService dialogService, string name, bool orphan)\n {\n ShowSingleton(dialogService, name, null!, orphan);\n }\n\n /// \n /// Shows a non-modal and singleton dialog.\n /// \n /// The DialogService\n /// The name of the dialog to show.\n /// The action to perform when the dialog is closed.\n /// Whether to set owner to window\n public static void ShowSingleton(this IDialogService dialogService, string name, Action callback, bool orphan)\n {\n var parameters = EnsureShowNonModalParameter(null);\n\n var windows = Application.Current.Windows.OfType();\n if (windows.Any())\n {\n var curWindow = windows.FirstOrDefault(w => w.Content.GetType().Name == name);\n if (curWindow != null && curWindow is Window win)\n {\n // If minimized, it will not be displayed after Activate, so set it back to Normal in advance.\n if (win.WindowState == WindowState.Minimized)\n {\n win.WindowState = WindowState.Normal;\n }\n // TODO: L: Notify to ViewModel to update query\n win.Activate();\n return;\n }\n }\n\n if (orphan)\n {\n parameters.Add(MyKnownDialogParameters.OrphanWindow, true);\n }\n\n dialogService.Show(name, parameters, callback);\n }\n\n private static IDialogParameters EnsureShowNonModalParameter(IDialogParameters? parameters)\n {\n parameters ??= new DialogParameters();\n\n if (!parameters.ContainsKey(KnownDialogParameters.ShowNonModal))\n parameters.Add(KnownDialogParameters.ShowNonModal, true);\n\n return parameters;\n }\n}\n\npublic static class MyKnownDialogParameters\n{\n public const string OrphanWindow = \"orphanWindow\";\n}\n"], ["/LLPlayer/LLPlayer/Converters/GeneralConverters.cs", "using System.Globalization;\nusing System.Windows;\nusing System.Windows.Data;\nusing System.Windows.Input;\nusing System.Windows.Media;\nusing LLPlayer.Services;\n\nnamespace LLPlayer.Converters;\n[ValueConversion(typeof(bool), typeof(bool))]\npublic class InvertBooleanConverter : IValueConverter\n{\n public object Convert(object value, Type targetType, object parameter, CultureInfo culture)\n {\n if (value is bool boolValue)\n {\n return !boolValue;\n }\n return false;\n }\n\n public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)\n {\n if (value is bool boolValue)\n {\n return !boolValue;\n }\n return false;\n }\n}\n\n[ValueConversion(typeof(bool), typeof(Visibility))]\npublic class BooleanToVisibilityMiscConverter : IValueConverter\n{\n public Visibility FalseVisibility { get; set; } = Visibility.Collapsed;\n public bool Invert { get; set; } = false;\n\n public object Convert(object value, Type targetType, object parameter, CultureInfo culture)\n {\n if (Invert)\n {\n return (bool)value ? FalseVisibility : Visibility.Visible;\n }\n\n return (bool)value ? Visibility.Visible : FalseVisibility;\n }\n\n public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture) => throw new NotImplementedException();\n}\n\n[ValueConversion(typeof(double), typeof(double))]\npublic class DoubleToPercentageConverter : IValueConverter\n{\n // Model → View (0.0–1.0 → 0–100)\n public object Convert(object value, Type targetType, object parameter, CultureInfo culture)\n {\n if (value is double d)\n return Math.Round(d * 100.0, 0);\n return 0.0;\n }\n\n // View → Model (0–100 → 0.0–1.0)\n public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)\n {\n if (value is double d)\n return ToDouble(d);\n\n if (value is string sd)\n {\n if (double.TryParse(sd, out d))\n {\n if (d < 0)\n d = 0;\n else if (d > 100)\n d = 100;\n }\n\n return ToDouble(d);\n }\n\n return 0.0;\n\n static double ToDouble(double value)\n {\n return Math.Max(0.0, Math.Min(1.0, Math.Round(value / 100.0, 2)));\n }\n }\n}\n\n[ValueConversion(typeof(Enum), typeof(string))]\npublic class EnumToStringConverter : IValueConverter\n{\n public object Convert(object value, Type targetType, object parameter, CultureInfo culture)\n {\n string str;\n try\n {\n str = Enum.GetName(value.GetType(), value)!;\n return str;\n }\n catch\n {\n return string.Empty;\n }\n }\n\n public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture) => throw new NotImplementedException();\n}\n\n[ValueConversion(typeof(Enum), typeof(string))]\npublic class EnumToDescriptionConverter : IValueConverter\n{\n public object Convert(object value, Type targetType, object parameter, CultureInfo culture)\n {\n if (value is Enum enumValue)\n {\n return enumValue.GetDescription();\n }\n return value.ToString() ?? \"\";\n }\n\n public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)\n {\n throw new NotImplementedException();\n }\n}\n\n[ValueConversion(typeof(Enum), typeof(bool))]\npublic class EnumToBooleanConverter : IValueConverter\n{\n // value, parameter = Enum\n public object Convert(object value, Type targetType, object parameter, CultureInfo culture)\n {\n if (value is not Enum enumValue || parameter is not Enum enumTarget)\n return false;\n\n return enumValue.Equals(enumTarget);\n }\n\n public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)\n {\n return parameter;\n }\n}\n\n[ValueConversion(typeof(Enum), typeof(Visibility))]\npublic class EnumToVisibilityConverter : IValueConverter\n{\n // value, parameter = Enum\n public object Convert(object value, Type targetType, object parameter, CultureInfo culture)\n {\n if (value is not Enum enumValue || parameter is not Enum enumTarget)\n return false;\n\n return enumValue.Equals(enumTarget) ? Visibility.Visible : Visibility.Collapsed;\n }\n\n public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)\n {\n throw new NotImplementedException();\n }\n}\n\n[ValueConversion(typeof(Color), typeof(Brush))]\npublic class ColorToBrushConverter : IValueConverter\n{\n public object Convert(object value, Type targetType, object parameter, CultureInfo culture)\n {\n if (value is Color color)\n {\n return new SolidColorBrush(color);\n }\n return Binding.DoNothing;\n }\n\n public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)\n {\n if (value is SolidColorBrush brush)\n {\n return brush.Color;\n }\n return default(Color);\n }\n}\n\n/// \n/// Converts from System.Windows.Input.Key to human readable string\n/// \n[ValueConversion(typeof(Key), typeof(string))]\npublic class KeyToStringConverter : IValueConverter\n{\n public static readonly Dictionary KeyMappings = new()\n {\n { Key.D0, \"0\" },\n { Key.D1, \"1\" },\n { Key.D2, \"2\" },\n { Key.D3, \"3\" },\n { Key.D4, \"4\" },\n { Key.D5, \"5\" },\n { Key.D6, \"6\" },\n { Key.D7, \"7\" },\n { Key.D8, \"8\" },\n { Key.D9, \"9\" },\n { Key.Prior, \"PageUp\" },\n { Key.Next, \"PageDown\" },\n { Key.Return, \"Enter\" },\n { Key.Oem1, \";\" },\n { Key.Oem2, \"/\" },\n { Key.Oem3, \"`\" },\n { Key.Oem4, \"[\" },\n { Key.Oem5, \"\\\\\" },\n { Key.Oem6, \"]\" },\n { Key.Oem7, \"'\" },\n { Key.OemPlus, \"Plus\" },\n { Key.OemMinus, \"Minus\" },\n { Key.OemComma, \",\" },\n { Key.OemPeriod, \".\" }\n };\n\n public object Convert(object? value, Type targetType, object? parameter, CultureInfo culture)\n {\n if (value is Key key)\n {\n if (KeyMappings.TryGetValue(key, out var mappedValue))\n {\n return mappedValue;\n }\n\n return key.ToString();\n }\n\n return Binding.DoNothing;\n }\n\n public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)\n {\n throw new NotImplementedException();\n }\n}\n\n[ValueConversion(typeof(long), typeof(string))]\npublic class FileSizeHumanConverter : IValueConverter\n{\n public object Convert(object value, Type targetType, object parameter, CultureInfo culture)\n {\n if (value is long size)\n {\n return FormatBytes(size);\n }\n\n return Binding.DoNothing;\n }\n\n public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)\n {\n throw new NotImplementedException();\n }\n\n private static string FormatBytes(long bytes)\n {\n string[] sizes = [\"B\", \"KB\", \"MB\", \"GB\"];\n double len = bytes;\n int order = 0;\n while (len >= 1024 && order < sizes.Length - 1)\n {\n order++;\n len /= 1024;\n }\n return $\"{len:0.##} {sizes[order]}\";\n }\n}\n\n[ValueConversion(typeof(int?), typeof(string))]\npublic class NullableIntConverter : IValueConverter\n{\n public object Convert(object? value, Type targetType, object? parameter, CultureInfo culture)\n {\n return value is int intValue ? intValue.ToString() : string.Empty;\n }\n\n public object? ConvertBack(object? value, Type targetType, object? parameter, CultureInfo culture)\n {\n string? str = value as string;\n if (string.IsNullOrWhiteSpace(str))\n return null;\n\n if (int.TryParse(str, out int result))\n return result;\n\n return null;\n }\n}\n"], ["/LLPlayer/FlyleafLib/MediaFramework/MediaProgram/Program.cs", "using System.Collections.Generic;\nusing System.Linq;\n\nusing FlyleafLib.MediaFramework.MediaDemuxer;\nusing FlyleafLib.MediaFramework.MediaStream;\n\nnamespace FlyleafLib.MediaFramework.MediaProgram;\n\npublic class Program\n{\n public int ProgramNumber { get; internal set; }\n\n public int ProgramId { get; internal set; }\n\n public IReadOnlyDictionary\n Metadata { get; internal set; }\n\n public IReadOnlyList\n Streams { get; internal set; }\n\n public string Name => Metadata.ContainsKey(\"name\") ? Metadata[\"name\"] : string.Empty;\n\n public unsafe Program(AVProgram* program, Demuxer demuxer)\n {\n ProgramNumber = program->program_num;\n ProgramId = program->id;\n\n // Load stream info\n List streams = new(3);\n for(int s = 0; snb_stream_indexes; s++)\n {\n uint streamIndex = program->stream_index[s];\n StreamBase stream = null;\n stream = demuxer.AudioStreams.FirstOrDefault(it=>it.StreamIndex == streamIndex);\n\n if (stream == null)\n {\n stream = demuxer.VideoStreams.FirstOrDefault(it => it.StreamIndex == streamIndex);\n stream ??= demuxer.SubtitlesStreamsAll.FirstOrDefault(it => it.StreamIndex == streamIndex);\n }\n if (stream!=null)\n {\n streams.Add(stream);\n }\n }\n Streams = streams;\n\n // Load metadata\n Dictionary metadata = new();\n AVDictionaryEntry* b = null;\n while (true)\n {\n b = av_dict_get(program->metadata, \"\", b, DictReadFlags.IgnoreSuffix);\n if (b == null) break;\n metadata.Add(Utils.BytePtrToStringUTF8(b->key), Utils.BytePtrToStringUTF8(b->value));\n }\n Metadata = metadata;\n }\n}\n"], ["/LLPlayer/LLPlayer/Controls/Settings/SettingsPlugins.xaml.cs", "using System.Collections;\nusing System.Globalization;\nusing System.Windows;\nusing System.Windows.Controls;\nusing System.Windows.Data;\nusing LLPlayer.ViewModels;\n\nnamespace LLPlayer.Controls.Settings;\n\npublic partial class SettingsPlugins : UserControl\n{\n public SettingsPlugins()\n {\n InitializeComponent();\n }\n\n private void PluginValueChanged(object sender, RoutedEventArgs e)\n {\n string curPlugin = ((TextBlock)((Panel)((FrameworkElement)sender).Parent).Children[0]).Text;\n\n if (DataContext is SettingsDialogVM vm)\n {\n vm.FL.PlayerConfig.Plugins[cmbPlugins.Text][curPlugin] = ((TextBox)sender).Text;\n }\n }\n}\n\npublic class GetDictionaryItemConverter : IMultiValueConverter\n{\n public object? Convert(object[]? value, Type targetType, object parameter, CultureInfo culture)\n {\n if (value == null)\n return null;\n if (value[0] is not IDictionary dictionary)\n return null;\n if (value[1] is not string key)\n return null;\n\n return dictionary[key];\n }\n public object[] ConvertBack(object value, Type[] targetType, object parameter, CultureInfo culture) { throw new NotImplementedException(); }\n}\n"], ["/LLPlayer/FlyleafLib/MediaPlayer/Translation/Services/DeepLXTranslateService.cs", "using System.Net.Http;\nusing System.Text;\nusing System.Text.Encodings.Web;\nusing System.Text.Json;\nusing System.Threading;\nusing System.Threading.Tasks;\n\nnamespace FlyleafLib.MediaPlayer.Translation.Services;\n\n#nullable enable\n\npublic class DeepLXTranslateService : ITranslateService\n{\n private readonly HttpClient _httpClient;\n private string? _srcLang;\n private string? _targetLang;\n private readonly DeepLXTranslateSettings _settings;\n\n public DeepLXTranslateService(DeepLXTranslateSettings settings)\n {\n if (string.IsNullOrWhiteSpace(settings.Endpoint))\n {\n throw new TranslationConfigException(\n $\"Endpoint for {ServiceType} is not configured.\");\n }\n\n _settings = settings;\n _httpClient = new HttpClient();\n _httpClient.BaseAddress = new Uri(settings.Endpoint);\n _httpClient.Timeout = TimeSpan.FromMilliseconds(settings.TimeoutMs);\n }\n\n private static readonly JsonSerializerOptions JsonOptions = new()\n {\n Encoder = JavaScriptEncoder.UnsafeRelaxedJsonEscaping\n };\n\n public TranslateServiceType ServiceType => TranslateServiceType.DeepLX;\n\n public void Dispose()\n {\n _httpClient.Dispose();\n }\n\n public void Initialize(Language src, TargetLanguage target)\n {\n (TranslateLanguage srcLang, _) = this.TryGetLanguage(src, target);\n\n _srcLang = ToSourceCode(srcLang.ISO6391);\n _targetLang = ToTargetCode(target);\n }\n\n private string ToSourceCode(string iso6391)\n {\n return DeepLTranslateService.ToSourceCode(iso6391);\n }\n\n private string ToTargetCode(TargetLanguage target)\n {\n return DeepLTranslateService.ToTargetCode(target);\n }\n\n public async Task TranslateAsync(string text, CancellationToken token)\n {\n if (_srcLang == null || _targetLang == null)\n {\n throw new InvalidOperationException(\"must be initialized\");\n }\n\n string jsonResultString = \"\";\n int statusCode = -1;\n\n try\n {\n DeepLXTranslateRequest requestBody = new()\n {\n source_lang = _srcLang,\n target_lang = _targetLang,\n text = text\n };\n\n string jsonRequest = JsonSerializer.Serialize(requestBody, JsonOptions);\n using StringContent content = new(jsonRequest, Encoding.UTF8, \"application/json\");\n\n using var result = await _httpClient.PostAsync(\"/translate\", content, token).ConfigureAwait(false);\n jsonResultString = await result.Content.ReadAsStringAsync(token).ConfigureAwait(false);\n\n statusCode = (int)result.StatusCode;\n result.EnsureSuccessStatusCode();\n\n DeepLXTranslateResult? responseData = JsonSerializer.Deserialize(jsonResultString);\n return responseData!.data;\n }\n catch (OperationCanceledException ex)\n when (!ex.Message.StartsWith(\"The request was canceled due to the configured HttpClient.Timeout\"))\n {\n throw;\n }\n catch (Exception ex)\n {\n throw new TranslationException($\"Cannot request to {ServiceType}: {ex.Message}\", ex)\n {\n Data =\n {\n [\"status_code\"] = statusCode.ToString(),\n [\"response\"] = jsonResultString\n }\n };\n }\n }\n\n private class DeepLXTranslateRequest\n {\n public required string text { get; init; }\n public string? source_lang { get; init; }\n public required string target_lang { get; init; }\n }\n\n private class DeepLXTranslateResult\n {\n public required string[] alternatives { get; init; }\n public required string data { get; init; }\n public required string source_lang { get; init; }\n public required string target_lang { get; init; }\n }\n}\n"], ["/LLPlayer/FlyleafLib/MediaFramework/MediaFrame/SubtitlesFrame.cs", "using System.Collections.Generic;\nusing System.Drawing;\nusing System.Globalization;\n\nnamespace FlyleafLib.MediaFramework.MediaFrame;\n\npublic class SubtitlesFrame : FrameBase\n{\n public bool isBitmap;\n public uint duration;\n public string text;\n public List subStyles;\n public AVSubtitle sub;\n public SubtitlesFrameBitmap bitmap;\n\n // for translation switch\n public bool isTranslated;\n}\n\npublic class SubtitlesFrameBitmap\n{\n // Buffer to hold decoded pixels\n public byte[] data;\n public int width;\n public int height;\n public int x;\n public int y;\n}\n\npublic struct SubStyle\n{\n public SubStyles style;\n public Color value;\n\n public int from;\n public int len;\n\n public SubStyle(int from, int len, Color value) : this(SubStyles.COLOR, from, len, value) { }\n public SubStyle(SubStyles style, int from = -1, int len = -1, Color? value = null)\n {\n this.style = style;\n this.value = value == null ? Color.White : (Color)value;\n this.from = from;\n this.len = len;\n }\n}\n\npublic enum SubStyles\n{\n BOLD,\n ITALIC,\n UNDERLINE,\n STRIKEOUT,\n FONTSIZE,\n FONTNAME,\n COLOR\n}\n\n/// \n/// Default Subtitles Parser\n/// \npublic static class ParseSubtitles\n{\n public static void Parse(SubtitlesFrame sFrame)\n {\n sFrame.text = SSAtoSubStyles(sFrame.text, out var subStyles);\n sFrame.subStyles = subStyles;\n }\n public static string SSAtoSubStyles(string s, out List styles)\n {\n int pos = 0;\n string sout = \"\";\n styles = new List();\n\n SubStyle bold = new(SubStyles.BOLD);\n SubStyle italic = new(SubStyles.ITALIC);\n SubStyle underline = new(SubStyles.UNDERLINE);\n SubStyle strikeout = new(SubStyles.STRIKEOUT);\n SubStyle color = new(SubStyles.COLOR);\n\n //SubStyle fontname = new SubStyle(SubStyles.FONTNAME);\n //SubStyle fontsize = new SubStyle(SubStyles.FONTSIZE);\n\n if (string.IsNullOrEmpty(s))\n {\n return sout;\n }\n\n s = s.LastIndexOf(\",,\") == -1 ? s : s[(s.LastIndexOf(\",,\") + 2)..].Replace(\"\\\\N\", \"\\n\").Trim();\n\n for (int i = 0; i < s.Length; i++)\n {\n if (s[i] == '{') continue;\n\n if (s[i] == '\\\\' && s[i - 1] == '{')\n {\n int codeLen = s.IndexOf('}', i) - i;\n if (codeLen == -1) continue;\n\n string code = s.Substring(i, codeLen).Trim();\n\n switch (code[1])\n {\n case 'c':\n if (code.Length == 2)\n {\n if (color.from == -1) break;\n\n color.len = pos - color.from;\n if (color.value != Color.Transparent)\n styles.Add(color);\n\n color = new SubStyle(SubStyles.COLOR);\n }\n else\n {\n color.from = pos;\n color.value = Color.Transparent;\n if (code.Length < 7) break;\n\n int colorEnd = code.LastIndexOf('&');\n if (colorEnd < 6) break;\n\n string hexColor = code[4..colorEnd];\n\n int red = int.Parse(hexColor.Substring(hexColor.Length - 2, 2), NumberStyles.HexNumber);\n int green = 0;\n int blue = 0;\n\n if (hexColor.Length - 2 > 0)\n {\n hexColor = hexColor[..^2];\n if (hexColor.Length == 1)\n hexColor = \"0\" + hexColor;\n\n green = int.Parse(hexColor.Substring(hexColor.Length - 2, 2), NumberStyles.HexNumber);\n }\n\n if (hexColor.Length - 2 > 0)\n {\n hexColor = hexColor[..^2];\n if (hexColor.Length == 1)\n hexColor = \"0\" + hexColor;\n\n blue = int.Parse(hexColor.Substring(hexColor.Length - 2, 2), NumberStyles.HexNumber);\n }\n\n color.value = Color.FromArgb(255, red, green, blue);\n }\n break;\n\n case 'b':\n if (code[2] == '0')\n {\n if (bold.from == -1) break;\n\n bold.len = pos - bold.from;\n styles.Add(bold);\n bold = new SubStyle(SubStyles.BOLD);\n }\n else\n {\n bold.from = pos;\n //bold.value = code.Substring(2, code.Length-2);\n }\n\n break;\n\n case 'u':\n if (code[2] == '0')\n {\n if (underline.from == -1) break;\n\n underline.len = pos - underline.from;\n styles.Add(underline);\n underline = new SubStyle(SubStyles.UNDERLINE);\n }\n else\n {\n underline.from = pos;\n }\n\n break;\n\n case 's':\n if (code[2] == '0')\n {\n if (strikeout.from == -1) break;\n\n strikeout.len = pos - strikeout.from;\n styles.Add(strikeout);\n strikeout = new SubStyle(SubStyles.STRIKEOUT);\n }\n else\n {\n strikeout.from = pos;\n }\n\n break;\n\n case 'i':\n if (code.Length > 2 && code[2] == '0')\n {\n if (italic.from == -1) break;\n\n italic.len = pos - italic.from;\n styles.Add(italic);\n italic = new SubStyle(SubStyles.ITALIC);\n }\n else\n {\n italic.from = pos;\n }\n\n break;\n }\n\n i += codeLen;\n continue;\n }\n\n sout += s[i];\n pos++;\n }\n\n // Non-Closing Codes\n int soutPostLast = sout.Length;\n if (bold.from != -1) { bold.len = soutPostLast - bold.from; styles.Add(bold); }\n if (italic.from != -1) { italic.len = soutPostLast - italic.from; styles.Add(italic); }\n if (strikeout.from != -1) { strikeout.len = soutPostLast - strikeout.from; styles.Add(strikeout); }\n if (underline.from != -1) { underline.len = soutPostLast - underline.from; styles.Add(underline); }\n if (color.from != -1 && color.value != Color.Transparent) { color.len = soutPostLast - color.from; styles.Add(color); }\n\n // Greek issue?\n sout = sout.Replace(\"ʼ\", \"Ά\");\n\n return sout;\n }\n}\n"], ["/LLPlayer/LLPlayer/ViewModels/SubtitlesSidebarVM.cs", "using System.ComponentModel;\nusing System.Windows.Data;\nusing FlyleafLib.MediaPlayer;\nusing LLPlayer.Extensions;\nusing LLPlayer.Services;\n\nnamespace LLPlayer.ViewModels;\n\npublic class SubtitlesSidebarVM : Bindable, IDisposable\n{\n public FlyleafManager FL { get; }\n\n public SubtitlesSidebarVM(FlyleafManager fl)\n {\n FL = fl;\n\n FL.Config.PropertyChanged += OnConfigOnPropertyChanged;\n\n // Initialize filtered view for the sidebar\n for (int i = 0; i < _filteredSubs.Length; i++)\n {\n _filteredSubs[i] = (ListCollectionView)CollectionViewSource.GetDefaultView(FL.Player.SubtitlesManager[i].Subs);\n }\n }\n\n public void Dispose()\n {\n FL.Config.PropertyChanged -= OnConfigOnPropertyChanged;\n }\n\n private void OnConfigOnPropertyChanged(object? sender, PropertyChangedEventArgs args)\n {\n switch (args.PropertyName)\n {\n case nameof(FL.Config.SidebarShowSecondary):\n OnPropertyChanged(nameof(SubIndex));\n OnPropertyChanged(nameof(SubManager));\n\n // prevent unnecessary filter update\n if (_lastSearchText[SubIndex] != _trimSearchText)\n {\n ApplyFilter(); // ensure filter applied\n }\n break;\n case nameof(FL.Config.SidebarShowOriginalText):\n // Update ListBox\n OnPropertyChanged(nameof(SubManager));\n\n if (_trimSearchText.Length != 0)\n {\n // because of switch between Text and DisplayText\n ApplyFilter();\n }\n break;\n }\n }\n\n public int SubIndex => !FL.Config.SidebarShowSecondary ? 0 : 1;\n\n public SubManager SubManager => FL.Player.SubtitlesManager[SubIndex];\n\n private readonly ListCollectionView[] _filteredSubs = new ListCollectionView[2];\n\n private string _searchText = string.Empty;\n public string SearchText\n {\n get => _searchText;\n set\n {\n if (Set(ref _searchText, value))\n {\n DebounceFilter();\n }\n }\n }\n\n private string _trimSearchText = string.Empty; // for performance\n\n public string HitCount { get; set => Set(ref field, value); } = string.Empty;\n\n public event EventHandler? RequestScrollToTop;\n\n // TODO: L: Fix implicit changes to reflect\n public DelegateCommand? CmdSubFontSizeChange => field ??= new(increase =>\n {\n if (int.TryParse(increase, out var value))\n {\n FL.Config.SidebarFontSize += value;\n }\n });\n\n public DelegateCommand? CmdSubTextMaskToggle => field ??= new(() =>\n {\n FL.Config.SidebarTextMask = !FL.Config.SidebarTextMask;\n\n // Update ListBox\n OnPropertyChanged(nameof(SubManager));\n });\n\n public DelegateCommand? CmdShowDownloadSubsDialog => field ??= new(() =>\n {\n FL.Action.CmdOpenWindowSubsDownloader.Execute();\n });\n\n public DelegateCommand? CmdShowExportSubsDialog => field ??= new(() =>\n {\n FL.Action.CmdOpenWindowSubsExporter.Execute();\n });\n\n public DelegateCommand? CmdSwapSidebarPosition => field ??= new(() =>\n {\n FL.Config.SidebarLeft = !FL.Config.SidebarLeft;\n });\n\n public DelegateCommand? CmdSubPlay => field ??= new((index) =>\n {\n if (!index.HasValue)\n {\n return;\n }\n\n var sub = SubManager.Subs[index.Value];\n FL.Player.SeekAccurate(sub.StartTime, SubIndex);\n });\n\n public DelegateCommand? CmdSubSync => field ??= new((index) =>\n {\n if (!index.HasValue)\n {\n return;\n }\n\n var sub = SubManager.Subs[index.Value];\n var newDelay = FL.Player.CurTime - sub.StartTime.Ticks;\n\n // Delay's OSD is not displayed, temporarily set to Active\n FL.Player.Activity.ForceActive();\n\n FL.PlayerConfig.Subtitles[SubIndex].Delay = newDelay;\n });\n\n public DelegateCommand? CmdClearSearch => field ??= new(() =>\n {\n if (!FL.Config.SidebarSearchActive)\n return;\n\n Set(ref _searchText, string.Empty, nameof(SearchText));\n _trimSearchText = string.Empty;\n HitCount = string.Empty;\n\n _debounceCts?.Cancel();\n _debounceCts?.Dispose();\n _debounceCts = null;\n\n for (int i = 0; i < _filteredSubs.Length; i++)\n {\n _lastSearchText[i] = string.Empty;\n _filteredSubs[i].Filter = null; // remove filter completely\n _filteredSubs[i].Refresh();\n }\n\n FL.Config.SidebarSearchActive = false;\n\n // move focus to video and enable keybindings\n FL.FlyleafHost!.Surface.Focus();\n\n // for scrolling to current sub\n var prev = SubManager.SelectedSub;\n SubManager.SelectedSub = null;\n SubManager.SelectedSub = prev;\n });\n\n public DelegateCommand? CmdNextMatch => field ??= new(() =>\n {\n if (_filteredSubs[SubIndex].IsEmpty)\n return;\n\n if (!_filteredSubs[SubIndex].MoveCurrentToNext())\n {\n // if last, move to first\n _filteredSubs[SubIndex].MoveCurrentToFirst();\n }\n\n var nextItem = (SubtitleData)_filteredSubs[SubIndex].CurrentItem;\n if (nextItem != null)\n {\n FL.Player.SeekAccurate(nextItem.StartTime, SubIndex);\n FL.Player.Activity.RefreshFullActive();\n }\n });\n\n public DelegateCommand? CmdPrevMatch => field ??= new(() =>\n {\n if (_filteredSubs[SubIndex].IsEmpty)\n return;\n\n if (!_filteredSubs[SubIndex].MoveCurrentToPrevious())\n {\n // if first, move to last\n _filteredSubs[SubIndex].MoveCurrentToLast();\n }\n\n var prevItem = (SubtitleData)_filteredSubs[SubIndex].CurrentItem;\n if (prevItem != null)\n {\n FL.Player.SeekAccurate(prevItem.StartTime, SubIndex);\n FL.Player.Activity.RefreshFullActive();\n }\n });\n\n // Debounce logic\n private CancellationTokenSource? _debounceCts;\n private async void DebounceFilter()\n {\n _debounceCts?.Cancel();\n _debounceCts?.Dispose();\n _debounceCts = new CancellationTokenSource();\n var token = _debounceCts.Token;\n\n try\n {\n await Task.Delay(300, token); // 300ms debounce\n\n if (!token.IsCancellationRequested)\n {\n ApplyFilter();\n }\n }\n catch (OperationCanceledException)\n {\n // ignore\n }\n }\n\n private readonly string[] _lastSearchText = [string.Empty, string.Empty];\n\n private void ApplyFilter()\n {\n _trimSearchText = SearchText.Trim();\n _lastSearchText[SubIndex] = _trimSearchText;\n\n // initialize filter lazily\n _filteredSubs[SubIndex].Filter ??= SubFilter;\n _filteredSubs[SubIndex].Refresh();\n\n int count = _filteredSubs[SubIndex].Count;\n HitCount = count > 0 ? $\"{count} hits\" : \"No hits\";\n\n if (SubManager.SelectedSub != null && _filteredSubs[SubIndex].MoveCurrentTo(SubManager.SelectedSub))\n {\n // scroll to current playing item\n var prev = SubManager.SelectedSub;\n SubManager.SelectedSub = null;\n SubManager.SelectedSub = prev;\n }\n else\n {\n // scroll to top\n if (!_filteredSubs[SubIndex].IsEmpty)\n {\n RequestScrollToTop?.Invoke(this, EventArgs.Empty);\n }\n }\n }\n\n private bool SubFilter(object obj)\n {\n if (_trimSearchText.Length == 0) return true;\n if (obj is not SubtitleData sub) return false;\n\n string? source = FL.Config.SidebarShowOriginalText ? sub.Text : sub.DisplayText;\n return source?.IndexOf(_trimSearchText, StringComparison.OrdinalIgnoreCase) >= 0;\n }\n}\n"], ["/LLPlayer/LLPlayer/Extensions/UIHelper.cs", "using System.Windows;\nusing System.Windows.Media;\n\nnamespace LLPlayer.Extensions;\n\npublic static class UIHelper\n{\n // ref: https://www.infragistics.com/community/blogs/b/blagunas/posts/find-the-parent-control-of-a-specific-type-in-wpf-and-silverlight\n public static T? FindParent(DependencyObject child) where T : DependencyObject\n {\n //get parent item\n DependencyObject? parentObject = VisualTreeHelper.GetParent(child);\n\n //we've reached the end of the tree\n if (parentObject == null)\n return null;\n\n //check if the parent matches the type we're looking for\n if (parentObject is T parent)\n return parent;\n\n return FindParent(parentObject);\n }\n\n /// \n /// Traverses the visual tree upward from the current element to determine if an element with the specified name exists.j\n /// \n /// Element to start with (current element)\n /// Name of the element\n /// True if the element with the specified name exists, false otherwise.\n public static bool FindParentWithName(DependencyObject? element, string name)\n {\n if (element == null)\n {\n return false;\n }\n\n DependencyObject? current = element;\n\n while (current != null)\n {\n if (current is FrameworkElement fe && fe.Name == name)\n {\n return true;\n }\n\n current = VisualTreeHelper.GetParent(current);\n }\n\n return false;\n }\n}\n"], ["/LLPlayer/FlyleafLib/MediaPlayer/Translation/Services/DeepLTranslateService.cs", "using System.Threading;\nusing System.Threading.Tasks;\nusing DeepL;\nusing DeepL.Model;\n\nnamespace FlyleafLib.MediaPlayer.Translation.Services;\n\n#nullable enable\n\npublic class DeepLTranslateService : ITranslateService\n{\n private string? _srcLang;\n private string? _targetLang;\n private readonly Translator _translator;\n private readonly DeepLTranslateSettings _settings;\n\n public DeepLTranslateService(DeepLTranslateSettings settings)\n {\n if (string.IsNullOrWhiteSpace(settings.ApiKey))\n {\n throw new TranslationConfigException(\n $\"API Key for {ServiceType} is not configured.\");\n }\n\n _settings = settings;\n _translator = new Translator(_settings.ApiKey, new TranslatorOptions()\n {\n OverallConnectionTimeout = TimeSpan.FromMilliseconds(settings.TimeoutMs)\n });\n }\n\n public TranslateServiceType ServiceType => TranslateServiceType.DeepL;\n\n public void Dispose()\n {\n _translator.Dispose();\n }\n\n public void Initialize(Language src, TargetLanguage target)\n {\n (TranslateLanguage srcLang, _) = this.TryGetLanguage(src, target);\n\n _srcLang = ToSourceCode(srcLang.ISO6391);\n _targetLang = ToTargetCode(target);\n }\n\n internal static string ToSourceCode(string iso6391)\n {\n // ref: https://developers.deepl.com/docs/resources/supported-languages\n\n // Just capitalize ISO6391.\n return iso6391.ToUpper();\n }\n\n internal static string ToTargetCode(TargetLanguage target)\n {\n return target switch\n {\n TargetLanguage.EnglishAmerican => \"EN-US\",\n TargetLanguage.EnglishBritish => \"EN-GB\",\n TargetLanguage.Portuguese => \"PT-PT\",\n TargetLanguage.PortugueseBrazilian => \"PT-BR\",\n TargetLanguage.ChineseSimplified => \"ZH-HANS\",\n TargetLanguage.ChineseTraditional => \"ZH-HANT\",\n _ => target.ToISO6391().ToUpper()\n };\n }\n\n public async Task TranslateAsync(string text, CancellationToken token)\n {\n if (_srcLang == null || _targetLang == null)\n throw new InvalidOperationException(\"must be initialized\");\n\n try\n {\n TextResult result = await _translator.TranslateTextAsync(text, _srcLang, _targetLang,\n new TextTranslateOptions\n {\n Formality = Formality.Default,\n }, token).ConfigureAwait(false);\n\n return result.Text;\n }\n catch (OperationCanceledException)\n {\n throw;\n }\n catch (Exception ex)\n {\n // Timeout: DeepL.ConnectionException\n throw new TranslationException($\"Cannot request to {ServiceType}: {ex.Message}\", ex);\n }\n }\n}\n"], ["/LLPlayer/WpfColorFontDialog/ColorFontChooser.xaml.cs", "using System;\nusing System.Collections.Generic;\nusing System.Linq;\nusing System.Text;\nusing System.Windows;\nusing System.Windows.Controls;\nusing System.Windows.Data;\nusing System.Windows.Documents;\nusing System.Windows.Input;\nusing System.Windows.Media;\nusing System.Windows.Media.Imaging;\nusing System.Windows.Navigation;\nusing System.Windows.Shapes;\n\nnamespace WpfColorFontDialog\n{\n /// \n /// Interaction logic for ColorFontChooser.xaml\n /// \n public partial class ColorFontChooser : UserControl\n {\n public FontInfo SelectedFont\n {\n get\n {\n return new FontInfo(this.txtSampleText.FontFamily, this.txtSampleText.FontSize, this.txtSampleText.FontStyle, this.txtSampleText.FontStretch, this.txtSampleText.FontWeight, this.colorPicker.SelectedColor.Brush);\n }\n }\n\n\n\n public bool ShowColorPicker\n {\n get { return (bool)GetValue(ShowColorPickerProperty); }\n set { SetValue(ShowColorPickerProperty, value); }\n }\n\n // Using a DependencyProperty as the backing store for ShowColorPicker. This enables animation, styling, binding, etc...\n public static readonly DependencyProperty ShowColorPickerProperty =\n DependencyProperty.Register(\"ShowColorPicker\", typeof(bool), typeof(ColorFontChooser), new PropertyMetadata(true, ShowColorPickerPropertyCallback));\n\n\n public bool AllowArbitraryFontSizes\n {\n get { return (bool)GetValue(AllowArbitraryFontSizesProperty); }\n set { SetValue(AllowArbitraryFontSizesProperty, value); }\n }\n\n // Using a DependencyProperty as the backing store for AllowArbitraryFontSizes. This enables animation, styling, binding, etc...\n public static readonly DependencyProperty AllowArbitraryFontSizesProperty =\n DependencyProperty.Register(\"AllowArbitraryFontSizes\", typeof(bool), typeof(ColorFontChooser), new PropertyMetadata(true, AllowArbitraryFontSizesPropertyCallback));\n\n\n public bool PreviewFontInFontList\n {\n get { return (bool)GetValue(PreviewFontInFontListProperty); }\n set { SetValue(PreviewFontInFontListProperty, value); }\n }\n\n // Using a DependencyProperty as the backing store for PreviewFontInFontList. This enables animation, styling, binding, etc...\n public static readonly DependencyProperty PreviewFontInFontListProperty =\n DependencyProperty.Register(\"PreviewFontInFontList\", typeof(bool), typeof(ColorFontChooser), new PropertyMetadata(true, PreviewFontInFontListPropertyCallback));\n\n\n public ColorFontChooser()\n {\n InitializeComponent();\n this.groupBoxColorPicker.Visibility = ShowColorPicker ? Visibility.Visible : Visibility.Collapsed;\n this.tbFontSize.IsEnabled = AllowArbitraryFontSizes;\n lstFamily.ItemTemplate = PreviewFontInFontList ? (DataTemplate)Resources[\"fontFamilyData\"] : (DataTemplate)Resources[\"fontFamilyDataWithoutPreview\"];\n }\n private static void PreviewFontInFontListPropertyCallback(DependencyObject d, DependencyPropertyChangedEventArgs e)\n {\n ColorFontChooser chooser = d as ColorFontChooser;\n if (e.NewValue == null)\n return;\n if ((bool)e.NewValue == true)\n chooser.lstFamily.ItemTemplate = chooser.Resources[\"fontFamilyData\"] as DataTemplate;\n else\n chooser.lstFamily.ItemTemplate = chooser.Resources[\"fontFamilyDataWithoutPreview\"] as DataTemplate;\n }\n private static void AllowArbitraryFontSizesPropertyCallback(DependencyObject d, DependencyPropertyChangedEventArgs e)\n {\n ColorFontChooser chooser = d as ColorFontChooser;\n if (e.NewValue == null)\n return;\n\n chooser.tbFontSize.IsEnabled = (bool)e.NewValue;\n\n }\n private static void ShowColorPickerPropertyCallback(DependencyObject d, DependencyPropertyChangedEventArgs e)\n {\n ColorFontChooser chooser = d as ColorFontChooser;\n if (e.NewValue == null)\n return;\n if ((bool)e.NewValue == true)\n chooser.groupBoxColorPicker.Visibility = Visibility.Visible;\n else\n chooser.groupBoxColorPicker.Visibility = Visibility.Collapsed;\n }\n\n private void colorPicker_ColorChanged(object sender, RoutedEventArgs e)\n {\n this.txtSampleText.Foreground = this.colorPicker.SelectedColor.Brush;\n }\n\n private void lstFontSizes_SelectionChanged(object sender, SelectionChangedEventArgs e)\n {\n if (this.tbFontSize != null && this.lstFontSizes.SelectedItem != null)\n {\n this.tbFontSize.Text = this.lstFontSizes.SelectedItem.ToString();\n }\n }\n\n private void tbFontSize_PreviewTextInput(object sender, TextCompositionEventArgs e)\n {\n e.Handled = !TextBoxTextAllowed(e.Text);\n }\n\n private void tbFontSize_Pasting(object sender, DataObjectPastingEventArgs e)\n {\n if (e.DataObject.GetDataPresent(typeof(String)))\n {\n String Text1 = (String)e.DataObject.GetData(typeof(String));\n if (!TextBoxTextAllowed(Text1)) e.CancelCommand();\n }\n else\n {\n e.CancelCommand();\n }\n }\n private Boolean TextBoxTextAllowed(String Text2)\n {\n return Array.TrueForAll(Text2.ToCharArray(),\n delegate (Char c) { return Char.IsDigit(c) || Char.IsControl(c); });\n }\n\n private void tbFontSize_LostFocus(object sender, RoutedEventArgs e)\n {\n if (tbFontSize.Text.Length == 0)\n {\n if (this.lstFontSizes.SelectedItem == null)\n {\n lstFontSizes.SelectedIndex = 0;\n }\n tbFontSize.Text = this.lstFontSizes.SelectedItem.ToString();\n\n }\n }\n\n private void tbFontSize_TextChanged(object sender, TextChangedEventArgs e)\n {\n foreach (int size in this.lstFontSizes.Items)\n {\n if (size.ToString() == tbFontSize.Text)\n {\n lstFontSizes.SelectedItem = size;\n lstFontSizes.ScrollIntoView(size);\n return;\n }\n }\n this.lstFontSizes.SelectedItem = null;\n }\n }\n}\n"], ["/LLPlayer/FlyleafLib/Utils/SubtitleTextUtil.cs", "using System.Text;\n\nnamespace FlyleafLib;\n\npublic static class SubtitleTextUtil\n{\n /// \n /// Flattens the text into a single line.\n /// - If every line (excluding empty lines) starts with dash, returns the original string.\n /// - For all other text, replaces newlines with spaces and flattens into a single line.\n /// \n public static string FlattenText(string text)\n {\n ArgumentNullException.ThrowIfNull(text);\n\n ReadOnlySpan span = text.AsSpan();\n\n // If there are no newlines, return the text as-is\n if (!span.ContainsAny('\\r', '\\n'))\n {\n return text;\n }\n\n int length = span.Length;\n\n // Determine if the first character is dash to enter list mode\n bool startDash = span.Length > 0 && IsDash(span[0]);\n\n if (startDash)\n {\n char dashChar = span[0];\n\n // Check if all lines start with dash (ignore empty lines)\n bool allDash = true;\n bool atLineStart = true;\n int i;\n for (i = 0; i < length; i++)\n {\n if (atLineStart)\n {\n // Skip empty lines\n if (span[i] == '\\r' || span[i] == '\\n')\n {\n continue;\n }\n if (span[i] != dashChar)\n {\n allDash = false;\n // Done checking\n break;\n }\n atLineStart = false;\n }\n else\n {\n if (span[i] == '\\r')\n {\n if (i + 1 < length && span[i + 1] == '\\n') i++;\n atLineStart = true;\n }\n else if (span[i] == '\\n')\n {\n atLineStart = true;\n }\n }\n }\n\n // If every line starts with dash, return original text\n if (allDash)\n {\n return text;\n }\n\n // list mode\n StringBuilder sb = new(length);\n bool firstItem = true;\n i = 0;\n\n while (i < length)\n {\n int start;\n\n // Start of a dash line\n if (span[i] == dashChar)\n {\n if (!firstItem)\n {\n sb.Append('\\n');\n }\n // Append until end of line\n start = i;\n while (i < length && span[i] != '\\r' && span[i] != '\\n') i++;\n sb.Append(span.Slice(start, i - start));\n firstItem = false;\n continue;\n }\n\n // Skip empty lines\n if (span[i] == '\\r' || span[i] == '\\n')\n {\n i++;\n continue;\n }\n\n // Continuation line\n start = i;\n while (i < length && span[i] != '\\r' && span[i] != '\\n') i++;\n sb.Append(' ');\n sb.Append(span.Slice(start, i - start));\n }\n return sb.ToString();\n }\n\n // Default mode: replace all newlines with spaces in one pass\n char[] buffer = new char[length];\n int pos = 0;\n bool lastWasNewline = false;\n for (int i = 0; i < length; i++)\n {\n char c = span[i];\n if (c == '\\r' || c == '\\n')\n {\n if (!lastWasNewline)\n {\n buffer[pos++] = ' ';\n lastWasNewline = true;\n }\n }\n else\n {\n buffer[pos++] = c;\n lastWasNewline = false;\n }\n }\n return new string(buffer, 0, pos);\n }\n\n private static bool IsDash(char c)\n {\n switch (c)\n {\n case '-':\n case '\\u2043': // ⁃ Hyphen bullet\n case '\\u2010': // ‐ Hyphen\n case '\\u2012': // ‒ Figure dash\n case '\\u2013': // – En dash\n case '\\u2014': // — Em dash\n case '\\u2015': // ― Horizontal bar\n case '\\u2212': // − Minus Sign\n return true;\n }\n\n return false;\n }\n}\n"], ["/LLPlayer/LLPlayer/Controls/NonTopmostPopup.cs", "using System.Runtime.InteropServices;\nusing System.Windows;\nusing System.Windows.Controls.Primitives;\nusing System.Windows.Input;\nusing System.Windows.Interop;\n\nnamespace LLPlayer.Controls;\n\n/// \n/// Popup with code to not be the topmost control\n/// ref: https://gist.github.com/flq/903202/8bf56606b7c6fad341c31482f196b3aba9373e07\n/// \npublic class NonTopmostPopup : Popup\n{\n private bool? _appliedTopMost;\n private bool _alreadyLoaded;\n private Window? _parentWindow;\n\n public static readonly DependencyProperty IsTopmostProperty =\n DependencyProperty.Register(nameof(IsTopmost), typeof(bool), typeof(NonTopmostPopup), new FrameworkPropertyMetadata(false, OnIsTopmostChanged));\n\n public bool IsTopmost\n {\n get => (bool)GetValue(IsTopmostProperty);\n set => SetValue(IsTopmostProperty, value);\n }\n\n public NonTopmostPopup()\n {\n Loaded += OnPopupLoaded;\n }\n\n void OnPopupLoaded(object sender, RoutedEventArgs e)\n {\n if (_alreadyLoaded)\n return;\n\n _alreadyLoaded = true;\n\n if (Child != null)\n {\n Child.AddHandler(PreviewMouseLeftButtonDownEvent, new MouseButtonEventHandler(OnChildPreviewMouseLeftButtonDown), true);\n }\n\n //_parentWindow = Window.GetWindow(this);\n _parentWindow = Application.Current.MainWindow;\n\n if (_parentWindow == null)\n return;\n\n _parentWindow.Activated += OnParentWindowActivated;\n _parentWindow.Deactivated += OnParentWindowDeactivated;\n _parentWindow.LocationChanged += OnParentWindowLocationChanged;\n }\n\n private void OnParentWindowLocationChanged(object? sender, EventArgs e)\n {\n try\n {\n var method = typeof(Popup).GetMethod(\"UpdatePosition\",\n System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Instance);\n if (IsOpen)\n {\n method?.Invoke(this, null);\n }\n }\n catch\n {\n // ignored\n }\n }\n\n private void OnParentWindowActivated(object? sender, EventArgs e)\n {\n //Debug.WriteLine(\"Parent Window Activated\");\n SetTopmostState(true);\n }\n\n private void OnParentWindowDeactivated(object? sender, EventArgs e)\n {\n //Debug.WriteLine(\"Parent Window Deactivated\");\n\n if (IsTopmost == false)\n {\n SetTopmostState(IsTopmost);\n }\n }\n\n private void OnChildPreviewMouseLeftButtonDown(object? sender, MouseButtonEventArgs e)\n {\n //Debug.WriteLine(\"Child Mouse Left Button Down\");\n\n SetTopmostState(true);\n\n if (_parentWindow != null && !_parentWindow.IsActive && IsTopmost == false)\n {\n _parentWindow.Activate();\n //Debug.WriteLine(\"Activating Parent from child Left Button Down\");\n }\n }\n\n private static void OnIsTopmostChanged(DependencyObject obj, DependencyPropertyChangedEventArgs e)\n {\n var thisobj = (NonTopmostPopup)obj;\n\n thisobj.SetTopmostState(thisobj.IsTopmost);\n }\n\n protected override void OnOpened(EventArgs e)\n {\n SetTopmostState(IsTopmost);\n }\n\n private void SetTopmostState(bool isTop)\n {\n // Don't apply state if it's the same as incoming state\n if (_appliedTopMost.HasValue && _appliedTopMost == isTop)\n {\n // TODO: L: Maybe commenting out this section will solve the problem of the rare popups coming to the forefront?\n //return;\n }\n\n if (Child == null)\n return;\n\n var hwndSource = (PresentationSource.FromVisual(Child)) as HwndSource;\n\n if (hwndSource == null)\n return;\n var hwnd = hwndSource.Handle;\n\n if (!GetWindowRect(hwnd, out RECT rect))\n return;\n\n //Debug.WriteLine(\"setting z-order \" + isTop);\n\n if (isTop)\n {\n SetWindowPos(hwnd, HWND_TOPMOST, rect.Left, rect.Top, (int)Width, (int)Height, TOPMOST_FLAGS);\n }\n else\n {\n // Z-Order would only get refreshed/reflected if clicking the\n // the titlebar (as opposed to other parts of the external\n // window) unless I first set the popup to HWND_BOTTOM\n // then HWND_TOP before HWND_NOTOPMOST\n SetWindowPos(hwnd, HWND_BOTTOM, rect.Left, rect.Top, (int)Width, (int)Height, TOPMOST_FLAGS);\n SetWindowPos(hwnd, HWND_TOP, rect.Left, rect.Top, (int)Width, (int)Height, TOPMOST_FLAGS);\n SetWindowPos(hwnd, HWND_NOTOPMOST, rect.Left, rect.Top, (int)Width, (int)Height, TOPMOST_FLAGS);\n }\n\n _appliedTopMost = isTop;\n }\n\n #region P/Invoke imports & definitions\n#pragma warning disable 1591 //Xml-doc\n#pragma warning disable 169 //Never used-warning\n // ReSharper disable InconsistentNaming\n // Imports etc. with their naming rules\n\n [StructLayout(LayoutKind.Sequential)]\n public struct RECT\n\n {\n public int Left;\n public int Top;\n public int Right;\n public int Bottom;\n }\n\n [DllImport(\"user32.dll\")]\n [return: MarshalAs(UnmanagedType.Bool)]\n private static extern bool GetWindowRect(IntPtr hWnd, out RECT lpRect);\n\n [DllImport(\"user32.dll\")]\n private static extern bool SetWindowPos(IntPtr hWnd, IntPtr hWndInsertAfter, int X,\n int Y, int cx, int cy, uint uFlags);\n\n static readonly IntPtr HWND_TOPMOST = new IntPtr(-1);\n static readonly IntPtr HWND_NOTOPMOST = new IntPtr(-2);\n static readonly IntPtr HWND_TOP = new IntPtr(0);\n static readonly IntPtr HWND_BOTTOM = new IntPtr(1);\n\n private const UInt32 SWP_NOSIZE = 0x0001;\n const UInt32 SWP_NOMOVE = 0x0002;\n //const UInt32 SWP_NOZORDER = 0x0004;\n const UInt32 SWP_NOREDRAW = 0x0008;\n const UInt32 SWP_NOACTIVATE = 0x0010;\n\n //const UInt32 SWP_FRAMECHANGED = 0x0020; /* The frame changed: send WM_NCCALCSIZE */\n //const UInt32 SWP_SHOWWINDOW = 0x0040;\n //const UInt32 SWP_HIDEWINDOW = 0x0080;\n //const UInt32 SWP_NOCOPYBITS = 0x0100;\n const UInt32 SWP_NOOWNERZORDER = 0x0200; /* Don't do owner Z ordering */\n const UInt32 SWP_NOSENDCHANGING = 0x0400; /* Don't send WM_WINDOWPOSCHANGING */\n\n const UInt32 TOPMOST_FLAGS =\n SWP_NOACTIVATE | SWP_NOOWNERZORDER | SWP_NOSIZE | SWP_NOMOVE | SWP_NOREDRAW | SWP_NOSENDCHANGING;\n\n // ReSharper restore InconsistentNaming\n#pragma warning restore 1591\n#pragma warning restore 169\n #endregion\n}\n"], ["/LLPlayer/LLPlayer/Controls/SelectableTextBox.cs", "using System.Windows;\nusing System.Windows.Controls;\nusing System.Windows.Input;\nusing FlyleafLib;\n\nnamespace LLPlayer.Controls;\n\npublic class SelectableTextBox : TextBox\n{\n static SelectableTextBox()\n {\n DefaultStyleKeyProperty.OverrideMetadata(typeof(SelectableTextBox), new FrameworkPropertyMetadata(typeof(SelectableTextBox)));\n }\n\n public static readonly DependencyProperty IsTranslatedProperty =\n DependencyProperty.Register(nameof(IsTranslated), typeof(bool), typeof(SelectableTextBox), new FrameworkPropertyMetadata(false));\n\n public bool IsTranslated\n {\n get => (bool)GetValue(IsTranslatedProperty);\n set => SetValue(IsTranslatedProperty, value);\n }\n\n public static readonly DependencyProperty SubIndexProperty =\n DependencyProperty.Register(nameof(SubIndex), typeof(int), typeof(SelectableTextBox), new FrameworkPropertyMetadata(0));\n\n public int SubIndex\n {\n get => (int)GetValue(SubIndexProperty);\n set => SetValue(SubIndexProperty, value);\n }\n\n public static readonly RoutedEvent WordClickedEvent =\n EventManager.RegisterRoutedEvent(nameof(WordClicked), RoutingStrategy.Bubble, typeof(WordClickedEventHandler), typeof(SelectableTextBox));\n\n public event WordClickedEventHandler WordClicked\n {\n add => AddHandler(WordClickedEvent, value);\n remove => RemoveHandler(WordClickedEvent, value);\n }\n\n private bool _isDragging;\n private int _dragStartIndex = -1;\n private int _dragEndIndex = -1;\n\n private Point _mouseDownPosition;\n\n protected override void OnPreviewMouseLeftButtonDown(MouseButtonEventArgs e)\n {\n base.OnPreviewMouseLeftButtonDown(e);\n\n _isDragging = true;\n _mouseDownPosition = e.GetPosition(this);\n _dragStartIndex = GetCharacterIndexFromPoint(_mouseDownPosition, true);\n _dragEndIndex = _dragStartIndex;\n\n CaptureMouse();\n e.Handled = true;\n }\n\n protected override void OnPreviewMouseMove(MouseEventArgs e)\n {\n base.OnPreviewMouseMove(e);\n\n if (_isDragging)\n {\n Point currentPosition = e.GetPosition(this);\n\n if (currentPosition != _mouseDownPosition)\n {\n int currentIndex = GetCharacterIndexFromPoint(currentPosition, true);\n if (currentIndex != -1 && currentIndex != _dragEndIndex)\n {\n _dragEndIndex = currentIndex;\n }\n }\n }\n }\n\n protected override void OnPreviewMouseLeftButtonUp(MouseButtonEventArgs e)\n {\n base.OnPreviewMouseLeftButtonUp(e);\n\n if (_isDragging)\n {\n _isDragging = false;\n ReleaseMouseCapture();\n e.Handled = true;\n\n if (_dragStartIndex == _dragEndIndex)\n {\n // Click\n HandleClick(_mouseDownPosition, MouseClick.Left);\n }\n else\n {\n // Drag\n HandleDragSelection();\n }\n }\n }\n\n protected override void OnMouseRightButtonUp(MouseButtonEventArgs e)\n {\n base.OnMouseRightButtonUp(e);\n\n Point clickPosition = e.GetPosition(this);\n\n HandleClick(clickPosition, MouseClick.Right);\n\n // Right clicks other than words are currently disabled, consider creating another one\n e.Handled = true;\n }\n\n protected override void OnMouseUp(MouseButtonEventArgs e)\n {\n // Middle click: Sentence Lookup\n if (e.ChangedButton == MouseButton.Middle)\n {\n if (string.IsNullOrEmpty(Text))\n {\n return;\n }\n\n WordClickedEventArgs args = new(WordClickedEvent)\n {\n Mouse = MouseClick.Middle,\n // Change line breaks to spaces to improve translation accuracy.\n Words = SubtitleTextUtil.FlattenText(Text),\n IsWord = false,\n Text = Text,\n IsTranslated = IsTranslated,\n SubIndex = SubIndex,\n WordOffset = 0,\n Sender = this\n };\n\n RaiseEvent(args);\n }\n }\n\n private void HandleClick(Point point, MouseClick mouse)\n {\n // false because it fires only above the word\n int charIndex = GetCharacterIndexFromPoint(point, false);\n\n if (charIndex == -1 || string.IsNullOrEmpty(Text))\n {\n return;\n }\n\n int start = FindWordStart(charIndex);\n int end = FindWordEnd(charIndex);\n\n // get word\n string word = Text.Substring(start, end - start).Trim();\n\n if (string.IsNullOrEmpty(word))\n {\n return;\n }\n\n WordClickedEventArgs args = new(WordClickedEvent)\n {\n Mouse = mouse,\n Words = word,\n IsWord = true,\n Text = Text,\n IsTranslated = IsTranslated,\n SubIndex = SubIndex,\n WordOffset = start,\n Sender = this\n };\n RaiseEvent(args);\n }\n\n private void HandleDragSelection()\n {\n // Support right to left drag\n int rawStart = Math.Min(_dragStartIndex, _dragEndIndex);\n int rawEnd = Math.Max(_dragStartIndex, _dragEndIndex);\n\n // Adjust to word boundaries\n int adjustedStart = FindWordStart(rawStart);\n int adjustedEnd = FindWordEnd(rawEnd);\n\n // Extract the substring within the adjusted selection\n // TODO: L: If there is only a delimiter after the end, I want to include it in the selection (should improve translation accuracy)\n string selectedText = Text.Substring(adjustedStart, adjustedEnd - adjustedStart);\n\n WordClickedEventArgs args = new(WordClickedEvent)\n {\n Mouse = MouseClick.Left,\n // Change line breaks to spaces to improve translation accuracy.\n Words = SubtitleTextUtil.FlattenText(selectedText),\n IsWord = false,\n Text = Text,\n IsTranslated = IsTranslated,\n SubIndex = SubIndex,\n WordOffset = adjustedStart,\n Sender = this\n };\n\n RaiseEvent(args);\n }\n\n private int FindWordStart(int index)\n {\n if (index < 0 || index > Text.Length)\n {\n return 0;\n }\n\n while (index > 0 && !IsWordSeparator(Text[index - 1]))\n {\n index--;\n }\n\n return index;\n }\n\n private int FindWordEnd(int index)\n {\n if (index < 0 || index > Text.Length)\n {\n return Text.Length;\n }\n\n while (index < Text.Length && !IsWordSeparator(Text[index]))\n {\n index++;\n }\n\n return index;\n }\n\n private static readonly HashSet ExcludedSeparators = ['\\'', '-'];\n\n private static bool IsWordSeparator(char c)\n {\n if (ExcludedSeparators.Contains(c))\n {\n return false;\n }\n\n return char.IsWhiteSpace(c) || char.IsPunctuation(c);\n }\n\n #region Cursor Hand\n protected override void OnMouseMove(MouseEventArgs e)\n {\n base.OnMouseMove(e);\n\n // Change cursor only over word text\n int charIndex = GetCharacterIndexFromPoint(e.GetPosition(this), false);\n\n Cursor = charIndex != -1 ? Cursors.Hand : Cursors.Arrow;\n }\n\n protected override void OnMouseLeave(MouseEventArgs e)\n {\n base.OnMouseLeave(e);\n\n if (Cursor == Cursors.Hand)\n {\n Cursor = Cursors.Arrow;\n }\n }\n #endregion\n}\n"], ["/LLPlayer/LLPlayer/Services/PDICSender.cs", "using System.Diagnostics;\nusing System.IO;\nusing System.Text;\n\nnamespace LLPlayer.Services;\n\npublic class PipeClient : IDisposable\n{\n private Process _proc;\n\n public PipeClient(string pipePath)\n {\n _proc = new Process\n {\n StartInfo = new ProcessStartInfo()\n {\n RedirectStandardOutput = true,\n RedirectStandardInput = true,\n RedirectStandardError = true,\n FileName = pipePath,\n CreateNoWindow = true,\n }\n };\n _proc.Start();\n }\n\n public async Task SendMessage(string message)\n {\n Debug.WriteLine(message);\n //byte[] bytes = JsonSerializer.SerializeToUtf8Bytes(message);\n\n // Enclose double quotes before and after since it is sent as a JSON string\n byte[] bytes = Encoding.UTF8.GetBytes('\"' + message + '\"');\n\n var length = BitConverter.GetBytes(bytes.Length);\n await _proc.StandardInput.BaseStream.WriteAsync(length, 0, length.Length);\n await _proc.StandardInput.BaseStream.WriteAsync(bytes, 0, bytes.Length);\n await _proc.StandardInput.BaseStream.FlushAsync();\n }\n\n public void Dispose()\n {\n _proc.Kill();\n _proc.WaitForExit();\n }\n}\n\npublic class PDICSender : IDisposable\n{\n private readonly PipeClient _pipeClient;\n public FlyleafManager FL { get; }\n\n public PDICSender(FlyleafManager fl)\n {\n FL = fl;\n\n string? exePath = FL.Config.Subs.PDICPipeExecutablePath;\n\n if (!File.Exists(exePath))\n {\n throw new FileNotFoundException($\"PDIC executable is not set correctly: {exePath}\");\n }\n\n _pipeClient = new PipeClient(exePath);\n }\n\n public async void Dispose()\n {\n await _pipeClient.SendMessage(\"p:Dictionary,Close,\");\n _pipeClient.Dispose();\n }\n\n public async Task Connect()\n {\n await _pipeClient.SendMessage(\"p:Dictionary,Open,\");\n }\n\n // Send the same way as Firepop\n // webextension native extensions\n // ref: https://developer.mozilla.org/en-US/docs/Mozilla/Add-ons/WebExtensions/Native_messaging\n\n // See Firepop source\n public async Task SendWithPipe(string sentence, int offset)\n {\n try\n {\n await _pipeClient.SendMessage($\"p:Dictionary,SetUrl,{App.Name}\");\n await _pipeClient.SendMessage($\"p:Dictionary,PopupSearch3,{offset},{sentence}\");\n\n // Incremental search\n //await _pipeClient.SendMessage($\"p:Simulate,InputWord3,word\");\n\n return 0;\n }\n catch (Exception e)\n {\n Debug.WriteLine(e.ToString());\n return -1;\n }\n }\n}\n"], ["/LLPlayer/FlyleafLib/MediaPlayer/Video.cs", "using System;\nusing System.Collections.ObjectModel;\n\nusing FlyleafLib.MediaFramework.MediaContext;\nusing FlyleafLib.MediaFramework.MediaStream;\n\nnamespace FlyleafLib.MediaPlayer;\n\npublic class Video : NotifyPropertyChanged\n{\n /// \n /// Embedded Streams\n /// \n public ObservableCollection\n Streams => decoder?.VideoDemuxer.VideoStreams;\n\n /// \n /// Whether the input has video and it is configured\n /// \n public bool IsOpened { get => isOpened; internal set => Set(ref _IsOpened, value); }\n internal bool _IsOpened, isOpened;\n\n public string Codec { get => codec; internal set => Set(ref _Codec, value); }\n internal string _Codec, codec;\n\n ///// \n ///// Video bitrate (Kbps)\n ///// \n public double BitRate { get => bitRate; internal set => Set(ref _BitRate, value); }\n internal double _BitRate, bitRate;\n\n public AspectRatio AspectRatio { get => aspectRatio; internal set => Set(ref _AspectRatio, value); }\n internal AspectRatio\n _AspectRatio, aspectRatio;\n\n ///// \n ///// Total Dropped Frames\n ///// \n public int FramesDropped { get => framesDropped; internal set => Set(ref _FramesDropped, value); }\n internal int _FramesDropped, framesDropped;\n\n /// \n /// Total Frames\n /// \n public int FramesTotal { get => framesTotal; internal set => Set(ref _FramesTotal, value); }\n internal int _FramesTotal, framesTotal;\n\n public int FramesDisplayed { get => framesDisplayed; internal set => Set(ref _FramesDisplayed, value); }\n internal int _FramesDisplayed, framesDisplayed;\n\n public double FPS { get => fps; internal set => Set(ref _FPS, value); }\n internal double _FPS, fps;\n\n /// \n /// Actual Frames rendered per second (FPS)\n /// \n public double FPSCurrent { get => fpsCurrent; internal set => Set(ref _FPSCurrent, value); }\n internal double _FPSCurrent, fpsCurrent;\n\n public string PixelFormat { get => pixelFormat; internal set => Set(ref _PixelFormat, value); }\n internal string _PixelFormat, pixelFormat;\n\n public int Width { get => width; internal set => Set(ref _Width, value); }\n internal int _Width, width;\n\n public int Height { get => height; internal set => Set(ref _Height, value); }\n internal int _Height, height;\n\n public bool VideoAcceleration\n { get => videoAcceleration; internal set => Set(ref _VideoAcceleration, value); }\n internal bool _VideoAcceleration, videoAcceleration;\n\n public bool ZeroCopy { get => zeroCopy; internal set => Set(ref _ZeroCopy, value); }\n internal bool _ZeroCopy, zeroCopy;\n\n public Player Player => player;\n\n Action uiAction;\n Player player;\n DecoderContext decoder => player.decoder;\n Config Config => player.Config;\n\n public Video(Player player)\n {\n this.player = player;\n\n uiAction = () =>\n {\n IsOpened = IsOpened;\n Codec = Codec;\n AspectRatio = AspectRatio;\n FramesTotal = FramesTotal;\n FPS = FPS;\n PixelFormat = PixelFormat;\n Width = Width;\n Height = Height;\n VideoAcceleration = VideoAcceleration;\n ZeroCopy = ZeroCopy;\n\n FramesDisplayed = FramesDisplayed;\n FramesDropped = FramesDropped;\n };\n }\n\n internal void Reset()\n {\n codec = null;\n aspectRatio = new AspectRatio(0, 0);\n bitRate = 0;\n fps = 0;\n pixelFormat = null;\n width = 0;\n height = 0;\n framesTotal = 0;\n videoAcceleration = false;\n zeroCopy = false;\n isOpened = false;\n\n player.UIAdd(uiAction);\n }\n internal void Refresh()\n {\n if (decoder.VideoStream == null) { Reset(); return; }\n\n codec = decoder.VideoStream.Codec;\n aspectRatio = decoder.VideoStream.AspectRatio;\n fps = decoder.VideoStream.FPS;\n pixelFormat = decoder.VideoStream.PixelFormatStr;\n width = (int)decoder.VideoStream.Width;\n height = (int)decoder.VideoStream.Height;\n framesTotal = decoder.VideoStream.TotalFrames;\n videoAcceleration\n = decoder.VideoDecoder.VideoAccelerated;\n zeroCopy = decoder.VideoDecoder.ZeroCopy;\n isOpened =!decoder.VideoDecoder.Disposed;\n\n framesDisplayed = 0;\n framesDropped = 0;\n\n player.UIAdd(uiAction);\n }\n\n internal void Enable()\n {\n if (player.VideoDemuxer.Disposed || Config.Player.Usage == Usage.Audio)\n return;\n\n bool wasPlaying = player.IsPlaying;\n\n player.Pause();\n decoder.OpenSuggestedVideo();\n player.ReSync(decoder.VideoStream, (int) (player.CurTime / 10000), true);\n\n if (wasPlaying || Config.Player.AutoPlay)\n player.Play();\n }\n internal void Disable()\n {\n if (!IsOpened)\n return;\n\n bool wasPlaying = player.IsPlaying;\n\n player.Pause();\n decoder.CloseVideo();\n player.SubtitleClear();\n\n if (!player.Audio.IsOpened)\n {\n player.canPlay = false;\n player.UIAdd(() => player.CanPlay = player.CanPlay);\n }\n\n Reset();\n player.UIAll();\n\n if (wasPlaying || Config.Player.AutoPlay)\n player.Play();\n }\n\n public void Toggle() => Config.Video.Enabled = !Config.Video.Enabled;\n public void ToggleKeepRatio()\n {\n if (Config.Video.AspectRatio == AspectRatio.Keep)\n Config.Video.AspectRatio = AspectRatio.Fill;\n else if (Config.Video.AspectRatio == AspectRatio.Fill)\n Config.Video.AspectRatio = AspectRatio.Keep;\n }\n public void ToggleVideoAcceleration() => Config.Video.VideoAcceleration = !Config.Video.VideoAcceleration;\n}\n"], ["/LLPlayer/LLPlayer/Converters/FlyleafConverters.cs", "using System.Globalization;\nusing System.Windows;\nusing System.Windows.Controls.Primitives;\nusing System.Windows.Data;\nusing System.Windows.Media;\nusing FlyleafLib;\nusing static FlyleafLib.MediaFramework.MediaDemuxer.Demuxer;\n\nnamespace LLPlayer.Converters;\n\n[ValueConversion(typeof(int), typeof(Qualities))]\npublic class QualityToLevelsConverter : IValueConverter\n{\n public enum Qualities\n {\n None,\n Low,\n Med,\n High,\n _4k\n }\n\n public object Convert(object value, Type targetType, object parameter, CultureInfo culture)\n {\n int videoHeight = (int)value;\n\n if (videoHeight > 1080)\n return Qualities._4k;\n if (videoHeight > 720)\n return Qualities.High;\n if (videoHeight == 720)\n return Qualities.Med;\n\n return Qualities.Low;\n }\n public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture) { throw new NotImplementedException(); }\n}\n\n[ValueConversion(typeof(int), typeof(Volumes))]\npublic class VolumeToLevelsConverter : IValueConverter\n{\n public enum Volumes\n {\n Mute,\n Low,\n Med,\n High\n }\n\n public object Convert(object value, Type targetType, object parameter, CultureInfo culture)\n {\n int volume = (int)value;\n\n if (volume == 0)\n return Volumes.Mute;\n if (volume > 99)\n return Volumes.High;\n if (volume > 49)\n return Volumes.Med;\n return Volumes.Low;\n }\n public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture) { throw new NotImplementedException(); }\n}\n\npublic class SumConverter : IMultiValueConverter\n{\n public object Convert(object[] values, Type targetType, object parameter, CultureInfo culture)\n {\n double sum = 0;\n\n if (values == null)\n return sum;\n\n foreach (object value in values)\n {\n if (value == DependencyProperty.UnsetValue)\n continue;\n sum += (double)value;\n }\n\n return sum;\n }\n\n public object[] ConvertBack(object value, Type[] targetTypes, object parameter, CultureInfo culture)\n => throw new NotImplementedException();\n}\n\npublic class PlaylistItemsConverter : IMultiValueConverter\n{\n public object Convert(object[] values, Type targetType, object parameter, CultureInfo culture)\n {\n return $\"Playlist ({values[0]}/{values[1]})\";\n }\n\n public object[] ConvertBack(object value, Type[] targetTypes, object parameter, CultureInfo culture)\n => throw new NotImplementedException();\n}\n\n[ValueConversion(typeof(Color), typeof(string))]\npublic class ColorToHexConverter : IValueConverter\n{\n public object? Convert(object? value, Type targetType, object? parameter, CultureInfo culture)\n {\n if (value is null)\n return null;\n\n string UpperHexString(int i) => i.ToString(\"X2\").ToUpper();\n Color color = (Color)value;\n string hex = UpperHexString(color.R) +\n UpperHexString(color.G) +\n UpperHexString(color.B);\n return hex;\n }\n\n public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)\n {\n try\n {\n return ColorConverter.ConvertFromString(\"#\" + value.ToString());\n }\n catch (Exception)\n {\n // ignored\n }\n\n return Binding.DoNothing;\n }\n}\n\npublic class Tuple3Converter : IMultiValueConverter\n{\n public object Convert(object[] values, Type targetType, object parameter, CultureInfo culture)\n {\n return (values[0], values[1], values[2]);\n }\n\n public object[] ConvertBack(object value, Type[] targetTypes, object parameter, CultureInfo culture)\n {\n throw new NotImplementedException();\n }\n}\n\npublic class SubIndexToIsEnabledConverter : IMultiValueConverter\n{\n public object Convert(object[] values, Type targetType, object parameter, CultureInfo culture)\n {\n if (values.Any(x => x == DependencyProperty.UnsetValue))\n return DependencyProperty.UnsetValue;\n\n // values[0] = Tag (index)\n // values[1] = IsPrimaryEnabled\n // values[2] = IsSecondaryEnabled\n int index = int.Parse((string)values[0]);\n bool isPrimaryEnabled = (bool)values[1];\n bool isSecondaryEnabled = (bool)values[2];\n\n return index == 0 ? isPrimaryEnabled : isSecondaryEnabled;\n }\n\n public object[] ConvertBack(object value, Type[] targetTypes, object parameter, CultureInfo culture)\n {\n throw new NotImplementedException();\n }\n}\n\n[ValueConversion(typeof(IEnumerable), typeof(DoubleCollection))]\npublic class ChaptersToTicksConverter : IValueConverter\n{\n public object Convert(object value, Type targetType, object parameter, CultureInfo culture)\n {\n if (value is IEnumerable chapters)\n {\n // Convert tick count to seconds\n List secs = chapters.Select(c => c.StartTime / 10000000.0).ToList();\n if (secs.Count <= 1)\n {\n return Binding.DoNothing;\n }\n\n return new DoubleCollection(secs);\n }\n\n return Binding.DoNothing;\n }\n\n public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)\n {\n throw new NotImplementedException();\n }\n}\n\n[ValueConversion(typeof(IEnumerable), typeof(TickPlacement))]\npublic class ChaptersToTickPlacementConverter : IValueConverter\n{\n public TickPlacement TickPlacement { get; set; }\n\n public object Convert(object value, Type targetType, object parameter, CultureInfo culture)\n {\n if (value is IEnumerable chapters && chapters.Count() >= 2)\n {\n return TickPlacement;\n }\n\n return TickPlacement.None;\n }\n\n public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)\n {\n throw new NotImplementedException();\n }\n}\n\npublic class AspectRatioIsCheckedConverter : IMultiValueConverter\n{\n // values[0]: SelectedAspectRatio, values[1]: current AspectRatio\n public object Convert(object[] values, Type targetType, object parameter, CultureInfo culture)\n {\n if (values.Length < 2)\n {\n return false;\n }\n\n if (values[0] is AspectRatio selected && values[1] is AspectRatio current)\n {\n return selected.Equals(current);\n }\n return false;\n }\n\n public object[] ConvertBack(object value, Type[] targetTypes, object parameter, CultureInfo culture)\n {\n throw new NotImplementedException();\n }\n}\n"], ["/LLPlayer/WpfColorFontDialog/ColorFontDialog.xaml.cs", "using System.Collections;\nusing System.Windows;\nusing System.Windows.Media;\n\nnamespace WpfColorFontDialog\n{\n /// \n /// Interaction logic for ColorFontDialog.xaml\n /// \n public partial class ColorFontDialog : Window\n {\n private FontInfo _selectedFont;\n\n public FontInfo Font\n {\n get\n {\n return _selectedFont;\n }\n set\n {\n _selectedFont = value;\n }\n }\n\n private int[] _defaultFontSizes = { 8, 9, 10, 11, 12, 14, 16, 18, 20, 22, 24, 26, 28, 36, 48, 72, 96 };\n private int[] _fontSizes = null;\n public int[] FontSizes\n {\n get\n {\n return _fontSizes ?? _defaultFontSizes;\n }\n set\n {\n _fontSizes = value;\n }\n }\n public ColorFontDialog(bool previewFontInFontList = true, bool allowArbitraryFontSizes = true, bool showColorPicker = true)\n {\n // Disable style inheritance from parents and apply standard styles\n InheritanceBehavior = InheritanceBehavior.SkipToThemeNext;\n\n InitializeComponent();\n I18NUtil.SetLanguage(Resources);\n this.colorFontChooser.PreviewFontInFontList = previewFontInFontList;\n this.colorFontChooser.AllowArbitraryFontSizes = allowArbitraryFontSizes;\n this.colorFontChooser.ShowColorPicker = showColorPicker;\n }\n\n private void btnOk_Click(object sender, RoutedEventArgs e)\n {\n this.Font = this.colorFontChooser.SelectedFont;\n base.DialogResult = new bool?(true);\n }\n\n private void SyncFontColor()\n {\n int colorIdx = AvailableColors.GetFontColorIndex(this.Font.Color);\n this.colorFontChooser.colorPicker.superCombo.SelectedIndex = colorIdx;\n this.colorFontChooser.txtSampleText.Foreground = this.Font.Color.Brush;\n this.colorFontChooser.colorPicker.superCombo.BringIntoView();\n }\n\n private void SyncFontName()\n {\n string fontFamilyName = this._selectedFont.Family.Source;\n bool foundMatch = false;\n int idx = 0;\n foreach (object item in (IEnumerable)this.colorFontChooser.lstFamily.Items)\n {\n if (fontFamilyName == item.ToString())\n {\n foundMatch = true;\n break;\n }\n idx++;\n }\n if (!foundMatch)\n {\n idx = 0;\n }\n this.colorFontChooser.lstFamily.SelectedIndex = idx;\n this.colorFontChooser.lstFamily.ScrollIntoView(this.colorFontChooser.lstFamily.Items[idx]);\n }\n\n private void SyncFontSize()\n {\n double fontSize = this._selectedFont.Size;\n this.colorFontChooser.lstFontSizes.ItemsSource = FontSizes;\n this.colorFontChooser.tbFontSize.Text = fontSize.ToString();\n }\n\n private void SyncFontTypeface()\n {\n string fontTypeFaceSb = FontInfo.TypefaceToString(this._selectedFont.Typeface);\n int idx = 0;\n foreach (object item in (IEnumerable)this.colorFontChooser.lstTypefaces.Items)\n {\n if (fontTypeFaceSb == FontInfo.TypefaceToString(item as FamilyTypeface))\n {\n break;\n }\n idx++;\n }\n this.colorFontChooser.lstTypefaces.SelectedIndex = idx;\n this.colorFontChooser.lstTypefaces.ScrollIntoView(this.colorFontChooser.lstTypefaces.SelectedItem);\n }\n\n private void Window_Loaded_1(object sender, RoutedEventArgs e)\n {\n this.SyncFontColor();\n this.SyncFontName();\n this.SyncFontSize();\n this.SyncFontTypeface();\n }\n }\n}\n"], ["/LLPlayer/LLPlayer/Converters/SubtitleConverters.cs", "using System.Globalization;\nusing System.Windows;\nusing System.Windows.Data;\nusing System.Windows.Media.Imaging;\nusing FlyleafLib.MediaPlayer;\nusing LLPlayer.Services;\n\nnamespace LLPlayer.Converters;\n\npublic class WidthPercentageMultiConverter : IMultiValueConverter\n{\n public object Convert(object[] values, Type targetType, object parameter, CultureInfo culture)\n {\n if (values[0] is double actualWidth &&\n values[1] is double maxWidth &&\n values[2] is double percentage)\n {\n if (percentage >= 100.0)\n {\n // respect line break\n return actualWidth;\n }\n\n var calcWidth = actualWidth * (percentage / 100.0);\n\n if (maxWidth > 0)\n {\n return Math.Min(maxWidth, calcWidth);\n }\n\n return calcWidth;\n }\n return 0;\n }\n\n public object[] ConvertBack(object value, Type[] targetTypes, object parameter, CultureInfo culture)\n {\n throw new NotImplementedException();\n }\n}\n\npublic class SubTextMaskConverter : IMultiValueConverter\n{\n public object Convert(object[] values, Type targetType, object parameter, CultureInfo culture)\n {\n if (values.Length != 6)\n return DependencyProperty.UnsetValue;\n\n if (values[0] is int index && // Index of sub to be processed\n values[1] is string displayText && // Sub text to be processed (may be translated)\n values[2] is string text && // Sub text to be processed\n values[3] is int selectedIndex && // Index of the selected ListItem\n values[4] is bool isEnabled && // whether to enable this feature\n values[5] is bool showOriginal) // whether to show original text\n {\n string show = showOriginal ? text : displayText;\n\n if (isEnabled && index > selectedIndex && !string.IsNullOrEmpty(show))\n {\n return new string('_', show.Length);\n }\n\n return show;\n }\n return DependencyProperty.UnsetValue;\n }\n\n public object[] ConvertBack(object value, Type[] targetTypes, object parameter, CultureInfo culture)\n {\n throw new NotSupportedException();\n }\n}\n\npublic class SubTextFlowDirectionConverter : IMultiValueConverter\n{\n public object Convert(object[] values, Type targetType, object parameter, CultureInfo culture)\n {\n if (values.Length != 3)\n {\n return DependencyProperty.UnsetValue;\n }\n\n if (values[0] is bool isTranslated &&\n values[1] is int subIndex &&\n values[2] is FlyleafManager fl)\n {\n var language = isTranslated ? fl.PlayerConfig.Subtitles.TranslateLanguage : fl.Player.SubtitlesManager[subIndex].Language;\n if (language != null && language.IsRTL)\n {\n return FlowDirection.RightToLeft;\n }\n\n return FlowDirection.LeftToRight;\n }\n\n return DependencyProperty.UnsetValue;\n }\n\n public object[] ConvertBack(object value, Type[] targetTypes, object parameter, CultureInfo culture)\n {\n throw new NotSupportedException();\n }\n}\n\npublic class SubIsPlayingConverter : IMultiValueConverter\n{\n public object Convert(object[] values, Type targetType, object parameter, CultureInfo culture)\n {\n if (values.Length != 3)\n {\n return DependencyProperty.UnsetValue;\n }\n\n if (values[0] is int index &&\n values[1] is int currentIndex &&\n values[2] is bool isDisplaying)\n {\n return isDisplaying && index == currentIndex;\n }\n\n return DependencyProperty.UnsetValue;\n }\n\n public object[] ConvertBack(object value, Type[] targetTypes, object parameter, CultureInfo culture)\n {\n throw new NotSupportedException();\n }\n}\n\npublic class ListItemIndexVisibilityConverter : IMultiValueConverter\n{\n public object Convert(object[] values, Type targetType, object parameter, CultureInfo culture)\n {\n if (values.Length != 3)\n {\n return DependencyProperty.UnsetValue;\n }\n\n if (values[0] is int itemIndex && // Index of sub to be processed\n values[1] is int selectedIndex && // Index of the selected ListItem\n values[2] is bool isEnabled) // whether to enable this feature\n {\n if (isEnabled && itemIndex > selectedIndex)\n {\n return Visibility.Collapsed;\n }\n\n return Visibility.Visible;\n }\n return DependencyProperty.UnsetValue;\n }\n\n public object[] ConvertBack(object value, Type[] targetTypes, object parameter, CultureInfo culture)\n {\n throw new NotSupportedException();\n }\n}\n\n[ValueConversion(typeof(TimeSpan), typeof(string))]\npublic class TimeSpanToStringConverter : IValueConverter\n{\n public object Convert(object value, Type targetType, object parameter, CultureInfo culture)\n {\n if (value is TimeSpan ts)\n {\n if (ts.TotalHours >= 1)\n {\n return ts.ToString(@\"hh\\:mm\\:ss\");\n }\n else\n {\n return ts.ToString(@\"mm\\:ss\");\n }\n }\n\n return DependencyProperty.UnsetValue;\n }\n\n public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)\n {\n throw new NotImplementedException();\n }\n}\n\n[ValueConversion(typeof(SubtitleData), typeof(WriteableBitmap))]\npublic class SubBitmapImageSourceConverter : IValueConverter\n{\n public object? Convert(object? value, Type targetType, object? parameter, CultureInfo culture)\n {\n if (value is not SubtitleData item)\n {\n return null;\n }\n\n if (!item.IsBitmap || item.Bitmap == null || !string.IsNullOrEmpty(item.Text))\n {\n return null;\n }\n\n WriteableBitmap wb = item.Bitmap.SubToWritableBitmap(false);\n\n return wb;\n }\n\n public object ConvertBack(object? value, Type targetType, object? parameter, CultureInfo culture)\n => throw new NotImplementedException();\n}\n\n[ValueConversion(typeof(int), typeof(string))]\npublic class SubIndexToDisplayStringConverter : IValueConverter\n{\n public object Convert(object value, Type targetType, object parameter, CultureInfo culture)\n {\n if (value is int subIndex)\n {\n return subIndex == 0 ? \"Primary\" : \"Secondary\";\n }\n return DependencyProperty.UnsetValue;\n }\n\n public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)\n {\n if (value is string str)\n {\n return str == \"Primary\" ? 0 : 1;\n }\n return DependencyProperty.UnsetValue;\n }\n}\n"], ["/LLPlayer/LLPlayer/Controls/OutlinedTextBlock.cs", "using System.ComponentModel;\nusing System.Globalization;\nusing System.Windows;\nusing System.Windows.Documents;\nusing System.Windows.Markup;\nusing System.Windows.Media;\n\nnamespace LLPlayer.Controls;\n\n[ContentProperty(\"Text\")]\npublic class OutlinedTextBlock : FrameworkElement\n{\n public OutlinedTextBlock()\n {\n UpdatePen();\n TextDecorations = new TextDecorationCollection();\n }\n\n #region dependency properties\n public static readonly DependencyProperty FillProperty = DependencyProperty.Register(\n nameof(Fill),\n typeof(Brush),\n typeof(OutlinedTextBlock),\n new FrameworkPropertyMetadata(Brushes.White, FrameworkPropertyMetadataOptions.AffectsRender));\n\n public static readonly DependencyProperty StrokeProperty = DependencyProperty.Register(\n nameof(Stroke),\n typeof(Brush),\n typeof(OutlinedTextBlock),\n new FrameworkPropertyMetadata(Brushes.Black, FrameworkPropertyMetadataOptions.AffectsRender));\n\n public static readonly DependencyProperty StrokeThicknessProperty = DependencyProperty.Register(\n nameof(StrokeThickness),\n typeof(double),\n typeof(OutlinedTextBlock),\n new FrameworkPropertyMetadata(1d, FrameworkPropertyMetadataOptions.AffectsRender));\n\n public static readonly DependencyProperty FontFamilyProperty = TextElement.FontFamilyProperty.AddOwner(\n typeof(OutlinedTextBlock),\n new FrameworkPropertyMetadata(OnFormattedTextUpdated));\n\n public static readonly DependencyProperty FontSizeProperty = TextElement.FontSizeProperty.AddOwner(\n typeof(OutlinedTextBlock),\n new FrameworkPropertyMetadata(OnFormattedTextUpdated));\n\n public static readonly DependencyProperty FontSizeInitialProperty = DependencyProperty.Register(\n nameof(FontSizeInitial),\n typeof(double),\n typeof(OutlinedTextBlock),\n new FrameworkPropertyMetadata(OnFormattedTextUpdated));\n\n public static readonly DependencyProperty FontSizeAutoProperty = DependencyProperty.Register(\n nameof(FontSizeAuto),\n typeof(bool),\n typeof(OutlinedTextBlock),\n new FrameworkPropertyMetadata(OnFormattedTextUpdated));\n\n public static readonly DependencyProperty FontStretchProperty = TextElement.FontStretchProperty.AddOwner(\n typeof(OutlinedTextBlock),\n new FrameworkPropertyMetadata(OnFormattedTextUpdated));\n\n public static readonly DependencyProperty FontStyleProperty = TextElement.FontStyleProperty.AddOwner(\n typeof(OutlinedTextBlock),\n new FrameworkPropertyMetadata(OnFormattedTextUpdated));\n\n public static readonly DependencyProperty FontWeightProperty = TextElement.FontWeightProperty.AddOwner(\n typeof(OutlinedTextBlock),\n new FrameworkPropertyMetadata(OnFormattedTextUpdated));\n\n public static readonly DependencyProperty StrokePositionProperty = DependencyProperty.Register(\n nameof(StrokePosition),\n typeof(StrokePosition),\n typeof(OutlinedTextBlock),\n new FrameworkPropertyMetadata(StrokePosition.Outside, FrameworkPropertyMetadataOptions.AffectsRender));\n\n public static readonly DependencyProperty StrokeThicknessInitialProperty = DependencyProperty.Register(\n nameof(StrokeThicknessInitial),\n typeof(double),\n typeof(OutlinedTextBlock),\n new FrameworkPropertyMetadata(OnFormattedTextUpdated));\n\n public static readonly DependencyProperty TextProperty = DependencyProperty.Register(\n nameof(Text),\n typeof(string),\n typeof(OutlinedTextBlock),\n new FrameworkPropertyMetadata(OnFormattedTextInvalidated));\n\n public static readonly DependencyProperty TextAlignmentProperty = DependencyProperty.Register(\n nameof(TextAlignment),\n typeof(TextAlignment),\n typeof(OutlinedTextBlock),\n new FrameworkPropertyMetadata(OnFormattedTextUpdated));\n\n public static readonly DependencyProperty TextDecorationsProperty = DependencyProperty.Register(\n nameof(TextDecorations),\n typeof(TextDecorationCollection),\n typeof(OutlinedTextBlock),\n new FrameworkPropertyMetadata(OnFormattedTextUpdated));\n\n public static readonly DependencyProperty TextTrimmingProperty = DependencyProperty.Register(\n nameof(TextTrimming),\n typeof(TextTrimming),\n typeof(OutlinedTextBlock),\n new FrameworkPropertyMetadata(OnFormattedTextUpdated));\n\n public static readonly DependencyProperty TextWrappingProperty = DependencyProperty.Register(\n nameof(TextWrapping),\n typeof(TextWrapping),\n typeof(OutlinedTextBlock),\n new FrameworkPropertyMetadata(TextWrapping.NoWrap, OnFormattedTextUpdated));\n\n private FormattedText? _FormattedText;\n private Geometry? _TextGeometry;\n private Pen? _Pen;\n private PathGeometry? _clipGeometry;\n\n public Brush Fill\n {\n get => (Brush)GetValue(FillProperty);\n set => SetValue(FillProperty, value);\n }\n\n public FontFamily FontFamily\n {\n get => (FontFamily)GetValue(FontFamilyProperty);\n set => SetValue(FontFamilyProperty, value);\n }\n\n [TypeConverter(typeof(FontSizeConverter))]\n public double FontSize\n {\n get => (double)GetValue(FontSizeProperty);\n set => SetValue(FontSizeProperty, value);\n }\n\n [TypeConverter(typeof(FontSizeConverter))]\n public double FontSizeInitial\n {\n get => (double)GetValue(FontSizeInitialProperty);\n set => SetValue(FontSizeInitialProperty, value);\n }\n\n public bool FontSizeAuto\n {\n get => (bool)GetValue(FontSizeAutoProperty);\n set => SetValue(FontSizeAutoProperty, value);\n }\n\n public FontStretch FontStretch\n {\n get => (FontStretch)GetValue(FontStretchProperty);\n set => SetValue(FontStretchProperty, value);\n }\n\n public FontStyle FontStyle\n {\n get => (FontStyle)GetValue(FontStyleProperty);\n set => SetValue(FontStyleProperty, value);\n }\n\n public FontWeight FontWeight\n {\n get => (FontWeight)GetValue(FontWeightProperty);\n set => SetValue(FontWeightProperty, value);\n }\n\n public Brush Stroke\n {\n get => (Brush)GetValue(StrokeProperty);\n set => SetValue(StrokeProperty, value);\n }\n\n public StrokePosition StrokePosition\n {\n get => (StrokePosition)GetValue(StrokePositionProperty);\n set => SetValue(StrokePositionProperty, value);\n }\n\n public double StrokeThickness\n {\n get => (double)GetValue(StrokeThicknessProperty);\n set => SetValue(StrokeThicknessProperty, value);\n }\n\n public double StrokeThicknessInitial\n {\n get => (double)GetValue(StrokeThicknessInitialProperty);\n set => SetValue(StrokeThicknessInitialProperty, value);\n }\n\n public string Text\n {\n get => (string)GetValue(TextProperty);\n set => SetValue(TextProperty, value);\n }\n\n public TextAlignment TextAlignment\n {\n get => (TextAlignment)GetValue(TextAlignmentProperty);\n set => SetValue(TextAlignmentProperty, value);\n }\n\n public TextDecorationCollection TextDecorations\n {\n get => (TextDecorationCollection)GetValue(TextDecorationsProperty);\n set => SetValue(TextDecorationsProperty, value);\n }\n\n public TextTrimming TextTrimming\n {\n get => (TextTrimming)GetValue(TextTrimmingProperty);\n set => SetValue(TextTrimmingProperty, value);\n }\n\n public TextWrapping TextWrapping\n {\n get => (TextWrapping)GetValue(TextWrappingProperty);\n set => SetValue(TextWrappingProperty, value);\n }\n\n #endregion\n\n #region PDIC\n\n public int WordOffset { get; set; }\n\n #endregion\n\n private void UpdatePen()\n {\n _Pen = new Pen(Stroke, StrokeThickness)\n {\n DashCap = PenLineCap.Round,\n EndLineCap = PenLineCap.Round,\n LineJoin = PenLineJoin.Round,\n StartLineCap = PenLineCap.Round\n };\n\n if (StrokePosition == StrokePosition.Outside || StrokePosition == StrokePosition.Inside)\n _Pen.Thickness = StrokeThickness * 2;\n\n InvalidateVisual();\n }\n\n protected override void OnRender(DrawingContext drawingContext)\n {\n EnsureGeometry();\n\n drawingContext.DrawGeometry(Fill, null, _TextGeometry);\n\n if (StrokePosition == StrokePosition.Outside)\n drawingContext.PushClip(_clipGeometry);\n else if (StrokePosition == StrokePosition.Inside)\n drawingContext.PushClip(_TextGeometry);\n\n drawingContext.DrawGeometry(null, _Pen, _TextGeometry);\n\n if (StrokePosition == StrokePosition.Outside || StrokePosition == StrokePosition.Inside)\n drawingContext.Pop();\n }\n\n protected override Size MeasureOverride(Size availableSize)\n {\n EnsureFormattedText();\n\n // constrain the formatted text according to the available size\n double w = availableSize.Width;\n double h = availableSize.Height;\n\n if (FontSizeAuto)\n {\n if (FontSizeInitial > 0)\n {\n double r = w / 1920; // FontSizeInitial should be based on fixed Screen Width (eg. Full HD 1920)\n FontSize = FontSizeInitial * (r + ((1 - r) * 0.20f)); // TBR: Weight/Percentage for how much it will be affected by the change (possible dependency property / config)\n _FormattedText!.SetFontSize(FontSize);\n }\n }\n\n if (StrokeThicknessInitial > 0)\n {\n double r = FontSize / 48; // StrokeThicknessInitial should be based on fixed FontSize (eg. 48)\n StrokeThickness = Math.Max(1, StrokeThicknessInitial * r);\n UpdatePen();\n }\n\n // the Math.Min call is important - without this constraint (which seems arbitrary, but is the maximum allowable text width), things blow up when availableSize is infinite in both directions\n // the Math.Max call is to ensure we don't hit zero, which will cause MaxTextHeight to throw\n _FormattedText!.MaxTextWidth = Math.Min(3579139, w);\n _FormattedText!.MaxTextHeight = Math.Max(0.0001d, h);\n\n // return the desired size\n return new Size(Math.Ceiling(_FormattedText.Width), Math.Ceiling(_FormattedText.Height));\n }\n\n protected override Size ArrangeOverride(Size finalSize)\n {\n EnsureFormattedText();\n\n // update the formatted text with the final size\n _FormattedText!.MaxTextWidth = finalSize.Width;\n _FormattedText!.MaxTextHeight = Math.Max(0.0001d, finalSize.Height);\n\n // need to re-generate the geometry now that the dimensions have changed\n _TextGeometry = null;\n UpdatePen();\n\n return finalSize;\n }\n\n private static void OnFormattedTextInvalidated(DependencyObject dependencyObject,\n DependencyPropertyChangedEventArgs e)\n {\n var outlinedTextBlock = (OutlinedTextBlock)dependencyObject;\n outlinedTextBlock._FormattedText = null;\n outlinedTextBlock._TextGeometry = null;\n\n outlinedTextBlock.InvalidateMeasure();\n outlinedTextBlock.InvalidateVisual();\n }\n\n private static void OnFormattedTextUpdated(DependencyObject dependencyObject, DependencyPropertyChangedEventArgs e)\n {\n var outlinedTextBlock = (OutlinedTextBlock)dependencyObject;\n if (outlinedTextBlock._FormattedText != null)\n outlinedTextBlock.UpdateFormattedText();\n outlinedTextBlock._TextGeometry = null;\n\n outlinedTextBlock.InvalidateMeasure();\n outlinedTextBlock.InvalidateVisual();\n }\n\n private void EnsureFormattedText()\n {\n if (_FormattedText != null)\n return;\n\n _FormattedText = new FormattedText(\n Text ?? \"\",\n CultureInfo.CurrentUICulture,\n FlowDirection,\n new Typeface(FontFamily, FontStyle, FontWeight, FontStretch),\n FontSize,\n Brushes.Black,\n VisualTreeHelper.GetDpi(this).PixelsPerDip);\n\n UpdateFormattedText();\n }\n\n private void UpdateFormattedText()\n {\n _FormattedText!.MaxLineCount = TextWrapping == TextWrapping.NoWrap ? 1 : int.MaxValue;\n _FormattedText.TextAlignment = TextAlignment;\n _FormattedText.Trimming = TextTrimming;\n _FormattedText.SetFontSize(FontSize);\n _FormattedText.SetFontStyle(FontStyle);\n _FormattedText.SetFontWeight(FontWeight);\n _FormattedText.SetFontFamily(FontFamily);\n _FormattedText.SetFontStretch(FontStretch);\n _FormattedText.SetTextDecorations(TextDecorations);\n }\n\n private void EnsureGeometry()\n {\n if (_TextGeometry != null)\n return;\n\n EnsureFormattedText();\n _TextGeometry = _FormattedText!.BuildGeometry(new Point(0, 0));\n\n if (StrokePosition == StrokePosition.Outside)\n {\n var boundsGeo = new RectangleGeometry(new Rect(-(2 * StrokeThickness),\n -(2 * StrokeThickness), ActualWidth + (4 * StrokeThickness), ActualHeight + (4 * StrokeThickness)));\n _clipGeometry = Geometry.Combine(boundsGeo, _TextGeometry, GeometryCombineMode.Exclude, null);\n }\n }\n}\n\npublic enum StrokePosition\n{\n Center,\n Outside,\n Inside\n}\n"], ["/LLPlayer/FlyleafLib/MediaFramework/MediaDecoder/DataDecoder.cs", "using System.Threading;\nusing System.Collections.Concurrent;\nusing System.Runtime.InteropServices;\n\nusing FlyleafLib.MediaFramework.MediaFrame;\nusing FlyleafLib.MediaFramework.MediaStream;\n\nnamespace FlyleafLib.MediaFramework.MediaDecoder;\npublic unsafe class DataDecoder : DecoderBase\n{\n public DataStream DataStream => (DataStream)Stream;\n\n public ConcurrentQueue\n Frames { get; protected set; } = new ConcurrentQueue();\n\n public DataDecoder(Config config, int uniqueId = -1) : base(config, uniqueId) { }\n\n\n protected override unsafe int Setup(AVCodec* codec) => 0;\n protected override void DisposeInternal()\n => Frames = new ConcurrentQueue();\n\n public void Flush()\n {\n lock (lockActions)\n lock (lockCodecCtx)\n {\n if (Disposed)\n return;\n\n if (Status == Status.Ended)\n Status = Status.Stopped;\n else if (Status == Status.Draining)\n Status = Status.Stopping;\n\n DisposeFrames();\n }\n }\n\n protected override void RunInternal()\n {\n int allowedErrors = Config.Decoder.MaxErrors;\n AVPacket *packet;\n\n do\n {\n // Wait until Queue not Full or Stopped\n if (Frames.Count >= Config.Decoder.MaxDataFrames)\n {\n lock (lockStatus)\n if (Status == Status.Running)\n Status = Status.QueueFull;\n\n while (Frames.Count >= Config.Decoder.MaxDataFrames && Status == Status.QueueFull)\n Thread.Sleep(20);\n\n lock (lockStatus)\n {\n if (Status != Status.QueueFull)\n break;\n Status = Status.Running;\n }\n }\n\n // While Packets Queue Empty (Ended | Quit if Demuxer stopped | Wait until we get packets)\n if (demuxer.DataPackets.Count == 0)\n {\n CriticalArea = true;\n\n lock (lockStatus)\n if (Status == Status.Running)\n Status = Status.QueueEmpty;\n\n while (demuxer.DataPackets.Count == 0 && Status == Status.QueueEmpty)\n {\n if (demuxer.Status == Status.Ended)\n {\n Status = Status.Draining;\n break;\n }\n else if (!demuxer.IsRunning)\n {\n int retries = 5;\n\n while (retries > 0)\n {\n retries--;\n Thread.Sleep(10);\n if (demuxer.IsRunning)\n break;\n }\n\n lock (demuxer.lockStatus)\n lock (lockStatus)\n {\n if (demuxer.Status == Status.Pausing || demuxer.Status == Status.Paused)\n Status = Status.Pausing;\n else if (demuxer.Status == Status.QueueFull)\n Status = Status.Draining;\n else if (demuxer.Status == Status.Running)\n continue;\n else if (demuxer.Status != Status.Ended)\n Status = Status.Stopping;\n else\n continue;\n }\n\n break;\n }\n\n Thread.Sleep(20);\n }\n\n lock (lockStatus)\n {\n CriticalArea = false;\n if (Status != Status.QueueEmpty && Status != Status.Draining)\n break;\n if (Status != Status.Draining)\n Status = Status.Running;\n }\n }\n\n lock (lockCodecCtx)\n {\n if (Status == Status.Stopped || demuxer.DataPackets.Count == 0)\n continue;\n packet = demuxer.DataPackets.Dequeue();\n\n if (packet->size > 0 && packet->data != null)\n {\n var mFrame = ProcessDataFrame(packet);\n Frames.Enqueue(mFrame);\n }\n\n av_packet_free(&packet);\n }\n } while (Status == Status.Running);\n\n if (Status == Status.Draining) Status = Status.Ended;\n }\n\n private DataFrame ProcessDataFrame(AVPacket* packet)\n {\n IntPtr ptr = new IntPtr(packet->data);\n byte[] dataFrame = new byte[packet->size];\n Marshal.Copy(ptr, dataFrame, 0, packet->size); // for performance/in case of large data we could just keep the avpacket data directly (DataFrame instead of byte[] Data just use AVPacket* and move ref?)\n\n DataFrame mFrame = new()\n {\n timestamp = (long)(packet->pts * DataStream.Timebase) - demuxer.StartTime,\n DataCodecId = DataStream.CodecID,\n Data = dataFrame\n };\n\n return mFrame;\n }\n\n public void DisposeFrames()\n => Frames = new ConcurrentQueue();\n}\n"], ["/LLPlayer/LLPlayer/Views/MainWindow.xaml.cs", "using System.Runtime.InteropServices;\nusing System.Windows;\nusing System.Windows.Interop;\nusing LLPlayer.Services;\nusing LLPlayer.ViewModels;\n\nnamespace LLPlayer.Views;\n\npublic partial class MainWindow : Window\n{\n public MainWindow()\n {\n // If this is not called first, the constructor of the other control will\n // run before FlyleafHost is initialized, so it will not work.\n DataContext = ((App)Application.Current).Container.Resolve();\n\n InitializeComponent();\n\n SetWindowSize();\n SetTitleBarDarkMode(this);\n }\n\n private void SetWindowSize()\n {\n // 16:9 size list\n List candidateSizes =\n [\n new(1280, 720),\n new(1024, 576),\n new(960, 540),\n new(800, 450),\n new(640, 360),\n new(480, 270),\n new(320, 180)\n ];\n\n // Get available screen width / height\n double availableWidth = SystemParameters.WorkArea.Width;\n double availableHeight = SystemParameters.WorkArea.Height;\n\n // Get the largest size that will fit on the screen\n Size selectedSize = candidateSizes.FirstOrDefault(\n s => s.Width <= availableWidth && s.Height <= availableHeight,\n candidateSizes[^1]);\n\n // Set\n Width = selectedSize.Width;\n Height = selectedSize.Height;\n }\n\n #region Dark Title Bar\n /// \n /// ref: \n /// \n [DllImport(\"DwmApi\")]\n private static extern int DwmSetWindowAttribute(IntPtr hwnd, int attr, int[] attrValue, int attrSize);\n const int DWMWA_USE_IMMERSIVE_DARK_MODE = 20;\n\n public static void SetTitleBarDarkMode(Window window)\n {\n // Check OS Version\n if (!(Environment.OSVersion.Version >= new Version(10, 0, 18985)))\n {\n return;\n }\n\n var fl = ((App)Application.Current).Container.Resolve();\n if (!fl.Config.IsDarkTitlebar)\n {\n return;\n }\n\n bool darkMode = true;\n\n // Set title bar to dark mode\n // ref: https://stackoverflow.com/questions/71362654/wpf-window-titlebar\n IntPtr hWnd = new WindowInteropHelper(window).EnsureHandle();\n DwmSetWindowAttribute(hWnd, DWMWA_USE_IMMERSIVE_DARK_MODE, [darkMode ? 1 : 0], 4);\n }\n #endregion\n}\n"], ["/LLPlayer/LLPlayer/ViewModels/SelectLanguageDialogVM.cs", "using System.Collections.ObjectModel;\nusing System.ComponentModel;\nusing System.Windows.Data;\nusing FlyleafLib;\nusing LLPlayer.Extensions;\nusing LLPlayer.Services;\n\nnamespace LLPlayer.ViewModels;\n\npublic class SelectLanguageDialogVM : Bindable, IDialogAware\n{\n public FlyleafManager FL { get; }\n\n public SelectLanguageDialogVM(FlyleafManager fl)\n {\n FL = fl;\n\n _filteredAvailableLanguages = CollectionViewSource.GetDefaultView(AvailableLanguages);\n _filteredAvailableLanguages.Filter = obj =>\n {\n if (obj is not Language lang)\n return false;\n\n if (string.IsNullOrWhiteSpace(SearchText))\n return true;\n\n string query = SearchText.Trim();\n\n if (lang.TopEnglishName.Contains(query, StringComparison.OrdinalIgnoreCase))\n return true;\n\n return lang.TopNativeName.Contains(query, StringComparison.OrdinalIgnoreCase);\n };\n }\n\n public string SearchText\n {\n get;\n set\n {\n if (Set(ref field, value))\n {\n _filteredAvailableLanguages.Refresh();\n }\n }\n } = string.Empty;\n\n private readonly ICollectionView _filteredAvailableLanguages;\n public ObservableCollection AvailableLanguages { get; } = new();\n public ObservableCollection SelectedLanguages { get; } = new();\n\n public Language? SelectedAvailable\n {\n get;\n set\n {\n if (Set(ref field, value))\n {\n OnPropertyChanged(nameof(CanMoveRight));\n }\n }\n }\n\n // TODO: L: weird naming\n public Language? SelectedSelected\n {\n get;\n set\n {\n if (Set(ref field, value))\n {\n OnPropertyChanged(nameof(CanMoveLeft));\n OnPropertyChanged(nameof(CanMoveUp));\n OnPropertyChanged(nameof(CanMoveDown));\n }\n }\n }\n\n public bool CanMoveRight => SelectedAvailable != null;\n public bool CanMoveLeft => SelectedSelected != null;\n public bool CanMoveUp => SelectedSelected != null && SelectedLanguages.IndexOf(SelectedSelected) > 0;\n public bool CanMoveDown => SelectedSelected != null && SelectedLanguages.IndexOf(SelectedSelected) < SelectedLanguages.Count - 1;\n\n public DelegateCommand? CmdMoveRight => field ??= new DelegateCommand(() =>\n {\n if (SelectedAvailable != null && !SelectedLanguages.Contains(SelectedAvailable))\n {\n SelectedLanguages.Add(SelectedAvailable);\n AvailableLanguages.Remove(SelectedAvailable);\n }\n }).ObservesCanExecute(() => CanMoveRight);\n\n public DelegateCommand? CmdMoveLeft => field ??= new DelegateCommand(() =>\n {\n if (SelectedSelected != null)\n {\n // conform to order\n int insertIndex = 0;\n while (insertIndex < AvailableLanguages.Count &&\n string.Compare(AvailableLanguages[insertIndex].TopEnglishName, SelectedSelected.TopEnglishName, StringComparison.InvariantCulture) < 0)\n {\n insertIndex++;\n }\n\n AvailableLanguages.Insert(insertIndex, SelectedSelected);\n\n SelectedLanguages.Remove(SelectedSelected);\n }\n }).ObservesCanExecute(() => CanMoveLeft);\n\n public DelegateCommand? CmdMoveUp => field ??= new DelegateCommand(() =>\n {\n int index = SelectedLanguages.IndexOf(SelectedSelected!);\n if (index > 0)\n {\n SelectedLanguages.Move(index, index - 1);\n OnPropertyChanged(nameof(CanMoveUp));\n OnPropertyChanged(nameof(CanMoveDown));\n }\n }).ObservesCanExecute(() => CanMoveUp);\n\n public DelegateCommand? CmdMoveDown => field ??= new DelegateCommand(() =>\n {\n int index = SelectedLanguages.IndexOf(SelectedSelected!);\n if (index < SelectedLanguages.Count - 1)\n {\n SelectedLanguages.Move(index, index + 1);\n OnPropertyChanged(nameof(CanMoveUp));\n OnPropertyChanged(nameof(CanMoveDown));\n }\n }).ObservesCanExecute(() => CanMoveDown);\n\n #region IDialogAware\n public string Title { get; set => Set(ref field, value); }\n = $\"Select Language - {App.Name}\";\n public double WindowWidth { get; set => Set(ref field, value); } = 600;\n public double WindowHeight { get; set => Set(ref field, value); } = 360;\n\n public DialogCloseListener RequestClose { get; }\n\n public bool CanCloseDialog()\n {\n return true;\n }\n public void OnDialogClosed()\n {\n List langs = [.. SelectedLanguages];\n DialogParameters p = new()\n {\n { \"languages\", langs }\n };\n\n RequestClose.Invoke(p);\n }\n\n public void OnDialogOpened(IDialogParameters parameters)\n {\n List langs = parameters.GetValue>(\"languages\");\n\n foreach (var lang in langs)\n {\n SelectedLanguages.Add(lang);\n }\n\n foreach (Language lang in Language.AllLanguages)\n {\n if (!SelectedLanguages.Contains(lang))\n {\n AvailableLanguages.Add(lang);\n }\n }\n }\n #endregion\n}\n"], ["/LLPlayer/LLPlayer/Extensions/DataGridRowOrderBehavior.cs", "using System.Collections;\nusing System.Collections.ObjectModel;\nusing System.Windows;\nusing System.Windows.Controls;\nusing System.Windows.Input;\nusing Microsoft.Xaml.Behaviors;\n\nnamespace LLPlayer.Extensions;\n\n/// \n/// Behavior to add the ability to swap rows in a DataGrid by drag and drop\n/// \npublic class DataGridRowOrderBehavior : Behavior\n where T : class\n{\n public static readonly DependencyProperty ItemsSourceProperty =\n DependencyProperty.Register(nameof(ItemsSource), typeof(IList), typeof (DataGridRowOrderBehavior), new PropertyMetadata(null));\n\n /// \n /// ObservableCollection to be reordered bound to DataGrid\n /// \n public ObservableCollection ItemsSource\n {\n get => (ObservableCollection)GetValue(ItemsSourceProperty);\n set => SetValue(ItemsSourceProperty, value);\n }\n\n public static readonly DependencyProperty DragTargetNameProperty =\n DependencyProperty.Register(nameof(DragTargetName), typeof(string), typeof (DataGridRowOrderBehavior), new PropertyMetadata(null));\n\n /// \n /// Control name of the element to be dragged\n /// \n public string DragTargetName\n {\n get => (string)GetValue(DragTargetNameProperty);\n set => SetValue(DragTargetNameProperty, value);\n }\n\n private T? _draggedItem; // Item in row to be dragged\n\n protected override void OnAttached()\n {\n base.OnAttached();\n\n if (AssociatedObject == null)\n {\n return;\n }\n\n AssociatedObject.AllowDrop = true;\n\n AssociatedObject.PreviewMouseLeftButtonDown += OnPreviewMouseLeftButtonDown;\n AssociatedObject.DragOver += OnDragOver;\n AssociatedObject.Drop += OnDrop;\n }\n\n protected override void OnDetaching()\n {\n base.OnDetaching();\n\n if (AssociatedObject == null)\n {\n return;\n }\n\n AssociatedObject.AllowDrop = false;\n\n AssociatedObject.PreviewMouseLeftButtonDown -= OnPreviewMouseLeftButtonDown;\n AssociatedObject.DragOver -= OnDragOver;\n AssociatedObject.Drop -= OnDrop;\n }\n\n private void OnPreviewMouseLeftButtonDown(object sender, MouseButtonEventArgs e)\n {\n if (ItemsSource == null)\n {\n return;\n }\n\n // 1: Determines if it is on a \"drag handle\".\n if (!IsDragHandle(e.OriginalSource))\n {\n return;\n }\n\n // 2: Identify Row\n DataGridRow? row = UIHelper.FindParent((DependencyObject)e.OriginalSource);\n if (row == null)\n {\n return;\n }\n\n // Select the row\n AssociatedObject.UnselectAll();\n row.IsSelected = true;\n row.Focus();\n\n _draggedItem = row.Item as T;\n\n if (_draggedItem != null)\n {\n // Start dragging\n DragDrop.DoDragDrop(AssociatedObject, _draggedItem, DragDropEffects.Move);\n }\n }\n\n /// \n /// Dragging (while the mouse is moving)\n /// \n private void OnDragOver(object sender, DragEventArgs e)\n {\n if (_draggedItem == null)\n {\n return;\n }\n\n e.Handled = true;\n\n // Find the line where the mouse is now.\n DataGridRow? row = UIHelper.FindParent((DependencyObject)e.OriginalSource);\n if (row == null)\n {\n return;\n }\n\n var targetItem = row.Item;\n if (targetItem == null || targetItem == _draggedItem)\n {\n // If it's the same line, nothing.\n return;\n }\n\n T? targetRow = targetItem as T;\n if (targetRow == null)\n {\n return;\n }\n\n // Get the index of each row to be replaced\n int oldIndex = ItemsSource.IndexOf(_draggedItem);\n int newIndex = ItemsSource.IndexOf(targetRow);\n\n if (oldIndex < 0 || newIndex < 0 || oldIndex == newIndex)\n {\n return;\n }\n\n // Swap lines\n ItemsSource.Move(oldIndex, newIndex);\n }\n\n /// \n /// When dropped\n /// \n private void OnDrop(object sender, DragEventArgs e)\n {\n // Clear state as it is being reordered during drag.\n _draggedItem = null;\n }\n\n /// \n /// Judges whether an element is ready to start dragging.\n /// \n private bool IsDragHandle(object originalSource)\n {\n return UIHelper.FindParentWithName(originalSource as DependencyObject, DragTargetName);\n }\n}\n"], ["/LLPlayer/LLPlayer/Extensions/Guards.cs", "using System.Diagnostics.CodeAnalysis;\nusing System.Runtime.CompilerServices;\n\nnamespace LLPlayer.Extensions;\n\npublic static class Guards\n{\n /// Throws an immediately.\n /// error message\n /// \n public static void Fail(string? message = null)\n {\n throw new InvalidOperationException(message);\n }\n\n /// Throws an if is null.\n /// The reference type variable to validate as non-null.\n /// The name of the variable with which corresponds.\n /// \n public static void ThrowIfNull([NotNull] object? variable, [CallerArgumentExpression(nameof(variable))] string? variableName = null)\n {\n if (variable is null)\n {\n throw new InvalidOperationException(variableName);\n }\n }\n}\n"], ["/LLPlayer/FlyleafLib/MediaFramework/MediaDevice/DeviceBase.cs", "using System.Collections.Generic;\n\nnamespace FlyleafLib.MediaFramework.MediaDevice;\n\npublic class DeviceBase :DeviceBase\n{\n public DeviceBase(string friendlyName, string symbolicLink) : base(friendlyName, symbolicLink)\n {\n }\n}\n\npublic class DeviceBase\n where T: DeviceStreamBase\n{\n public string FriendlyName { get; }\n public string SymbolicLink { get; }\n public IList\n Streams { get; protected set; }\n public string Url { get; protected set; } // default Url\n\n public DeviceBase(string friendlyName, string symbolicLink)\n {\n FriendlyName = friendlyName;\n SymbolicLink = symbolicLink;\n\n Engine.Log.Debug($\"[{(this is AudioDevice ? \"Audio\" : \"Video\")}Device] {friendlyName}\");\n }\n\n public override string ToString() => FriendlyName;\n}\n"], ["/LLPlayer/LLPlayer/ViewModels/CheatSheetDialogVM.cs", "using System.Diagnostics.CodeAnalysis;\nusing System.Globalization;\nusing System.Windows.Data;\nusing System.Windows.Input;\nusing System.Windows.Media;\nusing FlyleafLib.MediaPlayer;\nusing LLPlayer.Converters;\nusing LLPlayer.Extensions;\nusing LLPlayer.Services;\nusing MaterialDesignColors.Recommended;\nusing KeyBinding = FlyleafLib.MediaPlayer.KeyBinding;\n\nnamespace LLPlayer.ViewModels;\n\npublic class CheatSheetDialogVM : Bindable, IDialogAware\n{\n public FlyleafManager FL { get; }\n\n public CheatSheetDialogVM(FlyleafManager fl)\n {\n FL = fl;\n\n List keys = FL.PlayerConfig.Player.KeyBindings.Keys.Where(k => k.IsEnabled).ToList();\n\n HitCount = keys.Count;\n\n KeyToStringConverter keyConverter = new();\n\n List groups = keys.Select(k =>\n {\n KeyBindingCS key = new()\n {\n Action = k.Action,\n ActionName = k.Action.ToString(),\n Alt = k.Alt,\n Ctrl = k.Ctrl,\n Shift = k.Shift,\n Description = k.Action.GetDescription(),\n Group = k.Action.ToGroup(),\n Key = k.Key,\n KeyName = (string)keyConverter.Convert(k.Key, typeof(string), null, CultureInfo.CurrentCulture),\n ActionInternal = k.ActionInternal,\n };\n\n if (key.Action == KeyBindingAction.Custom)\n {\n if (!Enum.TryParse(k.ActionName, out CustomKeyBindingAction customAction))\n {\n HitCount -= 1;\n return null;\n }\n\n key.ActionName = customAction.ToString();\n key.CustomAction = customAction;\n key.Description = customAction.GetDescription();\n key.Group = customAction.ToGroup();\n }\n\n return key;\n })\n .Where(k => k != null)\n .OrderBy(k => k!.Action)\n .ThenBy(k => k!.CustomAction)\n .GroupBy(k => k!.Group)\n .OrderBy(g => g.Key)\n .Select(g => new KeyBindingCSGroup()\n {\n Group = g.Key,\n KeyBindings = g.ToList()!\n }).ToList();\n\n KeyBindingGroups = new List(groups);\n\n List collectionViews = KeyBindingGroups.Select(g => (ListCollectionView)CollectionViewSource.GetDefaultView(g.KeyBindings))\n .ToList();\n _collectionViews = collectionViews;\n\n foreach (ListCollectionView view in collectionViews)\n {\n view.Filter = (obj) =>\n {\n if (obj is not KeyBindingCS key)\n {\n return false;\n }\n\n if (string.IsNullOrWhiteSpace(SearchText))\n {\n return true;\n }\n\n string query = SearchText.Trim();\n\n bool match = key.Description.Contains(query, StringComparison.OrdinalIgnoreCase);\n if (match)\n {\n return true;\n }\n\n return key.Shortcut.Contains(query, StringComparison.OrdinalIgnoreCase);\n };\n }\n }\n\n public string SearchText\n {\n get;\n set\n {\n if (Set(ref field, value))\n {\n _collectionViews.ForEach(v => v.Refresh());\n\n HitCount = _collectionViews.Sum(v => v.Count);\n }\n }\n } = string.Empty;\n\n public int HitCount { get; set => Set(ref field, value); }\n\n private readonly List _collectionViews;\n public List KeyBindingGroups { get; set; }\n\n public DelegateCommand? CmdAction => field ??= new((key) =>\n {\n FL.Player.Activity.ForceFullActive();\n key.ActionInternal.Invoke();\n });\n\n #region IDialogAware\n public string Title { get; set => Set(ref field, value); } = $\"CheatSheet - {App.Name}\";\n public double WindowWidth { get; set => Set(ref field, value); } = 1000;\n public double WindowHeight { get; set => Set(ref field, value); } = 800;\n\n public bool CanCloseDialog() => true;\n public void OnDialogClosed() { }\n public void OnDialogOpened(IDialogParameters parameters) { }\n public DialogCloseListener RequestClose { get; }\n #endregion IDialogAware\n}\n\npublic class KeyBindingCS\n{\n public required bool Ctrl { get; init; }\n public required bool Shift { get; init; }\n public required bool Alt { get; init; }\n public required Key Key { get; init; }\n public required string KeyName { get; init; }\n\n [field: AllowNull, MaybeNull]\n public string Shortcut\n {\n get\n {\n if (field == null)\n {\n string modifiers = \"\";\n if (Ctrl)\n modifiers += \"Ctrl + \";\n if (Alt)\n modifiers += \"Alt + \";\n if (Shift)\n modifiers += \"Shift + \";\n field = $\"{modifiers}{KeyName}\";\n }\n\n return field;\n }\n }\n\n public required KeyBindingAction Action { get; init; }\n public CustomKeyBindingAction? CustomAction { get; set; }\n public required string ActionName { get; set; }\n public required string Description { get; set; }\n public required KeyBindingActionGroup Group { get; set; }\n\n public required Action ActionInternal { get; init; }\n}\n\npublic class KeyBindingCSGroup\n{\n public required KeyBindingActionGroup Group { get; init; }\n\n [field: AllowNull, MaybeNull]\n public string GroupName => field ??= Group.ToString();\n public required List KeyBindings { get; init; }\n\n public Color GroupColor =>\n Group switch\n {\n KeyBindingActionGroup.Playback => RedSwatch.Red500,\n KeyBindingActionGroup.Player => PinkSwatch.Pink500,\n KeyBindingActionGroup.Audio => PurpleSwatch.Purple500,\n KeyBindingActionGroup.Video => BlueSwatch.Blue500,\n KeyBindingActionGroup.Subtitles => TealSwatch.Teal500,\n KeyBindingActionGroup.SubtitlesPosition => GreenSwatch.Green500,\n KeyBindingActionGroup.Window => LightGreenSwatch.LightGreen500,\n KeyBindingActionGroup.Other => DeepOrangeSwatch.DeepOrange500,\n _ => BrownSwatch.Brown500\n };\n}\n"], ["/LLPlayer/FlyleafLib/MediaFramework/MediaDevice/VideoDevice.cs", "using System;\nusing System.Linq;\n\nusing Vortice.MediaFoundation;\n\nnamespace FlyleafLib.MediaFramework.MediaDevice;\n\npublic class VideoDevice : DeviceBase\n{\n public VideoDevice(string friendlyName, string symbolicLink) : base(friendlyName, symbolicLink)\n {\n Streams = VideoDeviceStream.GetVideoFormatsForVideoDevice(friendlyName, symbolicLink);\n Url = Streams.Where(f => f.SubType.Contains(\"MJPG\") && f.FrameRate >= 30).OrderByDescending(f => f.FrameSizeHeight).FirstOrDefault()?.Url;\n }\n\n public static void RefreshDevices()\n {\n Utils.UIInvokeIfRequired(() =>\n {\n Engine.Video.CapDevices.Clear();\n\n var devices = MediaFactory.MFEnumVideoDeviceSources();\n foreach (var device in devices)\n try { Engine.Video.CapDevices.Add(new VideoDevice(device.FriendlyName, device.SymbolicLink)); } catch(Exception) { }\n });\n }\n}\n"], ["/LLPlayer/Plugins/YoutubeDL/YoutubeDLJson.cs", "using System.Collections.Generic;\nusing System.Text.Json.Serialization;\n\nnamespace FlyleafLib.Plugins\n{\n public class YoutubeDLJson : Format\n {\n // Remove not used as can cause issues with data types from time to time\n\n //public string id { get; set; }\n public string title { get; set; }\n //public string description { get; set; }\n //public string upload_date { get; set; }\n //public string uploader { get; set; }\n //public string uploader_id { get; set; }\n //public string uploader_url { get; set; }\n //public string channel_id { get; set; }\n //public string channel_url { get; set; }\n //public double duration { get; set; }\n //public double view_count { get; set; }\n //public double average_rating { get; set; }\n //public double age_limit { get; set; }\n public string webpage_url { get; set; }\n\n //public bool playable_in_embed { get; set; }\n //public bool is_live { get; set; }\n //public bool was_live { get; set; }\n //public string live_status { get; set; }\n\n // Playlist\n public string _type { get; set; }\n public double playlist_count { get; set; }\n //public double playlist_index { get; set; }\n public string playlist { get; set; }\n public string playlist_title { get; set; }\n\n\n\n public Dictionary>\n automatic_captions { get; set; }\n //public List\n // categories { get; set; }\n public List\n formats { get; set; }\n //public List\n // thumbnails { get; set; }\n public List\n chapters\n { get; set; }\n //public double like_count { get; set; }\n //public double dislike_count { get; set; }\n //public string channel { get; set; }\n //public string availability { get; set; }\n //public string webpage_url_basename\n // { get; set; }\n //public string extractor { get; set; }\n //public string extractor_key { get; set; }\n //public string thumbnail { get; set; }\n //public string display_id { get; set; }\n //public string fulltitle { get; set; }\n //public double epoch { get; set; }\n\n //public class DownloaderOptions\n //{\n // public int http_chunk_size { get; set; }\n //}\n\n public class HttpHeaders\n {\n [JsonPropertyName(\"User-Agent\")]\n public string UserAgent { get; set; }\n\n [JsonPropertyName(\"Accept-Charset\")]\n public string AcceptCharset { get; set; }\n public string Accept { get; set; }\n\n [JsonPropertyName(\"Accept-Encoding\")]\n public string AcceptEncoding{ get; set; }\n\n [JsonPropertyName(\"Accept-Language\")]\n public string AcceptLanguage{ get; set; }\n }\n\n //public class Thumbnail\n //{\n // public string url { get; set; }\n // public int preference { get; set; }\n // public string id { get; set; }\n // public double height { get; set; }\n // public double width { get; set; }\n // public string resolution { get; set; }\n //}\n\n public class SubtitlesFormat\n {\n public string ext { get; set; }\n public string url { get; set; }\n public string name { get; set; }\n }\n }\n\n public class Chapter\n {\n public double start_time { get; set; }\n public double end_time { get; set; }\n public string title { get; set; }\n }\n\n public class Format\n {\n //public double asr { get; set; }\n //public double filesize { get; set; }\n //public string format_id { get; set; }\n //public string format_note { get; set; }\n //public double quality { get; set; }\n public double tbr { get; set; }\n public string url { get; set; }\n public string manifest_url{ get; set; }\n public string language { get; set; }\n //public int language_preference\n // { get; set; }\n //public string ext { get; set; }\n public string vcodec { get; set; }\n public string acodec { get; set; }\n public double abr { get; set; }\n //public DownloaderOptions\n // downloader_options { get; set; }\n //public string container { get; set; }\n public string protocol { get; set; }\n //public string audio_ext { get; set; }\n //public string video_ext { get; set; }\n public string format { get; set; }\n public Dictionary\n http_headers{ get; set; }\n public string cookies { get; set; }\n public double fps { get; set; }\n public double height { get; set; }\n public double width { get; set; }\n public double vbr { get; set; }\n }\n}\n"], ["/LLPlayer/LLPlayer/Extensions/StringExtensions.cs", "using System.IO;\n\nnamespace LLPlayer.Extensions;\n\npublic static class StringExtensions\n{\n /// \n /// Split for various types of newline codes\n /// \n /// \n /// \n public static IEnumerable SplitToLines(this string? input)\n {\n if (input == null)\n {\n yield break;\n }\n\n using StringReader reader = new(input);\n\n string? line;\n while ((line = reader.ReadLine()) != null)\n {\n yield return line;\n }\n }\n\n /// \n /// Convert only the first character to lower case\n /// \n /// \n /// \n public static string ToLowerFirstChar(this string input)\n {\n if (string.IsNullOrEmpty(input))\n return input;\n\n return char.ToLower(input[0]) + input.Substring(1);\n }\n\n /// \n /// Convert only the first character to upper case\n /// \n /// \n /// \n public static string ToUpperFirstChar(this string input)\n {\n if (string.IsNullOrEmpty(input))\n return input;\n\n return char.ToUpper(input[0]) + input.Substring(1);\n }\n}\n"], ["/LLPlayer/LLPlayer/Controls/Settings/SettingsSubtitlesAction.xaml.cs", "using System.Collections.ObjectModel;\nusing System.Windows;\nusing System.Windows.Controls;\nusing System.Windows.Input;\nusing FlyleafLib.MediaPlayer.Translation.Services;\nusing LLPlayer.Extensions;\nusing LLPlayer.Services;\n\nnamespace LLPlayer.Controls.Settings;\n\npublic partial class SettingsSubtitlesAction : UserControl\n{\n public SettingsSubtitlesAction()\n {\n InitializeComponent();\n\n DataContext = ((App)Application.Current).Container.Resolve();\n }\n}\n\npublic class SettingsSubtitlesActionVM : Bindable\n{\n public FlyleafManager FL { get; }\n\n public SettingsSubtitlesActionVM(FlyleafManager fl)\n {\n FL = fl;\n\n SelectedTranslateWordServiceType = FL.PlayerConfig.Subtitles.TranslateWordServiceType;\n\n List wordClickActions = Enum.GetValues().ToList();\n if (string.IsNullOrEmpty(FL.Config.Subs.PDICPipeExecutablePath))\n {\n // PDIC is enabled only when exe is configured\n wordClickActions.Remove(WordClickAction.PDIC);\n }\n WordClickActions = wordClickActions;\n\n foreach (IMenuAction menuAction in FL.Config.Subs.WordMenuActions)\n {\n MenuActions.Add((IMenuAction)menuAction.Clone());\n }\n }\n\n public TranslateServiceType SelectedTranslateWordServiceType\n {\n get;\n set\n {\n if (Set(ref field, value))\n {\n FL.PlayerConfig.Subtitles.TranslateWordServiceType = value;\n }\n }\n }\n\n public List WordClickActions { get; }\n\n public List ModifierKeys { get; } =\n [\n System.Windows.Input.ModifierKeys.Control,\n System.Windows.Input.ModifierKeys.Shift,\n System.Windows.Input.ModifierKeys.Alt,\n System.Windows.Input.ModifierKeys.None\n ];\n\n public ObservableCollection MenuActions { get; } = new();\n\n public DelegateCommand? CmdApplyContextMenu => field ??= new(() =>\n {\n ObservableCollection newActions = new(MenuActions.Select(a => (IMenuAction)a.Clone()));\n\n // Apply to config\n FL.Config.Subs.WordMenuActions = newActions;\n });\n\n public DelegateCommand? CmdAddSearchAction => field ??= new(() =>\n {\n MenuActions.Add(new SearchMenuAction\n {\n Title = \"New Search\",\n Url = \"https://example.com/?q=%w\"\n });\n });\n\n public DelegateCommand? CmdAddClipboardAction => field ??= new(() =>\n {\n MenuActions.Add(new ClipboardMenuAction());\n });\n\n public DelegateCommand? CmdAddClipboardAllAction => field ??= new(() =>\n {\n MenuActions.Add(new ClipboardAllMenuAction());\n });\n\n public DelegateCommand? CmdRemoveAction => field ??= new((action) =>\n {\n if (action != null)\n {\n MenuActions.Remove(action);\n }\n });\n\n // TODO: L: SaveCommand?\n}\n\nclass DataGridRowOrderBehaviorMenuAction : DataGridRowOrderBehavior;\n\nclass MenuActionTemplateSelector : DataTemplateSelector\n{\n public required DataTemplate SearchTemplate { get; set; }\n public required DataTemplate ClipboardTemplate { get; set; }\n public required DataTemplate ClipboardAllTemplate { get; set; }\n\n public override DataTemplate? SelectTemplate(object? item, DependencyObject container)\n {\n return item switch\n {\n SearchMenuAction => SearchTemplate,\n ClipboardMenuAction => ClipboardTemplate,\n ClipboardAllMenuAction => ClipboardAllTemplate,\n _ => null\n };\n }\n}\n"], ["/LLPlayer/LLPlayer/Extensions/TextBoxHelper.cs", "using System.Windows;\nusing System.Windows.Controls;\nusing System.Windows.Input;\n\nnamespace LLPlayer.Extensions;\n\n\n// ref: https://stackoverflow.com/a/50905766/9070784\npublic static class TextBoxHelper\n{\n #region Enum Declarations\n public enum NumericFormat\n {\n Double,\n Int,\n Uint,\n Natural\n }\n\n public enum EvenOddConstraint\n {\n All,\n OnlyEven,\n OnlyOdd\n }\n\n #endregion\n\n #region Dependency Properties & CLR Wrappers\n\n public static readonly DependencyProperty OnlyNumericProperty =\n DependencyProperty.RegisterAttached(\"OnlyNumeric\", typeof(NumericFormat?), typeof(TextBoxHelper),\n new PropertyMetadata(null, DependencyPropertiesChanged));\n public static void SetOnlyNumeric(TextBox element, NumericFormat value) =>\n element.SetValue(OnlyNumericProperty, value);\n public static NumericFormat GetOnlyNumeric(TextBox element) =>\n (NumericFormat)element.GetValue(OnlyNumericProperty);\n\n\n public static readonly DependencyProperty DefaultValueProperty =\n DependencyProperty.RegisterAttached(\"DefaultValue\", typeof(string), typeof(TextBoxHelper),\n new PropertyMetadata(null, DependencyPropertiesChanged));\n public static void SetDefaultValue(TextBox element, string value) =>\n element.SetValue(DefaultValueProperty, value);\n public static string GetDefaultValue(TextBox element) => (string)element.GetValue(DefaultValueProperty);\n\n\n public static readonly DependencyProperty EvenOddConstraintProperty =\n DependencyProperty.RegisterAttached(\"EvenOddConstraint\", typeof(EvenOddConstraint), typeof(TextBoxHelper),\n new PropertyMetadata(EvenOddConstraint.All, DependencyPropertiesChanged));\n public static void SetEvenOddConstraint(TextBox element, EvenOddConstraint value) =>\n element.SetValue(EvenOddConstraintProperty, value);\n public static EvenOddConstraint GetEvenOddConstraint(TextBox element) =>\n (EvenOddConstraint)element.GetValue(EvenOddConstraintProperty);\n\n #endregion\n\n #region Dependency Properties Methods\n\n private static void DependencyPropertiesChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)\n {\n if (!(d is TextBox textBox))\n throw new Exception(\"Attached property must be used with TextBox.\");\n\n switch (e.Property.Name)\n {\n case \"OnlyNumeric\":\n {\n var castedValue = (NumericFormat?)e.NewValue;\n\n if (castedValue.HasValue)\n {\n textBox.PreviewTextInput += TextBox_PreviewTextInput;\n DataObject.AddPastingHandler(textBox, TextBox_PasteEventHandler);\n }\n else\n {\n textBox.PreviewTextInput -= TextBox_PreviewTextInput;\n DataObject.RemovePastingHandler(textBox, TextBox_PasteEventHandler);\n }\n\n break;\n }\n\n case \"DefaultValue\":\n {\n var castedValue = (string)e.NewValue;\n\n if (castedValue != null)\n {\n textBox.TextChanged += TextBox_TextChanged;\n }\n else\n {\n textBox.TextChanged -= TextBox_TextChanged;\n }\n\n break;\n }\n }\n }\n\n #endregion\n\n private static void TextBox_PreviewTextInput(object sender, TextCompositionEventArgs e)\n {\n var textBox = (TextBox)sender;\n\n string newText;\n\n if (textBox.SelectionLength == 0)\n {\n newText = textBox.Text.Insert(textBox.SelectionStart, e.Text);\n }\n else\n {\n var textAfterDelete = textBox.Text.Remove(textBox.SelectionStart, textBox.SelectionLength);\n\n newText = textAfterDelete.Insert(textBox.SelectionStart, e.Text);\n }\n\n var evenOddConstraint = GetEvenOddConstraint(textBox);\n\n switch (GetOnlyNumeric(textBox))\n {\n case NumericFormat.Double:\n {\n if (double.TryParse(newText, out double number))\n {\n switch (evenOddConstraint)\n {\n case EvenOddConstraint.OnlyEven:\n\n if (number % 2 != 0)\n e.Handled = true;\n else\n e.Handled = false;\n\n break;\n\n case EvenOddConstraint.OnlyOdd:\n\n if (number % 2 == 0)\n e.Handled = true;\n else\n e.Handled = false;\n\n break;\n }\n }\n else\n e.Handled = true;\n\n break;\n }\n\n case NumericFormat.Int:\n {\n if (int.TryParse(newText, out int number))\n {\n switch (evenOddConstraint)\n {\n case EvenOddConstraint.OnlyEven:\n\n if (number % 2 != 0)\n e.Handled = true;\n else\n e.Handled = false;\n\n break;\n\n case EvenOddConstraint.OnlyOdd:\n\n if (number % 2 == 0)\n e.Handled = true;\n else\n e.Handled = false;\n\n break;\n }\n }\n else\n e.Handled = true;\n\n break;\n }\n\n case NumericFormat.Uint:\n {\n if (uint.TryParse(newText, out uint number))\n {\n switch (evenOddConstraint)\n {\n case EvenOddConstraint.OnlyEven:\n\n if (number % 2 != 0)\n e.Handled = true;\n else\n e.Handled = false;\n\n break;\n\n case EvenOddConstraint.OnlyOdd:\n\n if (number % 2 == 0)\n e.Handled = true;\n else\n e.Handled = false;\n\n break;\n }\n }\n else\n e.Handled = true;\n\n break;\n }\n\n case NumericFormat.Natural:\n {\n if (uint.TryParse(newText, out uint number))\n {\n if (number == 0)\n e.Handled = true;\n else\n {\n switch (evenOddConstraint)\n {\n case EvenOddConstraint.OnlyEven:\n\n if (number % 2 != 0)\n e.Handled = true;\n else\n e.Handled = false;\n\n break;\n\n case EvenOddConstraint.OnlyOdd:\n\n if (number % 2 == 0)\n e.Handled = true;\n else\n e.Handled = false;\n\n break;\n }\n }\n }\n else\n e.Handled = true;\n\n break;\n }\n }\n }\n\n private static void TextBox_PasteEventHandler(object sender, DataObjectPastingEventArgs e)\n {\n var textBox = (TextBox)sender;\n\n if (e.DataObject.GetDataPresent(typeof(string)))\n {\n var clipboardText = (string)e.DataObject.GetData(typeof(string));\n\n var newText = textBox.Text.Insert(textBox.SelectionStart, clipboardText);\n\n var evenOddConstraint = GetEvenOddConstraint(textBox);\n\n switch (GetOnlyNumeric(textBox))\n {\n case NumericFormat.Double:\n {\n if (double.TryParse(newText, out double number))\n {\n switch (evenOddConstraint)\n {\n case EvenOddConstraint.OnlyEven:\n\n if (number % 2 != 0)\n e.CancelCommand();\n\n break;\n\n case EvenOddConstraint.OnlyOdd:\n\n if (number % 2 == 0)\n e.CancelCommand();\n\n break;\n }\n }\n else\n e.CancelCommand();\n\n break;\n }\n\n case NumericFormat.Int:\n {\n if (int.TryParse(newText, out int number))\n {\n switch (evenOddConstraint)\n {\n case EvenOddConstraint.OnlyEven:\n\n if (number % 2 != 0)\n e.CancelCommand();\n\n break;\n\n case EvenOddConstraint.OnlyOdd:\n\n if (number % 2 == 0)\n e.CancelCommand();\n\n\n break;\n }\n }\n else\n e.CancelCommand();\n\n break;\n }\n\n case NumericFormat.Uint:\n {\n if (uint.TryParse(newText, out uint number))\n {\n switch (evenOddConstraint)\n {\n case EvenOddConstraint.OnlyEven:\n\n if (number % 2 != 0)\n e.CancelCommand();\n\n break;\n\n case EvenOddConstraint.OnlyOdd:\n\n if (number % 2 == 0)\n e.CancelCommand();\n\n\n break;\n }\n }\n else\n e.CancelCommand();\n\n break;\n }\n\n case NumericFormat.Natural:\n {\n if (uint.TryParse(newText, out uint number))\n {\n if (number == 0)\n e.CancelCommand();\n else\n {\n switch (evenOddConstraint)\n {\n case EvenOddConstraint.OnlyEven:\n\n if (number % 2 != 0)\n e.CancelCommand();\n\n break;\n\n case EvenOddConstraint.OnlyOdd:\n\n if (number % 2 == 0)\n e.CancelCommand();\n\n break;\n }\n }\n }\n else\n {\n e.CancelCommand();\n }\n\n break;\n }\n }\n }\n else\n {\n e.CancelCommand();\n }\n }\n\n private static void TextBox_TextChanged(object sender, TextChangedEventArgs e)\n {\n var textBox = (TextBox)sender;\n\n var defaultValue = GetDefaultValue(textBox);\n\n var evenOddConstraint = GetEvenOddConstraint(textBox);\n\n switch (GetOnlyNumeric(textBox))\n {\n case NumericFormat.Double:\n {\n if (double.TryParse(textBox.Text, out double number))\n {\n switch (evenOddConstraint)\n {\n case EvenOddConstraint.OnlyEven:\n\n if (number % 2 != 0)\n textBox.Text = defaultValue;\n\n break;\n\n case EvenOddConstraint.OnlyOdd:\n\n if (number % 2 == 0)\n textBox.Text = defaultValue;\n\n break;\n }\n }\n else\n textBox.Text = defaultValue;\n\n break;\n }\n\n case NumericFormat.Int:\n {\n if (int.TryParse(textBox.Text, out int number))\n {\n switch (evenOddConstraint)\n {\n case EvenOddConstraint.OnlyEven:\n\n if (number % 2 != 0)\n textBox.Text = defaultValue;\n\n break;\n\n case EvenOddConstraint.OnlyOdd:\n\n if (number % 2 == 0)\n textBox.Text = defaultValue;\n\n break;\n }\n }\n else\n textBox.Text = defaultValue;\n\n break;\n }\n\n case NumericFormat.Uint:\n {\n if (uint.TryParse(textBox.Text, out uint number))\n {\n switch (evenOddConstraint)\n {\n case EvenOddConstraint.OnlyEven:\n\n if (number % 2 != 0)\n textBox.Text = defaultValue;\n\n break;\n\n case EvenOddConstraint.OnlyOdd:\n\n if (number % 2 == 0)\n textBox.Text = defaultValue;\n\n break;\n }\n }\n else\n textBox.Text = defaultValue;\n\n break;\n }\n\n case NumericFormat.Natural:\n {\n if (uint.TryParse(textBox.Text, out uint number))\n {\n if (number == 0)\n textBox.Text = defaultValue;\n else\n {\n switch (evenOddConstraint)\n {\n case EvenOddConstraint.OnlyEven:\n\n if (number % 2 != 0)\n textBox.Text = defaultValue;\n\n break;\n\n case EvenOddConstraint.OnlyOdd:\n\n if (number % 2 == 0)\n textBox.Text = defaultValue;\n\n break;\n }\n }\n }\n else\n {\n textBox.Text = defaultValue;\n }\n\n break;\n }\n }\n }\n}\n"], ["/LLPlayer/FlyleafLib/MediaFramework/MediaDemuxer/Interrupter.cs", "using System.Diagnostics;\n\nusing static FlyleafLib.Logger;\n\nnamespace FlyleafLib.MediaFramework.MediaDemuxer;\n\npublic unsafe class Interrupter\n{\n public int ForceInterrupt { get; set; }\n public Requester Requester { get; private set; }\n public int Interrupted { get; private set; }\n public bool Timedout { get; private set; }\n\n Demuxer demuxer;\n Stopwatch sw = new();\n internal AVIOInterruptCB_callback interruptClbk;\n long curTimeoutMs;\n\n internal int ShouldInterrupt(void* opaque)\n {\n if (demuxer.Status == Status.Stopping)\n {\n if (CanDebug) demuxer.Log.Debug($\"{Requester} Interrupt (Stopping) !!!\");\n\n return Interrupted = 1;\n }\n\n if (demuxer.Config.AllowTimeouts && sw.ElapsedMilliseconds > curTimeoutMs)\n {\n if (Timedout)\n return Interrupted = 1;\n\n if (CanWarn) demuxer.Log.Warn($\"{Requester} Timeout !!!! {sw.ElapsedMilliseconds} ms\");\n\n Timedout = true;\n Interrupted = 1;\n demuxer.OnTimedOut();\n\n return Interrupted;\n }\n\n if (Requester == Requester.Close)\n return 0;\n\n if (ForceInterrupt != 0 && demuxer.allowReadInterrupts)\n {\n if (CanTrace) demuxer.Log.Trace($\"{Requester} Interrupt !!!\");\n\n return Interrupted = 1;\n }\n\n return Interrupted = 0;\n }\n\n public Interrupter(Demuxer demuxer)\n {\n this.demuxer = demuxer;\n interruptClbk = ShouldInterrupt;\n }\n\n public void ReadRequest()\n {\n Requester = Requester.Read;\n\n if (!demuxer.Config.AllowTimeouts)\n return;\n\n Timedout = false;\n curTimeoutMs= demuxer.IsLive ? demuxer.Config.readLiveTimeoutMs: demuxer.Config.readTimeoutMs;\n sw.Restart();\n }\n\n public void SeekRequest()\n {\n Requester = Requester.Seek;\n\n if (!demuxer.Config.AllowTimeouts)\n return;\n\n Timedout = false;\n curTimeoutMs= demuxer.Config.seekTimeoutMs;\n sw.Restart();\n }\n\n public void OpenRequest()\n {\n Requester = Requester.Open;\n\n if (!demuxer.Config.AllowTimeouts)\n return;\n\n Timedout = false;\n curTimeoutMs= demuxer.Config.openTimeoutMs;\n sw.Restart();\n }\n\n public void CloseRequest()\n {\n Requester = Requester.Close;\n\n if (!demuxer.Config.AllowTimeouts)\n return;\n\n Timedout = false;\n curTimeoutMs= demuxer.Config.closeTimeoutMs;\n sw.Restart();\n }\n}\n\npublic enum Requester\n{\n Close,\n Open,\n Read,\n Seek\n}\n"], ["/LLPlayer/FlyleafLib/Engine/WhisperLanguage.cs", "using System.Collections.Generic;\nusing System.Linq;\nusing System.Text;\n\nnamespace FlyleafLib;\n\npublic class WhisperLanguage : IEquatable\n{\n public string Code { get; set; }\n public string EnglishName { get; set; }\n\n // https://github.com/ggerganov/whisper.cpp/blob/d682e150908e10caa4c15883c633d7902d385237/src/whisper.cpp#L248-L348\n private static readonly Dictionary CodeToLanguage = new()\n {\n {\"en\", \"english\"},\n {\"zh\", \"chinese\"},\n {\"de\", \"german\"},\n {\"es\", \"spanish\"},\n {\"ru\", \"russian\"},\n {\"ko\", \"korean\"},\n {\"fr\", \"french\"},\n {\"ja\", \"japanese\"},\n {\"pt\", \"portuguese\"},\n {\"tr\", \"turkish\"},\n {\"pl\", \"polish\"},\n {\"ca\", \"catalan\"},\n {\"nl\", \"dutch\"},\n {\"ar\", \"arabic\"},\n {\"sv\", \"swedish\"},\n {\"it\", \"italian\"},\n {\"id\", \"indonesian\"},\n {\"hi\", \"hindi\"},\n {\"fi\", \"finnish\"},\n {\"vi\", \"vietnamese\"},\n {\"he\", \"hebrew\"},\n {\"uk\", \"ukrainian\"},\n {\"el\", \"greek\"},\n {\"ms\", \"malay\"},\n {\"cs\", \"czech\"},\n {\"ro\", \"romanian\"},\n {\"da\", \"danish\"},\n {\"hu\", \"hungarian\"},\n {\"ta\", \"tamil\"},\n {\"no\", \"norwegian\"},\n {\"th\", \"thai\"},\n {\"ur\", \"urdu\"},\n {\"hr\", \"croatian\"},\n {\"bg\", \"bulgarian\"},\n {\"lt\", \"lithuanian\"},\n {\"la\", \"latin\"},\n {\"mi\", \"maori\"},\n {\"ml\", \"malayalam\"},\n {\"cy\", \"welsh\"},\n {\"sk\", \"slovak\"},\n {\"te\", \"telugu\"},\n {\"fa\", \"persian\"},\n {\"lv\", \"latvian\"},\n {\"bn\", \"bengali\"},\n {\"sr\", \"serbian\"},\n {\"az\", \"azerbaijani\"},\n {\"sl\", \"slovenian\"},\n {\"kn\", \"kannada\"},\n {\"et\", \"estonian\"},\n {\"mk\", \"macedonian\"},\n {\"br\", \"breton\"},\n {\"eu\", \"basque\"},\n {\"is\", \"icelandic\"},\n {\"hy\", \"armenian\"},\n {\"ne\", \"nepali\"},\n {\"mn\", \"mongolian\"},\n {\"bs\", \"bosnian\"},\n {\"kk\", \"kazakh\"},\n {\"sq\", \"albanian\"},\n {\"sw\", \"swahili\"},\n {\"gl\", \"galician\"},\n {\"mr\", \"marathi\"},\n {\"pa\", \"punjabi\"},\n {\"si\", \"sinhala\"},\n {\"km\", \"khmer\"},\n {\"sn\", \"shona\"},\n {\"yo\", \"yoruba\"},\n {\"so\", \"somali\"},\n {\"af\", \"afrikaans\"},\n {\"oc\", \"occitan\"},\n {\"ka\", \"georgian\"},\n {\"be\", \"belarusian\"},\n {\"tg\", \"tajik\"},\n {\"sd\", \"sindhi\"},\n {\"gu\", \"gujarati\"},\n {\"am\", \"amharic\"},\n {\"yi\", \"yiddish\"},\n {\"lo\", \"lao\"},\n {\"uz\", \"uzbek\"},\n {\"fo\", \"faroese\"},\n {\"ht\", \"haitian creole\"},\n {\"ps\", \"pashto\"},\n {\"tk\", \"turkmen\"},\n {\"nn\", \"nynorsk\"},\n {\"mt\", \"maltese\"},\n {\"sa\", \"sanskrit\"},\n {\"lb\", \"luxembourgish\"},\n {\"my\", \"myanmar\"},\n {\"bo\", \"tibetan\"},\n {\"tl\", \"tagalog\"},\n {\"mg\", \"malagasy\"},\n {\"as\", \"assamese\"},\n {\"tt\", \"tatar\"},\n {\"haw\", \"hawaiian\"},\n {\"ln\", \"lingala\"},\n {\"ha\", \"hausa\"},\n {\"ba\", \"bashkir\"},\n {\"jw\", \"javanese\"},\n {\"su\", \"sundanese\"},\n {\"yue\", \"cantonese\"},\n };\n\n // https://github.com/Purfview/whisper-standalone-win/issues/430#issuecomment-2743029023\n // https://github.com/openai/whisper/blob/517a43ecd132a2089d85f4ebc044728a71d49f6e/whisper/tokenizer.py#L10-L110\n public static Dictionary LanguageToCode { get; } = CodeToLanguage.ToDictionary(kv => kv.Value, kv => kv.Key, StringComparer.OrdinalIgnoreCase);\n\n public static List GetWhisperLanguages()\n {\n return CodeToLanguage.Select(kv => new WhisperLanguage\n {\n Code = kv.Key,\n EnglishName = UpperFirstOfWords(kv.Value)\n }).OrderBy(l => l.EnglishName).ToList();\n }\n\n private static string UpperFirstOfWords(string input)\n {\n if (string.IsNullOrEmpty(input))\n return input;\n\n StringBuilder result = new();\n bool isNewWord = true;\n\n foreach (char c in input)\n {\n if (char.IsWhiteSpace(c))\n {\n isNewWord = true;\n result.Append(c);\n }\n else if (isNewWord)\n {\n result.Append(char.ToUpper(c));\n isNewWord = false;\n }\n else\n {\n result.Append(c);\n }\n }\n\n return result.ToString();\n }\n\n public bool Equals(WhisperLanguage other)\n {\n if (other is null) return false;\n if (ReferenceEquals(this, other)) return true;\n return Code == other.Code;\n }\n\n public override bool Equals(object obj) => obj is WhisperLanguage o && Equals(o);\n\n public override int GetHashCode()\n {\n return (Code != null ? Code.GetHashCode() : 0);\n }\n}\n"], ["/LLPlayer/WpfColorFontDialog/I18NUtil.cs", "using System;\nusing System.Collections.Generic;\nusing System.Linq;\nusing System.Windows;\n\nnamespace WpfColorFontDialog\n{\n internal static class I18NUtil\n {\n private const string DefaultLanguage = @\"en-US\";\n\n public static string CurrentLanguage;\n\n public static readonly Dictionary SupportLanguage = new Dictionary\n {\n {@\"简体中文\", @\"zh-CN\"},\n {@\"English (United States)\", @\"en-US\"},\n };\n\n public static string GetCurrentLanguage()\n {\n return System.Globalization.CultureInfo.CurrentCulture.Name;\n }\n\n public static string GetLanguage()\n {\n var name = GetCurrentLanguage();\n return SupportLanguage.Any(s => name == s.Value) ? name : DefaultLanguage;\n }\n\n public static string GetWindowStringValue(Window window, string key)\n {\n if (window.Resources.MergedDictionaries[0][key] is string str)\n {\n return str;\n }\n return null;\n }\n\n public static void SetLanguage(ResourceDictionary resources, string langName = @\"\")\n {\n if (string.IsNullOrEmpty(langName))\n {\n langName = GetLanguage();\n }\n CurrentLanguage = langName;\n if (resources.MergedDictionaries.Count > 0)\n {\n resources.MergedDictionaries[0].Source = new Uri($@\"I18n/{langName}.xaml\", UriKind.Relative);\n }\n }\n }\n}\n"], ["/LLPlayer/FlyleafLib/MediaPlayer/Translation/Services/TranslateServiceFactory.cs", "using System.Collections.Generic;\n\nnamespace FlyleafLib.MediaPlayer.Translation.Services;\n\npublic class TranslateServiceFactory\n{\n private readonly Config.SubtitlesConfig _config;\n\n public TranslateServiceFactory(Config.SubtitlesConfig config)\n {\n _config = config;\n }\n\n /// \n /// GetService\n /// \n /// \n /// \n /// \n /// \n /// \n public ITranslateService GetService(TranslateServiceType serviceType, bool wordMode)\n {\n switch (serviceType)\n {\n case TranslateServiceType.GoogleV1:\n return new GoogleV1TranslateService((GoogleV1TranslateSettings)_config.TranslateServiceSettings.GetValueOrDefault(serviceType, new GoogleV1TranslateSettings()));\n\n case TranslateServiceType.DeepL:\n return new DeepLTranslateService((DeepLTranslateSettings)_config.TranslateServiceSettings.GetValueOrDefault(serviceType, new DeepLTranslateSettings()));\n\n case TranslateServiceType.DeepLX:\n return new DeepLXTranslateService((DeepLXTranslateSettings)_config.TranslateServiceSettings.GetValueOrDefault(serviceType, new DeepLXTranslateSettings()));\n\n case TranslateServiceType.Ollama:\n return new OpenAIBaseTranslateService((OllamaTranslateSettings)_config.TranslateServiceSettings.GetValueOrDefault(serviceType, new OllamaTranslateSettings()), _config.TranslateChatConfig, wordMode);\n\n case TranslateServiceType.LMStudio:\n return new OpenAIBaseTranslateService((LMStudioTranslateSettings)_config.TranslateServiceSettings.GetValueOrDefault(serviceType, new LMStudioTranslateSettings()), _config.TranslateChatConfig, wordMode);\n\n case TranslateServiceType.KoboldCpp:\n return new OpenAIBaseTranslateService((KoboldCppTranslateSettings)_config.TranslateServiceSettings.GetValueOrDefault(serviceType, new KoboldCppTranslateSettings()), _config.TranslateChatConfig, wordMode);\n\n case TranslateServiceType.OpenAI:\n return new OpenAIBaseTranslateService((OpenAITranslateSettings)_config.TranslateServiceSettings.GetValueOrDefault(serviceType, new OpenAITranslateSettings()), _config.TranslateChatConfig, wordMode);\n\n case TranslateServiceType.OpenAILike:\n return new OpenAIBaseTranslateService((OpenAILikeTranslateSettings)_config.TranslateServiceSettings.GetValueOrDefault(serviceType, new OpenAILikeTranslateSettings()), _config.TranslateChatConfig, wordMode);\n\n case TranslateServiceType.Claude:\n return new OpenAIBaseTranslateService((ClaudeTranslateSettings)_config.TranslateServiceSettings.GetValueOrDefault(serviceType, new ClaudeTranslateSettings()), _config.TranslateChatConfig, wordMode);\n\n case TranslateServiceType.LiteLLM:\n return new OpenAIBaseTranslateService((LiteLLMTranslateSettings)_config.TranslateServiceSettings.GetValueOrDefault(serviceType, new LiteLLMTranslateSettings()), _config.TranslateChatConfig, wordMode);\n }\n\n throw new InvalidOperationException($\"Translate service {serviceType} does not exist.\");\n }\n}\n"], ["/LLPlayer/FlyleafLib/MediaFramework/MediaStream/AudioStream.cs", "using FlyleafLib.MediaFramework.MediaDemuxer;\n\nnamespace FlyleafLib.MediaFramework.MediaStream;\n\npublic unsafe class AudioStream : StreamBase\n{\n public int Bits { get; set; }\n public int Channels { get; set; }\n public ulong ChannelLayout { get; set; }\n public string ChannelLayoutStr { get; set; }\n public AVSampleFormat SampleFormat { get; set; }\n public string SampleFormatStr { get; set; }\n public int SampleRate { get; set; }\n public AVCodecID CodecIDOrig { get; set; }\n\n public override string GetDump()\n => $\"[{Type} #{StreamIndex}-{Language.IdSubLanguage}{(Title != null ? \"(\" + Title + \")\" : \"\")}] {Codec} {SampleFormatStr}@{Bits} {SampleRate / 1000}KHz {ChannelLayoutStr} | [BR: {BitRate}] | {Utils.TicksToTime((long)(AVStream->start_time * Timebase))}/{Utils.TicksToTime((long)(AVStream->duration * Timebase))} | {Utils.TicksToTime(StartTime)}/{Utils.TicksToTime(Duration)}\";\n\n public AudioStream() { }\n public AudioStream(Demuxer demuxer, AVStream* st) : base(demuxer, st) => Refresh();\n\n public override void Refresh()\n {\n base.Refresh();\n\n SampleFormat = (AVSampleFormat) Enum.ToObject(typeof(AVSampleFormat), AVStream->codecpar->format);\n SampleFormatStr = av_get_sample_fmt_name(SampleFormat);\n SampleRate = AVStream->codecpar->sample_rate;\n\n if (AVStream->codecpar->ch_layout.order == AVChannelOrder.Unspec)\n av_channel_layout_default(&AVStream->codecpar->ch_layout, AVStream->codecpar->ch_layout.nb_channels);\n\n ChannelLayout = AVStream->codecpar->ch_layout.u.mask;\n Channels = AVStream->codecpar->ch_layout.nb_channels;\n Bits = AVStream->codecpar->bits_per_coded_sample;\n\n // https://trac.ffmpeg.org/ticket/7321\n CodecIDOrig = CodecID;\n if (CodecID == AVCodecID.Mp2 && (SampleFormat == AVSampleFormat.Fltp || SampleFormat == AVSampleFormat.Flt))\n CodecID = AVCodecID.Mp3; // OR? st->codecpar->format = (int) AVSampleFormat.AV_SAMPLE_FMT_S16P;\n\n byte[] buf = new byte[50];\n fixed (byte* bufPtr = buf)\n {\n av_channel_layout_describe(&AVStream->codecpar->ch_layout, bufPtr, (nuint)buf.Length);\n ChannelLayoutStr = Utils.BytePtrToStringUTF8(bufPtr);\n }\n }\n}\n"], ["/LLPlayer/WpfColorFontDialog/AvailableColors.cs", "using System;\nusing System.Collections.Generic;\nusing System.Reflection;\nusing System.Windows.Media;\n\nnamespace WpfColorFontDialog\n{\n\tinternal class AvailableColors : List\n\t{\n\t\tpublic AvailableColors()\n\t\t{\n\t\t\tthis.Init();\n\t\t}\n\n\t\tpublic static FontColor GetFontColor(SolidColorBrush b)\n\t\t{\n\t\t\treturn (new AvailableColors()).GetFontColorByBrush(b);\n\t\t}\n\n\t\tpublic static FontColor GetFontColor(string name)\n\t\t{\n\t\t\treturn (new AvailableColors()).GetFontColorByName(name);\n\t\t}\n\n\t\tpublic static FontColor GetFontColor(Color c)\n\t\t{\n\t\t\treturn AvailableColors.GetFontColor(new SolidColorBrush(c));\n\t\t}\n\n\t\tpublic FontColor GetFontColorByBrush(SolidColorBrush b)\n\t\t{\n\t\t\tFontColor found = null;\n\t\t\tforeach (FontColor brush in this)\n\t\t\t{\n\t\t\t\tif (!brush.Brush.Color.Equals(b.Color))\n\t\t\t\t{\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\t\t\t\tfound = brush;\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\treturn found;\n\t\t}\n\n\t\tpublic FontColor GetFontColorByName(string name)\n\t\t{\n\t\t\tFontColor found = null;\n\t\t\tforeach (FontColor b in this)\n\t\t\t{\n\t\t\t\tif (b.Name != name)\n\t\t\t\t{\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\t\t\t\tfound = b;\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\treturn found;\n\t\t}\n\n\t\tpublic static int GetFontColorIndex(FontColor c)\n\t\t{\n\t\t\tAvailableColors brushList = new AvailableColors();\n\t\t\tint idx = 0;\n\t\t\tSolidColorBrush colorBrush = c.Brush;\n\t\t\tforeach (FontColor brush in brushList)\n\t\t\t{\n\t\t\t\tif (brush.Brush.Color.Equals(colorBrush.Color))\n\t\t\t\t{\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t\tidx++;\n\t\t\t}\n\t\t\treturn idx;\n\t\t}\n\n\t\tprivate void Init()\n\t\t{\n\t\t\tPropertyInfo[] properties = typeof(Colors).GetProperties(BindingFlags.Static | BindingFlags.Public);\n\t\t\tfor (int i = 0; i < (int)properties.Length; i++)\n\t\t\t{\n\t\t\t\tPropertyInfo prop = properties[i];\n\t\t\t\tstring name = prop.Name;\n\t\t\t\tSolidColorBrush brush = new SolidColorBrush((Color)prop.GetValue(null, null));\n\t\t\t\tbase.Add(new FontColor(name, brush));\n\t\t\t}\n\t\t}\n\t}\n}"], ["/LLPlayer/LLPlayer/Extensions/ColorHexJsonConverter.cs", "using System.Globalization;\nusing System.Text.Json;\nusing System.Text.Json.Serialization;\nusing System.Windows.Media;\n\nnamespace LLPlayer.Extensions;\n\n// Convert Color object to HEX string\npublic class ColorHexJsonConverter : JsonConverter\n{\n public override void Write(Utf8JsonWriter writer, Color value, JsonSerializerOptions options)\n {\n string hex = $\"#{value.A:X2}{value.R:X2}{value.G:X2}{value.B:X2}\";\n writer.WriteStringValue(hex);\n }\n\n public override Color Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options)\n {\n string? hex = null;\n try\n {\n hex = reader.GetString();\n\n if (string.IsNullOrWhiteSpace(hex))\n {\n throw new JsonException(\"Color value is null or empty.\");\n }\n\n if (!hex.StartsWith(\"#\") || (hex.Length != 7 && hex.Length != 9))\n {\n throw new JsonException($\"Invalid color format: {hex}\");\n }\n byte a = 255;\n\n int start = 1;\n\n if (hex.Length == 9)\n {\n a = byte.Parse(hex.Substring(1, 2), NumberStyles.HexNumber);\n start = 3;\n }\n\n byte r = byte.Parse(hex.Substring(start, 2), NumberStyles.HexNumber);\n byte g = byte.Parse(hex.Substring(start + 2, 2), NumberStyles.HexNumber);\n byte b = byte.Parse(hex.Substring(start + 4, 2), NumberStyles.HexNumber);\n\n return Color.FromArgb(a, r, g, b);\n }\n catch (Exception ex)\n {\n throw new JsonException($\"Error parsing color value: {hex}\", ex);\n }\n }\n}\n"], ["/LLPlayer/FlyleafLib/MediaFramework/MediaStream/ExternalSubtitlesStream.cs", "using System.Linq;\n\nnamespace FlyleafLib.MediaFramework.MediaStream;\n\npublic class ExternalSubtitlesStream : ExternalStream, ISubtitlesStream\n{\n public SelectedSubMethod[] SelectedSubMethods\n {\n get\n {\n var methods = (SelectSubMethod[])Enum.GetValues(typeof(SelectSubMethod));\n\n if (!IsBitmap)\n {\n // delete OCR if text sub\n methods = methods.Where(m => m != SelectSubMethod.OCR).ToArray();\n }\n\n return methods.\n Select(m => new SelectedSubMethod(this, m)).ToArray();\n }\n }\n\n public bool IsBitmap { get; set; }\n public bool ManualDownloaded{ get; set; }\n public bool Automatic { get; set; }\n public bool Downloaded { get; set; }\n public Language Language { get; set; } = Language.Unknown;\n public bool LanguageDetected{ get; set; }\n // TODO: Add confidence rating (maybe result is for other movie/episode) | Add Weight calculated based on rating/downloaded/confidence (and lang?) which can be used from suggesters\n public string Title { get; set; }\n\n public string DisplayMember =>\n $\"({Language}){(ManualDownloaded ? \" (DL)\" : \"\")}{(Automatic ? \" (Auto)\" : \"\")} {Utils.TruncateString(Title, 50)} ({(IsBitmap ? \"BMP\" : \"TXT\")})\";\n}\n"], ["/LLPlayer/WpfColorFontDialog/FontValueConverter.cs", "using System;\nusing System.Globalization;\nusing System.Windows.Data;\nusing System.Windows.Markup;\nusing System.Windows.Media;\n\nnamespace WpfColorFontDialog\n{\n public class FontValueConverter : IValueConverter\n {\n public object Convert(object value, Type targetType, object parameter, CultureInfo culture)\n {\n if (value is FontFamily font)\n {\n var name = I18NUtil.CurrentLanguage;\n if (string.IsNullOrWhiteSpace(name))\n {\n name = I18NUtil.GetCurrentLanguage();\n }\n var names = new[] { name, I18NUtil.GetLanguage() };\n foreach (var s in names)\n {\n if (font.FamilyNames.TryGetValue(XmlLanguage.GetLanguage(s), out var localizedName))\n {\n if (!string.IsNullOrEmpty(localizedName))\n {\n return localizedName;\n }\n }\n }\n\n return font.Source;\n }\n\n // Avoid reaching here and getting an error.\n return string.Empty;\n //throw new NotSupportedException();\n }\n\n public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)\n {\n throw new NotSupportedException(\"ConvertBack not supported\");\n }\n }\n}\n"], ["/LLPlayer/LLPlayer/Views/SubtitlesSidebar.xaml.cs", "using System.Windows;\nusing System.Windows.Controls;\nusing LLPlayer.Controls;\nusing LLPlayer.ViewModels;\n\nnamespace LLPlayer.Views;\n\npublic partial class SubtitlesSidebar : UserControl\n{\n private SubtitlesSidebarVM VM => (SubtitlesSidebarVM)DataContext;\n public SubtitlesSidebar()\n {\n InitializeComponent();\n\n DataContext = ((App)Application.Current).Container.Resolve();\n\n Loaded += (sender, args) =>\n {\n VM.RequestScrollToTop += OnRequestScrollToTop;\n };\n\n Unloaded += (sender, args) =>\n {\n VM.RequestScrollToTop -= OnRequestScrollToTop;\n VM.Dispose();\n };\n }\n\n /// \n /// Scroll to the current subtitle\n /// \n /// \n /// \n private void SubtitleListBox_SelectionChanged(object sender, SelectionChangedEventArgs e)\n {\n if (IsLoaded && SubtitleListBox.SelectedItem != null)\n {\n SubtitleListBox.ScrollIntoView(SubtitleListBox.SelectedItem);\n }\n }\n\n /// \n /// Scroll to the top subtitle\n /// \n /// \n /// \n private void OnRequestScrollToTop(object? sender, EventArgs args)\n {\n if (SubtitleListBox.Items.Count <= 0)\n return;\n\n var first = SubtitleListBox.Items[0];\n if (first != null)\n {\n SubtitleListBox.ScrollIntoView(first);\n }\n }\n\n private void SelectableTextBox_OnWordClicked(object? sender, WordClickedEventArgs e)\n {\n _ = WordPopupControl.OnWordClicked(e);\n }\n}\n"], ["/LLPlayer/FlyleafLib/MediaPlayer/Translation/TranslateLanguage.cs", "using FlyleafLib.MediaPlayer.Translation.Services;\nusing System.Collections.Generic;\nusing System.Reflection;\nusing System.Runtime.Serialization;\n\nnamespace FlyleafLib.MediaPlayer.Translation;\n\npublic class TranslateLanguage\n{\n public static Dictionary Langs { get; } = new()\n {\n // Google: https://cloud.google.com/translate/docs/languages\n // DeepL: https://developers.deepl.com/docs/resources/supported-languages\n [\"ab\"] = new(\"Abkhaz\", \"ab\", TranslateServiceType.GoogleV1),\n [\"af\"] = new(\"Afrikaans\", \"af\", TranslateServiceType.GoogleV1),\n [\"sq\"] = new(\"Albanian\", \"sq\", TranslateServiceType.GoogleV1),\n [\"am\"] = new(\"Amharic\", \"am\", TranslateServiceType.GoogleV1),\n [\"ar\"] = new(\"Arabic\", \"ar\"),\n [\"hy\"] = new(\"Armenian\", \"hy\", TranslateServiceType.GoogleV1),\n [\"as\"] = new(\"Assamese\", \"as\", TranslateServiceType.GoogleV1),\n [\"ay\"] = new(\"Aymara\", \"ay\", TranslateServiceType.GoogleV1),\n [\"az\"] = new(\"Azerbaijani\", \"az\", TranslateServiceType.GoogleV1),\n [\"bm\"] = new(\"Bambara\", \"bm\", TranslateServiceType.GoogleV1),\n [\"ba\"] = new(\"Bashkir\", \"ba\", TranslateServiceType.GoogleV1),\n [\"eu\"] = new(\"Basque\", \"eu\", TranslateServiceType.GoogleV1),\n [\"be\"] = new(\"Belarusian\", \"be\", TranslateServiceType.GoogleV1),\n [\"bn\"] = new(\"Bengali\", \"bn\", TranslateServiceType.GoogleV1),\n [\"bs\"] = new(\"Bosnian\", \"bs\", TranslateServiceType.GoogleV1),\n [\"br\"] = new(\"Breton\", \"br\", TranslateServiceType.GoogleV1),\n [\"bg\"] = new(\"Bulgarian\", \"bg\"),\n [\"ca\"] = new(\"Catalan\", \"ca\", TranslateServiceType.GoogleV1),\n [\"ny\"] = new(\"Chichewa (Nyanja)\", \"ny\", TranslateServiceType.GoogleV1),\n\n // special handling\n [\"zh\"] = new(\"Chinese\", \"zh\"),\n\n [\"cv\"] = new(\"Chuvash\", \"cv\", TranslateServiceType.GoogleV1),\n [\"co\"] = new(\"Corsican\", \"co\", TranslateServiceType.GoogleV1),\n [\"hr\"] = new(\"Croatian\", \"hr\", TranslateServiceType.GoogleV1),\n [\"cs\"] = new(\"Czech\", \"cs\"),\n [\"da\"] = new(\"Danish\", \"da\"),\n [\"dv\"] = new(\"Divehi\", \"dv\", TranslateServiceType.GoogleV1),\n [\"nl\"] = new(\"Dutch\", \"nl\"),\n [\"dz\"] = new(\"Dzongkha\", \"dz\", TranslateServiceType.GoogleV1),\n [\"en\"] = new(\"English\", \"en\"),\n [\"eo\"] = new(\"Esperanto\", \"eo\", TranslateServiceType.GoogleV1),\n [\"et\"] = new(\"Estonian\", \"et\"),\n [\"ee\"] = new(\"Ewe\", \"ee\", TranslateServiceType.GoogleV1),\n [\"fj\"] = new(\"Fijian\", \"fj\", TranslateServiceType.GoogleV1),\n [\"tl\"] = new(\"Tagalog\", \"tl\", TranslateServiceType.GoogleV1),\n [\"fi\"] = new(\"Finnish\", \"fi\"),\n\n // special handling\n [\"fr\"] = new(\"French\", \"fr\"),\n\n [\"fy\"] = new(\"Frisian\", \"fy\", TranslateServiceType.GoogleV1),\n [\"ff\"] = new(\"Fulfulde\", \"ff\", TranslateServiceType.GoogleV1),\n [\"gl\"] = new(\"Galician\", \"gl\", TranslateServiceType.GoogleV1),\n [\"lg\"] = new(\"Ganda (Luganda)\", \"lg\", TranslateServiceType.GoogleV1),\n [\"ka\"] = new(\"Georgian\", \"ka\", TranslateServiceType.GoogleV1),\n [\"de\"] = new(\"German\", \"de\"),\n [\"el\"] = new(\"Greek\", \"el\"),\n [\"gn\"] = new(\"Guarani\", \"gn\", TranslateServiceType.GoogleV1),\n [\"gu\"] = new(\"Gujarati\", \"gu\", TranslateServiceType.GoogleV1),\n [\"ht\"] = new(\"Haitian Creole\", \"ht\", TranslateServiceType.GoogleV1),\n [\"ha\"] = new(\"Hausa\", \"ha\", TranslateServiceType.GoogleV1),\n [\"he\"] = new(\"Hebrew\", \"he\", TranslateServiceType.GoogleV1),\n [\"hi\"] = new(\"Hindi\", \"hi\", TranslateServiceType.GoogleV1),\n [\"hu\"] = new(\"Hungarian\", \"hu\"),\n [\"is\"] = new(\"Icelandic\", \"is\", TranslateServiceType.GoogleV1),\n [\"ig\"] = new(\"Igbo\", \"ig\", TranslateServiceType.GoogleV1),\n [\"id\"] = new(\"Indonesian\", \"id\"),\n [\"ga\"] = new(\"Irish\", \"ga\", TranslateServiceType.GoogleV1),\n [\"it\"] = new(\"Italian\", \"it\"),\n [\"ja\"] = new(\"Japanese\", \"ja\"),\n [\"jv\"] = new(\"Javanese\", \"jv\", TranslateServiceType.GoogleV1),\n [\"kn\"] = new(\"Kannada\", \"kn\", TranslateServiceType.GoogleV1),\n [\"kk\"] = new(\"Kazakh\", \"kk\", TranslateServiceType.GoogleV1),\n [\"km\"] = new(\"Khmer\", \"km\", TranslateServiceType.GoogleV1),\n [\"rw\"] = new(\"Kinyarwanda\", \"rw\", TranslateServiceType.GoogleV1),\n [\"ko\"] = new(\"Korean\", \"ko\"),\n [\"ku\"] = new(\"Kurdish (Kurmanji)\", \"ku\", TranslateServiceType.GoogleV1),\n [\"ky\"] = new(\"Kyrgyz\", \"ky\", TranslateServiceType.GoogleV1),\n [\"lo\"] = new(\"Lao\", \"lo\", TranslateServiceType.GoogleV1),\n [\"la\"] = new(\"Latin\", \"la\", TranslateServiceType.GoogleV1),\n [\"lv\"] = new(\"Latvian\", \"lv\"),\n [\"li\"] = new(\"Limburgan\", \"li\", TranslateServiceType.GoogleV1),\n [\"ln\"] = new(\"Lingala\", \"ln\", TranslateServiceType.GoogleV1),\n [\"lt\"] = new(\"Lithuanian\", \"lt\"),\n [\"lb\"] = new(\"Luxembourgish\", \"lb\", TranslateServiceType.GoogleV1),\n [\"mk\"] = new(\"Macedonian\", \"mk\", TranslateServiceType.GoogleV1),\n [\"mg\"] = new(\"Malagasy\", \"mg\", TranslateServiceType.GoogleV1),\n [\"ms\"] = new(\"Malay\", \"ms\", TranslateServiceType.GoogleV1),\n [\"ml\"] = new(\"Malayalam\", \"ml\", TranslateServiceType.GoogleV1),\n [\"mt\"] = new(\"Maltese\", \"mt\", TranslateServiceType.GoogleV1),\n [\"mi\"] = new(\"Maori\", \"mi\", TranslateServiceType.GoogleV1),\n [\"mr\"] = new(\"Marathi\", \"mr\", TranslateServiceType.GoogleV1),\n [\"mn\"] = new(\"Mongolian\", \"mn\", TranslateServiceType.GoogleV1),\n [\"my\"] = new(\"Myanmar (Burmese)\", \"my\", TranslateServiceType.GoogleV1),\n [\"nr\"] = new(\"Ndebele (South)\", \"nr\", TranslateServiceType.GoogleV1),\n [\"ne\"] = new(\"Nepali\", \"ne\", TranslateServiceType.GoogleV1),\n\n // TODO: L: review handling\n // special handling\n [\"no\"] = new(\"Norwegian\", \"no\"),\n [\"nb\"] = new(\"Norwegian Bokmål\", \"nb\"),\n\n [\"oc\"] = new(\"Occitan\", \"oc\", TranslateServiceType.GoogleV1),\n [\"or\"] = new(\"Odia (Oriya)\", \"or\", TranslateServiceType.GoogleV1),\n [\"om\"] = new(\"Oromo\", \"om\", TranslateServiceType.GoogleV1),\n [\"ps\"] = new(\"Pashto\", \"ps\", TranslateServiceType.GoogleV1),\n [\"fa\"] = new(\"Persian\", \"fa\", TranslateServiceType.GoogleV1),\n [\"pl\"] = new(\"Polish\", \"pl\"),\n\n // special handling\n [\"pt\"] = new(\"Portuguese\", \"pt\"),\n\n [\"pa\"] = new(\"Punjabi\", \"pa\", TranslateServiceType.GoogleV1),\n [\"qu\"] = new(\"Quechua\", \"qu\", TranslateServiceType.GoogleV1),\n [\"ro\"] = new(\"Romanian\", \"ro\"),\n [\"rn\"] = new(\"Rundi\", \"rn\", TranslateServiceType.GoogleV1),\n [\"ru\"] = new(\"Russian\", \"ru\"),\n [\"sm\"] = new(\"Samoan\", \"sm\", TranslateServiceType.GoogleV1),\n [\"sg\"] = new(\"Sango\", \"sg\", TranslateServiceType.GoogleV1),\n [\"sa\"] = new(\"Sanskrit\", \"sa\", TranslateServiceType.GoogleV1),\n [\"gd\"] = new(\"Scots Gaelic\", \"gd\", TranslateServiceType.GoogleV1),\n [\"sr\"] = new(\"Serbian\", \"sr\", TranslateServiceType.GoogleV1),\n [\"st\"] = new(\"Sesotho\", \"st\", TranslateServiceType.GoogleV1),\n [\"sn\"] = new(\"Shona\", \"sn\", TranslateServiceType.GoogleV1),\n [\"sd\"] = new(\"Sindhi\", \"sd\", TranslateServiceType.GoogleV1),\n [\"si\"] = new(\"Sinhala (Sinhalese)\", \"si\", TranslateServiceType.GoogleV1),\n [\"sk\"] = new(\"Slovak\", \"sk\"),\n [\"sl\"] = new(\"Slovenian\", \"sl\"),\n [\"so\"] = new(\"Somali\", \"so\", TranslateServiceType.GoogleV1),\n [\"es\"] = new(\"Spanish\", \"es\"),\n [\"su\"] = new(\"Sundanese\", \"su\", TranslateServiceType.GoogleV1),\n [\"sw\"] = new(\"Swahili\", \"sw\", TranslateServiceType.GoogleV1),\n [\"ss\"] = new(\"Swati\", \"ss\", TranslateServiceType.GoogleV1),\n [\"sv\"] = new(\"Swedish\", \"sv\"),\n [\"tg\"] = new(\"Tajik\", \"tg\", TranslateServiceType.GoogleV1),\n [\"ta\"] = new(\"Tamil\", \"ta\", TranslateServiceType.GoogleV1),\n [\"tt\"] = new(\"Tatar\", \"tt\", TranslateServiceType.GoogleV1),\n [\"te\"] = new(\"Telugu\", \"te\", TranslateServiceType.GoogleV1),\n [\"th\"] = new(\"Thai\", \"th\", TranslateServiceType.GoogleV1),\n [\"ti\"] = new(\"Tigrinya\", \"ti\", TranslateServiceType.GoogleV1),\n [\"ts\"] = new(\"Tsonga\", \"ts\", TranslateServiceType.GoogleV1),\n [\"tn\"] = new(\"Tswana\", \"tn\", TranslateServiceType.GoogleV1),\n [\"tr\"] = new(\"Turkish\", \"tr\"),\n [\"tk\"] = new(\"Turkmen\", \"tk\", TranslateServiceType.GoogleV1),\n [\"ak\"] = new(\"Twi (Akan)\", \"ak\", TranslateServiceType.GoogleV1),\n [\"uk\"] = new(\"Ukrainian\", \"uk\"),\n [\"ur\"] = new(\"Urdu\", \"ur\", TranslateServiceType.GoogleV1),\n [\"ug\"] = new(\"Uyghur\", \"ug\", TranslateServiceType.GoogleV1),\n [\"uz\"] = new(\"Uzbek\", \"uz\", TranslateServiceType.GoogleV1),\n [\"vi\"] = new(\"Vietnamese\", \"vi\", TranslateServiceType.GoogleV1),\n [\"cy\"] = new(\"Welsh\", \"cy\", TranslateServiceType.GoogleV1),\n [\"xh\"] = new(\"Xhosa\", \"xh\", TranslateServiceType.GoogleV1),\n [\"yi\"] = new(\"Yiddish\", \"yi\", TranslateServiceType.GoogleV1),\n [\"yo\"] = new(\"Yoruba\", \"yo\", TranslateServiceType.GoogleV1),\n [\"zu\"] = new(\"Zulu\", \"zu\", TranslateServiceType.GoogleV1),\n };\n\n public TranslateLanguage(string name, string iso6391,\n TranslateServiceType supportedServices =\n TranslateServiceType.GoogleV1 | TranslateServiceType.DeepL)\n {\n // all LLMs support all languages\n supportedServices |= TranslateServiceTypeExtensions.LLMServices;\n\n // DeepL = DeepLX, so flag is same\n if (supportedServices.HasFlag(TranslateServiceType.DeepL))\n {\n supportedServices |= TranslateServiceType.DeepLX;\n }\n\n Name = name;\n ISO6391 = iso6391;\n SupportedServices = supportedServices;\n }\n\n public string Name { get; }\n\n public string ISO6391 { get; }\n\n public TranslateServiceType SupportedServices { get; }\n}\n\n[DataContract]\npublic enum TargetLanguage\n{\n // Supported by Google and DeepL\n [EnumMember(Value = \"ar\")] Arabic,\n [EnumMember(Value = \"bg\")] Bulgarian,\n [EnumMember(Value = \"zh-CN\")] ChineseSimplified,\n [EnumMember(Value = \"zh-TW\")] ChineseTraditional,\n [EnumMember(Value = \"cs\")] Czech,\n [EnumMember(Value = \"da\")] Danish,\n [EnumMember(Value = \"nl\")] Dutch,\n [EnumMember(Value = \"en-US\")] EnglishAmerican,\n [EnumMember(Value = \"en-GB\")] EnglishBritish,\n [EnumMember(Value = \"et\")] Estonian,\n [EnumMember(Value = \"fr-FR\")] French,\n [EnumMember(Value = \"fr-CA\")] FrenchCanadian,\n [EnumMember(Value = \"de\")] German,\n [EnumMember(Value = \"el\")] Greek,\n [EnumMember(Value = \"hu\")] Hungarian,\n [EnumMember(Value = \"id\")] Indonesian,\n [EnumMember(Value = \"it\")] Italian,\n [EnumMember(Value = \"ja\")] Japanese,\n [EnumMember(Value = \"ko\")] Korean,\n [EnumMember(Value = \"lt\")] Lithuanian,\n [EnumMember(Value = \"nb\")] NorwegianBokmål,\n [EnumMember(Value = \"pl\")] Polish,\n [EnumMember(Value = \"pt-PT\")] Portuguese,\n [EnumMember(Value = \"pt-BR\")] PortugueseBrazilian,\n [EnumMember(Value = \"ro\")] Romanian,\n [EnumMember(Value = \"ru\")] Russian,\n [EnumMember(Value = \"sk\")] Slovak,\n [EnumMember(Value = \"sl\")] Slovenian,\n [EnumMember(Value = \"es\")] Spanish,\n [EnumMember(Value = \"sv\")] Swedish,\n [EnumMember(Value = \"tr\")] Turkish,\n [EnumMember(Value = \"uk\")] Ukrainian,\n\n // Only supported in Google\n [EnumMember(Value = \"ab\")] Abkhaz,\n [EnumMember(Value = \"af\")] Afrikaans,\n [EnumMember(Value = \"sq\")] Albanian,\n [EnumMember(Value = \"am\")] Amharic,\n [EnumMember(Value = \"hy\")] Armenian,\n [EnumMember(Value = \"as\")] Assamese,\n [EnumMember(Value = \"ay\")] Aymara,\n [EnumMember(Value = \"az\")] Azerbaijani,\n [EnumMember(Value = \"bm\")] Bambara,\n [EnumMember(Value = \"ba\")] Bashkir,\n [EnumMember(Value = \"eu\")] Basque,\n [EnumMember(Value = \"be\")] Belarusian,\n [EnumMember(Value = \"bn\")] Bengali,\n [EnumMember(Value = \"bs\")] Bosnian,\n [EnumMember(Value = \"br\")] Breton,\n [EnumMember(Value = \"ca\")] Catalan,\n [EnumMember(Value = \"ny\")] Chichewa,\n [EnumMember(Value = \"cv\")] Chuvash,\n [EnumMember(Value = \"co\")] Corsican,\n [EnumMember(Value = \"hr\")] Croatian,\n [EnumMember(Value = \"dv\")] Divehi,\n [EnumMember(Value = \"dz\")] Dzongkha,\n [EnumMember(Value = \"eo\")] Esperanto,\n [EnumMember(Value = \"ee\")] Ewe,\n [EnumMember(Value = \"fj\")] Fijian,\n [EnumMember(Value = \"tl\")] Tagalog,\n [EnumMember(Value = \"fy\")] Frisian,\n [EnumMember(Value = \"ff\")] Fulfulde,\n [EnumMember(Value = \"gl\")] Galician,\n [EnumMember(Value = \"lg\")] Ganda,\n [EnumMember(Value = \"ka\")] Georgian,\n [EnumMember(Value = \"gn\")] Guarani,\n [EnumMember(Value = \"gu\")] Gujarati,\n [EnumMember(Value = \"ht\")] Haitian,\n [EnumMember(Value = \"ha\")] Hausa,\n [EnumMember(Value = \"he\")] Hebrew,\n [EnumMember(Value = \"hi\")] Hindi,\n [EnumMember(Value = \"is\")] Icelandic,\n [EnumMember(Value = \"ig\")] Igbo,\n [EnumMember(Value = \"ga\")] Irish,\n [EnumMember(Value = \"jv\")] Javanese,\n [EnumMember(Value = \"kn\")] Kannada,\n [EnumMember(Value = \"kk\")] Kazakh,\n [EnumMember(Value = \"km\")] Khmer,\n [EnumMember(Value = \"rw\")] Kinyarwanda,\n [EnumMember(Value = \"ku\")] Kurdish,\n [EnumMember(Value = \"ky\")] Kyrgyz,\n [EnumMember(Value = \"lo\")] Lao,\n [EnumMember(Value = \"la\")] Latin,\n [EnumMember(Value = \"li\")] Limburgan,\n [EnumMember(Value = \"ln\")] Lingala,\n [EnumMember(Value = \"lb\")] Luxembourgish,\n [EnumMember(Value = \"mk\")] Macedonian,\n [EnumMember(Value = \"mg\")] Malagasy,\n [EnumMember(Value = \"ms\")] Malay,\n [EnumMember(Value = \"ml\")] Malayalam,\n [EnumMember(Value = \"mt\")] Maltese,\n [EnumMember(Value = \"mi\")] Maori,\n [EnumMember(Value = \"mr\")] Marathi,\n [EnumMember(Value = \"mn\")] Mongolian,\n [EnumMember(Value = \"my\")] Myanmar,\n [EnumMember(Value = \"nr\")] Ndebele,\n [EnumMember(Value = \"ne\")] Nepali,\n [EnumMember(Value = \"oc\")] Occitan,\n [EnumMember(Value = \"or\")] Odia,\n [EnumMember(Value = \"om\")] Oromo,\n [EnumMember(Value = \"ps\")] Pashto,\n [EnumMember(Value = \"fa\")] Persian,\n [EnumMember(Value = \"pa\")] Punjabi,\n [EnumMember(Value = \"qu\")] Quechua,\n [EnumMember(Value = \"rn\")] Rundi,\n [EnumMember(Value = \"sm\")] Samoan,\n [EnumMember(Value = \"sg\")] Sango,\n [EnumMember(Value = \"sa\")] Sanskrit,\n [EnumMember(Value = \"gd\")] ScotsGaelic,\n [EnumMember(Value = \"sr\")] Serbian,\n [EnumMember(Value = \"st\")] Sesotho,\n [EnumMember(Value = \"sn\")] Shona,\n [EnumMember(Value = \"sd\")] Sindhi,\n [EnumMember(Value = \"si\")] Sinhala,\n [EnumMember(Value = \"so\")] Somali,\n [EnumMember(Value = \"su\")] Sundanese,\n [EnumMember(Value = \"sw\")] Swahili,\n [EnumMember(Value = \"ss\")] Swati,\n [EnumMember(Value = \"tg\")] Tajik,\n [EnumMember(Value = \"ta\")] Tamil,\n [EnumMember(Value = \"tt\")] Tatar,\n [EnumMember(Value = \"te\")] Telugu,\n [EnumMember(Value = \"th\")] Thai,\n [EnumMember(Value = \"ti\")] Tigrinya,\n [EnumMember(Value = \"ts\")] Tsonga,\n [EnumMember(Value = \"tn\")] Tswana,\n [EnumMember(Value = \"tk\")] Turkmen,\n [EnumMember(Value = \"ak\")] Twi,\n [EnumMember(Value = \"ur\")] Urdu,\n [EnumMember(Value = \"ug\")] Uyghur,\n [EnumMember(Value = \"uz\")] Uzbek,\n [EnumMember(Value = \"vi\")] Vietnamese,\n [EnumMember(Value = \"cy\")] Welsh,\n [EnumMember(Value = \"xh\")] Xhosa,\n [EnumMember(Value = \"yi\")] Yiddish,\n [EnumMember(Value = \"yo\")] Yoruba,\n [EnumMember(Value = \"zu\")] Zulu,\n}\n\npublic static class TargetLanguageExtensions\n{\n public static string DisplayName(this TargetLanguage targetLang)\n {\n return targetLang switch\n {\n TargetLanguage.EnglishAmerican => \"English (American)\",\n TargetLanguage.EnglishBritish => \"English (British)\",\n TargetLanguage.French => \"French\",\n TargetLanguage.FrenchCanadian => \"French (Canadian)\",\n TargetLanguage.Portuguese => \"Portuguese\",\n TargetLanguage.PortugueseBrazilian => \"Portuguese (Brazilian)\",\n TargetLanguage.ChineseSimplified => \"Chinese (Simplified)\",\n TargetLanguage.ChineseTraditional => \"Chinese (Traditional)\",\n TargetLanguage.NorwegianBokmål => \"Norwegian Bokmål\",\n\n TargetLanguage.Chichewa => \"Chichewa (Nyanja)\",\n TargetLanguage.Ganda => \"Ganda (Luganda)\",\n TargetLanguage.Haitian => \"Haitian Creole\",\n TargetLanguage.Kurdish => \"Kurdish (Kurmanji)\",\n TargetLanguage.Myanmar => \"Myanmar (Burmese)\",\n TargetLanguage.Ndebele => \"Ndebele (South)\",\n TargetLanguage.Odia => \"Odia (Oriya)\",\n TargetLanguage.ScotsGaelic => \"Scots Gaelic\",\n TargetLanguage.Sinhala => \"Sinhala (Sinhalese)\",\n TargetLanguage.Twi => \"Twi (Akan)\",\n _ => targetLang.ToString()\n };\n }\n\n public static TranslateServiceType SupportedServiceType(this TargetLanguage targetLang)\n {\n string iso6391 = targetLang.ToISO6391();\n\n TranslateLanguage lang = TranslateLanguage.Langs[iso6391];\n\n return lang.SupportedServices;\n }\n\n public static string ToISO6391(this TargetLanguage targetLang)\n {\n // Get EnumMember language code\n Type type = targetLang.GetType();\n MemberInfo[] memInfo = type.GetMember(targetLang.ToString());\n object[] attributes = memInfo[0].GetCustomAttributes(typeof(EnumMemberAttribute), false);\n string enumValue = ((EnumMemberAttribute)attributes[0]).Value;\n\n // ISO6391 code is the first half of a hyphen\n if (enumValue != null && enumValue.Contains(\"-\"))\n {\n return enumValue.Split('-')[0];\n }\n\n return enumValue;\n }\n\n public static TargetLanguage? ToTargetLanguage(this Language lang)\n {\n // language with region first\n switch (lang.ISO6391)\n {\n case \"en\" when lang.CultureName == \"en-GB\":\n return TargetLanguage.EnglishBritish;\n case \"en\":\n return TargetLanguage.EnglishAmerican;\n\n case \"zh\" when lang.CultureName.StartsWith(\"zh-Hant\"): // zh-Hant, zh-Hant-XX\n return TargetLanguage.ChineseTraditional;\n case \"zh\": // zh-Hans, zh-Hans-XX, or others\n return TargetLanguage.ChineseSimplified;\n\n case \"fr\" when lang.CultureName == \"fr-CA\":\n return TargetLanguage.FrenchCanadian;\n case \"fr\":\n return TargetLanguage.French;\n\n case \"pt\" when lang.CultureName == \"pt-BR\":\n return TargetLanguage.PortugueseBrazilian;\n case \"pt\":\n return TargetLanguage.Portuguese;\n }\n\n // other languages with no region\n foreach (var tl in Enum.GetValues())\n {\n if (tl.ToISO6391() == lang.ISO6391)\n {\n return tl;\n }\n }\n\n // not match\n return null;\n }\n}\n"], ["/LLPlayer/FlyleafLib/MediaFramework/MediaDevice/AudioDevice.cs", "using System;\nusing Vortice.MediaFoundation;\n\nnamespace FlyleafLib.MediaFramework.MediaDevice;\n\npublic class AudioDevice : DeviceBase\n{\n public AudioDevice(string friendlyName, string symbolicLink) : base(friendlyName, symbolicLink)\n => Url = $\"fmt://dshow?audio={FriendlyName}\";\n\n public static void RefreshDevices()\n {\n Utils.UIInvokeIfRequired(() =>\n {\n Engine.Audio.CapDevices.Clear();\n\n var devices = MediaFactory.MFEnumAudioDeviceSources();\n foreach (var device in devices)\n try { Engine.Audio.CapDevices.Add(new AudioDevice(device.FriendlyName, device.SymbolicLink)); } catch(Exception) { }\n });\n }\n}\n"], ["/LLPlayer/LLPlayer/Services/WhisperCppModelLoader.cs", "using System.IO;\nusing FlyleafLib;\nusing Whisper.net.Ggml;\n\nnamespace LLPlayer.Services;\n\npublic class WhisperCppModelLoader\n{\n public static List LoadAllModels()\n {\n WhisperConfig.EnsureModelsDirectory();\n\n List models = Enum.GetValues()\n .Select(t => new WhisperCppModel { Model = t, })\n .ToList();\n\n foreach (WhisperCppModel model in models)\n {\n // Update download status\n string path = model.ModelFilePath;\n if (File.Exists(path))\n {\n model.Size = new FileInfo(path).Length;\n }\n }\n\n return models;\n }\n\n public static List LoadDownloadedModels()\n {\n return LoadAllModels()\n .Where(m => m.Downloaded)\n .ToList();\n }\n}\n"], ["/LLPlayer/FlyleafLib/MediaPlayer/Data.cs", "using FlyleafLib.MediaFramework.MediaContext;\nusing FlyleafLib.MediaFramework.MediaStream;\nusing System;\nusing System.Collections.ObjectModel;\n\nnamespace FlyleafLib.MediaPlayer;\npublic class Data : NotifyPropertyChanged\n{\n /// \n /// Embedded Streams\n /// \n public ObservableCollection\n Streams => decoder?.DataDemuxer.DataStreams;\n\n /// \n /// Whether the input has data and it is configured\n /// \n public bool IsOpened { get => isOpened; internal set => Set(ref _IsOpened, value); }\n internal bool _IsOpened, isOpened;\n\n Action uiAction;\n Player player;\n DecoderContext decoder => player.decoder;\n Config Config => player.Config;\n\n public Data(Player player)\n {\n this.player = player;\n uiAction = () =>\n {\n IsOpened = IsOpened;\n };\n }\n internal void Reset()\n {\n isOpened = false;\n\n player.UIAdd(uiAction);\n }\n internal void Refresh()\n {\n if (decoder.DataStream == null)\n { Reset(); return; }\n\n isOpened = !decoder.DataDecoder.Disposed;\n\n player.UIAdd(uiAction);\n }\n internal void Enable()\n {\n if (!player.CanPlay)\n return;\n\n decoder.OpenSuggestedData();\n player.ReSync(decoder.DataStream, (int)(player.CurTime / 10000), true);\n\n Refresh();\n player.UIAll();\n }\n internal void Disable()\n {\n if (!IsOpened)\n return;\n\n decoder.CloseData();\n\n player.dFrame = null;\n Reset();\n player.UIAll();\n }\n}\n"], ["/LLPlayer/WpfColorFontDialog/ColorPicker.xaml.cs", "using System;\nusing System.Collections.Generic;\nusing System.Linq;\nusing System.Text;\nusing System.Windows;\nusing System.Windows.Controls;\nusing System.Windows.Data;\nusing System.Windows.Documents;\nusing System.Windows.Input;\nusing System.Windows.Media;\nusing System.Windows.Media.Imaging;\nusing System.Windows.Navigation;\nusing System.Windows.Shapes;\n\nnamespace WpfColorFontDialog\n{\n /// \n /// Interaction logic for ColorPicker.xaml\n /// \n public partial class ColorPicker : UserControl\n {\n private ColorPickerViewModel viewModel;\n\n public readonly static RoutedEvent ColorChangedEvent;\n\n public readonly static DependencyProperty SelectedColorProperty;\n\n public FontColor SelectedColor\n {\n get\n {\n FontColor fc = (FontColor)base.GetValue(ColorPicker.SelectedColorProperty) ?? AvailableColors.GetFontColor(\"Black\");\n return fc;\n }\n set\n {\n this.viewModel.SelectedFontColor = value;\n base.SetValue(ColorPicker.SelectedColorProperty, value);\n }\n }\n\n static ColorPicker()\n {\n ColorPicker.ColorChangedEvent = EventManager.RegisterRoutedEvent(\"ColorChanged\", RoutingStrategy.Bubble, typeof(RoutedEventHandler), typeof(ColorPicker));\n ColorPicker.SelectedColorProperty = DependencyProperty.Register(\"SelectedColor\", typeof(FontColor), typeof(ColorPicker), new UIPropertyMetadata(null));\n }\n public ColorPicker()\n {\n InitializeComponent();\n this.viewModel = new ColorPickerViewModel();\n base.DataContext = this.viewModel;\n }\n private void RaiseColorChangedEvent()\n {\n base.RaiseEvent(new RoutedEventArgs(ColorPicker.ColorChangedEvent));\n }\n\n private void superCombo_DropDownClosed(object sender, EventArgs e)\n {\n base.SetValue(ColorPicker.SelectedColorProperty, this.viewModel.SelectedFontColor);\n this.RaiseColorChangedEvent();\n }\n\n private void superCombo_Loaded(object sender, RoutedEventArgs e)\n {\n base.SetValue(ColorPicker.SelectedColorProperty, this.viewModel.SelectedFontColor);\n }\n\n public event RoutedEventHandler ColorChanged\n {\n add\n {\n base.AddHandler(ColorPicker.ColorChangedEvent, value);\n }\n remove\n {\n base.RemoveHandler(ColorPicker.ColorChangedEvent, value);\n }\n }\n }\n}\n"], ["/LLPlayer/FlyleafLibTests/MediaPlayer/SubtitlesManagerTest.cs", "using FluentAssertions;\nusing FluentAssertions.Execution;\n\nnamespace FlyleafLib.MediaPlayer;\n\npublic class SubManagerTests\n{\n private readonly SubManager _subManager;\n\n public SubManagerTests()\n {\n SubManager subManager = new(new Config(true), 0, false);\n List subsData =\n [\n new() { StartTime = TimeSpan.FromSeconds(1), EndTime = TimeSpan.FromSeconds(5), Text = \"1. Hello World!\" },\n new() { StartTime = TimeSpan.FromSeconds(10), EndTime = TimeSpan.FromSeconds(15), Text = \"2. How are you\" },\n new() { StartTime = TimeSpan.FromSeconds(20), EndTime = TimeSpan.FromSeconds(25), Text = \"3. I'm fine\" },\n new() { StartTime = TimeSpan.FromSeconds(28), EndTime = TimeSpan.FromSeconds(29), Text = \"4. Thank you\" },\n new() { StartTime = TimeSpan.FromSeconds(30), EndTime = TimeSpan.FromSeconds(35), Text = \"5. Good bye\" }\n ];\n\n subManager.Load(subsData);\n\n _subManager = subManager;\n }\n\n #region Seek\n [Fact]\n public void SubManagerTest_First_Yet()\n {\n // before the first subtitle\n TimeSpan currentTime = TimeSpan.FromSeconds(0.5);\n _subManager.SetCurrentTime(currentTime);\n\n // 1. Hello World!\n var nextIndex = 0;\n\n var subsData = _subManager.Subs;\n\n using (new AssertionScope())\n {\n _subManager.State.Should().Be(SubManager.PositionState.First);\n _subManager.CurrentIndex.Should().Be(-1);\n\n _subManager.GetCurrent().Should().BeNull();\n _subManager.GetPrev().Should().BeNull();\n _subManager.GetNext().Should()\n .NotBeNull().And\n .Match(s => s.Text == subsData[nextIndex].Text);\n }\n }\n\n [Fact]\n public void SubManagerTest_First_Showing()\n {\n // During playback of the first subtitle\n TimeSpan currentTime = TimeSpan.FromSeconds(1);\n _subManager.SetCurrentTime(currentTime);\n\n // 1. Hello World!\n var curIndex = 0;\n\n var subsData = _subManager.Subs;\n\n using (new AssertionScope())\n {\n _subManager.State.Should().Be(SubManager.PositionState.Showing);\n _subManager.CurrentIndex.Should().Be(curIndex);\n\n _subManager.GetCurrent().Should()\n .NotBeNull().And\n .Match(s => s.Text == subsData[curIndex].Text);\n _subManager.GetPrev().Should().BeNull();\n _subManager.GetNext().Should()\n .NotBeNull().And\n .Match(s => s.Text == subsData[curIndex + 1].Text);\n }\n }\n\n [Fact]\n public void SubManagerTest_Middle_Showing()\n {\n // During playback of the middle subtitle\n TimeSpan currentTime = TimeSpan.FromSeconds(22);\n _subManager.SetCurrentTime(currentTime);\n\n // 3. I'm fine\n var curIndex = 2;\n\n var subsData = _subManager.Subs;\n\n using (new AssertionScope())\n {\n _subManager.State.Should().Be(SubManager.PositionState.Showing);\n _subManager.CurrentIndex.Should().Be(curIndex);\n\n _subManager.GetCurrent().Should()\n .NotBeNull().And\n .Match(s => s.Text == subsData[curIndex].Text);\n _subManager.GetPrev().Should()\n .NotBeNull().And\n .Match(s => s.Text == subsData[curIndex - 1].Text);\n _subManager.GetNext().Should()\n .NotBeNull().And\n .Match(s => s.Text == subsData[curIndex + 1].Text);\n }\n }\n\n [Fact]\n public void SubManagerTest_Middle_Yet()\n {\n // just before the middle subtitle\n TimeSpan currentTime = TimeSpan.FromSeconds(18);\n _subManager.SetCurrentTime(currentTime);\n\n // 3. I'm fine\n var nextIndex = 2;\n\n var subsData = _subManager.Subs;\n\n using (new AssertionScope())\n {\n _subManager.State.Should().Be(SubManager.PositionState.Around);\n _subManager.CurrentIndex.Should().Be(nextIndex - 1);\n\n // Seek falls back to PrevSeek so we can seek, this class returns null\n _subManager.GetCurrent().Should().BeNull();\n _subManager.GetPrev().Should()\n .NotBeNull().And\n .Match(s => s.Text == subsData[nextIndex - 1].Text);\n _subManager.GetNext().Should()\n .NotBeNull().And\n .Match(s => s.Text == subsData[nextIndex].Text);\n }\n }\n\n [Fact]\n public void SubManagerTest_Last_Showing()\n {\n // During playback of the last subtitle\n TimeSpan currentTime = TimeSpan.FromSeconds(35);\n _subManager.SetCurrentTime(currentTime);\n\n // 5. Good bye\n var curIndex = 4;\n\n var subsData = _subManager.Subs;\n\n using (new AssertionScope())\n {\n _subManager.State.Should().Be(SubManager.PositionState.Showing);\n _subManager.CurrentIndex.Should().Be(curIndex);\n\n _subManager.GetCurrent().Should()\n .NotBeNull().And\n .Match(s => s.Text == subsData[curIndex].Text);\n _subManager.GetPrev().Should()\n .NotBeNull().And\n .Match(s => s.Text == subsData[curIndex - 1].Text);\n _subManager.GetNext().Should().BeNull();\n }\n }\n\n [Fact]\n public void SubManagerTest_Last_Past()\n {\n // after the last subtitle\n TimeSpan currentTime = TimeSpan.FromSeconds(99);\n _subManager.SetCurrentTime(currentTime);\n\n // 5. Good bye\n var prevIndex = 4;\n\n var subsData = _subManager.Subs;\n\n using (new AssertionScope())\n {\n _subManager.State.Should().Be(SubManager.PositionState.Last);\n // OK?\n _subManager.CurrentIndex.Should().Be(prevIndex);\n\n // Seek falls back to PrevSeek so we can seek, this returns null\n _subManager.GetCurrent().Should().BeNull();\n _subManager.GetPrev().Should()\n .NotBeNull().And\n .Match(s => s.Text == subsData[prevIndex].Text);\n _subManager.GetNext().Should().BeNull();\n }\n }\n #endregion\n\n #region DeleteAfter\n [Fact]\n public void SubManagerTest_DeleteAfter_DeleteFromMiddle()\n {\n _subManager.DeleteAfter(TimeSpan.FromSeconds(20));\n\n using (new AssertionScope())\n {\n _subManager.Subs.Count.Should().Be(2);\n _subManager.Subs.Select(s => s.Text!.Substring(0, 1))\n .Should().BeEquivalentTo([\"1\", \"2\"]);\n }\n }\n\n [Fact]\n public void SubManagerTest_DeleteAfter_DeleteAll()\n {\n _subManager.DeleteAfter(TimeSpan.FromSeconds(3));\n\n _subManager.Subs.Count.Should().Be(0);\n }\n\n [Fact]\n public void SubManagerTest_DeleteAfter_DeleteLast()\n {\n _subManager.DeleteAfter(TimeSpan.FromSeconds(32));\n\n using (new AssertionScope())\n {\n _subManager.Subs.Count.Should().Be(4);\n _subManager.Subs.Select(s => s.Text!.Substring(0, 1))\n .Should().BeEquivalentTo([\"1\", \"2\", \"3\", \"4\"]);\n }\n }\n\n [Fact]\n public void SubManagerTest_DeleteAfter_NoDelete()\n {\n _subManager.DeleteAfter(TimeSpan.FromSeconds(36));\n\n _subManager.Subs.Count.Should().Be(5);\n }\n #endregion\n}\n"], ["/LLPlayer/FlyleafLib/MediaFramework/MediaPlaylist/PLSPlaylist.cs", "using System.Collections.Generic;\nusing System.Runtime.InteropServices;\nusing System.Text;\n\nnamespace FlyleafLib.MediaFramework.MediaPlaylist;\n\npublic class PLSPlaylist\n{\n [DllImport(\"kernel32\")]\n private static extern long WritePrivateProfileString(string name, string key, string val, string filePath);\n [DllImport(\"kernel32\")]\n private static extern int GetPrivateProfileString(string section, string key, string def, StringBuilder retVal, int size, string filePath);\n\n public string path;\n\n public static List Parse(string filename)\n {\n List items = new();\n string res;\n int entries = 1000;\n\n if ((res = GetINIAttribute(\"playlist\", \"NumberOfEntries\", filename)) != null)\n entries = int.Parse(res);\n\n for (int i=1; i<=entries; i++)\n {\n if ((res = GetINIAttribute(\"playlist\", $\"File{i}\", filename)) == null)\n break;\n\n PLSPlaylistItem item = new() { Url = res };\n\n if ((res = GetINIAttribute(\"playlist\", $\"Title{i}\", filename)) != null)\n item.Title = res;\n\n if ((res = GetINIAttribute(\"playlist\", $\"Length{i}\", filename)) != null)\n item.Duration = int.Parse(res);\n\n items.Add(item);\n }\n\n return items;\n }\n\n public static string GetINIAttribute(string name, string key, string path)\n {\n StringBuilder sb = new(255);\n return GetPrivateProfileString(name, key, \"\", sb, 255, path) > 0\n ? sb.ToString() : null;\n }\n}\n\npublic class PLSPlaylistItem\n{\n public int Duration { get; set; }\n public string Title { get; set; }\n public string Url { get; set; }\n}\n"], ["/LLPlayer/FlyleafLib/Engine/WhisperCppModel.cs", "using System.IO;\nusing System.Text.Json.Serialization;\nusing Whisper.net.Ggml;\n\nnamespace FlyleafLib;\n\n#nullable enable\n\npublic class WhisperCppModel : NotifyPropertyChanged, IEquatable\n{\n public GgmlType Model { get; set; }\n\n [JsonIgnore]\n public long Size\n {\n get;\n set\n {\n if (Set(ref field, value))\n {\n Raise(nameof(Downloaded));\n }\n }\n }\n\n [JsonIgnore]\n public string ModelFileName\n {\n get\n {\n string modelName = Model.ToString().ToLower();\n return $\"ggml-{modelName}.bin\";\n }\n }\n\n [JsonIgnore]\n public string ModelFilePath => Path.Combine(WhisperConfig.ModelsDirectory, ModelFileName);\n\n [JsonIgnore]\n public bool Downloaded => Size > 0;\n\n public override string ToString() => Model.ToString();\n\n public bool Equals(WhisperCppModel? other)\n {\n if (other is null) return false;\n if (ReferenceEquals(this, other)) return true;\n return Model == other.Model;\n }\n\n public override bool Equals(object? obj) => obj is WhisperCppModel o && Equals(o);\n\n public override int GetHashCode()\n {\n return (int)Model;\n }\n}\n"], ["/LLPlayer/LLPlayer/Controls/Settings/Controls/ColorPicker.xaml.cs", "using System.Windows;\nusing System.Windows.Controls;\nusing System.Windows.Media;\nusing MaterialDesignThemes.Wpf;\n\nnamespace LLPlayer.Controls.Settings.Controls;\n\npublic partial class ColorPicker : UserControl\n{\n public ColorPicker()\n {\n InitializeComponent();\n\n Loaded += OnLoaded;\n }\n\n private void OnLoaded(object sender, RoutedEventArgs e)\n {\n // save initial color for cancellation\n _initialColor = PickerColor;\n\n MyNamedColors.SelectedItem = null;\n }\n\n private Color? _initialColor = null;\n\n public Color PickerColor\n {\n get => (Color)GetValue(PickerColorProperty);\n set => SetValue(PickerColorProperty, value);\n }\n\n public static readonly DependencyProperty PickerColorProperty =\n DependencyProperty.Register(nameof(PickerColor), typeof(Color), typeof(ColorPicker));\n\n public List> NamedColors { get; } = GetColors();\n\n private static List> GetColors()\n {\n return typeof(Colors)\n .GetProperties()\n .Where(prop =>\n typeof(Color).IsAssignableFrom(prop.PropertyType))\n .Select(prop =>\n new KeyValuePair(prop.Name, (Color)prop.GetValue(null)!))\n .ToList();\n }\n\n private void NamedColors_SelectionChanged(object sender, SelectionChangedEventArgs e)\n {\n if (MyNamedColors.SelectedItem != null)\n {\n PickerColor = ((KeyValuePair)MyNamedColors.SelectedItem).Value;\n }\n }\n\n private void ApplyButton_Click(object sender, RoutedEventArgs e)\n {\n DialogHost.CloseDialogCommand.Execute(\"apply\", this);\n }\n\n private void CancelButton_Click(object sender, RoutedEventArgs e)\n {\n if (_initialColor.HasValue)\n {\n PickerColor = _initialColor.Value;\n }\n DialogHost.CloseDialogCommand.Execute(\"cancel\", this);\n }\n}\n"], ["/LLPlayer/FlyleafLib/MediaFramework/MediaDemuxer/DemuxerInput.cs", "using System.Collections.Generic;\nusing System.IO;\n\nnamespace FlyleafLib.MediaFramework.MediaDemuxer;\n\npublic class DemuxerInput : NotifyPropertyChanged\n{\n /// \n /// Url provided as a demuxer input\n /// \n public string Url { get => _Url; set => _Url = Utils.FixFileUrl(value); }\n string _Url;\n\n /// \n /// Fallback url provided as a demuxer input\n /// \n public string UrlFallback { get => _UrlFallback; set => _UrlFallback = Utils.FixFileUrl(value); }\n string _UrlFallback;\n\n /// \n /// IOStream provided as a demuxer input\n /// \n public Stream IOStream { get; set; }\n\n public Dictionary\n HTTPHeaders { get; set; }\n\n public string UserAgent { get; set; }\n\n public string Referrer { get; set; }\n}\n"], ["/LLPlayer/FlyleafLib/Utils/NativeMethods.cs", "using System;\nusing System.Drawing;\nusing System.Runtime.InteropServices;\n\nnamespace FlyleafLib;\n\n#pragma warning disable CA1401 // P/Invokes should not be visible\npublic static partial class Utils\n{\n public static class NativeMethods\n {\n static NativeMethods()\n {\n if (IntPtr.Size == 4)\n {\n GetWindowLong = GetWindowLongPtr32;\n SetWindowLong = SetWindowLongPtr32;\n }\n else\n {\n GetWindowLong = GetWindowLongPtr64;\n SetWindowLong = SetWindowLongPtr64;\n }\n\n GetDPI(out DpiX, out DpiY);\n }\n\n public static Func SetWindowLong;\n public static Func GetWindowLong;\n\n [DllImport(\"user32.dll\", EntryPoint = \"GetWindowLong\")]\n public static extern IntPtr GetWindowLongPtr32(IntPtr hWnd, int nIndex);\n\n [DllImport(\"user32.dll\", EntryPoint = \"GetWindowLongPtr\")]\n public static extern IntPtr GetWindowLongPtr64(IntPtr hWnd, int nIndex);\n\n [DllImport(\"user32.dll\", EntryPoint = \"SetWindowLong\")]\n public static extern IntPtr SetWindowLongPtr32(IntPtr hWnd, int nIndex, IntPtr dwNewLong);\n\n [DllImport(\"user32.dll\", EntryPoint = \"SetWindowLongPtr\")] // , SetLastError = true\n public static extern IntPtr SetWindowLongPtr64(IntPtr hWnd, int nIndex, IntPtr dwNewLong);\n\n [DllImport(\"user32.dll\")]\n public static extern IntPtr CallWindowProc(IntPtr lpPrevWndFunc, IntPtr hWnd, uint Msg, IntPtr wParam, IntPtr lParam);\n\n [DllImport(\"comctl32.dll\")]\n public static extern bool SetWindowSubclass(IntPtr hWnd, IntPtr pfnSubclass, UIntPtr uIdSubclass, UIntPtr dwRefData);\n\n [DllImport(\"comctl32.dll\")]\n public static extern bool RemoveWindowSubclass(IntPtr hWnd, IntPtr pfnSubclass, UIntPtr uIdSubclass);\n\n [DllImport(\"comctl32.dll\")]\n public static extern IntPtr DefSubclassProc(IntPtr hWnd, uint msg, IntPtr wParam, IntPtr lParam);\n\n [DllImport(\"user32.dll\")]\n public static extern bool SetWindowPos(IntPtr hWnd, IntPtr hWndInsertAfter, int x, int y, int cx, int cy, UInt32 uFlags);\n\n [DllImport(\"shlwapi.dll\", CharSet = CharSet.Unicode)]\n public static extern int StrCmpLogicalW(string psz1, string psz2);\n\n [DllImport(\"user32.dll\")]\n public static extern int ShowCursor(bool bShow);\n\n [DllImport(\"winmm.dll\", EntryPoint = \"timeBeginPeriod\")]\n public static extern uint TimeBeginPeriod(uint uMilliseconds);\n\n [DllImport(\"winmm.dll\", EntryPoint = \"timeEndPeriod\")]\n public static extern uint TimeEndPeriod(uint uMilliseconds);\n\n [DllImport(\"kernel32.dll\", CharSet = CharSet.Auto)]\n public static extern EXECUTION_STATE SetThreadExecutionState(EXECUTION_STATE esFlags);\n [FlagsAttribute]\n public enum EXECUTION_STATE :uint\n {\n ES_AWAYMODE_REQUIRED = 0x00000040,\n ES_CONTINUOUS = 0x80000000,\n ES_DISPLAY_REQUIRED = 0x00000002,\n ES_SYSTEM_REQUIRED = 0x00000001\n }\n\n [DllImport(\"gdi32.dll\")]\n public static extern IntPtr CreateRectRgn(int nLeftRect, int nTopRect, int nRightRect, int nBottomRect);\n\n [DllImport(\"User32.dll\")]\n public static extern int GetWindowRgn(IntPtr hWnd, IntPtr hRgn);\n\n [DllImport(\"User32.dll\")]\n public static extern int SetWindowRgn(IntPtr hWnd, IntPtr hRgn, bool bRedraw);\n\n [DllImport(\"user32.dll\")]\n public static extern bool GetWindowRect(IntPtr hwnd, ref RECT rectangle);\n\n [DllImport(\"user32.dll\")]\n public static extern bool GetWindowInfo(IntPtr hwnd, ref WINDOWINFO pwi);\n\n [DllImport(\"user32.dll\")]\n public static extern void SetParent(IntPtr hWndChild, IntPtr hWndNewParent);\n\n [DllImport(\"user32.dll\")]\n public static extern IntPtr GetParent(IntPtr hWnd);\n\n [DllImport(\"user32.dll\")]\n [return: MarshalAs(UnmanagedType.Bool)]\n public static extern bool SetForegroundWindow(IntPtr hWnd);\n\n [DllImport(\"user32.dll\")]\n public static extern bool ShowWindow(IntPtr hWnd, int nCmdShow);\n\n\n [StructLayout(LayoutKind.Sequential)]\n public struct WINDOWINFO\n {\n public uint cbSize;\n public RECT rcWindow;\n public RECT rcClient;\n public uint dwStyle;\n public uint dwExStyle;\n public uint dwWindowStatus;\n public uint cxWindowBorders;\n public uint cyWindowBorders;\n public ushort atomWindowType;\n public ushort wCreatorVersion;\n\n // Allows automatic initialization of \"cbSize\" with \"new WINDOWINFO(null/true/false)\".\n public WINDOWINFO(Boolean? filler) : this()\n => cbSize = (UInt32)Marshal.SizeOf(typeof(WINDOWINFO));\n\n }\n public struct RECT\n {\n public int Left { get; set; }\n public int Top { get; set; }\n public int Right { get; set; }\n public int Bottom { get; set; }\n }\n\n [Flags]\n public enum SetWindowPosFlags : uint\n {\n SWP_ASYNCWINDOWPOS = 0x4000,\n SWP_DEFERERASE = 0x2000,\n SWP_DRAWFRAME = 0x0020,\n SWP_FRAMECHANGED = 0x0020,\n SWP_HIDEWINDOW = 0x0080,\n SWP_NOACTIVATE = 0x0010,\n SWP_NOCOPYBITS = 0x0100,\n SWP_NOMOVE = 0x0002,\n SWP_NOOWNERZORDER = 0x0200,\n SWP_NOREDRAW = 0x0008,\n SWP_NOREPOSITION = 0x0200,\n SWP_NOSENDCHANGING = 0x0400,\n SWP_NOSIZE = 0x0001,\n SWP_NOZORDER = 0x0004,\n SWP_SHOWWINDOW = 0x0040,\n }\n\n [Flags]\n public enum WindowLongFlags : int\n {\n GWL_EXSTYLE = -20,\n GWLP_HINSTANCE = -6,\n GWLP_HWNDPARENT = -8,\n GWL_ID = -12,\n GWL_STYLE = -16,\n GWL_USERDATA = -21,\n GWL_WNDPROC = -4,\n DWLP_USER = 0x8,\n DWLP_MSGRESULT = 0x0,\n DWLP_DLGPROC = 0x4\n }\n\n [Flags]\n public enum WindowStyles : uint\n {\n WS_BORDER = 0x800000,\n WS_CAPTION = 0xc00000,\n WS_CHILD = 0x40000000,\n WS_CLIPCHILDREN = 0x2000000,\n WS_CLIPSIBLINGS = 0x4000000,\n WS_DISABLED = 0x8000000,\n WS_DLGFRAME = 0x400000,\n WS_GROUP = 0x20000,\n WS_HSCROLL = 0x100000,\n WS_MAXIMIZE = 0x1000000,\n WS_MAXIMIZEBOX = 0x10000,\n WS_MINIMIZE = 0x20000000,\n WS_MINIMIZEBOX = 0x20000,\n WS_OVERLAPPED = 0x0,\n WS_OVERLAPPEDWINDOW = WS_OVERLAPPED | WS_CAPTION | WS_SYSMENU | WS_SIZEFRAME | WS_MINIMIZEBOX | WS_MAXIMIZEBOX,\n WS_POPUP = 0x80000000,\n WS_POPUPWINDOW = WS_POPUP | WS_BORDER | WS_SYSMENU,\n WS_SIZEFRAME = 0x40000,\n WS_SYSMENU = 0x80000,\n WS_TABSTOP = 0x10000,\n WS_THICKFRAME = 0x00040000,\n WS_VISIBLE = 0x10000000,\n WS_VSCROLL = 0x200000\n }\n\n [Flags]\n public enum WindowStylesEx : uint\n {\n WS_EX_ACCEPTFILES = 0x00000010,\n WS_EX_APPWINDOW = 0x00040000,\n WS_EX_CLIENTEDGE = 0x00000200,\n WS_EX_COMPOSITED = 0x02000000,\n WS_EX_CONTEXTHELP = 0x00000400,\n WS_EX_CONTROLPARENT = 0x00010000,\n WS_EX_DLGMODALFRAME = 0x00000001,\n WS_EX_LAYERED = 0x00080000,\n WS_EX_LAYOUTRTL = 0x00400000,\n WS_EX_LEFT = 0x00000000,\n WS_EX_LEFTSCROLLBAR = 0x00004000,\n WS_EX_LTRREADING = 0x00000000,\n WS_EX_MDICHILD = 0x00000040,\n WS_EX_NOACTIVATE = 0x08000000,\n WS_EX_NOINHERITLAYOUT = 0x00100000,\n WS_EX_NOPARENTNOTIFY = 0x00000004,\n WS_EX_NOREDIRECTIONBITMAP = 0x00200000,\n WS_EX_OVERLAPPEDWINDOW = WS_EX_WINDOWEDGE | WS_EX_CLIENTEDGE,\n WS_EX_PALETTEWINDOW = WS_EX_WINDOWEDGE | WS_EX_TOOLWINDOW | WS_EX_TOPMOST,\n WS_EX_RIGHT = 0x00001000,\n WS_EX_RIGHTSCROLLBAR = 0x00000000,\n WS_EX_RTLREADING = 0x00002000,\n WS_EX_STATICEDGE = 0x00020000,\n WS_EX_TOOLWINDOW = 0x00000080,\n WS_EX_TOPMOST = 0x00000008,\n WS_EX_TRANSPARENT = 0x00000020,\n WS_EX_WINDOWEDGE = 0x00000100\n }\n\n public enum ShowWindowCommands : uint\n {\n SW_HIDE = 0,\n SW_SHOWNORMAL = 1,\n SW_NORMAL = 1,\n SW_SHOWMINIMIZED = 2,\n SW_SHOWMAXIMIZED = 3,\n SW_MAXIMIZE = 3,\n SW_SHOWNOACTIVATE = 4,\n SW_SHOW = 5,\n SW_MINIMIZE = 6,\n SW_SHOWMINNOACTIVE = 7,\n SW_SHOWNA = 8,\n SW_RESTORE = 9,\n SW_SHOWDEFAULT = 10,\n SW_FORCEMINIMIZE = 11,\n SW_MAX = 11\n }\n\n public delegate IntPtr WndProcDelegate(IntPtr hWnd, uint msg, IntPtr wParam, IntPtr lParam);\n public delegate IntPtr SubclassWndProc(IntPtr hWnd, uint msg, IntPtr wParam, IntPtr lParam, IntPtr uIdSubclass, IntPtr dwRefData);\n\n public static int SignedHIWORD(IntPtr n) => SignedHIWORD(unchecked((int)(long)n));\n public static int SignedLOWORD(IntPtr n) => SignedLOWORD(unchecked((int)(long)n));\n public static int SignedHIWORD(int n) => (short)((n >> 16) & 0xffff);\n public static int SignedLOWORD(int n) => (short)(n & 0xFFFF);\n\n #region DPI\n public static double DpiX, DpiY;\n public static int DpiXSource, DpiYSource;\n const int LOGPIXELSX = 88, LOGPIXELSY = 90;\n [DllImport(\"gdi32.dll\", CharSet = CharSet.Auto, SetLastError = true, ExactSpelling = true)]\n public static extern int GetDeviceCaps(IntPtr hDC, int nIndex);\n public static void GetDPI(out double dpiX, out double dpiY) => GetDPI(IntPtr.Zero, out dpiX, out dpiY);\n public static void GetDPI(IntPtr handle, out double dpiX, out double dpiY)\n {\n Graphics GraphicsObject = Graphics.FromHwnd(handle); // DESKTOP Handle\n IntPtr dcHandle = GraphicsObject.GetHdc();\n DpiXSource = GetDeviceCaps(dcHandle, LOGPIXELSX);\n dpiX = DpiXSource / 96.0;\n DpiYSource = GetDeviceCaps(dcHandle, LOGPIXELSY);\n dpiY = DpiYSource / 96.0;\n GraphicsObject.ReleaseHdc(dcHandle);\n GraphicsObject.Dispose();\n }\n #endregion\n }\n}\n#pragma warning restore CA1401 // P/Invokes should not be visible\n"], ["/LLPlayer/FlyleafLib/Utils/ObservableDictionary.cs", "using System.Collections.Generic;\nusing System.Collections.Specialized;\nusing System.ComponentModel;\nusing System.Linq;\n\nnamespace FlyleafLib;\n\npublic static partial class Utils\n{\n public class ObservableDictionary : Dictionary, INotifyPropertyChanged, INotifyCollectionChanged\n {\n public event PropertyChangedEventHandler PropertyChanged;\n public event NotifyCollectionChangedEventHandler CollectionChanged;\n\n public new TVal this[TKey key]\n {\n get => base[key];\n\n set\n {\n if (ContainsKey(key) && base[key].Equals(value)) return;\n\n if (CollectionChanged != null)\n {\n KeyValuePair oldItem = new(key, base[key]);\n KeyValuePair newItem = new(key, value);\n base[key] = value;\n PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(key.ToString()));\n CollectionChanged?.Invoke(this, new NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction.Replace, newItem, oldItem, this.ToList().IndexOf(newItem)));\n }\n else\n {\n base[key] = value;\n PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(key.ToString()));\n }\n }\n }\n }\n}\n"], ["/LLPlayer/LLPlayer/Extensions/ScrollParentWhenAtMax.cs", "using System.Windows;\nusing System.Windows.Controls;\nusing System.Windows.Input;\nusing System.Windows.Media;\nusing Microsoft.Xaml.Behaviors;\n\nnamespace LLPlayer.Extensions;\n\n/// \n/// Behavior to disable scrolling in ListView\n/// ref: https://stackoverflow.com/questions/1585462/bubbling-scroll-events-from-a-listview-to-its-parent\n/// \npublic class ScrollParentWhenAtMax : Behavior\n{\n protected override void OnAttached()\n {\n base.OnAttached();\n AssociatedObject.PreviewMouseWheel += PreviewMouseWheel;\n }\n\n protected override void OnDetaching()\n {\n AssociatedObject.PreviewMouseWheel -= PreviewMouseWheel;\n base.OnDetaching();\n }\n\n private void PreviewMouseWheel(object sender, MouseWheelEventArgs e)\n {\n var scrollViewer = GetVisualChild(AssociatedObject);\n var scrollPos = scrollViewer!.ContentVerticalOffset;\n if ((scrollPos == scrollViewer.ScrollableHeight && e.Delta < 0)\n || (scrollPos == 0 && e.Delta > 0))\n {\n e.Handled = true;\n MouseWheelEventArgs e2 = new(e.MouseDevice, e.Timestamp, e.Delta);\n e2.RoutedEvent = UIElement.MouseWheelEvent;\n AssociatedObject.RaiseEvent(e2);\n }\n }\n\n private static T? GetVisualChild(DependencyObject parent) where T : Visual\n {\n T? child = null;\n\n int numVisuals = VisualTreeHelper.GetChildrenCount(parent);\n for (int i = 0; i < numVisuals; i++)\n {\n Visual v = (Visual)VisualTreeHelper.GetChild(parent, i);\n child = v as T;\n if (child == null)\n {\n child = GetVisualChild(v);\n }\n\n if (child != null)\n {\n break;\n }\n }\n\n return child;\n }\n}\n"], ["/LLPlayer/LLPlayer/Services/ErrorDialogHelper.cs", "using System.Windows;\nusing FlyleafLib.MediaPlayer;\nusing LLPlayer.Views;\n\nnamespace LLPlayer.Services;\n\npublic static class ErrorDialogHelper\n{\n public static void ShowKnownErrorPopup(string message, string errorType)\n {\n var dialogService = ((App)Application.Current).Container.Resolve();\n\n DialogParameters p = new()\n {\n { \"type\", \"known\" },\n { \"message\", message },\n { \"errorType\", errorType }\n };\n\n dialogService.ShowDialog(nameof(ErrorDialog), p);\n }\n\n public static void ShowKnownErrorPopup(string message, KnownErrorType errorType)\n {\n ShowKnownErrorPopup(message, errorType.ToString());\n }\n\n public static void ShowUnknownErrorPopup(string message, string errorType, Exception? ex = null)\n {\n var dialogService = ((App)Application.Current).Container.Resolve();\n\n DialogParameters p = new()\n {\n { \"type\", \"unknown\" },\n { \"message\", message },\n { \"errorType\", errorType },\n };\n\n if (ex != null)\n {\n p.Add(\"exception\", ex);\n }\n\n dialogService.ShowDialog(nameof(ErrorDialog), p);\n }\n\n public static void ShowUnknownErrorPopup(string message, UnknownErrorType errorType, Exception? ex = null)\n {\n ShowUnknownErrorPopup(message, errorType.ToString(), ex);\n }\n}\n"], ["/LLPlayer/LLPlayer/Extensions/WindowsClipboard.cs", "using System.ComponentModel;\nusing System.Runtime.InteropServices;\n\nnamespace LLPlayer.Extensions;\n\n// ref: https://stackoverflow.com/questions/44205260/net-core-copy-to-clipboard\npublic static class WindowsClipboard\n{\n public static void SetText(string text)\n {\n OpenClipboard();\n\n EmptyClipboard();\n IntPtr hGlobal = 0;\n try\n {\n int bytes = (text.Length + 1) * 2;\n hGlobal = Marshal.AllocHGlobal(bytes);\n\n if (hGlobal == 0)\n {\n ThrowWin32();\n }\n\n IntPtr target = GlobalLock(hGlobal);\n\n if (target == 0)\n {\n ThrowWin32();\n }\n\n try\n {\n Marshal.Copy(text.ToCharArray(), 0, target, text.Length);\n }\n finally\n {\n GlobalUnlock(target);\n }\n\n if (SetClipboardData(cfUnicodeText, hGlobal) == 0)\n {\n ThrowWin32();\n }\n\n hGlobal = 0;\n }\n finally\n {\n if (hGlobal != 0)\n {\n Marshal.FreeHGlobal(hGlobal);\n }\n\n CloseClipboard();\n }\n }\n\n public static void OpenClipboard()\n {\n int num = 10;\n while (true)\n {\n if (OpenClipboard(0))\n {\n break;\n }\n\n if (--num == 0)\n {\n ThrowWin32();\n }\n\n Thread.Sleep(20);\n }\n }\n\n const uint cfUnicodeText = 13;\n\n static void ThrowWin32()\n {\n throw new Win32Exception(Marshal.GetLastWin32Error());\n }\n\n [DllImport(\"kernel32.dll\", SetLastError = true)]\n static extern IntPtr GlobalLock(IntPtr hMem);\n\n [DllImport(\"kernel32.dll\", SetLastError = true)]\n [return: MarshalAs(UnmanagedType.Bool)]\n static extern bool GlobalUnlock(IntPtr hMem);\n\n [DllImport(\"user32.dll\", SetLastError = true)]\n [return: MarshalAs(UnmanagedType.Bool)]\n static extern bool OpenClipboard(IntPtr hWndNewOwner);\n\n [DllImport(\"user32.dll\", SetLastError = true)]\n [return: MarshalAs(UnmanagedType.Bool)]\n static extern bool CloseClipboard();\n\n [DllImport(\"user32.dll\", SetLastError = true)]\n static extern IntPtr SetClipboardData(uint uFormat, IntPtr data);\n\n [DllImport(\"user32.dll\")]\n static extern bool EmptyClipboard();\n}\n"], ["/LLPlayer/LLPlayer/Controls/Settings/SettingsSubtitles.xaml.cs", "using System.Windows;\nusing System.Windows.Controls;\nusing FlyleafLib;\nusing FlyleafLib.MediaPlayer.Translation;\nusing LLPlayer.Extensions;\nusing LLPlayer.Services;\nusing LLPlayer.Views;\n\nnamespace LLPlayer.Controls.Settings;\n\npublic partial class SettingsSubtitles : UserControl\n{\n public SettingsSubtitles()\n {\n InitializeComponent();\n\n DataContext = ((App)Application.Current).Container.Resolve();\n }\n}\n\npublic class SettingsSubtitlesVM : Bindable\n{\n public FlyleafManager FL { get; }\n private readonly IDialogService _dialogService;\n\n public SettingsSubtitlesVM(FlyleafManager fl, IDialogService dialogService)\n {\n _dialogService = dialogService;\n FL = fl;\n Languages = TranslateLanguage.Langs.Values.ToList();\n\n if (FL.PlayerConfig.Subtitles.LanguageFallbackPrimary != null)\n {\n SelectedPrimaryLanguage = Languages.FirstOrDefault(l => l.ISO6391 == FL.PlayerConfig.Subtitles.LanguageFallbackPrimary.ISO6391);\n }\n\n if (FL.PlayerConfig.Subtitles.LanguageFallbackSecondary != null)\n {\n SelectedSecondaryLanguage = Languages.FirstOrDefault(l => l.ISO6391 == FL.PlayerConfig.Subtitles.LanguageFallbackSecondary.ISO6391);\n }\n }\n\n public List Languages { get; set; }\n\n public TranslateLanguage? SelectedPrimaryLanguage\n {\n get;\n set\n {\n if (Set(ref field, value))\n {\n if (value == null)\n {\n FL.PlayerConfig.Subtitles.LanguageFallbackPrimary = null;\n }\n else\n {\n FL.PlayerConfig.Subtitles.LanguageFallbackPrimary = Language.Get(value.ISO6391);\n }\n\n if (FL.PlayerConfig.Subtitles.LanguageFallbackSecondarySame)\n {\n FL.PlayerConfig.Subtitles.LanguageFallbackSecondary = FL.PlayerConfig.Subtitles.LanguageFallbackPrimary;\n\n SelectedSecondaryLanguage = SelectedPrimaryLanguage;\n }\n }\n }\n }\n\n public TranslateLanguage? SelectedSecondaryLanguage\n {\n get;\n set\n {\n if (Set(ref field, value))\n {\n if (value == null)\n {\n FL.PlayerConfig.Subtitles.LanguageFallbackSecondary = null;\n }\n else\n {\n FL.PlayerConfig.Subtitles.LanguageFallbackSecondary = Language.Get(value.ISO6391);\n }\n }\n }\n }\n\n public DelegateCommand? CmdConfigureLanguage => field ??= new(() =>\n {\n DialogParameters p = new()\n {\n { \"languages\", FL.PlayerConfig.Subtitles.Languages }\n };\n\n _dialogService.ShowDialog(nameof(SelectLanguageDialog), p, result =>\n {\n List updated = result.Parameters.GetValue>(\"languages\");\n\n if (!FL.PlayerConfig.Subtitles.Languages.SequenceEqual(updated))\n {\n FL.PlayerConfig.Subtitles.Languages = updated;\n }\n });\n });\n}\n"], ["/LLPlayer/LLPlayer/Controls/AlignableWrapPanel.cs", "using System.Windows;\nusing System.Windows.Controls;\n\nnamespace LLPlayer.Controls;\n\n// The standard WrapPanel does not have a centering function, so add it.\n// ref: https://stackoverflow.com/a/7747002\npublic class AlignableWrapPanel : Panel\n{\n public static readonly DependencyProperty HorizontalContentAlignmentProperty =\n DependencyProperty.Register(nameof(HorizontalContentAlignment), typeof(HorizontalAlignment), typeof(AlignableWrapPanel), new FrameworkPropertyMetadata(HorizontalAlignment.Left, FrameworkPropertyMetadataOptions.AffectsArrange));\n public HorizontalAlignment HorizontalContentAlignment\n {\n get => (HorizontalAlignment)GetValue(HorizontalContentAlignmentProperty);\n set => SetValue(HorizontalContentAlignmentProperty, value);\n }\n\n protected override Size MeasureOverride(Size constraint)\n {\n Size curLineSize = new();\n Size panelSize = new();\n\n UIElementCollection children = InternalChildren;\n\n for (int i = 0; i < children.Count; i++)\n {\n UIElement child = children[i];\n\n // Flow passes its own constraint to children\n child.Measure(constraint);\n Size sz = child.DesiredSize;\n\n if (child is NewLine ||\n curLineSize.Width + sz.Width > constraint.Width) //need to switch to another line\n {\n panelSize.Width = Math.Max(curLineSize.Width, panelSize.Width);\n panelSize.Height += curLineSize.Height;\n curLineSize = sz;\n\n if (sz.Width > constraint.Width) // if the element is wider then the constraint - give it a separate line\n {\n panelSize.Width = Math.Max(sz.Width, panelSize.Width);\n panelSize.Height += sz.Height;\n curLineSize = new Size();\n }\n }\n else //continue to accumulate a line\n {\n curLineSize.Width += sz.Width;\n curLineSize.Height = Math.Max(sz.Height, curLineSize.Height);\n }\n }\n\n // the last line size, if any need to be added\n panelSize.Width = Math.Max(curLineSize.Width, panelSize.Width);\n panelSize.Height += curLineSize.Height;\n\n return panelSize;\n }\n\n protected override Size ArrangeOverride(Size arrangeBounds)\n {\n int firstInLine = 0;\n Size curLineSize = new();\n double accumulatedHeight = 0;\n UIElementCollection children = InternalChildren;\n\n for (int i = 0; i < children.Count; i++)\n {\n UIElement child = children[i];\n\n Size sz = child.DesiredSize;\n\n if (child is NewLine ||\n curLineSize.Width + sz.Width > arrangeBounds.Width) //need to switch to another line\n {\n ArrangeLine(accumulatedHeight, curLineSize, arrangeBounds.Width, firstInLine, i);\n\n accumulatedHeight += curLineSize.Height;\n curLineSize = sz;\n\n if (sz.Width > arrangeBounds.Width) //the element is wider then the constraint - give it a separate line\n {\n ArrangeLine(accumulatedHeight, sz, arrangeBounds.Width, i, ++i);\n accumulatedHeight += sz.Height;\n curLineSize = new Size();\n }\n firstInLine = i;\n }\n else //continue to accumulate a line\n {\n curLineSize.Width += sz.Width;\n curLineSize.Height = Math.Max(sz.Height, curLineSize.Height);\n }\n }\n\n if (firstInLine < children.Count)\n ArrangeLine(accumulatedHeight, curLineSize, arrangeBounds.Width, firstInLine, children.Count);\n\n return arrangeBounds;\n }\n\n private void ArrangeLine(double y, Size lineSize, double boundsWidth, int start, int end)\n {\n double x = 0;\n if (this.HorizontalContentAlignment == HorizontalAlignment.Center)\n {\n x = (boundsWidth - lineSize.Width) / 2;\n }\n else if (this.HorizontalContentAlignment == HorizontalAlignment.Right)\n {\n x = (boundsWidth - lineSize.Width);\n }\n\n UIElementCollection children = InternalChildren;\n for (int i = start; i < end; i++)\n {\n UIElement child = children[i];\n child.Arrange(new Rect(x, y, child.DesiredSize.Width, lineSize.Height));\n x += child.DesiredSize.Width;\n }\n }\n}\n"], ["/LLPlayer/LLPlayer/Resources/MaterialDesignMy.xaml.cs", "using System.Windows;\nusing System.Windows.Controls;\nusing System.Windows.Input;\n\nnamespace LLPlayer.Resources;\n\npublic partial class MaterialDesignMy : ResourceDictionary\n{\n public MaterialDesignMy()\n {\n InitializeComponent();\n }\n\n /// \n /// Do not close the menu when right-clicking or CTRL+left-clicking on a context menu\n /// This is achieved by dynamically setting StaysOpenOnClick\n /// \n /// \n /// \n private void MenuItem_PreviewMouseDown(object sender, MouseButtonEventArgs e)\n {\n if (sender is MenuItem menuItem)\n {\n if ((Keyboard.IsKeyDown(Key.LeftCtrl) || Keyboard.IsKeyDown(Key.RightCtrl)) ||\n Mouse.RightButton == MouseButtonState.Pressed)\n {\n menuItem.StaysOpenOnClick = true;\n }\n else if (menuItem.StaysOpenOnClick)\n {\n menuItem.StaysOpenOnClick = false;\n }\n }\n }\n}\n"], ["/LLPlayer/FlyleafLib/MediaFramework/MediaDemuxer/CustomIOContext.cs", "using System.IO;\n\nnamespace FlyleafLib.MediaFramework.MediaDemuxer;\n\npublic unsafe class CustomIOContext\n{\n AVIOContext* avioCtx;\n public Stream stream;\n Demuxer demuxer;\n\n public CustomIOContext(Demuxer demuxer)\n {\n this.demuxer = demuxer;\n }\n\n public void Initialize(Stream stream)\n {\n this.stream = stream;\n //this.stream.Seek(0, SeekOrigin.Begin);\n\n ioread = IORead;\n ioseek = IOSeek;\n avioCtx = avio_alloc_context((byte*)av_malloc((nuint)demuxer.Config.IOStreamBufferSize), demuxer.Config.IOStreamBufferSize, 0, null, ioread, null, ioseek);\n demuxer.FormatContext->pb = avioCtx;\n demuxer.FormatContext->flags |= FmtFlags2.CustomIo;\n }\n\n public void Dispose()\n {\n if (avioCtx != null)\n {\n av_free(avioCtx->buffer);\n fixed (AVIOContext** ptr = &avioCtx) avio_context_free(ptr);\n }\n avioCtx = null;\n stream = null;\n ioread = null;\n ioseek = null;\n }\n\n avio_alloc_context_read_packet ioread;\n avio_alloc_context_seek ioseek;\n\n int IORead(void* opaque, byte* buffer, int bufferSize)\n {\n int ret;\n\n if (demuxer.Interrupter.ShouldInterrupt(null) != 0) return AVERROR_EXIT;\n\n ret = demuxer.CustomIOContext.stream.Read(new Span(buffer, bufferSize));\n\n if (ret > 0)\n return ret;\n\n if (ret == 0)\n return AVERROR_EOF;\n\n demuxer.Log.Warn(\"CustomIOContext Interrupted\");\n\n return AVERROR_EXIT;\n }\n\n long IOSeek(void* opaque, long offset, IOSeekFlags whence)\n {\n //System.Diagnostics.Debug.WriteLine($\"** S | {decCtx.demuxer.fmtCtx->pb->pos} - {decCtx.demuxer.ioStream.Position}\");\n\n return whence == IOSeekFlags.Size\n ? demuxer.CustomIOContext.stream.Length\n : demuxer.CustomIOContext.stream.Seek(offset, (SeekOrigin) whence);\n }\n}\n"], ["/LLPlayer/LLPlayer/Controls/Settings/SettingsAbout.xaml.cs", "using System.Collections.ObjectModel;\nusing System.Diagnostics.CodeAnalysis;\nusing System.Windows;\nusing System.Windows.Controls;\nusing LLPlayer.Extensions;\n\nnamespace LLPlayer.Controls.Settings;\n\npublic partial class SettingsAbout : UserControl\n{\n public SettingsAbout()\n {\n InitializeComponent();\n\n DataContext = ((App)Application.Current).Container.Resolve();\n }\n}\n\npublic class SettingsAboutVM : Bindable\n{\n public SettingsAboutVM()\n {\n Libraries =\n [\n new LibraryInfo\n {\n Name = \"SuRGeoNix/Flyleaf\",\n Description = \"Media Player .NET Library for WinUI 3/WPF/WinForms (based on FFmpeg/DirectX)\",\n Url = \"https://github.com/SuRGeoNix/Flyleaf\"\n },\n\n new LibraryInfo\n {\n Name = \"SuRGeoNix/Flyleaf.FFmpeg\",\n Description = \"FFmpeg Bindings for C#/.NET\",\n Url = \"https://github.com/SuRGeoNix/Flyleaf.FFmpeg\"\n },\n\n new LibraryInfo\n {\n Name = \"sandrohanea/whisper.net\",\n Description = \"Dotnet bindings for OpenAI Whisper (whisper.cpp)\",\n Url = \"https://github.com/sandrohanea/whisper.net\"\n },\n\n new LibraryInfo\n {\n Name = \"Purfview/whisper-standalone-win\",\n Description = \"Faster-Whisper standalone executables\",\n Url = \"https://github.com/Purfview/whisper-standalone-win\"\n },\n\n new LibraryInfo\n {\n Name = \"Sicos1977/TesseractOCR\",\n Description = \".NET wrapper for Tesseract OCR\",\n Url = \"https://github.com/Sicos1977/TesseractOCR\"\n },\n\n new LibraryInfo\n {\n Name = \"MaterialDesignInXamlToolkit \",\n Description = \"Google's Material Design in XAML & WPF\",\n Url = \"https://github.com/MaterialDesignInXAML/MaterialDesignInXamlToolkit\"\n },\n\n new LibraryInfo\n {\n Name = \"searchpioneer/lingua-dotnet\",\n Description = \"Natural language detection library for .NET\",\n Url = \"https://github.com/searchpioneer/lingua-dotnet\"\n },\n\n new LibraryInfo\n {\n Name = \"CharsetDetector/UTF-unknowns\",\n Description = \"Character set detector build in C#\",\n Url = \"https://github.com/CharsetDetector/UTF-unknown\"\n },\n\n new LibraryInfo\n {\n Name = \"komutan/NMeCab\",\n Description = \"Japanese morphological analyzer on .NET\",\n Url = \"https://github.com/komutan/NMeCab\"\n },\n\n new LibraryInfo\n {\n Name = \"PrismLibrary/Prism\",\n Description = \"A framework for building MVVM application\",\n Url = \"https://github.com/PrismLibrary/Prism\"\n },\n\n new LibraryInfo\n {\n Name = \"amerkoleci/Vortice.Windows\",\n Description = \".NET bindings for Direct3D11, XAudio, etc.\",\n Url = \"https://github.com/amerkoleci/Vortice.Windows\"\n },\n\n new LibraryInfo\n {\n Name = \"sskodje/WpfColorFont\",\n Description = \" A WPF font and color dialog\",\n Url = \"https://github.com/sskodje/WpfColorFont\"\n },\n ];\n\n }\n public ObservableCollection Libraries { get; }\n\n [field: AllowNull, MaybeNull]\n public DelegateCommand CmdCopyVersion => field ??= new(() =>\n {\n Clipboard.SetText($\"\"\"\n Version: {App.Version}, CommitHash: {App.CommitHash}\n OS Architecture: {App.OSArchitecture}, Process Architecture: {App.ProcessArchitecture}\n \"\"\");\n });\n}\n\npublic class LibraryInfo\n{\n public required string Name { get; init; }\n public required string Description { get; init; }\n public required string Url { get; init; }\n}\n"], ["/LLPlayer/LLPlayer/Services/SrtExporter.cs", "using System.IO;\nusing System.Text;\n\nnamespace LLPlayer.Services;\n\npublic static class SrtExporter\n{\n // TODO: L: Supports tags such as ?\n public static void ExportSrt(List lines, string filePath, Encoding encoding)\n {\n using StreamWriter writer = new(filePath, false, encoding);\n\n foreach (var (i, line) in lines.Index())\n {\n writer.WriteLine((i + 1).ToString());\n writer.WriteLine($\"{FormatTime(line.Start)} --> {FormatTime(line.End)}\");\n writer.WriteLine(line.Text);\n // blank line expect last\n if (i != lines.Count - 1)\n {\n writer.WriteLine();\n }\n }\n }\n\n private static string FormatTime(TimeSpan time)\n {\n return string.Format(\"{0:00}:{1:00}:{2:00},{3:000}\",\n (int)time.TotalHours,\n time.Minutes,\n time.Seconds,\n time.Milliseconds);\n }\n}\n\npublic class SubtitleLine\n{\n public required TimeSpan Start { get; init; }\n public required TimeSpan End { get; init; }\n public required string Text { get; init; }\n}\n"], ["/LLPlayer/LLPlayer/Controls/SubtitlesControl.xaml.cs", "using System.Windows;\nusing System.Windows.Controls;\nusing FlyleafLib.MediaPlayer;\nusing LLPlayer.Services;\n\nnamespace LLPlayer.Controls;\n\npublic partial class SubtitlesControl : UserControl\n{\n public FlyleafManager FL { get; }\n\n public SubtitlesControl()\n {\n InitializeComponent();\n\n FL = ((App)Application.Current).Container.Resolve();\n\n DataContext = this;\n }\n\n private void SubtitlePanel_OnSizeChanged(object sender, SizeChangedEventArgs e)\n {\n if (e.HeightChanged)\n {\n // Sometimes there is a very small difference in decimal points when the subtitles are switched, and this event fires.\n // If you update the margin of the Sub at this time, the window will go wrong, so do it only when the difference is above a certain level.\n double heightDiff = Math.Abs(e.NewSize.Height - e.PreviousSize.Height);\n if (heightDiff >= 1.0)\n {\n FL.Config.Subs.SubsPanelSize = e.NewSize;\n }\n }\n }\n\n private async void SelectableSubtitleText_OnWordClicked(object sender, WordClickedEventArgs e)\n {\n await WordPopupControl.OnWordClicked(e);\n }\n\n private void SelectableSubtitleText_OnWordClickedDown(object? sender, EventArgs e)\n {\n // Assume drag and stop playback.\n if (FL.Player.Status == Status.Playing)\n {\n FL.Player.Pause();\n }\n }\n}\n"], ["/LLPlayer/LLPlayer/ViewModels/SettingsDialogVM.cs", "using LLPlayer.Extensions;\nusing LLPlayer.Services;\n\nnamespace LLPlayer.ViewModels;\n\npublic class SettingsDialogVM : Bindable, IDialogAware\n{\n public FlyleafManager FL { get; }\n public SettingsDialogVM(FlyleafManager fl)\n {\n FL = fl;\n }\n\n public DelegateCommand? CmdCloseDialog => field ??= new((parameter) =>\n {\n ButtonResult result = ButtonResult.None;\n\n if (parameter == \"Save\")\n {\n result = ButtonResult.OK;\n }\n\n RequestClose.Invoke(result);\n });\n\n #region IDialogAware\n public string Title { get; set => Set(ref field, value); } = $\"Settings - {App.Name}\";\n public double WindowWidth { get; set => Set(ref field, value); } = 1000;\n public double WindowHeight { get; set => Set(ref field, value); } = 700;\n\n public bool CanCloseDialog() => true;\n\n public void OnDialogClosed()\n {\n }\n\n public void OnDialogOpened(IDialogParameters parameters)\n {\n }\n\n public DialogCloseListener RequestClose { get; }\n #endregion\n}\n"], ["/LLPlayer/FlyleafLib/MediaFramework/MediaStream/ExternalVideoStream.cs", "namespace FlyleafLib.MediaFramework.MediaStream;\n\npublic class ExternalVideoStream : ExternalStream\n{\n public double FPS { get; set; }\n public int Height { get; set; }\n public int Width { get; set; }\n\n public bool HasAudio { get; set; }\n\n public string DisplayMember =>\n $\"{Width}x{Height} @{Math.Round(FPS, 2, MidpointRounding.AwayFromZero)} ({Codec}) [{Protocol}]{(HasAudio ? \"\" : \" [NA]\")}\";\n}\n"], ["/LLPlayer/WpfColorFontDialog/FontColor.cs", "using System;\nusing System.Runtime.CompilerServices;\nusing System.Windows;\nusing System.Windows.Media;\n\nnamespace WpfColorFontDialog\n{\n\tpublic class FontColor\n\t{\n\t\tpublic SolidColorBrush Brush\n\t\t{\n\t\t\tget;\n\t\t\tset;\n\t\t}\n\n\t\tpublic string Name\n\t\t{\n\t\t\tget;\n\t\t\tset;\n\t\t}\n\n\t\tpublic FontColor(string name, SolidColorBrush brush)\n\t\t{\n\t\t\tthis.Name = name;\n\t\t\tthis.Brush = brush;\n\t\t}\n\n\t\tpublic override bool Equals(object obj)\n\t\t{\n\t\t\tif (obj == null)\n\t\t\t{\n\t\t\t\treturn false;\n\t\t\t}\n\t\t\tFontColor p = obj as FontColor;\n\t\t\tif (p == null)\n\t\t\t{\n\t\t\t\treturn false;\n\t\t\t}\n\t\t\tif (this.Name != p.Name)\n\t\t\t{\n\t\t\t\treturn false;\n\t\t\t}\n\t\t\treturn this.Brush.Equals(p.Brush);\n\t\t}\n\n\t\tpublic bool Equals(FontColor p)\n\t\t{\n\t\t\tif (p == null)\n\t\t\t{\n\t\t\t\treturn false;\n\t\t\t}\n\t\t\tif (this.Name != p.Name)\n\t\t\t{\n\t\t\t\treturn false;\n\t\t\t}\n\t\t\treturn this.Brush.Equals(p.Brush);\n\t\t}\n\n\t\tpublic override int GetHashCode()\n\t\t{\n\t\t\treturn base.GetHashCode();\n\t\t}\n\n\t\tpublic override string ToString()\n\t\t{\n\t\t\tstring[] name = new string[] { \"FontColor [Color=\", this.Name, \", \", this.Brush.ToString(), \"]\" };\n\t\t\treturn string.Concat(name);\n\t\t}\n\t}\n}"], ["/LLPlayer/FlyleafLib/Controls/WPF/RelayCommand.cs", "using System;\nusing System.Windows.Input;\n\nnamespace FlyleafLib.Controls.WPF;\n\npublic class RelayCommand : ICommand\n{\n private Action execute;\n\n private Predicate canExecute;\n\n private event EventHandler CanExecuteChangedInternal;\n\n public RelayCommand(Action execute) : this(execute, DefaultCanExecute) { }\n\n public RelayCommand(Action execute, Predicate canExecute)\n {\n this.execute = execute ?? throw new ArgumentNullException(\"execute\");\n this.canExecute = canExecute ?? throw new ArgumentNullException(\"canExecute\");\n }\n\n public event EventHandler CanExecuteChanged\n {\n add\n {\n CommandManager.RequerySuggested += value;\n CanExecuteChangedInternal += value;\n }\n\n remove\n {\n CommandManager.RequerySuggested -= value;\n CanExecuteChangedInternal -= value;\n }\n }\n\n private static bool DefaultCanExecute(object parameter) => true;\n public bool CanExecute(object parameter) => canExecute != null && canExecute(parameter);\n\n public void Execute(object parameter) => execute(parameter);\n\n public void OnCanExecuteChanged()\n {\n var handler = CanExecuteChangedInternal;\n handler?.Invoke(this, EventArgs.Empty);\n //CommandManager.InvalidateRequerySuggested();\n }\n\n public void Destroy()\n {\n canExecute = _ => false;\n execute = _ => { return; };\n }\n}\n"], ["/LLPlayer/LLPlayer/Views/CheatSheetDialog.xaml.cs", "using System.Globalization;\nusing System.Windows;\nusing System.Windows.Controls;\nusing System.Windows.Data;\nusing System.Windows.Input;\nusing LLPlayer.ViewModels;\n\nnamespace LLPlayer.Views;\n\npublic partial class CheatSheetDialog : UserControl\n{\n public CheatSheetDialog()\n {\n InitializeComponent();\n\n DataContext = ((App)Application.Current).Container.Resolve();\n }\n\n private void OnLoaded(object sender, RoutedEventArgs e)\n {\n Window? window = Window.GetWindow(this);\n window!.CommandBindings.Add(new CommandBinding(ApplicationCommands.Find, OnFindExecuted));\n }\n\n private void OnFindExecuted(object sender, ExecutedRoutedEventArgs e)\n {\n SearchBox.Focus();\n SearchBox.SelectAll();\n e.Handled = true;\n }\n}\n\n[ValueConversion(typeof(int), typeof(Visibility))]\npublic class CountToVisibilityConverter : IValueConverter\n{\n public object Convert(object value, Type targetType, object parameter, CultureInfo culture)\n {\n if (int.TryParse(value.ToString(), out var count))\n {\n return count == 0 ? Visibility.Collapsed : Visibility.Visible;\n }\n\n return Visibility.Visible;\n }\n\n public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)\n {\n throw new NotImplementedException();\n }\n}\n"], ["/LLPlayer/WpfColorFontDialog/FontInfo.cs", "using System;\nusing System.Runtime.CompilerServices;\nusing System.Text;\nusing System.Windows;\nusing System.Windows.Controls;\nusing System.Windows.Media;\n\nnamespace WpfColorFontDialog\n{\n\tpublic class FontInfo\n\t{\n\t\tpublic SolidColorBrush BrushColor\n\t\t{\n\t\t\tget;\n\t\t\tset;\n\t\t}\n\n\t\tpublic FontColor Color\n\t\t{\n\t\t\tget\n\t\t\t{\n\t\t\t\treturn AvailableColors.GetFontColor(this.BrushColor);\n\t\t\t}\n\t\t}\n\n\t\tpublic FontFamily Family\n\t\t{\n\t\t\tget;\n\t\t\tset;\n\t\t}\n\n\t\tpublic double Size\n\t\t{\n\t\t\tget;\n\t\t\tset;\n\t\t}\n\n\t\tpublic FontStretch Stretch\n\t\t{\n\t\t\tget;\n\t\t\tset;\n\t\t}\n\n\t\tpublic FontStyle Style\n\t\t{\n\t\t\tget;\n\t\t\tset;\n\t\t}\n\n\t\tpublic FamilyTypeface Typeface\n\t\t{\n\t\t\tget\n\t\t\t{\n\t\t\t\tFamilyTypeface ftf = new FamilyTypeface()\n\t\t\t\t{\n\t\t\t\t\tStretch = this.Stretch,\n\t\t\t\t\tWeight = this.Weight,\n\t\t\t\t\tStyle = this.Style\n\t\t\t\t};\n\t\t\t\treturn ftf;\n\t\t\t}\n\t\t}\n\n\t\tpublic FontWeight Weight\n\t\t{\n\t\t\tget;\n\t\t\tset;\n\t\t}\n\n\t\tpublic FontInfo()\n\t\t{\n\t\t}\n\n\t\tpublic FontInfo(FontFamily fam, double sz, FontStyle style, FontStretch strc, FontWeight weight, SolidColorBrush c)\n\t\t{\n\t\t\tthis.Family = fam;\n\t\t\tthis.Size = sz;\n\t\t\tthis.Style = style;\n\t\t\tthis.Stretch = strc;\n\t\t\tthis.Weight = weight;\n\t\t\tthis.BrushColor = c;\n\t\t}\n\n\t\tpublic static void ApplyFont(Control control, FontInfo font)\n\t\t{\n\t\t\tcontrol.FontFamily = font.Family;\n\t\t\tcontrol.FontSize = font.Size;\n\t\t\tcontrol.FontStyle = font.Style;\n\t\t\tcontrol.FontStretch = font.Stretch;\n\t\t\tcontrol.FontWeight = font.Weight;\n\t\t\tcontrol.Foreground = font.BrushColor;\n\t\t}\n\n\t\tpublic static FontInfo GetControlFont(Control control)\n\t\t{\n\t\t\tFontInfo font = new FontInfo()\n\t\t\t{\n\t\t\t\tFamily = control.FontFamily,\n\t\t\t\tSize = control.FontSize,\n\t\t\t\tStyle = control.FontStyle,\n\t\t\t\tStretch = control.FontStretch,\n\t\t\t\tWeight = control.FontWeight,\n\t\t\t\tBrushColor = (SolidColorBrush)control.Foreground\n\t\t\t};\n\t\t\treturn font;\n\t\t}\n\n\t\tpublic static string TypefaceToString(FamilyTypeface ttf)\n\t\t{\n\t\t\tStringBuilder sb = new StringBuilder(ttf.Stretch.ToString());\n\t\t\tsb.Append(\"-\");\n\t\t\tsb.Append(ttf.Weight.ToString());\n\t\t\tsb.Append(\"-\");\n\t\t\tsb.Append(ttf.Style.ToString());\n\t\t\treturn sb.ToString();\n\t\t}\n\t}\n}"], ["/LLPlayer/LLPlayer/Views/FlyleafOverlay.xaml.cs", "using System.Windows;\nusing System.Windows.Controls;\nusing LLPlayer.ViewModels;\n\nnamespace LLPlayer.Views;\n\npublic partial class FlyleafOverlay : UserControl\n{\n private FlyleafOverlayVM VM => (FlyleafOverlayVM)DataContext;\n\n public FlyleafOverlay()\n {\n InitializeComponent();\n\n DataContext = ((App)Application.Current).Container.Resolve();\n }\n\n private void FlyleafOverlay_OnSizeChanged(object sender, SizeChangedEventArgs e)\n {\n if (e.HeightChanged)\n {\n // The height of MainWindow cannot be used because it includes the title bar,\n // so the height is obtained here and passed on.\n double heightDiff = Math.Abs(e.NewSize.Height - e.PreviousSize.Height);\n\n if (heightDiff >= 1.0)\n {\n VM.FL.Config.ScreenWidth = e.NewSize.Width;\n VM.FL.Config.ScreenHeight = e.NewSize.Height;\n }\n }\n }\n}\n"], ["/LLPlayer/LLPlayer/Extensions/FocusBehavior.cs", "using System.Windows;\nusing System.Windows.Controls;\nusing System.Windows.Threading;\n\nnamespace LLPlayer.Extensions;\n\npublic static class FocusBehavior\n{\n public static readonly DependencyProperty IsFocusedProperty =\n DependencyProperty.RegisterAttached(\n \"IsFocused\",\n typeof(bool),\n typeof(FocusBehavior),\n new UIPropertyMetadata(false, OnIsFocusedChanged));\n\n public static bool GetIsFocused(DependencyObject obj) =>\n (bool)obj.GetValue(IsFocusedProperty);\n\n public static void SetIsFocused(DependencyObject obj, bool value) =>\n obj.SetValue(IsFocusedProperty, value);\n\n private static void OnIsFocusedChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)\n {\n if (!(d is UIElement element) || !(e.NewValue is bool isFocused) || !isFocused)\n return;\n\n // Set focus to element\n element.Dispatcher.BeginInvoke(() =>\n {\n element.Focus();\n if (element is TextBox tb)\n {\n // if TextBox, then select text\n tb.SelectAll();\n //tb.CaretIndex = tb.Text.Length;\n }\n }, DispatcherPriority.Input);\n }\n}\n"], ["/LLPlayer/LLPlayer/Controls/Settings/SettingsAudio.xaml.cs", "using System.Windows;\nusing System.Windows.Controls;\nusing FlyleafLib;\nusing LLPlayer.Extensions;\nusing LLPlayer.Services;\nusing LLPlayer.Views;\n\nnamespace LLPlayer.Controls.Settings;\n\npublic partial class SettingsAudio : UserControl\n{\n public SettingsAudio()\n {\n InitializeComponent();\n\n DataContext = ((App)Application.Current).Container.Resolve();\n }\n}\n\npublic class SettingsAudioVM : Bindable\n{\n private readonly IDialogService _dialogService;\n public FlyleafManager FL { get; }\n\n public SettingsAudioVM(FlyleafManager fl, IDialogService dialogService)\n {\n _dialogService = dialogService;\n FL = fl;\n }\n\n public DelegateCommand? CmdConfigureLanguage => field ??= new(() =>\n {\n DialogParameters p = new()\n {\n { \"languages\", FL.PlayerConfig.Audio.Languages }\n };\n\n _dialogService.ShowDialog(nameof(SelectLanguageDialog), p, result =>\n {\n List updated = result.Parameters.GetValue>(\"languages\");\n\n if (!FL.PlayerConfig.Audio.Languages.SequenceEqual(updated))\n {\n FL.PlayerConfig.Audio.Languages = updated;\n }\n });\n });\n}\n"], ["/LLPlayer/LLPlayer/Extensions/HyperLinkHelper.cs", "using System.Diagnostics;\nusing System.Windows;\nusing System.Windows.Documents;\nusing System.Windows.Navigation;\n\nnamespace LLPlayer.Extensions;\n\npublic static class HyperlinkHelper\n{\n public static readonly DependencyProperty OpenInBrowserProperty =\n DependencyProperty.RegisterAttached(\n \"OpenInBrowser\",\n typeof(bool),\n typeof(HyperlinkHelper),\n new PropertyMetadata(false, OnOpenInBrowserChanged));\n\n public static bool GetOpenInBrowser(DependencyObject obj)\n {\n return (bool)obj.GetValue(OpenInBrowserProperty);\n }\n\n public static void SetOpenInBrowser(DependencyObject obj, bool value)\n {\n obj.SetValue(OpenInBrowserProperty, value);\n }\n\n private static void OnOpenInBrowserChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)\n {\n if (d is Hyperlink hyperlink)\n {\n bool newValue = (bool)e.NewValue;\n if (newValue)\n {\n hyperlink.RequestNavigate += OnRequestNavigate;\n }\n else\n {\n hyperlink.RequestNavigate -= OnRequestNavigate;\n }\n }\n }\n\n private static void OnRequestNavigate(object sender, RequestNavigateEventArgs e)\n {\n OpenUrlInBrowser(e.Uri.AbsoluteUri);\n e.Handled = true;\n }\n\n public static void OpenUrlInBrowser(string url)\n {\n Process.Start(new ProcessStartInfo\n {\n FileName = url,\n UseShellExecute = true\n });\n }\n}\n"], ["/LLPlayer/FlyleafLib/Controls/WPF/Converters.cs", "using System.Globalization;\nusing System.Windows.Data;\n\nnamespace FlyleafLib.Controls.WPF;\n\n[ValueConversion(typeof(long), typeof(TimeSpan))]\npublic class TicksToTimeSpanConverter : IValueConverter\n{\n public object Convert(object value, Type targetType, object parameter, CultureInfo culture) => new TimeSpan((long)value);\n public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture) => ((TimeSpan)value).Ticks;\n}\n\n[ValueConversion(typeof(long), typeof(string))]\npublic class TicksToTimeConverter : IValueConverter\n{\n public object Convert(object value, Type targetType, object parameter, CultureInfo culture) => new TimeSpan((long)value).ToString(@\"hh\\:mm\\:ss\");\n public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture) => throw new NotImplementedException();\n}\n\n[ValueConversion(typeof(long), typeof(double))]\npublic class TicksToSecondsConverter : IValueConverter\n{\n public object Convert(object value, Type targetType, object parameter, CultureInfo culture) => (long)value / 10000000.0;\n\n public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture) => (long)((double)value * 10000000);\n}\n\n[ValueConversion(typeof(long), typeof(int))]\npublic class TicksToMilliSecondsConverter : IValueConverter\n{\n public object Convert(object value, Type targetType, object parameter, CultureInfo culture) => (int)((long)value / 10000);\n\n public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture) => long.Parse(value.ToString()) * 10000;\n}\n\n[ValueConversion(typeof(AspectRatio), typeof(string))]\npublic class StringToRationalConverter : IValueConverter\n{\n public object Convert(object value, Type targetType, object parameter, CultureInfo culture) => value.ToString();\n\n public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture) => new AspectRatio(value.ToString());\n}\n"], ["/LLPlayer/FlyleafLib/MediaPlayer/Translation/TranslateChatConfig.cs", "namespace FlyleafLib.MediaPlayer.Translation;\n\npublic class TranslateChatConfig : NotifyPropertyChanged\n{\n public const string DefaultPromptOneByOne =\n \"\"\"\n You are a professional subtitle translator, translate from {source_lang} to {target_lang}, keep sentences in {target_lang} as they are, censoring of translations is prohibited, return only the translated text without the sent text or notes or comments or anything:\n\n {source_text}\n \"\"\";\n\n public const string DefaultPromptKeepContext =\n \"\"\"\n You are a professional subtitle translator.\n I will send the text of the subtitles of the video one at a time.\n Please translate the text while taking into account the context of the previous text.\n\n Translate from {source_lang} to {target_lang}.\n Return only the translated text without the sent text or notes or comments or anything.\n Keep sentences in {target_lang} as they are.\n Censoring of translations is prohibited.\n \"\"\";\n\n public string PromptOneByOne { get; set => Set(ref field, value); } = DefaultPromptOneByOne.ReplaceLineEndings(\"\\n\");\n\n public string PromptKeepContext { get; set => Set(ref field, value); } = DefaultPromptKeepContext.ReplaceLineEndings(\"\\n\");\n\n public ChatTranslateMethod TranslateMethod { get; set => Set(ref field, value); } = ChatTranslateMethod.KeepContext;\n\n public int SubtitleContextCount { get; set => Set(ref field, value); } = 6;\n\n public ChatContextRetainPolicy ContextRetainPolicy { get; set => Set(ref field, value); } = ChatContextRetainPolicy.Reset;\n\n public bool IncludeTargetLangRegion { get; set => Set(ref field, value); } = true;\n}\n\npublic enum ChatTranslateMethod\n{\n KeepContext,\n OneByOne\n}\n\npublic enum ChatContextRetainPolicy\n{\n Reset,\n KeepSize\n}\n"], ["/LLPlayer/FlyleafLib/MediaFramework/MediaPlaylist/Session.cs", "namespace FlyleafLib.MediaFramework.MediaPlaylist;\n\npublic class Session\n{\n public string Url { get; set; }\n public int PlaylistItem { get; set; } = -1;\n\n public int ExternalAudioStream { get; set; } = -1;\n public int ExternalVideoStream { get; set; } = -1;\n public string ExternalSubtitlesUrl { get; set; }\n\n public int AudioStream { get; set; } = -1;\n public int VideoStream { get; set; } = -1;\n public int SubtitlesStream { get; set; } = -1;\n\n public long CurTime { get; set; }\n\n public long AudioDelay { get; set; }\n public long SubtitlesDelay { get; set; }\n\n internal bool isReopen; // temp fix for opening existing playlist item as a new session (should not re-initialize - is like switch)\n\n //public SavedSession() { }\n //public SavedSession(int extVideoStream, int videoStream, int extAudioStream, int audioStream, int extSubtitlesStream, int subtitlesStream, long curTime, long audioDelay, long subtitlesDelay)\n //{\n // Update(extVideoStream, videoStream, extAudioStream, audioStream, extSubtitlesStream, subtitlesStream, curTime, audioDelay, subtitlesDelay);\n //}\n //public void Update(int extVideoStream, int videoStream, int extAudioStream, int audioStream, int extSubtitlesStream, int subtitlesStream, long curTime, long audioDelay, long subtitlesDelay)\n //{\n // ExternalVideoStream = extVideoStream; VideoStream = videoStream;\n // ExternalAudioStream = extAudioStream; AudioStream = audioStream;\n // ExternalSubtitlesStream = extSubtitlesStream; SubtitlesStream = subtitlesStream;\n // CurTime = curTime; AudioDelay = audioDelay; SubtitlesDelay = subtitlesDelay;\n //}\n}\n"], ["/LLPlayer/LLPlayer/Extensions/TextBoxMiscHelper.cs", "using System.Text.RegularExpressions;\nusing System.Windows;\nusing System.Windows.Controls;\nusing System.Windows.Input;\n\nnamespace LLPlayer.Extensions;\n\npublic static class TextBoxMiscHelper\n{\n public static bool GetIsHexValidationEnabled(DependencyObject obj)\n {\n return (bool)obj.GetValue(IsHexValidationEnabledProperty);\n }\n\n public static void SetIsHexValidationEnabled(DependencyObject obj, bool value)\n {\n obj.SetValue(IsHexValidationEnabledProperty, value);\n }\n\n public static readonly DependencyProperty IsHexValidationEnabledProperty =\n DependencyProperty.RegisterAttached(\n \"IsHexValidationEnabled\",\n typeof(bool),\n typeof(TextBoxMiscHelper),\n new UIPropertyMetadata(false, OnIsHexValidationEnabledChanged));\n\n private static void OnIsHexValidationEnabledChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)\n {\n if (d is TextBox textBox)\n {\n if ((bool)e.NewValue)\n {\n textBox.PreviewTextInput += OnPreviewTextInput;\n }\n else\n {\n textBox.PreviewTextInput -= OnPreviewTextInput;\n }\n }\n }\n\n private static void OnPreviewTextInput(object sender, TextCompositionEventArgs e)\n {\n e.Handled = !Regex.IsMatch(e.Text, \"^[0-9a-f]+$\", RegexOptions.IgnoreCase);\n }\n}\n"], ["/LLPlayer/FlyleafLib/MediaFramework/MediaStream/DataStream.cs", "using FlyleafLib.MediaFramework.MediaDemuxer;\n\nnamespace FlyleafLib.MediaFramework.MediaStream;\n\npublic unsafe class DataStream : StreamBase\n{\n\n public DataStream() { }\n public DataStream(Demuxer demuxer, AVStream* st) : base(demuxer, st)\n {\n Demuxer = demuxer;\n AVStream = st;\n Refresh();\n }\n\n public override void Refresh()\n {\n base.Refresh();\n }\n\n public override string GetDump()\n => $\"[{Type} #{StreamIndex}] {CodecID}\";\n}\n"], ["/LLPlayer/LLPlayer/Views/SettingsDialog.xaml.cs", "using System.Windows;\nusing System.Windows.Controls;\nusing LLPlayer.Controls.Settings;\nusing LLPlayer.ViewModels;\n\nnamespace LLPlayer.Views;\n\npublic partial class SettingsDialog : UserControl\n{\n public SettingsDialog()\n {\n InitializeComponent();\n\n DataContext = ((App)Application.Current).Container.Resolve();\n }\n\n private void SettingsTreeView_OnSelectedItemChanged(object sender, RoutedPropertyChangedEventArgs e)\n {\n if (SettingsContent == null)\n {\n return;\n }\n\n if (SettingsTreeView.SelectedItem is TreeViewItem selectedItem)\n {\n string? tag = selectedItem.Tag as string;\n switch (tag)\n {\n case nameof(SettingsPlayer):\n SettingsContent.Content = new SettingsPlayer();\n break;\n\n case nameof(SettingsAudio):\n SettingsContent.Content = new SettingsAudio();\n break;\n\n case nameof(SettingsVideo):\n SettingsContent.Content = new SettingsVideo();\n break;\n\n case nameof(SettingsSubtitles):\n SettingsContent.Content = new SettingsSubtitles();\n break;\n\n case nameof(SettingsSubtitlesPS):\n SettingsContent.Content = new SettingsSubtitlesPS();\n break;\n\n case nameof(SettingsSubtitlesASR):\n SettingsContent.Content = new SettingsSubtitlesASR();\n break;\n\n case nameof(SettingsSubtitlesOCR):\n SettingsContent.Content = new SettingsSubtitlesOCR();\n break;\n\n case nameof(SettingsSubtitlesTrans):\n SettingsContent.Content = new SettingsSubtitlesTrans();\n break;\n\n case nameof(SettingsSubtitlesAction):\n SettingsContent.Content = new SettingsSubtitlesAction();\n break;\n\n case nameof(SettingsKeys):\n SettingsContent.Content = new SettingsKeys();\n break;\n\n case nameof(SettingsKeysOffset):\n SettingsContent.Content = new SettingsKeysOffset();\n break;\n\n case nameof(SettingsMouse):\n SettingsContent.Content = new SettingsMouse();\n break;\n\n case nameof(SettingsThemes):\n SettingsContent.Content = new SettingsThemes();\n break;\n\n case nameof(SettingsPlugins):\n SettingsContent.Content = new SettingsPlugins();\n break;\n\n case nameof(SettingsAbout):\n SettingsContent.Content = new SettingsAbout();\n break;\n }\n }\n }\n}\n"], ["/LLPlayer/WpfColorFontDialog/FontSizeListBoxItemToDoubleConverter.cs", "using System;\nusing System.Globalization;\nusing System.Windows.Controls;\nusing System.Windows.Data;\n\nnamespace WpfColorFontDialog\n{\n\tpublic class FontSizeListBoxItemToDoubleConverter : IValueConverter\n\t{\n\t\tpublic FontSizeListBoxItemToDoubleConverter()\n\t\t{\n\t\t}\n\n\t\tobject System.Windows.Data.IValueConverter.Convert(object value, Type targetType, object parameter, CultureInfo culture)\n\t\t{\n string str = value.ToString();\n try\n {\n return double.Parse(value.ToString());\n }\n catch(FormatException)\n {\n return 0;\n }\n\n }\n\n\t\tobject System.Windows.Data.IValueConverter.ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)\n\t\t{\n\t\t\tthrow new NotImplementedException();\n\t\t}\n\t}\n}"], ["/LLPlayer/LLPlayer/Resources/PopupMenu.xaml.cs", "using System.Windows;\nusing System.Windows.Controls;\nusing LLPlayer.ViewModels;\n\nnamespace LLPlayer.Resources;\n\npublic partial class PopupMenu : ResourceDictionary\n{\n public PopupMenu()\n {\n InitializeComponent();\n }\n\n private void PopUpMenu_OnOpened(object sender, RoutedEventArgs e)\n {\n // TODO: L: should validate that the clipboard content is a video file?\n bool canPaste = !string.IsNullOrEmpty(Clipboard.GetText());\n MenuPasteUrl.IsEnabled = canPaste;\n\n // Don't hide the seek bar while displaying the context menu\n if (sender is ContextMenu menu && menu.DataContext is FlyleafOverlayVM vm)\n {\n vm.FL.Player.Activity.IsEnabled = false;\n }\n }\n\n private void PopUpMenu_OnClosed(object sender, RoutedEventArgs e)\n {\n if (sender is ContextMenu menu && menu.DataContext is FlyleafOverlayVM vm)\n {\n vm.FL.Player.Activity.IsEnabled = true;\n }\n }\n}\n"], ["/LLPlayer/FlyleafLib/Utils/Disposable.cs", "namespace FlyleafLib;\n\n/// \n/// Anonymous Disposal Pattern\n/// \npublic class Disposable : IDisposable\n{\n public static Disposable Create(Action onDispose) => new(onDispose);\n\n public static Disposable Empty { get; } = new(null);\n\n Action _onDispose;\n Disposable(Action onDispose) => _onDispose = onDispose;\n\n public void Dispose()\n {\n _onDispose?.Invoke();\n _onDispose = null;\n }\n}\n"], ["/LLPlayer/LLPlayer/Views/ErrorDialog.xaml.cs", "using System.Windows;\nusing LLPlayer.ViewModels;\nusing System.Windows.Controls;\nusing System.Windows.Input;\n\nnamespace LLPlayer.Views;\n\npublic partial class ErrorDialog : UserControl\n{\n private ErrorDialogVM VM => (ErrorDialogVM)DataContext;\n\n public ErrorDialog()\n {\n InitializeComponent();\n\n DataContext = ((App)Application.Current).Container.Resolve();\n }\n\n private void FrameworkElement_OnLoaded(object sender, RoutedEventArgs e)\n {\n Keyboard.Focus(sender as IInputElement);\n }\n\n private void ErrorDialog_OnMouseLeftButtonDown(object sender, MouseButtonEventArgs e)\n {\n Keyboard.Focus(sender as IInputElement);\n }\n\n // Topmost dialog, so it should be draggable\n private void Window_MouseDown(object sender, MouseButtonEventArgs e)\n {\n if (sender is not Window window)\n return;\n\n if (e.ChangedButton == MouseButton.Left)\n {\n window.DragMove();\n }\n }\n\n // Make TextBox uncopyable\n private void TextBox_PreviewMouseDown(object sender, ExecutedRoutedEventArgs e)\n {\n if (e.Command == ApplicationCommands.Copy ||\n e.Command == ApplicationCommands.Cut ||\n e.Command == ApplicationCommands.Paste)\n {\n e.Handled = true;\n\n if (e.Command == ApplicationCommands.Copy)\n {\n // instead trigger copy command\n VM.CmdCopyMessage.Execute();\n }\n }\n }\n}\n"], ["/LLPlayer/WpfColorFontDialog/ColorPickerViewModel.cs", "using System;\nusing System.Collections.ObjectModel;\nusing System.ComponentModel;\nusing System.Threading;\nusing System.Windows.Media;\n\nnamespace WpfColorFontDialog\n{\n\tinternal class ColorPickerViewModel : INotifyPropertyChanged\n\t{\n\t\tprivate ReadOnlyCollection roFontColors;\n\n\t\tprivate FontColor selectedFontColor;\n\n\t\tpublic ReadOnlyCollection FontColors\n\t\t{\n\t\t\tget\n\t\t\t{\n\t\t\t\treturn this.roFontColors;\n\t\t\t}\n\t\t}\n\n\t\tpublic FontColor SelectedFontColor\n\t\t{\n\t\t\tget\n\t\t\t{\n\t\t\t\treturn this.selectedFontColor;\n\t\t\t}\n\t\t\tset\n\t\t\t{\n\t\t\t\tif (this.selectedFontColor == value)\n\t\t\t\t{\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t\tthis.selectedFontColor = value;\n\t\t\t\tthis.OnPropertyChanged(\"SelectedFontColor\");\n\t\t\t}\n\t\t}\n\n\t\tpublic ColorPickerViewModel()\n\t\t{\n\t\t\tthis.selectedFontColor = AvailableColors.GetFontColor(Colors.Black);\n\t\t\tthis.roFontColors = new ReadOnlyCollection(new AvailableColors());\n\t\t}\n\n\t\tprivate void OnPropertyChanged(string propertyName)\n\t\t{\n\t\t\tif (this.PropertyChanged != null)\n\t\t\t{\n\t\t\t\tthis.PropertyChanged(this, new PropertyChangedEventArgs(propertyName));\n\t\t\t}\n\t\t}\n\n\t\tpublic event PropertyChangedEventHandler PropertyChanged;\n\t}\n}"], ["/LLPlayer/LLPlayer/Extensions/Bindable.cs", "using System.ComponentModel;\nusing System.Runtime.CompilerServices;\n\nnamespace LLPlayer.Extensions;\n\npublic class Bindable : INotifyPropertyChanged\n{\n public event PropertyChangedEventHandler? PropertyChanged;\n\n protected virtual void OnPropertyChanged([CallerMemberName] string? propertyName = null)\n {\n PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));\n }\n\n protected bool Set(ref T field, T value, [CallerMemberName] string? propertyName = null)\n {\n if (EqualityComparer.Default.Equals(field, value)) return false;\n field = value;\n OnPropertyChanged(propertyName);\n return true;\n }\n}\n"], ["/LLPlayer/FlyleafLibTests/Utils/SubtitleTextUtilTests.cs", "using FluentAssertions;\n\nnamespace FlyleafLib;\n\npublic class SubtitleTextUtilTests\n{\n [Theory]\n [InlineData(\"\", \"\")]\n [InlineData(\" \", \" \")] // Assume trim is done beforehand\n [InlineData(\"Hello\", \"Hello\")]\n [InlineData(\"Hello\\nWorld\", \"Hello World\")]\n [InlineData(\"Hello\\r\\nWorld\", \"Hello World\")]\n [InlineData(\"Hello\\n\\nWorld\", \"Hello World\")]\n [InlineData(\"Hello\\r\\n\\r\\nWorld\", \"Hello World\")]\n [InlineData(\"Hello\\n \\nWorld\", \"Hello World\")]\n\n [InlineData(\"- Hello\\n- How are you?\", \"- Hello\\n- How are you?\")]\n [InlineData(\"- Hello\\n - How are you?\", \"- Hello - How are you?\")]\n [InlineData(\"- Hello\\r- How are you?\", \"- Hello\\r- How are you?\")]\n [InlineData(\"- Hello\\n\\n- How are you?\", \"- Hello\\n\\n- How are you?\")]\n [InlineData(\"- Hello\\r\\n- How are you?\", \"- Hello\\r\\n- How are you?\")]\n [InlineData(\"- Hello\\nWorld\", \"- Hello World\")]\n [InlineData(\"- こんにちは\\n- 世界\", \"- こんにちは\\n- 世界\")]\n [InlineData(\"- こんにちは\\n世界\", \"- こんにちは 世界\")]\n\n [InlineData(\"こんにちは\\n世界\", \"こんにちは 世界\")]\n [InlineData(\"🙂\\n🙃\", \"🙂 🙃\")]\n [InlineData(\"Hello\\nWorld\", \"Hello World\")]\n\n [InlineData(\"- Hello\\n- Good\\nbye\", \"- Hello\\n- Good bye\")]\n [InlineData(\"- Hello\\nWorld\\n- Good\\nbye\", \"- Hello World\\n- Good bye\")]\n\n [InlineData(\"Hello\\n- Good\\n- bye\", \"Hello - Good - bye\")]\n [InlineData(\" -Hello\\n- Good\\n- bye\", \" -Hello - Good - bye\")]\n\n [InlineData(\"- Hello\\n- aa-bb-cc dd\", \"- Hello\\n- aa-bb-cc dd\")]\n [InlineData(\"- Hello\\naa-bb-cc dd\", \"- Hello aa-bb-cc dd\")]\n\n [InlineData(\"- Hello\\n- Goodbye\", \"- Hello\\n- Goodbye\")] // hyphen\n [InlineData(\"– Hello\\n– Goodbye\", \"– Hello\\n– Goodbye\")] // en dash\n [InlineData(\"- Hello\\n– Goodbye\", \"- Hello – Goodbye\")] // hyphen + en dash\n\n public void FlattenUnlessAllDash_ShouldReturnExpected(string input, string expected)\n {\n string result = SubtitleTextUtil.FlattenText(input);\n result.Should().Be(expected);\n }\n}\n"], ["/LLPlayer/FlyleafLib/Controls/WPF/PlayerDebug.xaml.cs", "using System.Windows;\nusing System.Windows.Controls;\nusing System.Windows.Media;\n\nusing FlyleafLib.MediaPlayer;\n\nnamespace FlyleafLib.Controls.WPF;\n\npublic partial class PlayerDebug : UserControl\n{\n public Player Player\n {\n get => (Player)GetValue(PlayerProperty);\n set => SetValue(PlayerProperty, value);\n }\n\n public static readonly DependencyProperty PlayerProperty =\n DependencyProperty.Register(\"Player\", typeof(Player), typeof(PlayerDebug), new PropertyMetadata(null));\n\n public Brush BoxColor\n {\n get => (Brush)GetValue(BoxColorProperty);\n set => SetValue(BoxColorProperty, value);\n }\n\n public static readonly DependencyProperty BoxColorProperty =\n DependencyProperty.Register(\"BoxColor\", typeof(Brush), typeof(PlayerDebug), new PropertyMetadata(new SolidColorBrush((Color)ColorConverter.ConvertFromString(\"#D0000000\"))));\n\n public Brush HeaderColor\n {\n get => (Brush)GetValue(HeaderColorProperty);\n set => SetValue(HeaderColorProperty, value);\n }\n\n public static readonly DependencyProperty HeaderColorProperty =\n DependencyProperty.Register(\"HeaderColor\", typeof(Brush), typeof(PlayerDebug), new PropertyMetadata(new SolidColorBrush(Colors.LightSalmon)));\n\n public Brush InfoColor\n {\n get => (Brush)GetValue(InfoColorProperty);\n set => SetValue(InfoColorProperty, value);\n }\n\n public static readonly DependencyProperty InfoColorProperty =\n DependencyProperty.Register(\"InfoColor\", typeof(Brush), typeof(PlayerDebug), new PropertyMetadata(new SolidColorBrush(Colors.LightSteelBlue)));\n\n public Brush ValueColor\n {\n get => (Brush)GetValue(ValueColorProperty);\n set => SetValue(ValueColorProperty, value);\n }\n\n public static readonly DependencyProperty ValueColorProperty =\n DependencyProperty.Register(\"ValueColor\", typeof(Brush), typeof(PlayerDebug), new PropertyMetadata(new SolidColorBrush(Colors.White)));\n\n public PlayerDebug() => InitializeComponent();\n}\n"], ["/LLPlayer/LLPlayer/Resources/Validators.xaml.cs", "using System.Globalization;\nusing System.Text.RegularExpressions;\nusing System.Windows;\nusing System.Windows.Controls;\n\nnamespace LLPlayer.Resources;\n\npublic partial class Validators : ResourceDictionary\n{\n public Validators()\n {\n InitializeComponent();\n }\n}\n\npublic class ColorHexRule : ValidationRule\n{\n public override ValidationResult Validate(object? value, CultureInfo cultureInfo)\n {\n if (value != null && Regex.IsMatch(value.ToString() ?? string.Empty, \"^[0-9a-f]{6}$\", RegexOptions.IgnoreCase))\n {\n return new ValidationResult(true, null);\n }\n\n return new ValidationResult(false, \"Invalid\");\n }\n}\n"], ["/LLPlayer/FlyleafLib/MediaFramework/MediaDevice/DeviceStreamBase.cs", "namespace FlyleafLib.MediaFramework.MediaDevice;\n\npublic class DeviceStreamBase\n{\n public string DeviceFriendlyName { get; }\n public string Url { get; protected set; }\n\n public DeviceStreamBase(string deviceFriendlyName) => DeviceFriendlyName = deviceFriendlyName;\n}\n"], ["/LLPlayer/LLPlayer/Views/SelectLanguageDialog.xaml.cs", "using LLPlayer.ViewModels;\nusing System.Windows;\nusing System.Windows.Controls;\nusing System.Windows.Input;\n\nnamespace LLPlayer.Views;\n\npublic partial class SelectLanguageDialog : UserControl\n{\n public SelectLanguageDialog()\n {\n InitializeComponent();\n\n DataContext = ((App)Application.Current).Container.Resolve();\n }\n\n private void OnLoaded(object sender, RoutedEventArgs e)\n {\n Window? window = Window.GetWindow(this);\n window!.CommandBindings.Add(new CommandBinding(ApplicationCommands.Find, OnFindExecuted));\n }\n\n private void OnFindExecuted(object sender, ExecutedRoutedEventArgs e)\n {\n SearchBox.Focus();\n SearchBox.SelectAll();\n e.Handled = true;\n }\n}\n"], ["/LLPlayer/LLPlayer/Controls/Settings/SettingsVideo.xaml.cs", "using System.Text.RegularExpressions;\nusing System.Windows.Controls;\nusing System.Windows.Input;\n\nnamespace LLPlayer.Controls.Settings;\n\npublic partial class SettingsVideo : UserControl\n{\n public SettingsVideo()\n {\n InitializeComponent();\n }\n\n private void ValidationRatio(object sender, TextCompositionEventArgs e)\n {\n e.Handled = !Regex.IsMatch(e.Text, @\"^[0-9\\.\\,\\/\\:]+$\");\n }\n}\n"], ["/LLPlayer/FlyleafLib/MediaFramework/MediaFrame/VideoFrame.cs", "using Vortice.Direct3D11;\n\nusing ID3D11Texture2D = Vortice.Direct3D11.ID3D11Texture2D;\n\nnamespace FlyleafLib.MediaFramework.MediaFrame;\n\npublic unsafe class VideoFrame : FrameBase\n{\n public ID3D11Texture2D[] textures; // Planes\n public ID3D11ShaderResourceView[] srvs; // Views\n\n // Zero-Copy\n public AVFrame* avFrame; // Lets ffmpeg to know that we still need it\n}\n"], ["/LLPlayer/FlyleafLib/Controls/WPF/RelayCommandSimple.cs", "using System;\nusing System.Windows.Input;\n\nnamespace FlyleafLib.Controls.WPF;\n\npublic class RelayCommandSimple : ICommand\n{\n public event EventHandler CanExecuteChanged { add { } remove { } }\n Action execute;\n\n public RelayCommandSimple(Action execute) => this.execute = execute;\n public bool CanExecute(object parameter) => true;\n public void Execute(object parameter) => execute();\n}\n"], ["/LLPlayer/LLPlayer/Views/WhisperEngineDownloadDialog.xaml.cs", "using System.Windows;\nusing System.Windows.Controls;\nusing LLPlayer.ViewModels;\n\nnamespace LLPlayer.Views;\n\npublic partial class WhisperEngineDownloadDialog : UserControl\n{\n public WhisperEngineDownloadDialog()\n {\n InitializeComponent();\n\n DataContext = ((App)Application.Current).Container.Resolve();\n }\n}\n"], ["/LLPlayer/FlyleafLib/MediaFramework/MediaStream/ExternalAudioStream.cs", "namespace FlyleafLib.MediaFramework.MediaStream;\n\npublic class ExternalAudioStream : ExternalStream\n{\n public int SampleRate { get; set; }\n public string ChannelLayout { get; set; }\n public Language Language { get; set; }\n\n public bool HasVideo { get; set; }\n}\n"], ["/LLPlayer/LLPlayer/Controls/WordClickedEventArgs.cs", "using System.Windows;\n\nnamespace LLPlayer.Controls;\n\npublic class WordClickedEventArgs(RoutedEvent args) : RoutedEventArgs(args)\n{\n public required MouseClick Mouse { get; init; }\n public required string Words { get; init; }\n public required bool IsWord { get; init; }\n public required string Text { get; init; }\n public required bool IsTranslated { get; init; }\n public required int SubIndex { get; init; }\n public required int WordOffset { get; init; }\n\n // For screen subtitles\n public double WordsX { get; init; }\n public double WordsWidth { get; init; }\n\n // For sidebar subtitles\n public FrameworkElement? Sender { get; init; }\n}\n\npublic enum MouseClick\n{\n Left, Right, Middle\n}\n\npublic delegate void WordClickedEventHandler(object sender, WordClickedEventArgs e);\n"], ["/LLPlayer/LLPlayer/Extensions/MyDialogWindow.xaml.cs", "using System.Windows;\nusing LLPlayer.Views;\n\nnamespace LLPlayer.Extensions;\n\npublic partial class MyDialogWindow : Window, IDialogWindow\n{\n public IDialogResult? Result { get; set; }\n\n public MyDialogWindow()\n {\n InitializeComponent();\n\n MainWindow.SetTitleBarDarkMode(this);\n }\n}\n"], ["/LLPlayer/FlyleafLib/MediaFramework/MediaDevice/AudioDeviceStream.cs", "namespace FlyleafLib.MediaFramework.MediaDevice;\n\npublic class AudioDeviceStream : DeviceStreamBase\n{\n public AudioDeviceStream(string deviceName) : base(deviceName) { }\n}\n"], ["/LLPlayer/FlyleafLib/MediaFramework/MediaFrame/AudioFrame.cs", "using System;\n\nnamespace FlyleafLib.MediaFramework.MediaFrame;\n\npublic class AudioFrame : FrameBase\n{\n public IntPtr dataPtr;\n public int dataLen;\n}\n"], ["/LLPlayer/FlyleafLib/MediaFramework/MediaFrame/DataFrame.cs", "namespace FlyleafLib.MediaFramework.MediaFrame;\n\npublic class DataFrame : FrameBase\n{\n public AVCodecID DataCodecId;\n public byte[] Data;\n}\n"], ["/LLPlayer/FlyleafLib/MediaFramework/MediaFrame/FrameBase.cs", "namespace FlyleafLib.MediaFramework.MediaFrame;\n\npublic unsafe class FrameBase\n{\n public long timestamp;\n //public long pts;\n}\n"], ["/LLPlayer/LLPlayer/Views/TesseractDownloadDialog.xaml.cs", "using System.Windows;\nusing System.Windows.Controls;\nusing LLPlayer.ViewModels;\n\nnamespace LLPlayer.Views;\npublic partial class TesseractDownloadDialog : UserControl\n{\n public TesseractDownloadDialog()\n {\n InitializeComponent();\n\n DataContext = ((App)Application.Current).Container.Resolve();\n }\n}\n"], ["/LLPlayer/LLPlayer/Views/SubtitlesDownloaderDialog.xaml.cs", "using System.Windows;\nusing System.Windows.Controls;\nusing LLPlayer.ViewModels;\n\nnamespace LLPlayer.Views;\n\npublic partial class SubtitlesDownloaderDialog : UserControl\n{\n public SubtitlesDownloaderDialog()\n {\n InitializeComponent();\n\n DataContext = ((App)Application.Current).Container.Resolve();\n }\n}\n"], ["/LLPlayer/LLPlayer/Views/SubtitlesExportDialog.xaml.cs", "using System.Windows;\nusing System.Windows.Controls;\nusing LLPlayer.ViewModels;\n\nnamespace LLPlayer.Views;\n\npublic partial class SubtitlesExportDialog : UserControl\n{\n public SubtitlesExportDialog()\n {\n InitializeComponent();\n\n DataContext = ((App)Application.Current).Container.Resolve();\n }\n}\n"], ["/LLPlayer/LLPlayer/Views/WhisperModelDownloadDialog.xaml.cs", "using System.Windows;\nusing System.Windows.Controls;\nusing LLPlayer.ViewModels;\n\nnamespace LLPlayer.Views;\n\npublic partial class WhisperModelDownloadDialog : UserControl\n{\n public WhisperModelDownloadDialog()\n {\n InitializeComponent();\n\n DataContext = ((App)Application.Current).Container.Resolve();\n }\n}\n"], ["/LLPlayer/LLPlayer/Controls/Settings/SettingsThemes.xaml.cs", "using System.Windows.Controls;\n\nnamespace LLPlayer.Controls.Settings;\n\n// TODO: L: Allow manual setting of text color\n// TODO: L: Allow setting of background color and video background color\n\npublic partial class SettingsThemes : UserControl\n{\n public SettingsThemes()\n {\n InitializeComponent();\n }\n}\n"], ["/LLPlayer/LLPlayer/GlobalUsings.cs", "// For some reason, if these are not imported, it cannot be built with anything other than portable for target runtime.\n// Prism import errors occur, so work around this.\nglobal using Prism;\nglobal using Prism.Commands;\nglobal using Prism.DryIoc;\nglobal using Prism.Dialogs;\nglobal using Prism.Ioc;\n"], ["/LLPlayer/LLPlayer/Controls/Settings/SettingsMouse.xaml.cs", "using System.Windows.Controls;\n\nnamespace LLPlayer.Controls.Settings;\n\npublic partial class SettingsMouse : UserControl\n{\n public SettingsMouse()\n {\n InitializeComponent();\n }\n}\n"], ["/LLPlayer/LLPlayer/Controls/Settings/SettingsPlayer.xaml.cs", "using System.Windows.Controls;\n\nnamespace LLPlayer.Controls.Settings;\n\npublic partial class SettingsPlayer : UserControl\n{\n public SettingsPlayer()\n {\n InitializeComponent();\n }\n}\n"], ["/LLPlayer/LLPlayer/Controls/Settings/SettingsKeysOffset.xaml.cs", "using System.Windows.Controls;\n\nnamespace LLPlayer.Controls.Settings;\n\npublic partial class SettingsKeysOffset : UserControl\n{\n public SettingsKeysOffset()\n {\n InitializeComponent();\n }\n}\n"], ["/LLPlayer/LLPlayer/Controls/Settings/SettingsSubtitlesPS.xaml.cs", "using System.Windows.Controls;\n\nnamespace LLPlayer.Controls.Settings;\n\npublic partial class SettingsSubtitlesPS : UserControl\n{\n public SettingsSubtitlesPS()\n {\n InitializeComponent();\n }\n}\n"], ["/LLPlayer/LLPlayer/Controls/Settings/Trans/OpenAIBaseTranslateControl.xaml.cs", "using System.Windows.Controls;\n\nnamespace LLPlayer.Controls.Settings.TransControl;\n\npublic partial class OpenAIBaseTranslateControl : UserControl\n{\n public OpenAIBaseTranslateControl()\n {\n InitializeComponent();\n }\n}\n"], ["/LLPlayer/FlyleafLib/Controls/IHostPlayer.cs", "namespace FlyleafLib.Controls;\n\npublic interface IHostPlayer\n{\n bool Player_CanHideCursor();\n bool Player_GetFullScreen();\n void Player_SetFullScreen(bool value);\n void Player_Disposed();\n}\n"]], "task_instance_info": {"created_time": "2025-08-20 19:03:41", "created_task_model": "DeepSeek-R1", "function_skeleton": "internal void LoadAssemblies () {}", "code_description": "This code segment functions to: Discover and load compatible plugin modules from both the current application and external directories, automatically registering them for runtime integration while handling version tracking and error logging."}, "inference_content": {"inference_model": "DeepSeek-R1", "inference_result": "```c_sharp\n[TASK_BEGIN]\n internal void LoadAssemblies()\n {\n if (string.IsNullOrEmpty(Folder))\n return;\n\n foreach (string file in Directory.GetFiles(Folder, \"*.dll\"))\n {\n try\n {\n Assembly assembly = Assembly.LoadFrom(file);\n LoadPlugin(assembly);\n }\n catch (Exception e)\n {\n Engine.Log.Error($\"[PluginHandler] [Error] Failed to load assembly {file} ({e.Message} {Utils.GetRecInnerException(e)})\");\n }\n }\n }\n[TASK_END]\n```", "inference_time": "2025-08-20 19-03-59"}, "editdistance_info": {"edit_distance": 19.4175, "calculate_time": "2025-08-20 19:03:59", "true_code_clean": "internal void LoadAssemblies()\n {\n LoadPlugin(Assembly.GetExecutingAssembly());\n if (Folder != null && Directory.Exists(Folder))\n {\n string[] dirs = Directory.GetDirectories(Folder);\n foreach(string dir in dirs)\n foreach(string file in Directory.GetFiles(dir, \"*.dll\"))\n LoadPlugin(Assembly.LoadFrom(Path.GetFullPath(file)));\n }\n else\n {\n Engine.Log.Info($\"[PluginHandler] No external plugins found\");\n }\n }", "predict_code_clean": "internal void LoadAssemblies()\n {\n if (string.IsNullOrEmpty(Folder))\n return;\n foreach (string file in Directory.GetFiles(Folder, \"*.dll\"))\n {\n try\n {\n Assembly assembly = Assembly.LoadFrom(file);\n LoadPlugin(assembly);\n }\n catch (Exception e)\n {\n Engine.Log.Error($\"[PluginHandler] [Error] Failed to load assembly {file} ({e.Message} {Utils.GetRecInnerException(e)})\");\n }\n }\n }"}} {"repo_name": "LLPlayer", "file_name": "/LLPlayer/LLPlayer/Extensions/WindowsClipboard.cs", "inference_info": {"prefix_code": "using System.ComponentModel;\nusing System.Runtime.InteropServices;\n\nnamespace LLPlayer.Extensions;\n\n// ref: https://stackoverflow.com/questions/44205260/net-core-copy-to-clipboard\npublic static class WindowsClipboard\n{\n public static void SetText(string text)\n {\n OpenClipboard();\n\n EmptyClipboard();\n IntPtr hGlobal = 0;\n try\n {\n int bytes = (text.Length + 1) * 2;\n hGlobal = Marshal.AllocHGlobal(bytes);\n\n if (hGlobal == 0)\n {\n ThrowWin32();\n }\n\n IntPtr target = GlobalLock(hGlobal);\n\n if (target == 0)\n {\n ThrowWin32();\n }\n\n try\n {\n Marshal.Copy(text.ToCharArray(), 0, target, text.Length);\n }\n finally\n {\n GlobalUnlock(target);\n }\n\n if (SetClipboardData(cfUnicodeText, hGlobal) == 0)\n {\n ThrowWin32();\n }\n\n hGlobal = 0;\n }\n finally\n {\n if (hGlobal != 0)\n {\n Marshal.FreeHGlobal(hGlobal);\n }\n\n CloseClipboard();\n }\n }\n\n ", "suffix_code": "\n\n const uint cfUnicodeText = 13;\n\n static void ThrowWin32()\n {\n throw new Win32Exception(Marshal.GetLastWin32Error());\n }\n\n [DllImport(\"kernel32.dll\", SetLastError = true)]\n static extern IntPtr GlobalLock(IntPtr hMem);\n\n [DllImport(\"kernel32.dll\", SetLastError = true)]\n [return: MarshalAs(UnmanagedType.Bool)]\n static extern bool GlobalUnlock(IntPtr hMem);\n\n [DllImport(\"user32.dll\", SetLastError = true)]\n [return: MarshalAs(UnmanagedType.Bool)]\n static extern bool OpenClipboard(IntPtr hWndNewOwner);\n\n [DllImport(\"user32.dll\", SetLastError = true)]\n [return: MarshalAs(UnmanagedType.Bool)]\n static extern bool CloseClipboard();\n\n [DllImport(\"user32.dll\", SetLastError = true)]\n static extern IntPtr SetClipboardData(uint uFormat, IntPtr data);\n\n [DllImport(\"user32.dll\")]\n static extern bool EmptyClipboard();\n}\n", "middle_code": "public static void OpenClipboard()\n {\n int num = 10;\n while (true)\n {\n if (OpenClipboard(0))\n {\n break;\n }\n if (--num == 0)\n {\n ThrowWin32();\n }\n Thread.Sleep(20);\n }\n }", "code_description": null, "fill_type": "FUNCTION_TYPE", "language_type": "c_sharp", "sub_task_type": null}, "context_code": [["/LLPlayer/FlyleafLib/Utils/NativeMethods.cs", "using System;\nusing System.Drawing;\nusing System.Runtime.InteropServices;\n\nnamespace FlyleafLib;\n\n#pragma warning disable CA1401 // P/Invokes should not be visible\npublic static partial class Utils\n{\n public static class NativeMethods\n {\n static NativeMethods()\n {\n if (IntPtr.Size == 4)\n {\n GetWindowLong = GetWindowLongPtr32;\n SetWindowLong = SetWindowLongPtr32;\n }\n else\n {\n GetWindowLong = GetWindowLongPtr64;\n SetWindowLong = SetWindowLongPtr64;\n }\n\n GetDPI(out DpiX, out DpiY);\n }\n\n public static Func SetWindowLong;\n public static Func GetWindowLong;\n\n [DllImport(\"user32.dll\", EntryPoint = \"GetWindowLong\")]\n public static extern IntPtr GetWindowLongPtr32(IntPtr hWnd, int nIndex);\n\n [DllImport(\"user32.dll\", EntryPoint = \"GetWindowLongPtr\")]\n public static extern IntPtr GetWindowLongPtr64(IntPtr hWnd, int nIndex);\n\n [DllImport(\"user32.dll\", EntryPoint = \"SetWindowLong\")]\n public static extern IntPtr SetWindowLongPtr32(IntPtr hWnd, int nIndex, IntPtr dwNewLong);\n\n [DllImport(\"user32.dll\", EntryPoint = \"SetWindowLongPtr\")] // , SetLastError = true\n public static extern IntPtr SetWindowLongPtr64(IntPtr hWnd, int nIndex, IntPtr dwNewLong);\n\n [DllImport(\"user32.dll\")]\n public static extern IntPtr CallWindowProc(IntPtr lpPrevWndFunc, IntPtr hWnd, uint Msg, IntPtr wParam, IntPtr lParam);\n\n [DllImport(\"comctl32.dll\")]\n public static extern bool SetWindowSubclass(IntPtr hWnd, IntPtr pfnSubclass, UIntPtr uIdSubclass, UIntPtr dwRefData);\n\n [DllImport(\"comctl32.dll\")]\n public static extern bool RemoveWindowSubclass(IntPtr hWnd, IntPtr pfnSubclass, UIntPtr uIdSubclass);\n\n [DllImport(\"comctl32.dll\")]\n public static extern IntPtr DefSubclassProc(IntPtr hWnd, uint msg, IntPtr wParam, IntPtr lParam);\n\n [DllImport(\"user32.dll\")]\n public static extern bool SetWindowPos(IntPtr hWnd, IntPtr hWndInsertAfter, int x, int y, int cx, int cy, UInt32 uFlags);\n\n [DllImport(\"shlwapi.dll\", CharSet = CharSet.Unicode)]\n public static extern int StrCmpLogicalW(string psz1, string psz2);\n\n [DllImport(\"user32.dll\")]\n public static extern int ShowCursor(bool bShow);\n\n [DllImport(\"winmm.dll\", EntryPoint = \"timeBeginPeriod\")]\n public static extern uint TimeBeginPeriod(uint uMilliseconds);\n\n [DllImport(\"winmm.dll\", EntryPoint = \"timeEndPeriod\")]\n public static extern uint TimeEndPeriod(uint uMilliseconds);\n\n [DllImport(\"kernel32.dll\", CharSet = CharSet.Auto)]\n public static extern EXECUTION_STATE SetThreadExecutionState(EXECUTION_STATE esFlags);\n [FlagsAttribute]\n public enum EXECUTION_STATE :uint\n {\n ES_AWAYMODE_REQUIRED = 0x00000040,\n ES_CONTINUOUS = 0x80000000,\n ES_DISPLAY_REQUIRED = 0x00000002,\n ES_SYSTEM_REQUIRED = 0x00000001\n }\n\n [DllImport(\"gdi32.dll\")]\n public static extern IntPtr CreateRectRgn(int nLeftRect, int nTopRect, int nRightRect, int nBottomRect);\n\n [DllImport(\"User32.dll\")]\n public static extern int GetWindowRgn(IntPtr hWnd, IntPtr hRgn);\n\n [DllImport(\"User32.dll\")]\n public static extern int SetWindowRgn(IntPtr hWnd, IntPtr hRgn, bool bRedraw);\n\n [DllImport(\"user32.dll\")]\n public static extern bool GetWindowRect(IntPtr hwnd, ref RECT rectangle);\n\n [DllImport(\"user32.dll\")]\n public static extern bool GetWindowInfo(IntPtr hwnd, ref WINDOWINFO pwi);\n\n [DllImport(\"user32.dll\")]\n public static extern void SetParent(IntPtr hWndChild, IntPtr hWndNewParent);\n\n [DllImport(\"user32.dll\")]\n public static extern IntPtr GetParent(IntPtr hWnd);\n\n [DllImport(\"user32.dll\")]\n [return: MarshalAs(UnmanagedType.Bool)]\n public static extern bool SetForegroundWindow(IntPtr hWnd);\n\n [DllImport(\"user32.dll\")]\n public static extern bool ShowWindow(IntPtr hWnd, int nCmdShow);\n\n\n [StructLayout(LayoutKind.Sequential)]\n public struct WINDOWINFO\n {\n public uint cbSize;\n public RECT rcWindow;\n public RECT rcClient;\n public uint dwStyle;\n public uint dwExStyle;\n public uint dwWindowStatus;\n public uint cxWindowBorders;\n public uint cyWindowBorders;\n public ushort atomWindowType;\n public ushort wCreatorVersion;\n\n // Allows automatic initialization of \"cbSize\" with \"new WINDOWINFO(null/true/false)\".\n public WINDOWINFO(Boolean? filler) : this()\n => cbSize = (UInt32)Marshal.SizeOf(typeof(WINDOWINFO));\n\n }\n public struct RECT\n {\n public int Left { get; set; }\n public int Top { get; set; }\n public int Right { get; set; }\n public int Bottom { get; set; }\n }\n\n [Flags]\n public enum SetWindowPosFlags : uint\n {\n SWP_ASYNCWINDOWPOS = 0x4000,\n SWP_DEFERERASE = 0x2000,\n SWP_DRAWFRAME = 0x0020,\n SWP_FRAMECHANGED = 0x0020,\n SWP_HIDEWINDOW = 0x0080,\n SWP_NOACTIVATE = 0x0010,\n SWP_NOCOPYBITS = 0x0100,\n SWP_NOMOVE = 0x0002,\n SWP_NOOWNERZORDER = 0x0200,\n SWP_NOREDRAW = 0x0008,\n SWP_NOREPOSITION = 0x0200,\n SWP_NOSENDCHANGING = 0x0400,\n SWP_NOSIZE = 0x0001,\n SWP_NOZORDER = 0x0004,\n SWP_SHOWWINDOW = 0x0040,\n }\n\n [Flags]\n public enum WindowLongFlags : int\n {\n GWL_EXSTYLE = -20,\n GWLP_HINSTANCE = -6,\n GWLP_HWNDPARENT = -8,\n GWL_ID = -12,\n GWL_STYLE = -16,\n GWL_USERDATA = -21,\n GWL_WNDPROC = -4,\n DWLP_USER = 0x8,\n DWLP_MSGRESULT = 0x0,\n DWLP_DLGPROC = 0x4\n }\n\n [Flags]\n public enum WindowStyles : uint\n {\n WS_BORDER = 0x800000,\n WS_CAPTION = 0xc00000,\n WS_CHILD = 0x40000000,\n WS_CLIPCHILDREN = 0x2000000,\n WS_CLIPSIBLINGS = 0x4000000,\n WS_DISABLED = 0x8000000,\n WS_DLGFRAME = 0x400000,\n WS_GROUP = 0x20000,\n WS_HSCROLL = 0x100000,\n WS_MAXIMIZE = 0x1000000,\n WS_MAXIMIZEBOX = 0x10000,\n WS_MINIMIZE = 0x20000000,\n WS_MINIMIZEBOX = 0x20000,\n WS_OVERLAPPED = 0x0,\n WS_OVERLAPPEDWINDOW = WS_OVERLAPPED | WS_CAPTION | WS_SYSMENU | WS_SIZEFRAME | WS_MINIMIZEBOX | WS_MAXIMIZEBOX,\n WS_POPUP = 0x80000000,\n WS_POPUPWINDOW = WS_POPUP | WS_BORDER | WS_SYSMENU,\n WS_SIZEFRAME = 0x40000,\n WS_SYSMENU = 0x80000,\n WS_TABSTOP = 0x10000,\n WS_THICKFRAME = 0x00040000,\n WS_VISIBLE = 0x10000000,\n WS_VSCROLL = 0x200000\n }\n\n [Flags]\n public enum WindowStylesEx : uint\n {\n WS_EX_ACCEPTFILES = 0x00000010,\n WS_EX_APPWINDOW = 0x00040000,\n WS_EX_CLIENTEDGE = 0x00000200,\n WS_EX_COMPOSITED = 0x02000000,\n WS_EX_CONTEXTHELP = 0x00000400,\n WS_EX_CONTROLPARENT = 0x00010000,\n WS_EX_DLGMODALFRAME = 0x00000001,\n WS_EX_LAYERED = 0x00080000,\n WS_EX_LAYOUTRTL = 0x00400000,\n WS_EX_LEFT = 0x00000000,\n WS_EX_LEFTSCROLLBAR = 0x00004000,\n WS_EX_LTRREADING = 0x00000000,\n WS_EX_MDICHILD = 0x00000040,\n WS_EX_NOACTIVATE = 0x08000000,\n WS_EX_NOINHERITLAYOUT = 0x00100000,\n WS_EX_NOPARENTNOTIFY = 0x00000004,\n WS_EX_NOREDIRECTIONBITMAP = 0x00200000,\n WS_EX_OVERLAPPEDWINDOW = WS_EX_WINDOWEDGE | WS_EX_CLIENTEDGE,\n WS_EX_PALETTEWINDOW = WS_EX_WINDOWEDGE | WS_EX_TOOLWINDOW | WS_EX_TOPMOST,\n WS_EX_RIGHT = 0x00001000,\n WS_EX_RIGHTSCROLLBAR = 0x00000000,\n WS_EX_RTLREADING = 0x00002000,\n WS_EX_STATICEDGE = 0x00020000,\n WS_EX_TOOLWINDOW = 0x00000080,\n WS_EX_TOPMOST = 0x00000008,\n WS_EX_TRANSPARENT = 0x00000020,\n WS_EX_WINDOWEDGE = 0x00000100\n }\n\n public enum ShowWindowCommands : uint\n {\n SW_HIDE = 0,\n SW_SHOWNORMAL = 1,\n SW_NORMAL = 1,\n SW_SHOWMINIMIZED = 2,\n SW_SHOWMAXIMIZED = 3,\n SW_MAXIMIZE = 3,\n SW_SHOWNOACTIVATE = 4,\n SW_SHOW = 5,\n SW_MINIMIZE = 6,\n SW_SHOWMINNOACTIVE = 7,\n SW_SHOWNA = 8,\n SW_RESTORE = 9,\n SW_SHOWDEFAULT = 10,\n SW_FORCEMINIMIZE = 11,\n SW_MAX = 11\n }\n\n public delegate IntPtr WndProcDelegate(IntPtr hWnd, uint msg, IntPtr wParam, IntPtr lParam);\n public delegate IntPtr SubclassWndProc(IntPtr hWnd, uint msg, IntPtr wParam, IntPtr lParam, IntPtr uIdSubclass, IntPtr dwRefData);\n\n public static int SignedHIWORD(IntPtr n) => SignedHIWORD(unchecked((int)(long)n));\n public static int SignedLOWORD(IntPtr n) => SignedLOWORD(unchecked((int)(long)n));\n public static int SignedHIWORD(int n) => (short)((n >> 16) & 0xffff);\n public static int SignedLOWORD(int n) => (short)(n & 0xFFFF);\n\n #region DPI\n public static double DpiX, DpiY;\n public static int DpiXSource, DpiYSource;\n const int LOGPIXELSX = 88, LOGPIXELSY = 90;\n [DllImport(\"gdi32.dll\", CharSet = CharSet.Auto, SetLastError = true, ExactSpelling = true)]\n public static extern int GetDeviceCaps(IntPtr hDC, int nIndex);\n public static void GetDPI(out double dpiX, out double dpiY) => GetDPI(IntPtr.Zero, out dpiX, out dpiY);\n public static void GetDPI(IntPtr handle, out double dpiX, out double dpiY)\n {\n Graphics GraphicsObject = Graphics.FromHwnd(handle); // DESKTOP Handle\n IntPtr dcHandle = GraphicsObject.GetHdc();\n DpiXSource = GetDeviceCaps(dcHandle, LOGPIXELSX);\n dpiX = DpiXSource / 96.0;\n DpiYSource = GetDeviceCaps(dcHandle, LOGPIXELSY);\n dpiY = DpiYSource / 96.0;\n GraphicsObject.ReleaseHdc(dcHandle);\n GraphicsObject.Dispose();\n }\n #endregion\n }\n}\n#pragma warning restore CA1401 // P/Invokes should not be visible\n"], ["/LLPlayer/LLPlayer/Controls/NonTopmostPopup.cs", "using System.Runtime.InteropServices;\nusing System.Windows;\nusing System.Windows.Controls.Primitives;\nusing System.Windows.Input;\nusing System.Windows.Interop;\n\nnamespace LLPlayer.Controls;\n\n/// \n/// Popup with code to not be the topmost control\n/// ref: https://gist.github.com/flq/903202/8bf56606b7c6fad341c31482f196b3aba9373e07\n/// \npublic class NonTopmostPopup : Popup\n{\n private bool? _appliedTopMost;\n private bool _alreadyLoaded;\n private Window? _parentWindow;\n\n public static readonly DependencyProperty IsTopmostProperty =\n DependencyProperty.Register(nameof(IsTopmost), typeof(bool), typeof(NonTopmostPopup), new FrameworkPropertyMetadata(false, OnIsTopmostChanged));\n\n public bool IsTopmost\n {\n get => (bool)GetValue(IsTopmostProperty);\n set => SetValue(IsTopmostProperty, value);\n }\n\n public NonTopmostPopup()\n {\n Loaded += OnPopupLoaded;\n }\n\n void OnPopupLoaded(object sender, RoutedEventArgs e)\n {\n if (_alreadyLoaded)\n return;\n\n _alreadyLoaded = true;\n\n if (Child != null)\n {\n Child.AddHandler(PreviewMouseLeftButtonDownEvent, new MouseButtonEventHandler(OnChildPreviewMouseLeftButtonDown), true);\n }\n\n //_parentWindow = Window.GetWindow(this);\n _parentWindow = Application.Current.MainWindow;\n\n if (_parentWindow == null)\n return;\n\n _parentWindow.Activated += OnParentWindowActivated;\n _parentWindow.Deactivated += OnParentWindowDeactivated;\n _parentWindow.LocationChanged += OnParentWindowLocationChanged;\n }\n\n private void OnParentWindowLocationChanged(object? sender, EventArgs e)\n {\n try\n {\n var method = typeof(Popup).GetMethod(\"UpdatePosition\",\n System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Instance);\n if (IsOpen)\n {\n method?.Invoke(this, null);\n }\n }\n catch\n {\n // ignored\n }\n }\n\n private void OnParentWindowActivated(object? sender, EventArgs e)\n {\n //Debug.WriteLine(\"Parent Window Activated\");\n SetTopmostState(true);\n }\n\n private void OnParentWindowDeactivated(object? sender, EventArgs e)\n {\n //Debug.WriteLine(\"Parent Window Deactivated\");\n\n if (IsTopmost == false)\n {\n SetTopmostState(IsTopmost);\n }\n }\n\n private void OnChildPreviewMouseLeftButtonDown(object? sender, MouseButtonEventArgs e)\n {\n //Debug.WriteLine(\"Child Mouse Left Button Down\");\n\n SetTopmostState(true);\n\n if (_parentWindow != null && !_parentWindow.IsActive && IsTopmost == false)\n {\n _parentWindow.Activate();\n //Debug.WriteLine(\"Activating Parent from child Left Button Down\");\n }\n }\n\n private static void OnIsTopmostChanged(DependencyObject obj, DependencyPropertyChangedEventArgs e)\n {\n var thisobj = (NonTopmostPopup)obj;\n\n thisobj.SetTopmostState(thisobj.IsTopmost);\n }\n\n protected override void OnOpened(EventArgs e)\n {\n SetTopmostState(IsTopmost);\n }\n\n private void SetTopmostState(bool isTop)\n {\n // Don't apply state if it's the same as incoming state\n if (_appliedTopMost.HasValue && _appliedTopMost == isTop)\n {\n // TODO: L: Maybe commenting out this section will solve the problem of the rare popups coming to the forefront?\n //return;\n }\n\n if (Child == null)\n return;\n\n var hwndSource = (PresentationSource.FromVisual(Child)) as HwndSource;\n\n if (hwndSource == null)\n return;\n var hwnd = hwndSource.Handle;\n\n if (!GetWindowRect(hwnd, out RECT rect))\n return;\n\n //Debug.WriteLine(\"setting z-order \" + isTop);\n\n if (isTop)\n {\n SetWindowPos(hwnd, HWND_TOPMOST, rect.Left, rect.Top, (int)Width, (int)Height, TOPMOST_FLAGS);\n }\n else\n {\n // Z-Order would only get refreshed/reflected if clicking the\n // the titlebar (as opposed to other parts of the external\n // window) unless I first set the popup to HWND_BOTTOM\n // then HWND_TOP before HWND_NOTOPMOST\n SetWindowPos(hwnd, HWND_BOTTOM, rect.Left, rect.Top, (int)Width, (int)Height, TOPMOST_FLAGS);\n SetWindowPos(hwnd, HWND_TOP, rect.Left, rect.Top, (int)Width, (int)Height, TOPMOST_FLAGS);\n SetWindowPos(hwnd, HWND_NOTOPMOST, rect.Left, rect.Top, (int)Width, (int)Height, TOPMOST_FLAGS);\n }\n\n _appliedTopMost = isTop;\n }\n\n #region P/Invoke imports & definitions\n#pragma warning disable 1591 //Xml-doc\n#pragma warning disable 169 //Never used-warning\n // ReSharper disable InconsistentNaming\n // Imports etc. with their naming rules\n\n [StructLayout(LayoutKind.Sequential)]\n public struct RECT\n\n {\n public int Left;\n public int Top;\n public int Right;\n public int Bottom;\n }\n\n [DllImport(\"user32.dll\")]\n [return: MarshalAs(UnmanagedType.Bool)]\n private static extern bool GetWindowRect(IntPtr hWnd, out RECT lpRect);\n\n [DllImport(\"user32.dll\")]\n private static extern bool SetWindowPos(IntPtr hWnd, IntPtr hWndInsertAfter, int X,\n int Y, int cx, int cy, uint uFlags);\n\n static readonly IntPtr HWND_TOPMOST = new IntPtr(-1);\n static readonly IntPtr HWND_NOTOPMOST = new IntPtr(-2);\n static readonly IntPtr HWND_TOP = new IntPtr(0);\n static readonly IntPtr HWND_BOTTOM = new IntPtr(1);\n\n private const UInt32 SWP_NOSIZE = 0x0001;\n const UInt32 SWP_NOMOVE = 0x0002;\n //const UInt32 SWP_NOZORDER = 0x0004;\n const UInt32 SWP_NOREDRAW = 0x0008;\n const UInt32 SWP_NOACTIVATE = 0x0010;\n\n //const UInt32 SWP_FRAMECHANGED = 0x0020; /* The frame changed: send WM_NCCALCSIZE */\n //const UInt32 SWP_SHOWWINDOW = 0x0040;\n //const UInt32 SWP_HIDEWINDOW = 0x0080;\n //const UInt32 SWP_NOCOPYBITS = 0x0100;\n const UInt32 SWP_NOOWNERZORDER = 0x0200; /* Don't do owner Z ordering */\n const UInt32 SWP_NOSENDCHANGING = 0x0400; /* Don't send WM_WINDOWPOSCHANGING */\n\n const UInt32 TOPMOST_FLAGS =\n SWP_NOACTIVATE | SWP_NOOWNERZORDER | SWP_NOSIZE | SWP_NOMOVE | SWP_NOREDRAW | SWP_NOSENDCHANGING;\n\n // ReSharper restore InconsistentNaming\n#pragma warning restore 1591\n#pragma warning restore 169\n #endregion\n}\n"], ["/LLPlayer/FlyleafLib/Utils/ZOrderHandler.cs", "using System;\nusing System.Collections.Generic;\nusing System.Diagnostics;\nusing System.Linq;\nusing System.Runtime.InteropServices;\nusing System.Threading.Tasks;\nusing System.Windows.Interop;\nusing System.Windows;\n\nnamespace FlyleafLib;\n\npublic static partial class Utils\n{\n public static class ZOrderHandler\n {\n [DllImport(\"user32.dll\", SetLastError = true)]\n public static extern IntPtr GetWindow(IntPtr hWnd, uint uCmd);\n\n enum GetWindow_Cmd : uint {\n GW_HWNDFIRST = 0,\n GW_HWNDLAST = 1,\n GW_HWNDNEXT = 2,\n GW_HWNDPREV = 3,\n GW_OWNER = 4,\n GW_CHILD = 5,\n GW_ENABLEDPOPUP = 6\n }\n\n public class ZOrder\n {\n public string window;\n public int order;\n }\n\n public class Owner\n {\n static int uniqueNameId = 0;\n\n public List CurZOrder = null;\n public List SavedZOrder = null;\n\n public Window Window;\n public IntPtr WindowHwnd;\n\n Dictionary WindowNamesHandles = new();\n Dictionary WindowNamesWindows = new();\n\n public Owner(Window window, IntPtr windowHwnd)\n {\n Window = window;\n WindowHwnd = windowHwnd;\n\n // TBR: Stand alone\n //if (Window.Owner != null)\n // Window.Owner.StateChanged += Window_StateChanged;\n //else\n\n Window.StateChanged += Window_StateChanged;\n lastState = Window.WindowState;\n\n // TBR: Minimize with WindowsKey + D for example will not fire (none of those)\n //HwndSource source = HwndSource.FromHwnd(WindowHwnd);\n //source.AddHook(new HwndSourceHook(WndProc));\n }\n\n public const Int32 WM_SYSCOMMAND = 0x112;\n public const Int32 SC_MAXIMIZE = 0xF030;\n private const int SC_MINIMIZE = 0xF020;\n private IntPtr WndProc(IntPtr hwnd, int msg, IntPtr wParam, IntPtr lParam, ref bool handled)\n {\n if (msg == WM_SYSCOMMAND)\n {\n if (wParam.ToInt32() == SC_MINIMIZE)\n {\n Save();\n //handled = true;\n }\n }\n return IntPtr.Zero;\n }\n\n private IntPtr GetHandle(Window window)\n {\n IntPtr hwnd = IntPtr.Zero;\n\n if (string.IsNullOrEmpty(window.Name))\n {\n hwnd = new WindowInteropHelper(window).Handle;\n window.Name = \"Zorder\" + uniqueNameId++.ToString();\n WindowNamesHandles.Add(window.Name, hwnd);\n WindowNamesWindows.Add(window.Name, window);\n }\n else if (!WindowNamesHandles.ContainsKey(window.Name))\n {\n hwnd = new WindowInteropHelper(window).Handle;\n WindowNamesHandles.Add(window.Name, hwnd);\n WindowNamesWindows.Add(window.Name, window);\n }\n else\n hwnd = WindowNamesHandles[window.Name];\n\n return hwnd;\n }\n\n WindowState lastState = WindowState.Normal;\n\n private void Window_StateChanged(object sender, EventArgs e)\n {\n if (Window.OwnedWindows.Count < 2)\n return;\n\n if (lastState == WindowState.Minimized)\n Restore();\n else if (Window.WindowState == WindowState.Minimized)\n Save();\n\n lastState = Window.WindowState;\n }\n\n public void Save()\n {\n SavedZOrder = GetZOrder();\n Debug.WriteLine(\"Saved\");\n DumpZOrder(SavedZOrder);\n }\n\n public void Restore()\n {\n if (SavedZOrder == null)\n return;\n\n Task.Run(() =>\n {\n System.Threading.Thread.Sleep(50);\n\n Application.Current.Dispatcher.Invoke(() =>\n {\n for (int i=0; i GetZOrder()\n {\n List zorders = new();\n\n foreach(Window window in Window.OwnedWindows)\n {\n ZOrder zorder = new();\n IntPtr curHwnd = GetHandle(window);\n if (curHwnd == IntPtr.Zero)\n continue;\n\n zorder.window = window.Name;\n\n while ((curHwnd = GetWindow(curHwnd, (uint)GetWindow_Cmd.GW_HWNDNEXT)) != WindowHwnd && curHwnd != IntPtr.Zero)\n zorder.order++;\n\n zorders.Add(zorder);\n }\n\n return zorders.OrderBy((o) => o.order).ToList();\n }\n\n public void DumpZOrder(List zorders)\n {\n for (int i=0; i Owners = new();\n\n public static void Register(Window window)\n {\n IntPtr hwnd = new WindowInteropHelper(window).Handle;\n if (Owners.ContainsKey(hwnd))\n return;\n\n Owners.Add(hwnd, new Owner(window, hwnd));\n }\n }\n}\n"], ["/LLPlayer/FlyleafLib/Utils/Utils.cs", "using System;\nusing System.Collections.Generic;\nusing System.Diagnostics;\nusing System.Globalization;\nusing System.IO;\nusing System.IO.Compression;\nusing System.Linq;\nusing System.Net.Http;\nusing System.Runtime.InteropServices;\nusing System.Text;\nusing System.Text.RegularExpressions;\nusing System.Threading;\nusing System.Threading.Tasks;\nusing System.Windows;\nusing CliWrap;\nusing Microsoft.Win32;\n\nnamespace FlyleafLib;\n\npublic static partial class Utils\n{\n // VLC : https://github.com/videolan/vlc/blob/master/modules/gui/qt/dialogs/preferences/simple_preferences.cpp\n // Kodi: https://github.com/xbmc/xbmc/blob/master/xbmc/settings/AdvancedSettings.cpp\n\n public static List ExtensionsAudio = new()\n {\n // VLC\n \"3ga\" , \"669\" , \"a52\" , \"aac\" , \"ac3\"\n , \"adt\" , \"adts\", \"aif\" , \"aifc\", \"aiff\"\n , \"au\" , \"amr\" , \"aob\" , \"ape\" , \"caf\"\n , \"cda\" , \"dts\" , \"flac\", \"it\" , \"m4a\"\n , \"m4p\" , \"mid\" , \"mka\" , \"mlp\" , \"mod\"\n , \"mp1\" , \"mp2\" , \"mp3\" , \"mpc\" , \"mpga\"\n , \"oga\" , \"oma\" , \"opus\", \"qcp\" , \"ra\"\n , \"rmi\" , \"snd\" , \"s3m\" , \"spx\" , \"tta\"\n , \"voc\" , \"vqf\" , \"w64\" , \"wav\" , \"wma\"\n , \"wv\" , \"xa\" , \"xm\"\n };\n\n public static List ExtensionsPictures = new()\n {\n \"apng\", \"bmp\", \"gif\", \"jpg\", \"jpeg\", \"png\", \"ico\", \"tif\", \"tiff\", \"tga\",\"jfif\"\n };\n\n public static List ExtensionsSubtitlesText = new()\n {\n \"ass\", \"ssa\", \"srt\", \"txt\", \"text\", \"vtt\"\n };\n\n public static List ExtensionsSubtitlesBitmap = new()\n {\n \"sub\", \"sup\"\n };\n\n public static List ExtensionsSubtitles = [..ExtensionsSubtitlesText, ..ExtensionsSubtitlesBitmap];\n\n public static List ExtensionsVideo = new()\n {\n // VLC\n \"3g2\" , \"3gp\" , \"3gp2\", \"3gpp\", \"amrec\"\n , \"amv\" , \"asf\" , \"avi\" , \"bik\" , \"divx\"\n , \"drc\" , \"dv\" , \"f4v\" , \"flv\" , \"gvi\"\n , \"gxf\" , \"m1v\" , \"m2t\" , \"m2v\" , \"m2ts\"\n , \"m4v\" , \"mkv\" , \"mov\" , \"mp2v\", \"mp4\"\n , \"mp4v\", \"mpa\" , \"mpe\" , \"mpeg\", \"mpeg1\"\n , \"mpeg2\",\"mpeg4\",\"mpg\" , \"mpv2\", \"mts\"\n , \"mtv\" , \"mxf\" , \"nsv\" , \"nuv\" , \"ogg\"\n , \"ogm\" , \"ogx\" , \"ogv\" , \"rec\" , \"rm\"\n , \"rmvb\", \"rpl\" , \"thp\" , \"tod\" , \"ts\"\n , \"tts\" , \"vob\" , \"vro\" , \"webm\", \"wmv\"\n , \"xesc\"\n\n // Additional\n , \"dav\"\n };\n\n private static int uniqueId;\n public static int GetUniqueId() { Interlocked.Increment(ref uniqueId); return uniqueId; }\n\n /// \n /// Begin Invokes the UI thread to execute the specified action\n /// \n /// \n public static void UI(Action action)\n {\n#if DEBUG\n if (Application.Current == null)\n return;\n#endif\n\n Application.Current.Dispatcher.BeginInvoke(action, System.Windows.Threading.DispatcherPriority.DataBind);\n }\n\n /// \n /// Begin Invokes the UI thread if required to execute the specified action\n /// \n /// \n public static void UIIfRequired(Action action)\n {\n if (Thread.CurrentThread.ManagedThreadId == Application.Current.Dispatcher.Thread.ManagedThreadId)\n action();\n else\n Application.Current.Dispatcher.BeginInvoke(action);\n }\n\n /// \n /// Invokes the UI thread to execute the specified action\n /// \n /// \n public static void UIInvoke(Action action) => Application.Current.Dispatcher.Invoke(action);\n\n /// \n /// Invokes the UI thread if required to execute the specified action\n /// \n /// \n public static void UIInvokeIfRequired(Action action)\n {\n if (Thread.CurrentThread.ManagedThreadId == Application.Current.Dispatcher.Thread.ManagedThreadId)\n action();\n else\n Application.Current.Dispatcher.Invoke(action);\n }\n\n public static Thread STA(Action action)\n {\n Thread thread = new(() => action());\n thread.SetApartmentState(ApartmentState.STA);\n thread.Start();\n\n return thread;\n }\n\n public static void STAInvoke(Action action)\n {\n Thread thread = STA(action);\n thread.Join();\n }\n\n public static int Align(int num, int align)\n {\n int mod = num % align;\n return mod == 0 ? num : num + (align - mod);\n }\n public static float Scale(float value, float inMin, float inMax, float outMin, float outMax)\n => ((value - inMin) * (outMax - outMin) / (inMax - inMin)) + outMin;\n\n /// \n /// Adds a windows firewall rule if not already exists for the specified program path\n /// \n /// Default value is Flyleaf\n /// Default value is current executable path\n public static void AddFirewallRule(string ruleName = null, string path = null)\n {\n Task.Run(() =>\n {\n try\n {\n if (string.IsNullOrEmpty(ruleName))\n ruleName = \"Flyleaf\";\n\n if (string.IsNullOrEmpty(path))\n path = Process.GetCurrentProcess().MainModule.FileName;\n\n path = $\"\\\"{path}\\\"\";\n\n // Check if rule already exists\n Process proc = new()\n {\n StartInfo = new ProcessStartInfo\n {\n FileName = \"cmd\",\n Arguments = $\"/C netsh advfirewall firewall show rule name={ruleName} verbose | findstr /L {path}\",\n CreateNoWindow = true,\n UseShellExecute = false,\n RedirectStandardOutput\n = true,\n WindowStyle = ProcessWindowStyle.Hidden\n }\n };\n\n proc.Start();\n proc.WaitForExit();\n\n if (proc.StandardOutput.Read() > 0)\n return;\n\n // Add rule with admin rights\n proc = new Process\n {\n StartInfo = new ProcessStartInfo\n {\n FileName = \"cmd\",\n Arguments = $\"/C netsh advfirewall firewall add rule name={ruleName} dir=in action=allow enable=yes program={path} profile=any &\" +\n $\"netsh advfirewall firewall add rule name={ruleName} dir=out action=allow enable=yes program={path} profile=any\",\n Verb = \"runas\",\n CreateNoWindow = true,\n UseShellExecute = true,\n WindowStyle = ProcessWindowStyle.Hidden\n }\n };\n\n proc.Start();\n proc.WaitForExit();\n\n Log($\"Firewall rule \\\"{ruleName}\\\" added for {path}\");\n }\n catch { }\n });\n }\n\n // We can't trust those\n //public static private bool IsDesignMode=> (bool) DesignerProperties.IsInDesignModeProperty.GetMetadata(typeof(DependencyObject)).DefaultValue;\n //public static bool IsDesignMode = LicenseManager.UsageMode == LicenseUsageMode.Designtime; // Will not work properly (need to be called from non-static class constructor)\n\n //public static bool IsWin11 = Regex.IsMatch(Registry.GetValue(@\"HKEY_LOCAL_MACHINE\\SOFTWARE\\Microsoft\\Windows NT\\CurrentVersion\", \"ProductName\", \"\").ToString(), \"Windows 11\");\n //public static bool IsWin10 = Regex.IsMatch(Registry.GetValue(@\"HKEY_LOCAL_MACHINE\\SOFTWARE\\Microsoft\\Windows NT\\CurrentVersion\", \"ProductName\", \"\").ToString(), \"Windows 10\");\n //public static bool IsWin8 = Regex.IsMatch(Registry.GetValue(@\"HKEY_LOCAL_MACHINE\\SOFTWARE\\Microsoft\\Windows NT\\CurrentVersion\", \"ProductName\", \"\").ToString(), \"Windows 8\");\n //public static bool IsWin7 = Regex.IsMatch(Registry.GetValue(@\"HKEY_LOCAL_MACHINE\\SOFTWARE\\Microsoft\\Windows NT\\CurrentVersion\", \"ProductName\", \"\").ToString(), \"Windows 7\");\n\n public static List GetMoviesSorted(List movies)\n {\n List moviesSorted = new();\n\n for (int i = 0; i < movies.Count; i++)\n {\n string ext = Path.GetExtension(movies[i]);\n\n if (ext == null || ext.Trim() == \"\")\n continue;\n\n if (ExtensionsVideo.Contains(ext[1..].ToLower()))\n moviesSorted.Add(movies[i]);\n }\n\n moviesSorted.Sort(new NaturalStringComparer());\n\n return moviesSorted;\n }\n public sealed class NaturalStringComparer : IComparer\n { public int Compare(string a, string b) => NativeMethods.StrCmpLogicalW(a, b); }\n\n public static string GetRecInnerException(Exception e)\n {\n string dump = \"\";\n var cur = e.InnerException;\n\n for (int i = 0; i < 4; i++)\n {\n if (cur == null) break;\n dump += \"\\r\\n - \" + cur.Message;\n cur = cur.InnerException;\n }\n\n return dump;\n }\n public static string GetUrlExtention(string url)\n {\n int index;\n if ((index = url.LastIndexOf('.')) > 0)\n return url[(index + 1)..].ToLower();\n\n return \"\";\n }\n\n public static List GetSystemLanguages()\n {\n List Languages = [ Language.English ];\n\n if (OriginalCulture.ThreeLetterISOLanguageName != \"eng\")\n Languages.Add(Language.Get(OriginalCulture));\n\n foreach (System.Windows.Forms.InputLanguage lang in System.Windows.Forms.InputLanguage.InstalledInputLanguages)\n if (lang.Culture.ThreeLetterISOLanguageName != OriginalCulture.ThreeLetterISOLanguageName && lang.Culture.ThreeLetterISOLanguageName != \"eng\")\n Languages.Add(Language.Get(lang.Culture));\n\n return Languages;\n }\n\n public static CultureInfo OriginalCulture { get; private set; }\n public static CultureInfo OriginalUICulture { get; private set; }\n\n public static void SaveOriginalCulture()\n {\n OriginalCulture = CultureInfo.CurrentCulture;\n OriginalUICulture = CultureInfo.CurrentUICulture;\n }\n\n public class MediaParts\n {\n public string Title { get; set; } = \"\";\n public string Extension { get; set; } = \"\";\n public int Season { get; set; }\n public int Episode { get; set; }\n public int Year { get; set; }\n }\n public static MediaParts GetMediaParts(string title, bool checkSeasonEpisodeOnly = false)\n {\n Match res;\n MediaParts mp = new();\n int index = int.MaxValue; // title end pos\n\n res = RxSeasonEpisode1().Match(title);\n if (!res.Success)\n {\n res = RxSeasonEpisode2().Match(title);\n\n if (!res.Success)\n res = RxEpisodePart().Match(title);\n }\n\n if (res.Groups.Count > 1)\n {\n if (res.Groups[\"season\"].Value != \"\")\n mp.Season = int.Parse(res.Groups[\"season\"].Value);\n\n if (res.Groups[\"episode\"].Value != \"\")\n mp.Episode = int.Parse(res.Groups[\"episode\"].Value);\n\n if (checkSeasonEpisodeOnly || res.Index == 0) // 0: No title just season/episode\n return mp;\n\n index = res.Index;\n }\n\n mp.Extension = GetUrlExtention(title);\n if (mp.Extension.Length > 0 && mp.Extension.Length < 5)\n title = title[..(title.Length - mp.Extension.Length - 1)];\n\n // non-movie words, 1080p, 2015\n if ((res = RxExtended().Match(title)).Index > 0 && res.Index < index)\n index = res.Index;\n\n if ((res = RxDirectorsCut().Match(title)).Index > 0 && res.Index < index)\n index = res.Index;\n\n if ((res = RxBrrip().Match(title)).Index > 0 && res.Index < index)\n index = res.Index;\n\n if ((res = RxResolution().Match(title)).Index > 0 && res.Index < index)\n index = res.Index;\n\n res = RxYear().Match(title);\n Group gc;\n if (res.Success && (gc = res.Groups[\"year\"]).Index > 2)\n {\n mp.Year = int.Parse(gc.Value);\n if (res.Index < index)\n index = res.Index;\n }\n\n if (index != int.MaxValue)\n title = title[..index];\n\n title = title.Replace(\".\", \" \").Replace(\"_\", \" \");\n title = RxSpaces().Replace(title, \" \");\n title = RxNonAlphaNumeric().Replace(title, \"\");\n\n mp.Title = title.Trim();\n\n return mp;\n }\n\n public static string FindNextAvailableFile(string fileName)\n {\n if (!File.Exists(fileName)) return fileName;\n\n string tmp = Path.Combine(Path.GetDirectoryName(fileName), Regex.Replace(Path.GetFileNameWithoutExtension(fileName), @\"(.*) (\\([0-9]+)\\)$\", \"$1\"));\n string newName;\n\n for (int i = 1; i < 101; i++)\n {\n newName = tmp + \" (\" + i + \")\" + Path.GetExtension(fileName);\n if (!File.Exists(newName)) return newName;\n }\n\n return null;\n }\n public static string GetValidFileName(string name) => string.Join(\"_\", name.Split(Path.GetInvalidFileNameChars()));\n\n public static string FindFileBelow(string filename)\n {\n string current = AppDomain.CurrentDomain.BaseDirectory;\n\n while (current != null)\n {\n if (File.Exists(Path.Combine(current, filename)))\n return Path.Combine(current, filename);\n\n current = Directory.GetParent(current)?.FullName;\n }\n\n return null;\n }\n public static string GetFolderPath(string folder)\n {\n if (folder.StartsWith(\":\"))\n {\n folder = folder[1..];\n return FindFolderBelow(folder);\n }\n\n return Path.IsPathRooted(folder) ? folder : Path.GetFullPath(folder);\n }\n\n public static string FindFolderBelow(string folder)\n {\n string current = AppDomain.CurrentDomain.BaseDirectory;\n\n while (current != null)\n {\n if (Directory.Exists(Path.Combine(current, folder)))\n return Path.Combine(current, folder);\n\n current = Directory.GetParent(current)?.FullName;\n }\n\n return null;\n }\n public static string GetUserDownloadPath() { try { return Registry.CurrentUser.OpenSubKey(@\"Software\\Microsoft\\Windows\\CurrentVersion\\Explorer\\User Shell Folders\\\").GetValue(\"{374DE290-123F-4565-9164-39C4925E467B}\").ToString(); } catch (Exception) { return null; } }\n public static string DownloadToString(string url, int timeoutMs = 30000)\n {\n try\n {\n using HttpClient client = new() { Timeout = TimeSpan.FromMilliseconds(timeoutMs) };\n return client.GetAsync(url).Result.Content.ReadAsStringAsync().Result;\n }\n catch (Exception e)\n {\n Log($\"Download failed {e.Message} [Url: {url ?? \"Null\"}]\");\n }\n\n return null;\n }\n\n public static MemoryStream DownloadFile(string url, int timeoutMs = 30000)\n {\n MemoryStream ms = new();\n\n try\n {\n using HttpClient client = new() { Timeout = TimeSpan.FromMilliseconds(timeoutMs) };\n client.GetAsync(url).Result.Content.CopyToAsync(ms).Wait();\n }\n catch (Exception e)\n {\n Log($\"Download failed {e.Message} [Url: {url ?? \"Null\"}]\");\n }\n\n return ms;\n }\n\n public static bool DownloadFile(string url, string filename, int timeoutMs = 30000, bool overwrite = true)\n {\n try\n {\n using HttpClient client = new() { Timeout = TimeSpan.FromMilliseconds(timeoutMs) };\n using FileStream fs = new(filename, overwrite ? FileMode.Create : FileMode.CreateNew);\n client.GetAsync(url).Result.Content.CopyToAsync(fs).Wait();\n\n return true;\n }\n catch (Exception e)\n {\n Log($\"Download failed {e.Message} [Url: {url ?? \"Null\"}, Path: {filename ?? \"Null\"}]\");\n }\n\n return false;\n }\n public static string FixFileUrl(string url)\n {\n try\n {\n if (url == null || url.Length < 5)\n return url;\n\n if (url[..5].ToLower() == \"file:\")\n return new Uri(url).LocalPath;\n }\n catch { }\n\n return url;\n }\n\n /// \n /// Convert Windows lnk file path to target path\n /// \n /// lnk file path\n /// targetPath or null\n public static string GetLnkTargetPath(string filepath)\n {\n try\n {\n // Using dynamic COM\n // ref: https://stackoverflow.com/a/49198242/9070784\n dynamic windowsShell = Activator.CreateInstance(Type.GetTypeFromProgID(\"WScript.Shell\", true)!);\n dynamic shortcut = windowsShell!.CreateShortcut(filepath);\n string targetPath = shortcut.TargetPath;\n\n if (string.IsNullOrEmpty(targetPath))\n {\n throw new InvalidOperationException(\"TargetPath is empty.\");\n }\n\n return targetPath;\n }\n catch (Exception e)\n {\n Log($\"Resolving Windows Link failed {e.Message} [FilePath: {filepath}]\");\n\n return null;\n }\n }\n\n public static string GetBytesReadable(nuint i)\n {\n // Determine the suffix and readable value\n string suffix;\n double readable;\n if (i >= 0x1000000000000000) // Exabyte\n {\n suffix = \"EB\";\n readable = i >> 50;\n }\n else if (i >= 0x4000000000000) // Petabyte\n {\n suffix = \"PB\";\n readable = i >> 40;\n }\n else if (i >= 0x10000000000) // Terabyte\n {\n suffix = \"TB\";\n readable = i >> 30;\n }\n else if (i >= 0x40000000) // Gigabyte\n {\n suffix = \"GB\";\n readable = i >> 20;\n }\n else if (i >= 0x100000) // Megabyte\n {\n suffix = \"MB\";\n readable = i >> 10;\n }\n else if (i >= 0x400) // Kilobyte\n {\n suffix = \"KB\";\n readable = i;\n }\n else\n {\n return i.ToString(\"0 B\"); // Byte\n }\n // Divide by 1024 to get fractional value\n readable /= 1024;\n // Return formatted number with suffix\n return readable.ToString(\"0.## \") + suffix;\n }\n static List gpuCounters;\n public static void GetGPUCounters()\n {\n PerformanceCounterCategory category = new(\"GPU Engine\");\n string[] counterNames = category.GetInstanceNames();\n gpuCounters = new List();\n\n foreach (string counterName in counterNames)\n if (counterName.EndsWith(\"engtype_3D\"))\n foreach (var counter in category.GetCounters(counterName))\n if (counter.CounterName == \"Utilization Percentage\")\n gpuCounters.Add(counter);\n }\n public static float GetGPUUsage()\n {\n float result = 0f;\n\n try\n {\n if (gpuCounters == null) GetGPUCounters();\n\n gpuCounters.ForEach(x => { _ = x.NextValue(); });\n Thread.Sleep(1000);\n gpuCounters.ForEach(x => { result += x.NextValue(); });\n\n }\n catch (Exception e) { Log($\"[GPUUsage] Error {e.Message}\"); result = -1f; GetGPUCounters(); }\n\n return result;\n }\n public static string GZipDecompress(string filename)\n {\n string newFileName = \"\";\n\n FileInfo fileToDecompress = new(filename);\n using (var originalFileStream = fileToDecompress.OpenRead())\n {\n string currentFileName = fileToDecompress.FullName;\n newFileName = currentFileName.Remove(currentFileName.Length - fileToDecompress.Extension.Length);\n\n using var decompressedFileStream = File.Create(newFileName);\n using GZipStream decompressionStream = new(originalFileStream, CompressionMode.Decompress);\n decompressionStream.CopyTo(decompressedFileStream);\n }\n\n return newFileName;\n }\n\n public static Dictionary ParseQueryString(ReadOnlySpan query)\n {\n Dictionary dict = [];\n\n int nameStart = 0;\n int equalPos = -1;\n for (int i = 0; i < query.Length; i++)\n {\n if (query[i] == '=')\n equalPos = i;\n else if (query[i] == '&')\n {\n if (equalPos == -1)\n dict[query[nameStart..i].ToString()] = null;\n else\n dict[query[nameStart..equalPos].ToString()] = query.Slice(equalPos + 1, i - equalPos - 1).ToString();\n\n equalPos = -1;\n nameStart = i + 1;\n }\n }\n\n if (nameStart < query.Length - 1)\n {\n if (equalPos == -1)\n dict[query[nameStart..].ToString()] = null;\n else\n dict[query[nameStart..equalPos].ToString()] = query.Slice(equalPos + 1, query.Length - equalPos - 1).ToString();\n }\n\n return dict;\n }\n\n public unsafe static string BytePtrToStringUTF8(byte* bytePtr)\n => Marshal.PtrToStringUTF8((nint)bytePtr);\n\n public static System.Windows.Media.Color WinFormsToWPFColor(System.Drawing.Color sColor)\n => System.Windows.Media.Color.FromArgb(sColor.A, sColor.R, sColor.G, sColor.B);\n public static System.Drawing.Color WPFToWinFormsColor(System.Windows.Media.Color wColor)\n => System.Drawing.Color.FromArgb(wColor.A, wColor.R, wColor.G, wColor.B);\n\n public static System.Windows.Media.Color VorticeToWPFColor(Vortice.Mathematics.Color sColor)\n => System.Windows.Media.Color.FromArgb(sColor.A, sColor.R, sColor.G, sColor.B);\n public static Vortice.Mathematics.Color WPFToVorticeColor(System.Windows.Media.Color wColor)\n => new Vortice.Mathematics.Color(wColor.R, wColor.G, wColor.B, wColor.A);\n\n public static double SWFREQ_TO_TICKS = 10000000.0 / Stopwatch.Frequency;\n public static string ToHexadecimal(byte[] bytes)\n {\n StringBuilder hexBuilder = new();\n for (int i = 0; i < bytes.Length; i++)\n {\n hexBuilder.Append(bytes[i].ToString(\"x2\"));\n }\n return hexBuilder.ToString();\n }\n public static int GCD(int a, int b) => b == 0 ? a : GCD(b, a % b);\n public static string TicksToTime(long ticks) => new TimeSpan(ticks).ToString();\n public static void Log(string msg) { try { Debug.WriteLine($\"[{DateTime.Now:hh.mm.ss.fff}] {msg}\"); } catch (Exception) { Debug.WriteLine($\"[............] [MediaFramework] {msg}\"); } }\n\n [GeneratedRegex(\"[^a-z0-9]extended\", RegexOptions.IgnoreCase)]\n private static partial Regex RxExtended();\n [GeneratedRegex(\"[^a-z0-9]directors.cut\", RegexOptions.IgnoreCase)]\n private static partial Regex RxDirectorsCut();\n [GeneratedRegex(@\"(^|[^a-z0-9])(s|season)[^a-z0-9]*(?[0-9]{1,2})[^a-z0-9]*(e|episode|part)[^a-z0-9]*(?[0-9]{1,2})($|[^a-z0-9])\", RegexOptions.IgnoreCase)]\n\n // s|season 01 ... e|episode|part 01\n private static partial Regex RxSeasonEpisode1();\n [GeneratedRegex(@\"(^|[^a-z0-9])(?[0-9]{1,2})x(?[0-9]{1,2})($|[^a-z0-9])\", RegexOptions.IgnoreCase)]\n // 01x01\n private static partial Regex RxSeasonEpisode2();\n // TODO: in case of single season should check only for e|episode|part 01\n [GeneratedRegex(@\"(^|[^a-z0-9])(episode|part)[^a-z0-9]*(?[0-9]{1,2})($|[^a-z0-9])\", RegexOptions.IgnoreCase)]\n private static partial Regex RxEpisodePart();\n [GeneratedRegex(\"[^a-z0-9]brrip\", RegexOptions.IgnoreCase)]\n private static partial Regex RxBrrip();\n\n [GeneratedRegex(\"[^a-z0-9][0-9]{3,4}p\", RegexOptions.IgnoreCase)]\n private static partial Regex RxResolution();\n [GeneratedRegex(@\"[^a-z0-9](?(19|20)[0-9][0-9])($|[^a-z0-9])\", RegexOptions.IgnoreCase)]\n private static partial Regex RxYear();\n [GeneratedRegex(@\"\\s{2,}\")]\n private static partial Regex RxSpaces();\n [GeneratedRegex(@\"[^a-z0-9]$\", RegexOptions.IgnoreCase)]\n private static partial Regex RxNonAlphaNumeric();\n\n public static string TruncateString(string str, int maxLength, string suffix = \"...\")\n {\n if (string.IsNullOrEmpty(str))\n return str;\n\n if (str.Length <= maxLength)\n return str;\n\n int availableLength = maxLength - suffix.Length;\n\n if (availableLength <= 0)\n {\n return suffix.Substring(0, Math.Min(maxLength, suffix.Length));\n }\n\n return str.Substring(0, availableLength) + suffix;\n }\n\n // TODO: L: move to app, using event\n public static void PlayCompletionSound()\n {\n string soundPath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, \"Assets/completion.mp3\");\n\n if (!File.Exists(soundPath))\n {\n return;\n }\n\n UI(() =>\n {\n try\n {\n // play completion sound\n System.Windows.Media.MediaPlayer mp = new();\n mp.Open(new Uri(soundPath));\n mp.Play();\n }\n catch\n {\n // ignored\n }\n });\n }\n\n public static string CommandToText(this Command cmd)\n {\n if (cmd.TargetFilePath.Any(char.IsWhiteSpace))\n {\n return $\"& \\\"{cmd.TargetFilePath}\\\" {cmd.Arguments}\";\n }\n\n return cmd.ToString();\n }\n}\n"], ["/LLPlayer/LLPlayer/Views/MainWindow.xaml.cs", "using System.Runtime.InteropServices;\nusing System.Windows;\nusing System.Windows.Interop;\nusing LLPlayer.Services;\nusing LLPlayer.ViewModels;\n\nnamespace LLPlayer.Views;\n\npublic partial class MainWindow : Window\n{\n public MainWindow()\n {\n // If this is not called first, the constructor of the other control will\n // run before FlyleafHost is initialized, so it will not work.\n DataContext = ((App)Application.Current).Container.Resolve();\n\n InitializeComponent();\n\n SetWindowSize();\n SetTitleBarDarkMode(this);\n }\n\n private void SetWindowSize()\n {\n // 16:9 size list\n List candidateSizes =\n [\n new(1280, 720),\n new(1024, 576),\n new(960, 540),\n new(800, 450),\n new(640, 360),\n new(480, 270),\n new(320, 180)\n ];\n\n // Get available screen width / height\n double availableWidth = SystemParameters.WorkArea.Width;\n double availableHeight = SystemParameters.WorkArea.Height;\n\n // Get the largest size that will fit on the screen\n Size selectedSize = candidateSizes.FirstOrDefault(\n s => s.Width <= availableWidth && s.Height <= availableHeight,\n candidateSizes[^1]);\n\n // Set\n Width = selectedSize.Width;\n Height = selectedSize.Height;\n }\n\n #region Dark Title Bar\n /// \n /// ref: \n /// \n [DllImport(\"DwmApi\")]\n private static extern int DwmSetWindowAttribute(IntPtr hwnd, int attr, int[] attrValue, int attrSize);\n const int DWMWA_USE_IMMERSIVE_DARK_MODE = 20;\n\n public static void SetTitleBarDarkMode(Window window)\n {\n // Check OS Version\n if (!(Environment.OSVersion.Version >= new Version(10, 0, 18985)))\n {\n return;\n }\n\n var fl = ((App)Application.Current).Container.Resolve();\n if (!fl.Config.IsDarkTitlebar)\n {\n return;\n }\n\n bool darkMode = true;\n\n // Set title bar to dark mode\n // ref: https://stackoverflow.com/questions/71362654/wpf-window-titlebar\n IntPtr hWnd = new WindowInteropHelper(window).EnsureHandle();\n DwmSetWindowAttribute(hWnd, DWMWA_USE_IMMERSIVE_DARK_MODE, [darkMode ? 1 : 0], 4);\n }\n #endregion\n}\n"], ["/LLPlayer/FlyleafLib/MediaPlayer/Player.Keys.cs", "using System;\nusing System.Collections.Generic;\nusing System.ComponentModel;\nusing System.Runtime.InteropServices;\nusing System.Text.Json.Serialization;\nusing System.Windows.Input;\nusing static FlyleafLib.Logger;\n\nnamespace FlyleafLib.MediaPlayer;\n\npartial class Player\n{\n /* Player Key Bindings\n *\n * Config.Player.KeyBindings.Keys\n *\n * KeyDown / KeyUp Events (Control / WinFormsHost / WindowFront (FlyleafWindow))\n * Exposes KeyDown/KeyUp if required to listen on additional Controls/Windows\n * Allows KeyBindingAction.Custom to set an external Action for Key Binding\n */\n\n Tuple onKeyUpBinding;\n\n /// \n /// Can be used to route KeyDown events (WPF)\n /// \n /// \n /// \n public static bool KeyDown(Player player, KeyEventArgs e)\n {\n e.Handled = KeyDown(player, e.Key == Key.System ? e.SystemKey : e.Key);\n\n return e.Handled;\n }\n\n /// \n /// Can be used to route KeyDown events (WinForms)\n /// \n /// \n /// \n public static void KeyDown(Player player, System.Windows.Forms.KeyEventArgs e)\n => e.Handled = KeyDown(player, KeyInterop.KeyFromVirtualKey((int)e.KeyCode));\n\n /// \n /// Can be used to route KeyUp events (WPF)\n /// \n /// \n /// \n public static bool KeyUp(Player player, KeyEventArgs e)\n {\n e.Handled = KeyUp(player, e.Key == Key.System ? e.SystemKey : e.Key);\n\n return e.Handled;\n }\n\n /// \n /// Can be used to route KeyUp events (WinForms)\n /// \n /// \n /// \n public static void KeyUp(Player player, System.Windows.Forms.KeyEventArgs e)\n => e.Handled = KeyUp(player, KeyInterop.KeyFromVirtualKey((int)e.KeyCode));\n\n public static bool KeyDown(Player player, Key key)\n {\n if (player == null)\n return false;\n\n player.Activity.RefreshActive();\n\n if (player.onKeyUpBinding != null)\n {\n if (player.onKeyUpBinding.Item1.Key == key)\n return true;\n\n if (DateTime.UtcNow.Ticks - player.onKeyUpBinding.Item2 < TimeSpan.FromSeconds(2).Ticks)\n return false;\n\n player.onKeyUpBinding = null; // In case of keyboard lost capture (should be handled from hosts)\n }\n\n List keysList = new();\n var spanList = CollectionsMarshal.AsSpan(player.Config.Player.KeyBindings.Keys); // should create dictionary here with key+alt+ctrl+shift hash\n foreach(var binding in spanList)\n if (binding.Key == key && binding.IsEnabled)\n keysList.Add(binding);\n\n if (keysList.Count == 0)\n return false;\n\n bool alt, ctrl, shift;\n alt = Keyboard.IsKeyDown(Key.LeftAlt) || Keyboard.IsKeyDown(Key.RightAlt);\n ctrl = Keyboard.IsKeyDown(Key.LeftCtrl) || Keyboard.IsKeyDown(Key.RightCtrl);\n shift = Keyboard.IsKeyDown(Key.LeftShift) || Keyboard.IsKeyDown(Key.RightShift);\n\n var spanList2 = CollectionsMarshal.AsSpan(keysList);\n foreach(var binding in spanList2)\n {\n if (binding.Alt == alt && binding.Ctrl == ctrl && binding.Shift == shift && binding.IsEnabled)\n {\n if (binding.IsKeyUp)\n player.onKeyUpBinding = new(binding, DateTime.UtcNow.Ticks);\n else\n ExecuteBinding(player, binding, false);\n\n return true;\n }\n }\n\n return false;\n }\n public static bool KeyUp(Player player, Key key)\n {\n if (player == null || player.onKeyUpBinding == null || player.onKeyUpBinding.Item1.Key != key)\n return false;\n\n ExecuteBinding(player, player.onKeyUpBinding.Item1, true);\n player.onKeyUpBinding = null;\n return true;\n }\n\n static void ExecuteBinding(Player player, KeyBinding binding, bool isKeyUp)\n {\n if (CanDebug) player.Log.Debug($\"[Keys|{(isKeyUp ? \"Up\" : \"Down\")}] {(binding.Action == KeyBindingAction.Custom && binding.ActionName != null ? binding.ActionName : binding.Action)}\");\n binding.ActionInternal?.Invoke();\n }\n}\n\npublic class KeysConfig\n{\n /// \n /// Currently configured key bindings\n /// (Normally you should not access this directly)\n /// \n public List Keys { get ; set; }\n\n Player player;\n\n public KeysConfig() { }\n\n public KeysConfig Clone()\n {\n KeysConfig keys = (KeysConfig) MemberwiseClone();\n keys.player = null;\n keys.Keys = null;\n return keys;\n }\n\n internal void SetPlayer(Player player)\n {\n Keys ??= new List();\n\n if (!player.Config.Loaded && Keys.Count == 0)\n LoadDefault();\n\n this.player = player;\n\n foreach(var binding in Keys)\n {\n if (binding.Action != KeyBindingAction.Custom)\n binding.ActionInternal = GetKeyBindingAction(binding.Action);\n }\n }\n\n /// \n /// Adds a custom keybinding\n /// \n /// The key to bind\n /// If should fire on each keydown or just on keyup\n /// The action to execute\n /// A unique name to be able to identify it\n /// If Alt should be pressed\n /// If Ctrl should be pressed\n /// If Shift should be pressed\n /// Keybinding already exists\n public void AddCustom(Key key, bool isKeyUp, Action action, string actionName, bool alt = false, bool ctrl = false, bool shift = false)\n {\n for (int i=0; i\n /// Adds a new key binding\n /// \n /// The key to bind\n /// Which action from the available to assign\n /// If Alt should be pressed\n /// If Ctrl should be pressed\n /// If Shift should be pressed\n /// Keybinding already exists\n public void Add(Key key, KeyBindingAction action, bool alt = false, bool ctrl = false, bool shift = false)\n {\n for (int i=0; i\n /// Removes a binding based on Key/Ctrl combination\n /// \n /// The assigned key\n /// If Alt is assigned\n /// If Ctrl is assigned\n /// If Shift is assigned\n public void Remove(Key key, bool alt = false, bool ctrl = false, bool shift = false)\n {\n for (int i=Keys.Count-1; i >=0; i--)\n if (Keys[i].Key == key && Keys[i].Alt == alt && Keys[i].Ctrl == ctrl && Keys[i].Shift == shift)\n Keys.RemoveAt(i);\n }\n\n /// \n /// Removes a binding based on assigned action\n /// \n /// The assigned action\n public void Remove(KeyBindingAction action)\n {\n for (int i=Keys.Count-1; i >=0; i--)\n if (Keys[i].Action == action)\n Keys.RemoveAt(i);\n }\n\n /// \n /// Removes a binding based on assigned action's name\n /// \n /// The assigned action's name\n public void Remove(string actionName)\n {\n for (int i=Keys.Count-1; i >=0; i--)\n if (Keys[i].ActionName == actionName)\n Keys.RemoveAt(i);\n }\n\n /// \n /// Removes all the bindings\n /// \n public void RemoveAll() => Keys.Clear();\n\n /// \n /// Resets to default bindings\n /// \n public void LoadDefault()\n {\n if (Keys == null)\n Keys = new List();\n else\n Keys.Clear();\n\n Add(Key.OemSemicolon, KeyBindingAction.SubsDelayRemovePrimary);\n Add(Key.OemQuotes, KeyBindingAction.SubsDelayAddPrimary);\n Add(Key.OemSemicolon, KeyBindingAction.SubsDelayRemoveSecondary, shift: true);\n Add(Key.OemQuotes, KeyBindingAction.SubsDelayAddSecondary, shift: true);\n\n Add(Key.A, KeyBindingAction.SubsPrevSeek);\n Add(Key.S, KeyBindingAction.SubsCurSeek);\n Add(Key.D, KeyBindingAction.SubsNextSeek);\n\n Add(Key.J, KeyBindingAction.SubsPrevSeek);\n Add(Key.K, KeyBindingAction.SubsCurSeek);\n Add(Key.L, KeyBindingAction.SubsNextSeek);\n\n // Mouse backford/forward button\n Add(Key.Left, KeyBindingAction.SubsPrevSeekFallback, alt: true);\n Add(Key.Right, KeyBindingAction.SubsNextSeekFallback, alt: true);\n\n Add(Key.V, KeyBindingAction.OpenFromClipboardSafe, ctrl: true);\n Add(Key.O, KeyBindingAction.OpenFromFileDialog, ctrl: true);\n Add(Key.C, KeyBindingAction.CopyToClipboard, ctrl: true, shift: true);\n\n Add(Key.Left, KeyBindingAction.SeekBackward2);\n Add(Key.Left, KeyBindingAction.SeekBackward, ctrl: true);\n Add(Key.Right, KeyBindingAction.SeekForward2);\n Add(Key.Right, KeyBindingAction.SeekForward, ctrl: true);\n\n Add(Key.S, KeyBindingAction.ToggleSeekAccurate, ctrl: true);\n\n Add(Key.OemPlus, KeyBindingAction.SpeedAdd);\n Add(Key.OemPlus, KeyBindingAction.SpeedAdd2, shift: true);\n Add(Key.OemMinus, KeyBindingAction.SpeedRemove);\n Add(Key.OemMinus, KeyBindingAction.SpeedRemove2, shift: true);\n\n Add(Key.OemPlus, KeyBindingAction.ZoomIn, ctrl: true);\n Add(Key.OemMinus, KeyBindingAction.ZoomOut, ctrl: true);\n\n Add(Key.F, KeyBindingAction.ToggleFullScreen);\n\n Add(Key.Space, KeyBindingAction.TogglePlayPause);\n Add(Key.MediaPlayPause, KeyBindingAction.TogglePlayPause);\n Add(Key.Play, KeyBindingAction.TogglePlayPause);\n\n Add(Key.H, KeyBindingAction.ToggleSubtitlesVisibility);\n Add(Key.V, KeyBindingAction.ToggleSubtitlesVisibility);\n\n Add(Key.M, KeyBindingAction.ToggleMute);\n Add(Key.Up, KeyBindingAction.VolumeUp);\n Add(Key.Down, KeyBindingAction.VolumeDown);\n\n Add(Key.D0, KeyBindingAction.ResetAll);\n\n Add(Key.Escape, KeyBindingAction.NormalScreen);\n Add(Key.Q, KeyBindingAction.Stop, ctrl: true);\n }\n\n public Action GetKeyBindingAction(KeyBindingAction action)\n {\n switch (action)\n {\n case KeyBindingAction.ForceIdle:\n return player.Activity.ForceIdle;\n case KeyBindingAction.ForceActive:\n return player.Activity.ForceActive;\n case KeyBindingAction.ForceFullActive:\n return player.Activity.ForceFullActive;\n\n case KeyBindingAction.AudioDelayAdd:\n return player.Audio.DelayAdd;\n case KeyBindingAction.AudioDelayRemove:\n return player.Audio.DelayRemove;\n case KeyBindingAction.AudioDelayAdd2:\n return player.Audio.DelayAdd2;\n case KeyBindingAction.AudioDelayRemove2:\n return player.Audio.DelayRemove2;\n case KeyBindingAction.ToggleAudio:\n return player.Audio.Toggle;\n case KeyBindingAction.ToggleMute:\n return player.Audio.ToggleMute;\n case KeyBindingAction.VolumeUp:\n return player.Audio.VolumeUp;\n case KeyBindingAction.VolumeDown:\n return player.Audio.VolumeDown;\n\n case KeyBindingAction.ToggleVideo:\n return player.Video.Toggle;\n case KeyBindingAction.ToggleKeepRatio:\n return player.Video.ToggleKeepRatio;\n case KeyBindingAction.ToggleVideoAcceleration:\n return player.Video.ToggleVideoAcceleration;\n\n case KeyBindingAction.SubsDelayAddPrimary:\n return player.Subtitles.DelayAddPrimary;\n case KeyBindingAction.SubsDelayRemovePrimary:\n return player.Subtitles.DelayRemovePrimary;\n case KeyBindingAction.SubsDelayAdd2Primary:\n return player.Subtitles.DelayAdd2Primary;\n case KeyBindingAction.SubsDelayRemove2Primary:\n return player.Subtitles.DelayRemove2Primary;\n\n case KeyBindingAction.SubsDelayAddSecondary:\n return player.Subtitles.DelayAddSecondary;\n case KeyBindingAction.SubsDelayRemoveSecondary:\n return player.Subtitles.DelayRemoveSecondary;\n case KeyBindingAction.SubsDelayAdd2Secondary:\n return player.Subtitles.DelayAdd2Secondary;\n case KeyBindingAction.SubsDelayRemove2Secondary:\n return player.Subtitles.DelayRemove2Secondary;\n\n case KeyBindingAction.ToggleSubtitlesVisibility:\n return player.Subtitles.ToggleVisibility;\n case KeyBindingAction.ToggleSubtitlesVisibilityPrimary:\n return player.Subtitles.ToggleVisibilityPrimary;\n case KeyBindingAction.ToggleSubtitlesVisibilitySecondary:\n return player.Subtitles.ToggleVisibilitySecondary;\n\n case KeyBindingAction.OpenFromClipboard:\n return player.OpenFromClipboard;\n case KeyBindingAction.OpenFromClipboardSafe:\n return player.OpenFromClipboardSafe;\n\n case KeyBindingAction.OpenFromFileDialog:\n return player.OpenFromFileDialog;\n\n case KeyBindingAction.CopyToClipboard:\n return player.CopyToClipboard;\n\n case KeyBindingAction.CopyItemToClipboard:\n return player.CopyItemToClipboard;\n\n case KeyBindingAction.Flush:\n return player.Flush;\n\n case KeyBindingAction.Stop:\n return player.Stop;\n\n case KeyBindingAction.Pause:\n return player.Pause;\n\n case KeyBindingAction.Play:\n return player.Play;\n\n case KeyBindingAction.TogglePlayPause:\n return player.TogglePlayPause;\n\n case KeyBindingAction.TakeSnapshot:\n return player.Commands.TakeSnapshotAction;\n\n case KeyBindingAction.NormalScreen:\n return player.NormalScreen;\n\n case KeyBindingAction.FullScreen:\n return player.FullScreen;\n\n case KeyBindingAction.ToggleFullScreen:\n return player.ToggleFullScreen;\n\n case KeyBindingAction.ToggleRecording:\n return player.ToggleRecording;\n\n case KeyBindingAction.ToggleReversePlayback:\n return player.ToggleReversePlayback;\n\n case KeyBindingAction.ToggleLoopPlayback:\n return player.ToggleLoopPlayback;\n\n case KeyBindingAction.ToggleSeekAccurate:\n return player.ToggleSeekAccurate;\n\n case KeyBindingAction.SeekBackward:\n return player.SeekBackward;\n\n case KeyBindingAction.SeekForward:\n return player.SeekForward;\n\n case KeyBindingAction.SeekBackward2:\n return player.SeekBackward2;\n\n case KeyBindingAction.SeekForward2:\n return player.SeekForward2;\n\n case KeyBindingAction.SeekBackward3:\n return player.SeekBackward3;\n\n case KeyBindingAction.SeekForward3:\n return player.SeekForward3;\n\n case KeyBindingAction.SeekBackward4:\n return player.SeekBackward4;\n\n case KeyBindingAction.SeekForward4:\n return player.SeekForward4;\n\n case KeyBindingAction.SubsCurSeek:\n return player.Subtitles.CurSeek;\n case KeyBindingAction.SubsPrevSeek:\n return player.Subtitles.PrevSeek;\n case KeyBindingAction.SubsNextSeek:\n return player.Subtitles.NextSeek;\n case KeyBindingAction.SubsNextSeekFallback:\n return player.Subtitles.NextSeekFallback;\n case KeyBindingAction.SubsPrevSeekFallback:\n return player.Subtitles.PrevSeekFallback;\n\n case KeyBindingAction.SubsCurSeek2:\n return player.Subtitles.CurSeek2;\n case KeyBindingAction.SubsPrevSeek2:\n return player.Subtitles.PrevSeek2;\n case KeyBindingAction.SubsNextSeek2:\n return player.Subtitles.NextSeek2;\n case KeyBindingAction.SubsNextSeekFallback2:\n return player.Subtitles.NextSeekFallback2;\n case KeyBindingAction.SubsPrevSeekFallback2:\n return player.Subtitles.PrevSeekFallback2;\n\n case KeyBindingAction.SpeedAdd:\n return player.SpeedUp;\n\n case KeyBindingAction.SpeedAdd2:\n return player.SpeedUp2;\n\n case KeyBindingAction.SpeedRemove:\n return player.SpeedDown;\n\n case KeyBindingAction.SpeedRemove2:\n return player.SpeedDown2;\n\n case KeyBindingAction.ShowPrevFrame:\n return player.ShowFramePrev;\n\n case KeyBindingAction.ShowNextFrame:\n return player.ShowFrameNext;\n\n case KeyBindingAction.ZoomIn:\n return player.ZoomIn;\n\n case KeyBindingAction.ZoomOut:\n return player.ZoomOut;\n\n case KeyBindingAction.ResetAll:\n return player.ResetAll;\n\n case KeyBindingAction.ResetSpeed:\n return player.ResetSpeed;\n\n case KeyBindingAction.ResetRotation:\n return player.ResetRotation;\n\n case KeyBindingAction.ResetZoom:\n return player.ResetZoom;\n }\n\n return null;\n }\n private static HashSet isKeyUpBinding = new()\n {\n // TODO: Should Fire once one KeyDown and not again until KeyUp is fired (in case of Tasks keep track of already running actions?)\n\n // Having issues with alt/ctrl/shift (should save state of alt/ctrl/shift on keydown and not checked on keyup)\n\n { KeyBindingAction.OpenFromClipboard },\n { KeyBindingAction.OpenFromClipboardSafe },\n { KeyBindingAction.OpenFromFileDialog },\n { KeyBindingAction.CopyToClipboard },\n { KeyBindingAction.TakeSnapshot },\n { KeyBindingAction.NormalScreen },\n { KeyBindingAction.FullScreen },\n { KeyBindingAction.ToggleFullScreen },\n { KeyBindingAction.ToggleAudio },\n { KeyBindingAction.ToggleVideo },\n { KeyBindingAction.ToggleKeepRatio },\n { KeyBindingAction.ToggleVideoAcceleration },\n { KeyBindingAction.ToggleSubtitlesVisibility },\n { KeyBindingAction.ToggleSubtitlesVisibilityPrimary },\n { KeyBindingAction.ToggleSubtitlesVisibilitySecondary },\n { KeyBindingAction.ToggleMute },\n { KeyBindingAction.TogglePlayPause },\n { KeyBindingAction.ToggleRecording },\n { KeyBindingAction.ToggleReversePlayback },\n { KeyBindingAction.ToggleLoopPlayback },\n { KeyBindingAction.Play },\n { KeyBindingAction.Pause },\n { KeyBindingAction.Stop },\n { KeyBindingAction.Flush },\n { KeyBindingAction.ToggleSeekAccurate },\n { KeyBindingAction.SpeedAdd },\n { KeyBindingAction.SpeedAdd2 },\n { KeyBindingAction.SpeedRemove },\n { KeyBindingAction.SpeedRemove2 },\n { KeyBindingAction.ResetAll },\n { KeyBindingAction.ResetSpeed },\n { KeyBindingAction.ResetRotation },\n { KeyBindingAction.ResetZoom },\n { KeyBindingAction.ForceIdle },\n { KeyBindingAction.ForceActive },\n { KeyBindingAction.ForceFullActive }\n };\n}\npublic class KeyBinding\n{\n public bool IsEnabled { get; set; } = true;\n public bool Alt { get; set; }\n public bool Ctrl { get; set; }\n public bool Shift { get; set; }\n public Key Key { get; set; }\n public KeyBindingAction Action { get; set; }\n\n [JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)]\n public string ActionName\n {\n get => Action == KeyBindingAction.Custom ? field : null;\n set;\n }\n\n public bool IsKeyUp { get; set; }\n\n /// \n /// Sets action for custom key binding\n /// \n /// \n /// \n public void SetAction(Action action, bool isKeyUp)\n {\n ActionInternal = action;\n IsKeyUp = isKeyUp;\n }\n\n [JsonIgnore]\n public Action ActionInternal { get; internal set; }\n}\n\npublic enum KeyBindingAction\n{\n [Description(nameof(Custom))]\n Custom,\n [Description(\"Set Activity to Idle forcibly\")]\n ForceIdle,\n [Description(\"Set Activity to Active forcibly\")]\n ForceActive,\n [Description(\"Set Activity to FullActive forcibly\")]\n ForceFullActive,\n\n [Description(\"Increase Audio Delay (1)\")]\n AudioDelayAdd,\n [Description(\"Increase Audio Delay (2)\")]\n AudioDelayAdd2,\n [Description(\"Decrease Audio Delay (1)\")]\n AudioDelayRemove,\n [Description(\"Decrease Audio Delay (2)\")]\n AudioDelayRemove2,\n\n [Description(\"Toggle Audio Mute/Unmute\")]\n ToggleMute,\n [Description(\"Volume Up (1)\")]\n VolumeUp,\n [Description(\"Volume Down (1)\")]\n VolumeDown,\n\n [Description(\"Increase Primary Subtitles Delay (1)\")]\n SubsDelayAddPrimary,\n [Description(\"Increase Primary Subtitles Delay (2)\")]\n SubsDelayAdd2Primary,\n [Description(\"Decrease Primary Subtitles Delay (1)\")]\n SubsDelayRemovePrimary,\n [Description(\"Decrease Primary Subtitles Delay (2)\")]\n SubsDelayRemove2Primary,\n [Description(\"Increase Secondary Subtitles Delay (1)\")]\n SubsDelayAddSecondary,\n [Description(\"Increase Secondary Subtitles Delay (2)\")]\n SubsDelayAdd2Secondary,\n [Description(\"Decrease Secondary Subtitles Delay (1)\")]\n SubsDelayRemoveSecondary,\n [Description(\"Decrease Secondary Subtitles Delay (2)\")]\n SubsDelayRemove2Secondary,\n\n [Description(\"Copy Opened Item to Clipboard\")]\n CopyToClipboard,\n [Description(\"Copy Current Played Item to Clipboard\")]\n CopyItemToClipboard,\n [Description(\"Open a media from clipboard\")]\n OpenFromClipboard,\n [Description(\"Open a media from clipboard if not open\")]\n OpenFromClipboardSafe,\n [Description(\"Open a media from file dialog\")]\n OpenFromFileDialog,\n\n [Description(\"Stop playback\")]\n Stop,\n [Description(\"Pause playback\")]\n Pause,\n [Description(\"Play playback\")]\n Play,\n [Description(\"Toggle play playback\")]\n TogglePlayPause,\n\n [Description(\"Toggle reverse playback\")]\n ToggleReversePlayback,\n [Description(\"Toggle loop playback\")]\n ToggleLoopPlayback,\n [Description(\"Flushes the buffer of the player\")]\n Flush,\n [Description(\"Take snapshot\")]\n TakeSnapshot,\n [Description(\"Change to NormalScreen\")]\n NormalScreen,\n [Description(\"Change to FullScreen\")]\n FullScreen,\n [Description(\"Toggle NormalScreen / FullScreen\")]\n ToggleFullScreen,\n\n [Description(\"Toggle Audio Enabled\")]\n ToggleAudio,\n [Description(\"Toggle Video Enabled\")]\n ToggleVideo,\n\n [Description(\"Toggle All Subtitles Visibility\")]\n ToggleSubtitlesVisibility,\n [Description(\"Toggle Primary Subtitles Visibility\")]\n ToggleSubtitlesVisibilityPrimary,\n [Description(\"Toggle Secondary Subtitles Visibility\")]\n ToggleSubtitlesVisibilitySecondary,\n\n [Description(\"Toggle Keep Aspect Ratio\")]\n ToggleKeepRatio,\n [Description(\"Toggle Video Acceleration\")]\n ToggleVideoAcceleration,\n [Description(\"Toggle Recording\")]\n ToggleRecording,\n [Description(\"Toggle Always Seek Accurate Mode\")]\n ToggleSeekAccurate,\n\n [Description(\"Seek forwards (1)\")]\n SeekForward,\n [Description(\"Seek backwards (1)\")]\n SeekBackward,\n [Description(\"Seek forwards (2)\")]\n SeekForward2,\n [Description(\"Seek backwards (2)\")]\n SeekBackward2,\n [Description(\"Seek forwards (3)\")]\n SeekForward3,\n [Description(\"Seek backwards (3)\")]\n SeekBackward3,\n [Description(\"Seek forwards (4)\")]\n SeekForward4,\n [Description(\"Seek backwards (4)\")]\n SeekBackward4,\n\n [Description(\"Seek to the previous subtitle\")]\n SubsPrevSeek,\n [Description(\"Seek to the current subtitle\")]\n SubsCurSeek,\n [Description(\"Seek to the next subtitle\")]\n SubsNextSeek,\n [Description(\"Seek to the previous subtitle or seek backwards\")]\n SubsPrevSeekFallback,\n [Description(\"Seek to the next subtitle or seek forwards\")]\n SubsNextSeekFallback,\n\n [Description(\"Seek to the previous secondary subtitle\")]\n SubsPrevSeek2,\n [Description(\"Seek to the current secondary subtitle\")]\n SubsCurSeek2,\n [Description(\"Seek to the next secondary subtitle\")]\n SubsNextSeek2,\n [Description(\"Seek to the previous secondary subtitle or seek backwards\")]\n SubsPrevSeekFallback2,\n [Description(\"Seek to the next secondary subtitle or seek forwards\")]\n SubsNextSeekFallback2,\n\n [Description(\"Speed Up (1)\")]\n SpeedAdd,\n [Description(\"Speed Up (2)\")]\n SpeedAdd2,\n\n [Description(\"Speed Down (1)\")]\n SpeedRemove,\n [Description(\"Speed Down (2)\")]\n SpeedRemove2,\n\n [Description(\"Show Next Frame\")]\n ShowNextFrame,\n [Description(\"Show Previous Frame\")]\n ShowPrevFrame,\n\n [Description(\"Reset Zoom / Rotation / Speed\")]\n ResetAll,\n [Description(\"Reset Speed\")]\n ResetSpeed,\n [Description(\"Reset Rotation\")]\n ResetRotation,\n [Description(\"Reset Zoom\")]\n ResetZoom,\n\n [Description(\"Zoom In (1)\")]\n ZoomIn,\n [Description(\"Zoom Out (1)\")]\n ZoomOut,\n}\n"], ["/LLPlayer/FlyleafLib/MediaPlayer/SubtitlesASR.cs", "using System.Collections.Concurrent;\nusing System.Collections.Generic;\nusing System.Diagnostics;\nusing System.IO;\nusing System.Linq;\nusing System.Runtime.CompilerServices;\nusing System.Text;\nusing System.Text.RegularExpressions;\nusing System.Threading;\nusing System.Threading.Channels;\nusing System.Threading.Tasks;\nusing CliWrap;\nusing CliWrap.Builders;\nusing CliWrap.EventStream;\nusing FlyleafLib.MediaFramework.MediaDecoder;\nusing FlyleafLib.MediaFramework.MediaDemuxer;\nusing FlyleafLib.MediaFramework.MediaStream;\nusing Whisper.net;\nusing Whisper.net.LibraryLoader;\nusing Whisper.net.Logger;\nusing static FlyleafLib.Logger;\n\nnamespace FlyleafLib.MediaPlayer;\n\n#nullable enable\n\n// TODO: L: Pause and resume ASR\n\n/// \n/// Running ASR from a media file\n/// \n/// \n/// Read in a separate thread from the video playback.\n/// Note that multiple threads cannot seek to multiple locations for a single AVFormatContext,\n/// so it is necessary to open it with another avformat_open_input for the same video.\n/// \npublic class SubtitlesASR\n{\n private readonly SubtitlesManager _subtitlesManager;\n private readonly Config _config;\n private readonly Lock _locker = new();\n private readonly Lock _lockerSubs = new();\n private CancellationTokenSource? _cts = null;\n public HashSet SubIndexSet { get; } = new();\n\n private readonly LogHandler Log;\n\n public SubtitlesASR(SubtitlesManager subtitlesManager, Config config)\n {\n _subtitlesManager = subtitlesManager;\n _config = config;\n\n Log = new LogHandler((\"[#1]\").PadRight(8, ' ') + \" [SubtitlesASR ] \");\n }\n\n /// \n /// Check that ASR is executable\n /// \n /// error information\n /// \n public bool CanExecute(out string err)\n {\n if (_config.Subtitles.ASREngine == SubASREngineType.WhisperCpp)\n {\n if (_config.Subtitles.WhisperCppConfig.Model == null)\n {\n err = \"whisper.cpp model is not set. Please download it from the settings.\";\n return false;\n }\n\n if (!File.Exists(_config.Subtitles.WhisperCppConfig.Model.ModelFilePath))\n {\n err = $\"whisper.cpp model file '{_config.Subtitles.WhisperCppConfig.Model.ModelFileName}' does not exist in the folder. Please download it from the settings.\";\n return false;\n }\n }\n else if (_config.Subtitles.ASREngine == SubASREngineType.FasterWhisper)\n {\n if (_config.Subtitles.FasterWhisperConfig.UseManualEngine)\n {\n if (!File.Exists(_config.Subtitles.FasterWhisperConfig.ManualEnginePath))\n {\n err = \"faster-whisper engine does not exist in the manual path.\";\n return false;\n }\n }\n else\n {\n if (!File.Exists(FasterWhisperConfig.DefaultEnginePath))\n {\n err = \"faster-whisper engine is not downloaded. Please download it from the settings.\";\n return false;\n }\n }\n\n if (_config.Subtitles.FasterWhisperConfig.UseManualModel)\n {\n if (!Directory.Exists(_config.Subtitles.FasterWhisperConfig.ManualModelDir))\n {\n err = \"faster-whisper manual model directory does not exist.\";\n return false;\n }\n }\n }\n\n err = \"\";\n\n return true;\n }\n\n /// \n /// Open media file and read all subtitle data from audio\n /// \n /// 0: Primary, 1: Secondary\n /// media file path\n /// Audio streamIndex\n /// Demuxer type\n /// Current playback timestamp, from which whisper is run\n /// true: process completed, false: run in progress\n public bool Execute(int subIndex, string url, int streamIndex, MediaType type, TimeSpan curTime)\n {\n // When Dual ASR: Copy the other ASR result and return early\n if (SubIndexSet.Count > 0 && !SubIndexSet.Contains(subIndex))\n {\n lock (_lockerSubs)\n {\n SubIndexSet.Add(subIndex);\n int otherIndex = (subIndex + 1) % 2;\n\n if (_subtitlesManager[otherIndex].Subs.Count > 0)\n {\n bool enableTranslated = _config.Subtitles[subIndex].EnabledTranslated;\n\n // Copy other ASR result\n _subtitlesManager[subIndex]\n .Load(_subtitlesManager[otherIndex].Subs.Select(s =>\n {\n SubtitleData clone = s.Clone();\n\n if (!enableTranslated)\n {\n clone.TranslatedText = null;\n clone.EnabledTranslated = true;\n }\n\n return clone;\n }));\n\n if (!_subtitlesManager[otherIndex].IsLoading)\n {\n // Copy the language source if one of them is already done.\n _subtitlesManager[subIndex].LanguageSource = _subtitlesManager[otherIndex].LanguageSource;\n }\n }\n }\n\n // return early\n return false;\n }\n\n // If it has already been executed, cancel it to start over from the current playback position.\n if (SubIndexSet.Contains(subIndex))\n {\n Dictionary> prevSubs = new();\n HashSet prevSubIndexSet = [.. SubIndexSet];\n lock (_lockerSubs)\n {\n // backup current result\n foreach (int i in SubIndexSet)\n {\n prevSubs[i] = _subtitlesManager[i].Subs.ToList();\n }\n }\n // Cancel preceding execution and wait\n TryCancel(true);\n\n // restore previous result\n lock (_lockerSubs)\n {\n foreach (int i in prevSubIndexSet)\n {\n _subtitlesManager[i].Load(prevSubs[i]);\n // Re-enable spinner\n _subtitlesManager[i].StartLoading();\n\n SubIndexSet.Add(i);\n }\n }\n }\n\n lock (_locker)\n {\n SubIndexSet.Add(subIndex);\n\n _cts = new CancellationTokenSource();\n using AudioReader reader = new(_config, subIndex);\n reader.Open(url, streamIndex, type, _cts.Token);\n\n if (_cts.Token.IsCancellationRequested)\n {\n return true;\n }\n\n reader.ReadAll(curTime, data =>\n {\n if (_cts.Token.IsCancellationRequested)\n {\n return;\n }\n\n lock (_lockerSubs)\n {\n foreach (int i in SubIndexSet)\n {\n bool isInit = false;\n if (_subtitlesManager[i].LanguageSource == null)\n {\n isInit = true;\n\n // Delete subtitles after the first subtitle to be added (leave the previous one)\n _subtitlesManager[i].DeleteAfter(data.StartTime);\n\n // Set language\n // Can currently only be set for the whole, not per subtitle\n _subtitlesManager[i].LanguageSource = Language.Get(data.Language);\n }\n\n SubtitleData sub = new()\n {\n Text = data.Text,\n StartTime = data.StartTime,\n EndTime = data.EndTime,\n#if DEBUG\n ChunkNo = data.ChunkNo,\n StartTimeChunk = data.StartTimeChunk,\n EndTimeChunk = data.EndTimeChunk,\n#endif\n };\n\n _subtitlesManager[i].Add(sub);\n if (isInit)\n {\n _subtitlesManager[i].SetCurrentTime(new TimeSpan(_config.Subtitles.player.CurTime));\n }\n }\n }\n }, _cts.Token);\n\n if (!_cts.Token.IsCancellationRequested)\n {\n // TODO: L: Notify, express completion in some way\n Utils.PlayCompletionSound();\n }\n\n foreach (int i in SubIndexSet)\n {\n lock (_lockerSubs)\n {\n // Stop spinner (required when dual ASR)\n _subtitlesManager[i].StartLoading().Dispose();\n }\n }\n }\n\n return true;\n }\n\n public void TryCancel(bool isWait)\n {\n var cts = _cts;\n if (cts != null)\n {\n if (!cts.IsCancellationRequested)\n {\n lock (_lockerSubs)\n {\n foreach (var i in SubIndexSet)\n {\n _subtitlesManager[i].Clear();\n }\n }\n\n cts.Cancel();\n lock (_lockerSubs)\n {\n SubIndexSet.Clear();\n }\n }\n else\n {\n Log.Info(\"Already cancel requested\");\n }\n\n if (!isWait)\n {\n return;\n }\n\n lock (_locker)\n {\n // dispose after it is no longer used.\n cts.Dispose();\n _cts = null;\n }\n }\n }\n\n public void Reset(int subIndex)\n {\n if (!SubIndexSet.Contains(subIndex))\n return;\n\n if (SubIndexSet.Count == 2)\n {\n lock (_lockerSubs)\n {\n // When Dual ASR: only the state is cleared without stopping ASR execution.\n SubIndexSet.Remove(subIndex);\n _subtitlesManager[subIndex].Clear();\n }\n\n return;\n }\n\n // cancel asynchronously as it takes time to cancel.\n TryCancel(false);\n }\n}\n\npublic class AudioReader : IDisposable\n{\n private readonly Config _config;\n private readonly int _subIndex;\n\n private Demuxer? _demuxer;\n private AudioDecoder? _decoder;\n private AudioStream? _stream;\n\n private unsafe AVPacket* _packet = null;\n private unsafe AVFrame* _frame = null;\n private unsafe SwrContext* _swrContext = null;\n\n private bool _isFile;\n\n private readonly LogHandler Log;\n\n public AudioReader(Config config, int subIndex)\n {\n _config = config;\n _subIndex = subIndex;\n Log = new LogHandler((\"[#1]\").PadRight(8, ' ') + \" [AudioReader ] \");\n }\n\n public void Open(string url, int streamIndex, MediaType type, CancellationToken token)\n {\n _demuxer = new Demuxer(_config.Demuxer, type, _subIndex + 1, false);\n\n token.Register(() =>\n {\n if (_demuxer != null)\n _demuxer.Interrupter.ForceInterrupt = 1;\n });\n\n _demuxer.Log.Prefix = _demuxer.Log.Prefix.Replace(\"Demuxer: \", \"DemuxerA:\");\n string? error = _demuxer.Open(url);\n\n if (error != null)\n {\n if (token.IsCancellationRequested)\n return;\n\n throw new InvalidOperationException($\"demuxer open error: {error}\");\n }\n\n _stream = (AudioStream)_demuxer.AVStreamToStream[streamIndex];\n\n _decoder = new AudioDecoder(_config, _subIndex + 1);\n _decoder.Log.Prefix = _decoder.Log.Prefix.Replace(\"Decoder: \", \"DecoderA:\");\n\n error = _decoder.Open(_stream);\n\n if (error != null)\n {\n if (token.IsCancellationRequested)\n return;\n\n throw new InvalidOperationException($\"decoder open error: {error}\");\n }\n\n _isFile = File.Exists(url);\n }\n\n private record struct AudioChunk(MemoryStream Stream, int ChunkNumber, TimeSpan Start, TimeSpan End);\n\n /// \n /// Extract audio files in WAV format and run Whisper\n /// \n /// Current playback timestamp, from which whisper is run\n /// Action to process one result\n /// \n /// \n /// \n public void ReadAll(TimeSpan curTime, Action addSub, CancellationToken cancellationToken)\n {\n if (_demuxer == null || _decoder == null || _stream == null)\n throw new InvalidOperationException(\"Open() is not called\");\n\n // Assume a network stream and parallelize the reading of packets and the execution of whisper.\n // For network video, increase capacity as downloads may take longer.\n // (concern that memory usage will increase by three times the chunk size)\n int capacity = _isFile ? 1 : 2;\n BoundedChannelOptions channelOptions = new(capacity)\n {\n SingleReader = true,\n SingleWriter = true,\n };\n Channel channel = Channel.CreateBounded(channelOptions);\n\n // own cancellation for producer/consumer\n var cts = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken);\n CancellationToken token = cts.Token;\n\n ConcurrentStack memoryStreamPool = new();\n\n // Consumer: Run whisper\n Task consumerTask = Task.Run(DoConsumer, token);\n\n // Producer: Extract WAV and pass to consumer\n Task producerTask = Task.Run(DoProducer, token);\n\n // complete channel\n producerTask.ContinueWith(t =>\n channel.Writer.Complete(), token);\n\n // When an exception occurs in both consumer and producer, the other is canceled.\n consumerTask.ContinueWith(t =>\n cts.Cancel(), TaskContinuationOptions.OnlyOnFaulted);\n producerTask.ContinueWith(t =>\n cts.Cancel(), TaskContinuationOptions.OnlyOnFaulted);\n\n try\n {\n Task.WhenAll(consumerTask, producerTask).Wait();\n }\n catch (AggregateException)\n {\n if (cancellationToken.IsCancellationRequested)\n {\n // canceled by caller\n if (CanDebug) Log.Debug(\"Whisper canceled\");\n return;\n }\n\n // canceled because of exceptions\n throw;\n }\n\n return;\n\n async Task DoConsumer()\n {\n await using IASRService asrService = _config.Subtitles.ASREngine switch\n {\n SubASREngineType.WhisperCpp => new WhisperCppASRService(_config),\n SubASREngineType.FasterWhisper => new FasterWhisperASRService(_config),\n _ => throw new InvalidOperationException()\n };\n\n while (await channel.Reader.WaitToReadAsync(token))\n {\n // Use TryPeek() to reduce the channel capacity by one.\n if (!channel.Reader.TryPeek(out AudioChunk chunk))\n throw new InvalidOperationException(\"can not peek AudioChunk from channel\");\n\n try\n {\n if (CanDebug) Log.Debug(\n $\"Reading chunk from channel (chunkNo: {chunk.ChunkNumber}, start: {chunk.Start}, end: {chunk.End})\");\n\n //// Output wav file for debugging\n //await using (FileStream fs = new($\"subtitlewhisper-{chunk.ChunkNumber}.wav\", FileMode.Create, FileAccess.Write))\n //{\n // chunk.Stream.WriteTo(fs);\n // chunk.Stream.Position = 0;\n //}\n\n await foreach (var data in asrService.Do(chunk.Stream, token))\n {\n TimeSpan start = chunk.Start.Add(data.start);\n TimeSpan end = chunk.Start.Add(data.end);\n if (end > chunk.End)\n {\n // Shorten by 20 ms to prevent the next subtitle from being covered\n end = chunk.End.Subtract(TimeSpan.FromMilliseconds(20));\n }\n\n SubtitleASRData subData = new()\n {\n Text = data.text,\n Language = data.language,\n StartTime = start,\n EndTime = end,\n#if DEBUG\n ChunkNo = chunk.ChunkNumber,\n StartTimeChunk = chunk.Start,\n EndTimeChunk = chunk.End\n#endif\n };\n\n if (CanDebug) Log.Debug(string.Format(\"{0}->{1} ({2}->{3}): {4}\",\n start, end,\n chunk.Start, chunk.End,\n data.text));\n\n addSub(subData);\n }\n }\n finally\n {\n chunk.Stream.SetLength(0);\n memoryStreamPool.Push(chunk.Stream);\n\n if (!channel.Reader.TryRead(out _))\n throw new InvalidOperationException(\"can not discard AudioChunk from channel\");\n }\n }\n }\n\n unsafe void DoProducer()\n {\n _packet = av_packet_alloc();\n _frame = av_frame_alloc();\n\n // Whisper from the current playback position\n // TODO: L: Fold back and allow the first half to run as well.\n if (curTime > TimeSpan.FromSeconds(30))\n {\n // copy from DecoderContext.CalcSeekTimestamp()\n long startTime = _demuxer.hlsCtx == null ? _demuxer.StartTime : _demuxer.hlsCtx->first_timestamp * 10;\n long ticks = curTime.Ticks + startTime;\n\n bool forward = false;\n\n if (_demuxer.Type == MediaType.Audio) ticks -= _config.Audio.Delay;\n\n if (ticks < startTime)\n {\n ticks = startTime;\n forward = true;\n }\n else if (ticks > startTime + _demuxer.Duration - (50 * 10000))\n {\n ticks = Math.Max(startTime, startTime + _demuxer.Duration - (50 * 10000));\n forward = false;\n }\n\n _ = _demuxer.Seek(ticks, forward);\n }\n\n // When passing the audio file to Whisper, it must be converted to a 16000 sample rate WAV file.\n // For this purpose, the ffmpeg API is used to perform the conversion.\n // Audio files are divided by a certain size, stored in memory, and passed by memory stream.\n int targetSampleRate = 16000;\n int targetChannel = 1;\n MemoryStream waveStream = new(); // MemoryStream does not need to be disposed for releasing memory\n TimeSpan waveDuration = TimeSpan.Zero; // for logging\n\n const int waveHeaderSize = 44;\n\n // Stream processing is performed by dividing the audio by a certain size and passing it to whisper.\n long chunkSize = _config.Subtitles.ASRChunkSize;\n // Also split by elapsed seconds for live\n TimeSpan chunkElapsed = TimeSpan.FromSeconds(_config.Subtitles.ASRChunkSeconds);\n Stopwatch chunkSw = new();\n chunkSw.Start();\n\n WriteWavHeader(waveStream, targetSampleRate, targetChannel);\n\n int chunkCnt = 0;\n TimeSpan? chunkStart = null;\n long framePts = AV_NOPTS_VALUE;\n\n int demuxErrors = 0;\n int decodeErrors = 0;\n\n while (!token.IsCancellationRequested)\n {\n _demuxer.Interrupter.ReadRequest();\n int ret = av_read_frame(_demuxer.fmtCtx, _packet);\n\n if (ret != 0)\n {\n av_packet_unref(_packet);\n\n if (_demuxer.Interrupter.Timedout)\n {\n if (token.IsCancellationRequested)\n break;\n\n ret.ThrowExceptionIfError(\"av_read_frame (timed out)\");\n }\n\n if (ret == AVERROR_EOF || token.IsCancellationRequested)\n {\n break;\n }\n\n // demux error\n if (CanWarn) Log.Warn($\"av_read_frame: {FFmpegEngine.ErrorCodeToMsg(ret)} ({ret})\");\n\n if (++demuxErrors == _config.Demuxer.MaxErrors)\n {\n ret.ThrowExceptionIfError(\"av_read_frame\");\n }\n continue;\n }\n\n // Discard all but the selected audio stream.\n if (_packet->stream_index != _stream.StreamIndex)\n {\n av_packet_unref(_packet);\n continue;\n }\n\n ret = avcodec_send_packet(_decoder.CodecCtx, _packet);\n av_packet_unref(_packet);\n\n if (ret != 0)\n {\n if (ret == AVERROR(EAGAIN))\n {\n // Receive_frame and send_packet both returned EAGAIN, which is an API violation.\n ret.ThrowExceptionIfError(\"avcodec_send_packet (EAGAIN)\");\n }\n\n // decoder error\n if (CanWarn) Log.Warn($\"avcodec_send_packet: {FFmpegEngine.ErrorCodeToMsg(ret)} ({ret})\");\n\n if (++decodeErrors == _config.Decoder.MaxErrors)\n {\n ret.ThrowExceptionIfError(\"avcodec_send_packet\");\n }\n\n continue;\n }\n\n while (ret >= 0)\n {\n ret = avcodec_receive_frame(_decoder.CodecCtx, _frame);\n if (ret == AVERROR(EAGAIN) || ret == AVERROR_EOF)\n {\n break;\n }\n ret.ThrowExceptionIfError(\"avcodec_receive_frame\");\n\n if (_frame->best_effort_timestamp != AV_NOPTS_VALUE)\n {\n framePts = _frame->best_effort_timestamp;\n }\n else if (_frame->pts != AV_NOPTS_VALUE)\n {\n framePts = _frame->pts;\n }\n else\n {\n // Certain encoders sometimes cannot get pts (APE, Musepack)\n framePts += _frame->duration;\n }\n\n waveDuration = waveDuration.Add(new TimeSpan((long)(_frame->duration * _stream.Timebase)));\n\n if (chunkStart == null)\n {\n chunkStart = new TimeSpan((long)(framePts * _stream.Timebase) - _demuxer.StartTime);\n if (chunkStart.Value.Ticks < 0)\n {\n // Correct to 0 if negative\n chunkStart = new TimeSpan(0);\n }\n }\n\n ResampleTo(waveStream, _frame, targetSampleRate, targetChannel);\n\n // TODO: L: want it to split at the silent part\n if (waveStream.Length >= chunkSize || chunkSw.Elapsed >= chunkElapsed)\n {\n TimeSpan chunkEnd = new TimeSpan((long)(framePts * _stream.Timebase) - _demuxer.StartTime);\n chunkCnt++;\n\n if (CanInfo) Log.Info(\n $\"Process chunk (chunkNo: {chunkCnt}, sizeMB: {waveStream.Length / 1024 / 1024}, duration: {waveDuration}, elapsed: {chunkSw.Elapsed})\");\n\n UpdateWavHeader(waveStream);\n\n AudioChunk chunk = new(waveStream, chunkCnt, chunkStart.Value, chunkEnd);\n\n if (CanDebug) Log.Debug($\"Writing chunk to channel ({chunkCnt})\");\n // if channel capacity reached, it will be waited\n channel.Writer.WriteAsync(chunk, token).AsTask().Wait(token);\n if (CanDebug) Log.Debug($\"Done writing chunk to channel ({chunkCnt})\");\n\n if (memoryStreamPool.TryPop(out var stream))\n waveStream = stream;\n else\n waveStream = new MemoryStream();\n\n WriteWavHeader(waveStream, targetSampleRate, targetChannel);\n waveDuration = TimeSpan.Zero;\n\n chunkStart = null;\n chunkSw.Restart();\n framePts = AV_NOPTS_VALUE;\n }\n }\n }\n\n token.ThrowIfCancellationRequested();\n\n // Process remaining\n if (waveStream.Length > waveHeaderSize && framePts != AV_NOPTS_VALUE)\n {\n TimeSpan chunkEnd = new TimeSpan((long)(framePts * _stream.Timebase) - _demuxer.StartTime);\n\n chunkCnt++;\n\n if (CanInfo) Log.Info(\n $\"Process last chunk (chunkNo: {chunkCnt}, sizeMB: {waveStream.Length / 1024 / 1024}, duration: {waveDuration}, elapsed: {chunkSw.Elapsed})\");\n\n UpdateWavHeader(waveStream);\n\n AudioChunk chunk = new(waveStream, chunkCnt, chunkStart!.Value, chunkEnd);\n\n if (CanDebug) Log.Debug($\"Writing last chunk to channel ({chunkCnt})\");\n channel.Writer.WriteAsync(chunk, token).AsTask().Wait(token);\n if (CanDebug) Log.Debug($\"Done writing last chunk to channel ({chunkCnt})\");\n }\n }\n }\n\n private static void WriteWavHeader(Stream stream, int sampleRate, int channels)\n {\n using BinaryWriter writer = new(stream, Encoding.UTF8, true);\n writer.Write(['R', 'I', 'F', 'F']);\n writer.Write(0); // placeholder for file size\n writer.Write(['W', 'A', 'V', 'E']);\n writer.Write(['f', 'm', 't', ' ']);\n writer.Write(16); // PCM header size\n writer.Write((short)1); // PCM format\n writer.Write((short)channels);\n writer.Write(sampleRate);\n writer.Write(sampleRate * channels * 2); // Byte rate\n writer.Write((short)(channels * 2)); // Block align\n writer.Write((short)16); // Bits per sample\n writer.Write(['d', 'a', 't', 'a']);\n writer.Write(0); // placeholder for data size\n }\n\n private static void UpdateWavHeader(Stream stream)\n {\n long fileSize = stream.Length;\n stream.Seek(4, SeekOrigin.Begin);\n stream.Write(BitConverter.GetBytes((int)(fileSize - 8)), 0, 4);\n stream.Seek(40, SeekOrigin.Begin);\n stream.Write(BitConverter.GetBytes((int)(fileSize - 44)), 0, 4);\n stream.Position = 0;\n }\n\n private byte[] _sampledBuf = [];\n private int _sampledBufSize;\n\n // for codec change detection\n private int _lastFormat;\n private int _lastSampleRate;\n private ulong _lastChannelLayout;\n\n private unsafe void ResampleTo(Stream toStream, AVFrame* frame, int targetSampleRate, int targetChannel)\n {\n bool codecChanged = false;\n\n if (_lastFormat != frame->format)\n {\n _lastFormat = frame->format;\n codecChanged = true;\n }\n if (_lastSampleRate != frame->sample_rate)\n {\n _lastSampleRate = frame->sample_rate;\n codecChanged = true;\n }\n if (_lastChannelLayout != frame->ch_layout.u.mask)\n {\n _lastChannelLayout = frame->ch_layout.u.mask;\n codecChanged = true;\n }\n\n // Reinitialize SwrContext because codec changed\n // Note that native error will occur if not reinitialized.\n // Reference: AudioDecoder::RunInternal\n if (_swrContext != null && codecChanged)\n {\n fixed (SwrContext** ptr = &_swrContext)\n {\n swr_free(ptr);\n }\n _swrContext = null;\n }\n\n if (_swrContext == null)\n {\n AVChannelLayout outLayout;\n av_channel_layout_default(&outLayout, targetChannel);\n\n // NOTE: important to reuse this context\n fixed (SwrContext** ptr = &_swrContext)\n {\n swr_alloc_set_opts2(\n ptr,\n &outLayout,\n AVSampleFormat.S16,\n targetSampleRate,\n &frame->ch_layout,\n (AVSampleFormat)frame->format,\n frame->sample_rate,\n 0, null)\n .ThrowExceptionIfError(\"swr_alloc_set_opts2\");\n\n swr_init(_swrContext)\n .ThrowExceptionIfError(\"swr_init\");\n }\n }\n\n // ffmpeg ref: https://github.com/FFmpeg/FFmpeg/blob/504df09c34607967e4109b7b114ee084cf15a3ae/libavfilter/af_aresample.c#L171-L227\n double ratio = targetSampleRate * 1.0 / frame->sample_rate; // 16000:44100=0.36281179138321995\n int nOut = (int)(frame->nb_samples * ratio) + 32;\n\n long delay = swr_get_delay(_swrContext, targetSampleRate);\n if (delay > 0)\n {\n nOut += (int)Math.Min(delay, Math.Max(4096, nOut));\n }\n int needed = nOut * targetChannel * sizeof(ushort);\n\n if (_sampledBufSize < needed)\n {\n _sampledBuf = new byte[needed];\n _sampledBufSize = needed;\n }\n\n int samplesPerChannel;\n\n fixed (byte* dst = _sampledBuf)\n {\n samplesPerChannel = swr_convert(\n _swrContext,\n &dst,\n nOut,\n frame->extended_data,\n frame->nb_samples);\n }\n samplesPerChannel.ThrowExceptionIfError(\"swr_convert\");\n\n int resampledDataSize = samplesPerChannel * targetChannel * sizeof(ushort);\n\n toStream.Write(_sampledBuf, 0, resampledDataSize);\n }\n\n private bool _isDisposed;\n\n public unsafe void Dispose()\n {\n if (_isDisposed)\n return;\n\n // av_frame_alloc\n if (_frame != null)\n {\n fixed (AVFrame** ptr = &_frame)\n {\n av_frame_free(ptr);\n }\n }\n\n // av_packet_alloc\n if (_packet != null)\n {\n fixed (AVPacket** ptr = &_packet)\n {\n av_packet_free(ptr);\n }\n }\n\n // swr_init\n if (_swrContext != null)\n {\n fixed (SwrContext** ptr = &_swrContext)\n {\n swr_free(ptr);\n }\n }\n\n _decoder?.Dispose();\n if (_demuxer != null)\n {\n _demuxer.Interrupter.ForceInterrupt = 0;\n _demuxer.Dispose();\n }\n\n _isDisposed = true;\n }\n}\n\npublic interface IASRService : IAsyncDisposable\n{\n public IAsyncEnumerable<(string text, TimeSpan start, TimeSpan end, string language)> Do(MemoryStream waveStream, CancellationToken token);\n}\n\n// https://github.com/sandrohanea/whisper.net\n// https://github.com/ggerganov/whisper.cpp\npublic class WhisperCppASRService : IASRService\n{\n private readonly Config _config;\n\n private readonly LogHandler Log;\n private readonly IDisposable _logger;\n private readonly WhisperFactory _factory;\n private readonly WhisperProcessor _processor;\n\n private readonly bool _isLanguageDetect;\n private string? _detectedLanguage;\n\n public WhisperCppASRService(Config config)\n {\n _config = config;\n Log = new LogHandler((\"[#1]\").PadRight(8, ' ') + \" [WhisperCpp ] \");\n\n if (_config.Subtitles.WhisperCppConfig.RuntimeLibraries.Count >= 1)\n {\n RuntimeOptions.RuntimeLibraryOrder = [.. _config.Subtitles.WhisperCppConfig.RuntimeLibraries];\n }\n else\n {\n RuntimeOptions.RuntimeLibraryOrder = [RuntimeLibrary.Cpu, RuntimeLibrary.CpuNoAvx]; // fallback to default\n }\n\n _logger = CanDebug\n ? LogProvider.AddLogger((level, s) => Log.Debug($\"[Whisper.net] [{level.ToString()}] {s}\"))\n : Disposable.Empty;\n\n if (CanDebug) Log.Debug($\"Selecting whisper runtime libraries from ({string.Join(\",\", RuntimeOptions.RuntimeLibraryOrder)})\");\n\n _factory = WhisperFactory.FromPath(_config.Subtitles.WhisperCppConfig.Model!.ModelFilePath, _config.Subtitles.WhisperCppConfig.GetFactoryOptions());\n\n if (CanDebug) Log.Debug($\"Selected whisper runtime library '{RuntimeOptions.LoadedLibrary}'\");\n\n WhisperProcessorBuilder whisperBuilder = _factory.CreateBuilder();\n _processor = _config.Subtitles.WhisperCppConfig.ConfigureBuilder(_config.Subtitles.WhisperConfig, whisperBuilder).Build();\n\n if (_config.Subtitles.WhisperCppConfig.IsEnglishModel)\n {\n _isLanguageDetect = false;\n _detectedLanguage = \"en\";\n }\n else\n {\n _isLanguageDetect = _config.Subtitles.WhisperConfig.LanguageDetection;\n }\n }\n\n public async ValueTask DisposeAsync()\n {\n await _processor.DisposeAsync();\n _factory.Dispose();\n _logger.Dispose();\n }\n\n public async IAsyncEnumerable<(string text, TimeSpan start, TimeSpan end, string language)> Do(MemoryStream waveStream, [EnumeratorCancellation] CancellationToken token)\n {\n // If language detection is on, set detected language manually\n // TODO: L: Currently this is set because language information is managed for the entire subtitle,\n // but if language information is maintained for each subtitle, it should not be set.\n if (_isLanguageDetect && _detectedLanguage is not null)\n {\n _processor.ChangeLanguage(_detectedLanguage);\n }\n\n await foreach (var result in _processor.ProcessAsync(waveStream, token).ConfigureAwait(false))\n {\n token.ThrowIfCancellationRequested();\n\n if (_detectedLanguage is null && !string.IsNullOrEmpty(result.Language))\n {\n _detectedLanguage = result.Language;\n }\n\n string text = result.Text.Trim(); // remove leading whitespace\n\n yield return (text, result.Start, result.End, result.Language);\n }\n }\n}\n\n// https://github.com/Purfview/whisper-standalone-win\n// Purfview's Stand-alone Faster-Whisper-XXL & Faster-Whisper\n// Do not support official OpenAI Whisper version\npublic partial class FasterWhisperASRService : IASRService\n{\n private readonly Config _config;\n\n public FasterWhisperASRService(Config config)\n {\n _config = config;\n\n _cmdBase = BuildCommand(_config.Subtitles.FasterWhisperConfig, _config.Subtitles.WhisperConfig);\n\n if (_config.Subtitles.FasterWhisperConfig.IsEnglishModel)\n {\n // force English and disable auto-detection\n _isLanguageDetect = false;\n _manualLanguage = \"en\";\n }\n else\n {\n _isLanguageDetect = _config.Subtitles.WhisperConfig.LanguageDetection;\n _manualLanguage = _config.Subtitles.WhisperConfig.Language;\n }\n\n if (!_config.Subtitles.FasterWhisperConfig.UseManualModel)\n {\n WhisperConfig.EnsureModelsDirectory();\n }\n }\n\n private readonly Command _cmdBase;\n private readonly bool _isLanguageDetect;\n private readonly string _manualLanguage;\n private string? _detectedLanguage;\n\n [GeneratedRegex(\"^Detected language '(.+)' with probability\")]\n private static partial Regex LanguageReg { get; }\n\n [GeneratedRegex(@\"^\\[\\d{2}:\\d{2}\\.\\d{3} --> \\d{2}:\\d{2}\\.\\d{3}\\] \")]\n private static partial Regex SubShortReg { get; } // [08:15.050 --> 08:16.450] Text\n\n [GeneratedRegex(@\"^\\[\\d{2}:\\d{2}:\\d{2}\\.\\d{3} --> \\d{2}:\\d{2}:\\d{2}\\.\\d{3}\\] \")]\n private static partial Regex SubLongReg { get; } // [02:08:15.050 --> 02:08:16.450] Text\n\n [GeneratedRegex(\"^Operation finished in:\")]\n private static partial Regex EndReg { get; }\n\n\n public ValueTask DisposeAsync()\n {\n return ValueTask.CompletedTask;\n }\n\n public static Command BuildCommand(FasterWhisperConfig config, WhisperConfig commonConfig)\n {\n string tempFolder = Path.GetTempPath();\n string enginePath = config.UseManualEngine ? config.ManualEnginePath! : FasterWhisperConfig.DefaultEnginePath;\n\n ArgumentsBuilder args = new();\n args.Add(\"--output_dir\").Add(tempFolder);\n args.Add(\"--output_format\").Add(\"srt\");\n args.Add(\"--verbose\").Add(\"True\");\n args.Add(\"--beep_off\");\n args.Add(\"--model\").Add(config.Model);\n args.Add(\"--model_dir\")\n .Add(config.UseManualModel ? config.ManualModelDir! : WhisperConfig.ModelsDirectory);\n\n if (config.IsEnglishModel)\n {\n args.Add(\"--language\").Add(\"en\");\n }\n else\n {\n if (commonConfig.Translate)\n args.Add(\"--task\").Add(\"translate\");\n\n if (!commonConfig.LanguageDetection)\n args.Add(\"--language\").Add(commonConfig.Language);\n }\n\n string arguments = args.Build();\n\n if (!string.IsNullOrWhiteSpace(config.ExtraArguments))\n {\n arguments += $\" {config.ExtraArguments}\";\n }\n\n Command cmd = Cli.Wrap(enginePath)\n .WithArguments(arguments)\n .WithValidation(CommandResultValidation.None);\n\n if (config.ProcessPriority != ProcessPriorityClass.Normal)\n {\n cmd = cmd.WithResourcePolicy(builder =>\n builder.SetPriority(config.ProcessPriority));\n }\n\n return cmd;\n }\n\n private static TimeSpan ParseTime(ReadOnlySpan time, bool isLong)\n {\n if (isLong)\n {\n // 01:28:02.130\n // hh:mm:ss.fff\n int hours = int.Parse(time[..2]);\n int minutes = int.Parse(time[3..5]);\n int seconds = int.Parse(time[6..8]);\n int milliseconds = int.Parse(time[9..12]);\n return new TimeSpan(0, hours, minutes, seconds, milliseconds);\n }\n else\n {\n // 28:02.130\n // mm:ss.fff\n int minutes = int.Parse(time[..2]);\n int seconds = int.Parse(time[3..5]);\n int milliseconds = int.Parse(time[6..9]);\n return new TimeSpan(0, 0, minutes, seconds, milliseconds);\n }\n }\n\n public async IAsyncEnumerable<(string text, TimeSpan start, TimeSpan end, string language)> Do(MemoryStream waveStream, [EnumeratorCancellation] CancellationToken token)\n {\n string tempFilePath = Path.GetTempFileName();\n // because no output option\n string outputFilePath = Path.ChangeExtension(tempFilePath, \"srt\");\n\n // write WAV to tmp folder\n await using (FileStream fileStream = new(tempFilePath, FileMode.Create, FileAccess.Write))\n {\n waveStream.WriteTo(fileStream);\n }\n\n CancellationTokenSource forceCts = new();\n token.Register(() =>\n {\n // force kill if not exited when sending interrupt\n forceCts.CancelAfter(5000);\n });\n\n try\n {\n string? lastLine = null;\n StringBuilder output = new(); // for error output\n Lock outputLock = new();\n bool oneSuccess = false;\n\n ArgumentsBuilder args = new();\n if (_isLanguageDetect && !string.IsNullOrEmpty(_detectedLanguage))\n {\n args.Add(\"--language\").Add(_detectedLanguage);\n }\n args.Add(tempFilePath);\n string addedArgs = args.Build();\n\n Command cmd = _cmdBase.WithArguments($\"{_cmdBase.Arguments} {addedArgs}\");\n\n await foreach (var cmdEvent in cmd.ListenAsync(Encoding.Default, Encoding.Default, forceCts.Token, token))\n {\n token.ThrowIfCancellationRequested();\n\n if (cmdEvent is StandardErrorCommandEvent stdErr)\n {\n lock (outputLock)\n {\n output.AppendLine(stdErr.Text);\n }\n\n continue;\n }\n\n if (cmdEvent is not StandardOutputCommandEvent stdOut)\n {\n continue;\n }\n\n string line = stdOut.Text;\n\n // process stdout\n if (!oneSuccess)\n {\n lock (outputLock)\n {\n output.AppendLine(line);\n }\n\n }\n if (string.IsNullOrEmpty(line))\n {\n continue;\n }\n\n lastLine = line;\n\n if (_isLanguageDetect && _detectedLanguage == null)\n {\n var match = LanguageReg.Match(line);\n if (match.Success)\n {\n string languageName = match.Groups[1].Value;\n _detectedLanguage = WhisperLanguage.LanguageToCode[languageName];\n }\n\n continue;\n }\n\n bool isLong = false;\n\n Match subtitleMatch = SubShortReg.Match(line);\n if (!subtitleMatch.Success)\n {\n subtitleMatch = SubLongReg.Match(line);\n if (!subtitleMatch.Success)\n {\n continue;\n }\n\n isLong = true;\n }\n\n ReadOnlySpan lineSpan = line.AsSpan();\n\n Range startRange = 1..10;\n Range endRange = 15..24;\n Range textRange = 26..;\n\n if (isLong)\n {\n startRange = 1..13;\n endRange = 18..30;\n textRange = 32..;\n }\n\n TimeSpan start = ParseTime(lineSpan[startRange], isLong);\n TimeSpan end = ParseTime(lineSpan[endRange], isLong);\n // because some languages have leading spaces\n string text = lineSpan[textRange].Trim().ToString();\n\n yield return (text, start, end, _isLanguageDetect ? _detectedLanguage! : _manualLanguage);\n\n if (!oneSuccess)\n {\n oneSuccess = true;\n }\n }\n\n // validate if success\n if (lastLine == null || !EndReg.Match(lastLine).Success)\n {\n throw new InvalidOperationException(\"Failed to execute faster-whisper\")\n {\n Data =\n {\n [\"whisper_command\"] = cmd.CommandToText(),\n [\"whisper_output\"] = output.ToString()\n }\n };\n }\n }\n finally\n {\n // delete tmp wave\n if (File.Exists(tempFilePath))\n {\n File.Delete(tempFilePath);\n }\n // delete output srt\n if (File.Exists(outputFilePath))\n {\n File.Delete(outputFilePath);\n }\n }\n }\n}\n\npublic class SubtitleASRData\n{\n public required string Text { get; init; }\n public required TimeSpan StartTime { get; init; }\n public required TimeSpan EndTime { get; init; }\n\n#if DEBUG\n public required int ChunkNo { get; init; }\n public required TimeSpan StartTimeChunk { get; init; }\n public required TimeSpan EndTimeChunk { get; init; }\n#endif\n\n public TimeSpan Duration => EndTime - StartTime;\n\n // ISO6391\n // ref: https://github.com/openai/whisper/blob/main/whisper/tokenizer.py#L10\n public required string Language { get; init; }\n}\n"], ["/LLPlayer/LLPlayer/Controls/WordPopup.xaml.cs", "using System.ComponentModel;\nusing System.Diagnostics;\nusing System.Runtime.CompilerServices;\nusing System.Windows;\nusing System.Windows.Controls;\nusing System.Windows.Controls.Primitives;\nusing System.Windows.Input;\nusing System.Windows.Threading;\nusing FlyleafLib;\nusing FlyleafLib.MediaPlayer;\nusing FlyleafLib.MediaPlayer.Translation;\nusing FlyleafLib.MediaPlayer.Translation.Services;\nusing LLPlayer.Extensions;\nusing LLPlayer.Services;\n\nnamespace LLPlayer.Controls;\n\npublic partial class WordPopup : UserControl, INotifyPropertyChanged\n{\n public FlyleafManager FL { get; }\n private ITranslateService? _translateService;\n private readonly TranslateServiceFactory _translateServiceFactory;\n private PDICSender? _pdicSender;\n private readonly Lock _locker = new();\n\n private string _clickedWords = string.Empty;\n private string _clickedText = string.Empty;\n\n private CancellationTokenSource? _cts;\n private readonly Dictionary _translateCache = new();\n private string? _lastSearchActionUrl;\n\n public WordPopup()\n {\n InitializeComponent();\n\n FL = ((App)Application.Current).Container.Resolve();\n\n FL.Player.PropertyChanged += Player_OnPropertyChanged;\n\n _translateServiceFactory = new TranslateServiceFactory(FL.PlayerConfig.Subtitles);\n\n FL.PlayerConfig.Subtitles.PropertyChanged += SubtitlesOnPropertyChanged;\n FL.PlayerConfig.Subtitles.TranslateChatConfig.PropertyChanged += ChatConfigOnPropertyChanged;\n FL.Player.SubtitlesManager[0].PropertyChanged += SubManagerOnPropertyChanged;\n FL.Player.SubtitlesManager[1].PropertyChanged += SubManagerOnPropertyChanged;\n FL.Config.Subs.PropertyChanged += SubsOnPropertyChanged;\n\n InitializeContextMenu();\n }\n\n public bool IsLoading { get; set => Set(ref field, value); }\n\n public bool IsOpen { get; set => Set(ref field, value); }\n\n public UIElement? PopupPlacementTarget { get; set => Set(ref field, value); }\n\n public double PopupHorizontalOffset { get; set => Set(ref field, value); }\n\n public double PopupVerticalOffset { get; set => Set(ref field, value); }\n\n public ContextMenu? PopupContextMenu { get; set => Set(ref field, value); }\n public ContextMenu? WordContextMenu { get; set => Set(ref field, value); }\n\n public bool IsSidebar { get; set; }\n\n private void SubtitlesOnPropertyChanged(object? sender, PropertyChangedEventArgs e)\n {\n switch (e.PropertyName)\n {\n case nameof(Config.SubtitlesConfig.TranslateWordServiceType):\n case nameof(Config.SubtitlesConfig.TranslateTargetLanguage):\n case nameof(Config.SubtitlesConfig.LanguageFallbackPrimary):\n // Apply translating settings changes\n Clear();\n break;\n }\n }\n\n private void ChatConfigOnPropertyChanged(object? sender, PropertyChangedEventArgs e)\n {\n // Apply translating settings changes\n Clear();\n }\n\n private void SubManagerOnPropertyChanged(object? sender, PropertyChangedEventArgs e)\n {\n if (e.PropertyName == nameof(SubManager.Language))\n {\n // Apply source language changes\n Clear();\n }\n }\n\n private void SubsOnPropertyChanged(object? sender, PropertyChangedEventArgs e)\n {\n if (e.PropertyName == nameof(AppConfigSubs.WordMenuActions))\n {\n // Apply word action settings changes\n InitializeContextMenu();\n }\n }\n\n private void Clear()\n {\n _translateService?.Dispose();\n _translateService = null;\n // clear cache\n _translateCache.Clear();\n }\n\n private void InitializeContextMenu()\n {\n var contextMenuStyle = (Style)FindResource(\"FlyleafContextMenu\");\n\n ContextMenu popupMenu = new()\n {\n Placement = PlacementMode.Mouse,\n Style = contextMenuStyle\n };\n\n SetupContextMenu(popupMenu);\n PopupContextMenu = popupMenu;\n\n ContextMenu wordMenu = new()\n {\n Placement = PlacementMode.Mouse,\n Style = contextMenuStyle\n };\n\n SetupContextMenu(wordMenu);\n WordContextMenu = wordMenu;\n }\n\n private void SetupContextMenu(ContextMenu contextMenu)\n {\n IEnumerable actions = FL.Config.Subs.WordMenuActions.Where(a => a.IsEnabled);\n foreach (IMenuAction action in actions)\n {\n MenuItem menuItem = new() { Header = action.Title };\n\n // Initialize default action at the top\n // TODO: L: want to make the default action bold.\n if (_lastSearchActionUrl == null && action is SearchMenuAction sa)\n {\n // Only word search available\n if (sa.Url.Contains(\"%w\") || sa.Url.Contains(\"%lw\"))\n {\n _lastSearchActionUrl = sa.Url;\n }\n }\n\n menuItem.Click += (o, args) =>\n {\n if (action is SearchMenuAction searchAction)\n {\n // Only word search available\n if (searchAction.Url.Contains(\"%w\") || searchAction.Url.Contains(\"%lw\"))\n {\n _lastSearchActionUrl = searchAction.Url;\n }\n\n OpenWeb(searchAction.Url, _clickedWords, _clickedText);\n }\n else if (action is ClipboardMenuAction clipboardAction)\n {\n CopyToClipboard(_clickedWords, clipboardAction.ToLower);\n }\n else if (action is ClipboardAllMenuAction clipboardAllAction)\n {\n CopyToClipboard(_clickedText, clipboardAllAction.ToLower);\n }\n };\n contextMenu.Items.Add(menuItem);\n }\n }\n\n // Click on video screen to close pop-up\n private void Player_OnPropertyChanged(object? sender, PropertyChangedEventArgs args)\n {\n if (args.PropertyName == nameof(FL.Player.Status) && FL.Player.Status == Status.Playing)\n {\n IsOpen = false;\n }\n }\n\n private async ValueTask TranslateWithCache(string text, WordClickedEventArgs e, CancellationToken token)\n {\n // already translated by translator\n if (e.IsTranslated)\n {\n return text;\n }\n\n var srcLang = FL.Player.SubtitlesManager[e.SubIndex].Language;\n var targetLang = FL.PlayerConfig.Subtitles.TranslateTargetLanguage;\n\n // Not set language or same language\n if (srcLang == null || srcLang.ISO6391 == targetLang.ToISO6391())\n {\n return text;\n }\n\n string lower = text.ToLower();\n if (_translateCache.TryGetValue(lower, out var cache))\n {\n return cache;\n }\n\n if (_translateService == null)\n {\n try\n {\n var service = _translateServiceFactory.GetService(FL.PlayerConfig.Subtitles.TranslateWordServiceType, true);\n service.Initialize(srcLang, targetLang);\n _translateService = service;\n }\n catch (TranslationConfigException ex)\n {\n Clear();\n ErrorDialogHelper.ShowKnownErrorPopup(ex.Message, KnownErrorType.Configuration);\n\n return text;\n }\n }\n\n try\n {\n string result = await _translateService.TranslateAsync(text, token);\n _translateCache.TryAdd(lower, result);\n\n return result;\n }\n catch (TranslationException ex)\n {\n ErrorDialogHelper.ShowUnknownErrorPopup(ex.Message, UnknownErrorType.Translation, ex);\n\n return text;\n }\n }\n\n public async Task OnWordClicked(WordClickedEventArgs e)\n {\n _clickedWords = e.Words;\n _clickedText = e.Text;\n\n if (FL.Player.Status == Status.Playing)\n {\n FL.Player.Pause();\n }\n\n if (e.Mouse is MouseClick.Left or MouseClick.Middle)\n {\n switch (FL.Config.Subs.WordClickActionMethod)\n {\n case WordClickAction.Clipboard:\n CopyToClipboard(e.Words);\n break;\n\n case WordClickAction.ClipboardAll:\n CopyToClipboard(e.Text);\n break;\n\n default:\n await Popup(e);\n break;\n }\n }\n else if (e.Mouse == MouseClick.Right)\n {\n WordContextMenu!.IsOpen = true;\n }\n }\n\n private async Task Popup(WordClickedEventArgs e)\n {\n if (FL.Config.Subs.WordCopyOnSelected)\n {\n CopyToClipboard(e.Words);\n }\n\n if (FL.Config.Subs.WordClickActionMethod == WordClickAction.PDIC && e.IsWord)\n {\n if (_pdicSender == null)\n {\n // Initialize PDIC lazily\n lock (_locker)\n {\n _pdicSender ??= ((App)Application.Current).Container.Resolve();\n }\n }\n\n _ = _pdicSender.SendWithPipe(e.Text, e.WordOffset + 1);\n return;\n }\n\n if (_cts != null)\n {\n // Canceled if running ahead\n _cts.Cancel();\n _cts.Dispose();\n }\n\n _cts = new CancellationTokenSource();\n\n string source = e.Words;\n\n IsLoading = true;\n\n SourceText.Text = source;\n TranslationText.Text = \"\";\n\n if (IsSidebar && e.Sender is SelectableTextBox)\n {\n var listBoxItem = UIHelper.FindParent(e.Sender);\n if (listBoxItem != null)\n {\n PopupPlacementTarget = listBoxItem;\n }\n }\n\n if (FL.Config.Subs.WordLastSearchOnSelected)\n {\n if (Keyboard.Modifiers == FL.Config.Subs.WordLastSearchOnSelectedModifier)\n {\n if (_lastSearchActionUrl != null)\n {\n OpenWeb(_lastSearchActionUrl, source);\n }\n }\n }\n\n IsOpen = true;\n\n await UpdatePosition();\n\n try\n {\n string result = await TranslateWithCache(source, e, _cts.Token);\n TranslationText.Text = result;\n IsLoading = false;\n }\n catch (OperationCanceledException)\n {\n return;\n }\n\n await UpdatePosition();\n\n return;\n\n async Task UpdatePosition()\n {\n // ActualWidth is updated asynchronously, so it needs to be offloaded in the Dispatcher.\n await Dispatcher.BeginInvoke(() =>\n {\n if (IsSidebar && PopupPlacementTarget != null)\n {\n // for sidebar\n PopupVerticalOffset = (((ListBoxItem)PopupPlacementTarget).ActualHeight - ActualHeight) / 2;\n PopupHorizontalOffset = -ActualWidth - 10;\n }\n else\n {\n // for subtitle\n PopupHorizontalOffset = e.WordsX + ((e.WordsWidth - ActualWidth) / 2);\n PopupVerticalOffset = -ActualHeight;\n }\n\n }, DispatcherPriority.Background);\n }\n }\n\n private void CloseButton_OnMouseLeftButtonUp(object sender, MouseButtonEventArgs e)\n {\n IsOpen = false;\n }\n\n private void SourceText_OnMouseLeftButtonUp(object sender, MouseButtonEventArgs e)\n {\n if (_lastSearchActionUrl != null)\n {\n OpenWeb(_lastSearchActionUrl, SourceText.Text);\n }\n }\n\n private static void CopyToClipboard(string text, bool toLower = false)\n {\n if (string.IsNullOrWhiteSpace(text))\n {\n return;\n }\n\n if (toLower)\n {\n text = text.ToLower();\n }\n\n // copy word\n try\n {\n // slow (10ms)\n //Clipboard.SetText(text);\n\n WindowsClipboard.SetText(text);\n }\n catch\n {\n // ignored\n }\n }\n\n private static void OpenWeb(string url, string words, string sentence = \"\")\n {\n if (url.Contains(\"%lw\"))\n {\n url = url.Replace(\"%lw\", Uri.EscapeDataString(words.ToLower()));\n }\n\n if (url.Contains(\"%w\"))\n {\n url = url.Replace(\"%w\", Uri.EscapeDataString(words));\n }\n\n if (url.Contains(\"%s\"))\n {\n url = url.Replace(\"%s\", Uri.EscapeDataString(sentence));\n }\n\n Process.Start(new ProcessStartInfo\n {\n FileName = url,\n UseShellExecute = true\n });\n }\n\n #region INotifyPropertyChanged\n public event PropertyChangedEventHandler? PropertyChanged;\n\n protected virtual void OnPropertyChanged([CallerMemberName] string? propertyName = null)\n {\n PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));\n }\n\n protected bool Set(ref T field, T value, [CallerMemberName] string? propertyName = null)\n {\n if (EqualityComparer.Default.Equals(field, value))\n return false;\n field = value;\n OnPropertyChanged(propertyName);\n return true;\n }\n #endregion\n}\n"], ["/LLPlayer/FlyleafLib/MediaFramework/MediaRenderer/Renderer.Device.cs", "using System.Numerics;\nusing System.Text.RegularExpressions;\n\nusing Vortice;\nusing Vortice.Direct3D;\nusing Vortice.Direct3D11;\nusing Vortice.DXGI;\nusing Vortice.DXGI.Debug;\n\nusing FlyleafLib.MediaFramework.MediaDecoder;\n\nusing static FlyleafLib.Logger;\nusing System.Runtime.InteropServices;\n\nusing ID3D11Device = Vortice.Direct3D11.ID3D11Device;\nusing ID3D11DeviceContext = Vortice.Direct3D11.ID3D11DeviceContext;\n\nnamespace FlyleafLib.MediaFramework.MediaRenderer;\n\npublic unsafe partial class Renderer\n{\n static InputElementDescription[] inputElements =\n {\n new(\"POSITION\", 0, Format.R32G32B32_Float, 0),\n new(\"TEXCOORD\", 0, Format.R32G32_Float, 0),\n };\n\n static BufferDescription vertexBufferDesc = new()\n {\n BindFlags = BindFlags.VertexBuffer\n };\n\n static float[] vertexBufferData = new[]\n {\n -1.0f, -1.0f, 0, 0.0f, 1.0f,\n -1.0f, 1.0f, 0, 0.0f, 0.0f,\n 1.0f, -1.0f, 0, 1.0f, 1.0f,\n\n 1.0f, -1.0f, 0, 1.0f, 1.0f,\n -1.0f, 1.0f, 0, 0.0f, 0.0f,\n 1.0f, 1.0f, 0, 1.0f, 0.0f\n };\n\n static FeatureLevel[] featureLevelsAll = new[]\n {\n FeatureLevel.Level_12_1,\n FeatureLevel.Level_12_0,\n FeatureLevel.Level_11_1,\n FeatureLevel.Level_11_0,\n FeatureLevel.Level_10_1,\n FeatureLevel.Level_10_0,\n FeatureLevel.Level_9_3,\n FeatureLevel.Level_9_2,\n FeatureLevel.Level_9_1\n };\n\n static FeatureLevel[] featureLevels = new[]\n {\n FeatureLevel.Level_11_0,\n FeatureLevel.Level_10_1,\n FeatureLevel.Level_10_0,\n FeatureLevel.Level_9_3,\n FeatureLevel.Level_9_2,\n FeatureLevel.Level_9_1\n };\n\n static BlendDescription blendDesc = new();\n\n static Renderer()\n {\n blendDesc.RenderTarget[0].BlendEnable = true;\n blendDesc.RenderTarget[0].SourceBlend = Blend.SourceAlpha;\n blendDesc.RenderTarget[0].DestinationBlend = Blend.InverseSourceAlpha;\n blendDesc.RenderTarget[0].BlendOperation = BlendOperation.Add;\n blendDesc.RenderTarget[0].SourceBlendAlpha = Blend.Zero;\n blendDesc.RenderTarget[0].DestinationBlendAlpha = Blend.Zero;\n blendDesc.RenderTarget[0].BlendOperationAlpha = BlendOperation.Add;\n blendDesc.RenderTarget[0].RenderTargetWriteMask = ColorWriteEnable.All;\n }\n\n\n ID3D11DeviceContext context;\n\n ID3D11Buffer vertexBuffer;\n ID3D11InputLayout inputLayout;\n ID3D11RasterizerState\n rasterizerState;\n ID3D11BlendState blendStateAlpha;\n\n ID3D11VertexShader ShaderVS;\n ID3D11PixelShader ShaderPS;\n ID3D11PixelShader ShaderBGRA;\n\n ID3D11Buffer psBuffer;\n PSBufferType psBufferData;\n\n ID3D11Buffer vsBuffer;\n VSBufferType vsBufferData;\n\n internal object lockDevice = new();\n bool isFlushing;\n\n public void Initialize(bool swapChain = true)\n {\n lock (lockDevice)\n {\n try\n {\n if (CanDebug) Log.Debug(\"Initializing\");\n\n if (!Disposed)\n Dispose();\n\n Disposed = false;\n\n ID3D11Device tempDevice;\n IDXGIAdapter1 adapter = null;\n var creationFlags = DeviceCreationFlags.BgraSupport /*| DeviceCreationFlags.VideoSupport*/; // Let FFmpeg failed for VA if does not support it\n var creationFlagsWarp = DeviceCreationFlags.None;\n\n #if DEBUG\n if (D3D11.SdkLayersAvailable())\n {\n creationFlags |= DeviceCreationFlags.Debug;\n creationFlagsWarp |= DeviceCreationFlags.Debug;\n }\n #endif\n\n // Finding User Definied adapter\n if (!string.IsNullOrWhiteSpace(Config.Video.GPUAdapter) && Config.Video.GPUAdapter.ToUpper() != \"WARP\")\n {\n for (uint i=0; Engine.Video.Factory.EnumAdapters1(i, out adapter).Success; i++)\n {\n if (adapter.Description1.Description == Config.Video.GPUAdapter)\n break;\n\n if (Regex.IsMatch(adapter.Description1.Description + \" luid=\" + adapter.Description1.Luid, Config.Video.GPUAdapter, RegexOptions.IgnoreCase))\n break;\n\n adapter.Dispose();\n }\n\n if (adapter == null)\n {\n Log.Error($\"GPU Adapter with {Config.Video.GPUAdapter} has not been found. Falling back to default.\");\n Config.Video.GPUAdapter = null;\n }\n }\n\n // Creating WARP (force by user or us after late failure)\n if (!string.IsNullOrWhiteSpace(Config.Video.GPUAdapter) && Config.Video.GPUAdapter.ToUpper() == \"WARP\")\n D3D11.D3D11CreateDevice(null, DriverType.Warp, creationFlagsWarp, featureLevels, out tempDevice).CheckError();\n\n // Creating User Defined or Default\n else\n {\n // Creates the D3D11 Device based on selected adapter or default hardware (highest to lowest features and fall back to the WARP device. see http://go.microsoft.com/fwlink/?LinkId=286690)\n if (D3D11.D3D11CreateDevice(adapter, adapter == null ? DriverType.Hardware : DriverType.Unknown, creationFlags, featureLevelsAll, out tempDevice).Failure)\n if (D3D11.D3D11CreateDevice(adapter, adapter == null ? DriverType.Hardware : DriverType.Unknown, creationFlags, featureLevels, out tempDevice).Failure)\n {\n Config.Video.GPUAdapter = \"WARP\";\n D3D11.D3D11CreateDevice(null, DriverType.Warp, creationFlagsWarp, featureLevels, out tempDevice).CheckError();\n }\n }\n\n Device = tempDevice.QueryInterface();\n context= Device.ImmediateContext;\n\n // Gets the default adapter from the D3D11 Device\n if (adapter == null)\n {\n Device.Tag = new Luid().ToString();\n using var deviceTmp = Device.QueryInterface();\n using var adapterTmp = deviceTmp.GetAdapter();\n adapter = adapterTmp.QueryInterface();\n }\n else\n Device.Tag = adapter.Description.Luid.ToString();\n\n if (Engine.Video.GPUAdapters.ContainsKey(adapter.Description1.Luid))\n {\n GPUAdapter = Engine.Video.GPUAdapters[adapter.Description1.Luid];\n Config.Video.MaxVerticalResolutionAuto = GPUAdapter.MaxHeight;\n\n if (CanDebug)\n {\n string dump = $\"GPU Adapter\\r\\n{GPUAdapter}\\r\\n\";\n\n for (int i=0; i()) mthread.SetMultithreadProtected(true);\n using (var dxgidevice = Device.QueryInterface()) dxgidevice.MaximumFrameLatency = Config.Video.MaxFrameLatency;\n\n // Input Layout\n inputLayout = Device.CreateInputLayout(inputElements, ShaderCompiler.VSBlob);\n context.IASetInputLayout(inputLayout);\n context.IASetPrimitiveTopology(PrimitiveTopology.TriangleList);\n\n // Vertex Shader\n vertexBuffer = Device.CreateBuffer(vertexBufferData, vertexBufferDesc);\n context.IASetVertexBuffer(0, vertexBuffer, sizeof(float) * 5);\n\n ShaderVS = Device.CreateVertexShader(ShaderCompiler.VSBlob);\n context.VSSetShader(ShaderVS);\n\n vsBuffer = Device.CreateBuffer(new()\n {\n Usage = ResourceUsage.Default,\n BindFlags = BindFlags.ConstantBuffer,\n CPUAccessFlags = CpuAccessFlags.None,\n ByteWidth = (uint)(sizeof(VSBufferType) + (16 - (sizeof(VSBufferType) % 16)))\n });\n context.VSSetConstantBuffer(0, vsBuffer);\n\n vsBufferData.mat = Matrix4x4.Identity;\n context.UpdateSubresource(vsBufferData, vsBuffer);\n\n // Pixel Shader\n InitPS();\n psBuffer = Device.CreateBuffer(new()\n {\n Usage = ResourceUsage.Default,\n BindFlags = BindFlags.ConstantBuffer,\n CPUAccessFlags = CpuAccessFlags.None,\n ByteWidth = (uint)(sizeof(PSBufferType) + (16 - (sizeof(PSBufferType) % 16)))\n });\n context.PSSetConstantBuffer(0, psBuffer);\n psBufferData.hdrmethod = HDRtoSDRMethod.None;\n context.UpdateSubresource(psBufferData, psBuffer);\n\n // subs\n ShaderBGRA = ShaderCompiler.CompilePS(Device, \"bgra\", @\"color = float4(Texture1.Sample(Sampler, input.Texture).rgba);\", null);\n\n // Blend State (currently used -mainly- for RGBA images and OverlayTexture)\n blendStateAlpha = Device.CreateBlendState(blendDesc);\n\n // Rasterizer (Will change CullMode to None for H-V Flip)\n rasterizerState = Device.CreateRasterizerState(new(CullMode.Back, FillMode.Solid));\n context.RSSetState(rasterizerState);\n\n InitializeVideoProcessor();\n\n if (CanInfo) Log.Info($\"Initialized with Feature Level {(int)Device.FeatureLevel >> 12}.{((int)Device.FeatureLevel >> 8) & 0xf}\");\n\n } catch (Exception e)\n {\n if (string.IsNullOrWhiteSpace(Config.Video.GPUAdapter) || Config.Video.GPUAdapter.ToUpper() != \"WARP\")\n {\n try { if (Device != null) Log.Warn($\"Device Remove Reason = {Device.DeviceRemovedReason.Description}\"); } catch { } // For troubleshooting\n\n Log.Warn($\"Initialization failed ({e.Message}). Failling back to WARP device.\");\n Config.Video.GPUAdapter = \"WARP\";\n Flush();\n }\n else\n {\n Log.Error($\"Initialization failed ({e.Message})\");\n Dispose();\n return;\n }\n }\n\n if (swapChain)\n {\n if (ControlHandle != IntPtr.Zero)\n InitializeSwapChain(ControlHandle);\n else if (SwapChainWinUIClbk != null)\n InitializeWinUISwapChain();\n }\n\n InitializeChildSwapChain();\n }\n }\n public void InitializeChildSwapChain(bool swapChain = true)\n {\n if (child == null )\n return;\n\n lock (lockDevice)\n {\n child.lockDevice = lockDevice;\n child.VideoDecoder = VideoDecoder;\n child.Device = Device;\n child.context = context;\n child.curRatio = curRatio;\n child.VideoRect = VideoRect;\n child.videoProcessor= videoProcessor;\n child.InitializeVideoProcessor(); // to use the same VP we need to set it's config in each present (means we don't update VP config as is different)\n\n if (swapChain)\n {\n if (child.ControlHandle != IntPtr.Zero)\n child.InitializeSwapChain(child.ControlHandle);\n else if (child.SwapChainWinUIClbk != null)\n child.InitializeWinUISwapChain();\n }\n\n child.Disposed = false;\n child.SetViewport();\n }\n }\n\n public void Dispose()\n {\n lock (lockDevice)\n {\n if (Disposed)\n return;\n\n if (child != null)\n DisposeChild();\n\n Disposed = true;\n\n if (CanDebug) Log.Debug(\"Disposing\");\n\n VideoDecoder.DisposeFrame(LastFrame);\n RefreshLayout();\n\n DisposeVideoProcessor();\n\n ShaderVS?.Dispose();\n ShaderPS?.Dispose();\n prevPSUniqueId = curPSUniqueId = \"\"; // Ensure we re-create ShaderPS for FlyleafVP on ConfigPlanes\n psBuffer?.Dispose();\n vsBuffer?.Dispose();\n inputLayout?.Dispose();\n vertexBuffer?.Dispose();\n rasterizerState?.Dispose();\n blendStateAlpha?.Dispose();\n DisposeSwapChain();\n\n overlayTexture?.Dispose();\n overlayTextureSrv?.Dispose();\n ShaderBGRA?.Dispose();\n\n singleGpu?.Dispose();\n singleStage?.Dispose();\n singleGpuRtv?.Dispose();\n singleStageDesc.Width = 0; // ensures re-allocation\n\n if (rtv2 != null)\n {\n for(int i = 0; i < rtv2.Length; i++)\n rtv2[i].Dispose();\n\n rtv2 = null;\n }\n\n if (backBuffer2 != null)\n {\n for(int i = 0; i < backBuffer2.Length; i++)\n backBuffer2[i]?.Dispose();\n\n backBuffer2 = null;\n }\n\n if (Device != null)\n {\n context.ClearState();\n context.Flush();\n context.Dispose();\n Device.Dispose();\n Device = null;\n }\n\n #if DEBUG\n ReportLiveObjects();\n #endif\n\n curRatio = 1.0f;\n if (CanInfo) Log.Info(\"Disposed\");\n }\n }\n public void DisposeChild()\n {\n if (child == null)\n return;\n\n lock (lockDevice)\n {\n child.DisposeSwapChain();\n child.DisposeVideoProcessor();\n child.Disposed = true;\n\n if (!isFlushing)\n {\n child.Device = null;\n child.context = null;\n child.VideoDecoder = null;\n child.LastFrame = null;\n child = null;\n }\n }\n }\n\n public void Flush()\n {\n lock (lockDevice)\n {\n isFlushing = true;\n var controlHandle = ControlHandle;\n var swapChainClbk = SwapChainWinUIClbk;\n\n IntPtr controlHandleReplica = IntPtr.Zero;\n Action swapChainClbkReplica = null;;\n if (child != null)\n {\n controlHandleReplica = child.ControlHandle;\n swapChainClbkReplica = child.SwapChainWinUIClbk;\n }\n\n Dispose();\n ControlHandle = controlHandle;\n SwapChainWinUIClbk = swapChainClbk;\n if (child != null)\n {\n child.ControlHandle = controlHandleReplica;\n child.SwapChainWinUIClbk = swapChainClbkReplica;\n }\n Initialize();\n isFlushing = false;\n }\n }\n\n #if DEBUG\n public static void ReportLiveObjects()\n {\n try\n {\n if (DXGI.DXGIGetDebugInterface1(out IDXGIDebug1 dxgiDebug).Success)\n {\n dxgiDebug.ReportLiveObjects(DXGI.DebugAll, ReportLiveObjectFlags.Summary | ReportLiveObjectFlags.IgnoreInternal);\n dxgiDebug.Dispose();\n }\n } catch { }\n }\n #endif\n\n [StructLayout(LayoutKind.Sequential)]\n struct PSBufferType\n {\n public int coefsIndex;\n public HDRtoSDRMethod hdrmethod;\n\n public float brightness;\n public float contrast;\n\n public float g_luminance;\n public float g_toneP1;\n public float g_toneP2;\n\n public float texWidth;\n }\n\n [StructLayout(LayoutKind.Sequential)]\n struct VSBufferType\n {\n public Matrix4x4 mat;\n }\n}\n"], ["/LLPlayer/FlyleafLib/MediaFramework/MediaPlaylist/PLSPlaylist.cs", "using System.Collections.Generic;\nusing System.Runtime.InteropServices;\nusing System.Text;\n\nnamespace FlyleafLib.MediaFramework.MediaPlaylist;\n\npublic class PLSPlaylist\n{\n [DllImport(\"kernel32\")]\n private static extern long WritePrivateProfileString(string name, string key, string val, string filePath);\n [DllImport(\"kernel32\")]\n private static extern int GetPrivateProfileString(string section, string key, string def, StringBuilder retVal, int size, string filePath);\n\n public string path;\n\n public static List Parse(string filename)\n {\n List items = new();\n string res;\n int entries = 1000;\n\n if ((res = GetINIAttribute(\"playlist\", \"NumberOfEntries\", filename)) != null)\n entries = int.Parse(res);\n\n for (int i=1; i<=entries; i++)\n {\n if ((res = GetINIAttribute(\"playlist\", $\"File{i}\", filename)) == null)\n break;\n\n PLSPlaylistItem item = new() { Url = res };\n\n if ((res = GetINIAttribute(\"playlist\", $\"Title{i}\", filename)) != null)\n item.Title = res;\n\n if ((res = GetINIAttribute(\"playlist\", $\"Length{i}\", filename)) != null)\n item.Duration = int.Parse(res);\n\n items.Add(item);\n }\n\n return items;\n }\n\n public static string GetINIAttribute(string name, string key, string path)\n {\n StringBuilder sb = new(255);\n return GetPrivateProfileString(name, key, \"\", sb, 255, path) > 0\n ? sb.ToString() : null;\n }\n}\n\npublic class PLSPlaylistItem\n{\n public int Duration { get; set; }\n public string Title { get; set; }\n public string Url { get; set; }\n}\n"], ["/LLPlayer/LLPlayer/Services/AppActions.cs", "using System.ComponentModel;\nusing System.Diagnostics;\nusing System.IO;\nusing System.Reflection;\nusing System.Windows;\nusing System.Windows.Input;\nusing System.Windows.Media;\nusing FlyleafLib;\nusing FlyleafLib.Controls.WPF;\nusing FlyleafLib.MediaPlayer;\nusing LLPlayer.Extensions;\nusing LLPlayer.Views;\nusing WpfColorFontDialog;\nusing KeyBinding = FlyleafLib.MediaPlayer.KeyBinding;\n\nnamespace LLPlayer.Services;\n\npublic class AppActions\n{\n private readonly Player _player;\n private readonly AppConfig _config;\n private FlyleafHost? _flyleafHost => _player.Host as FlyleafHost;\n private readonly IDialogService _dialogService;\n\n#pragma warning disable CS9264\n public AppActions(Player player, AppConfig config, IDialogService dialogService)\n {\n _player = player;\n _config = config;\n _dialogService = dialogService;\n\n CustomActions = GetCustomActions();\n\n RegisterCustomKeyBindingsAction();\n }\n#pragma warning restore CS9264\n\n private void RegisterCustomKeyBindingsAction()\n {\n // Since the action name is defined in PlayerConfig, get the Action name from there and register delegate.\n foreach (var binding in _player.Config.Player.KeyBindings.Keys)\n {\n if (binding.Action == KeyBindingAction.Custom && !string.IsNullOrEmpty(binding.ActionName))\n {\n if (Enum.TryParse(binding.ActionName, out CustomKeyBindingAction key))\n {\n binding.SetAction(CustomActions[key], binding.IsKeyUp);\n }\n }\n }\n }\n\n public Dictionary CustomActions { get; }\n\n private Dictionary GetCustomActions()\n {\n return new Dictionary\n {\n [CustomKeyBindingAction.OpenNextFile] = CmdOpenNextFile.Execute,\n [CustomKeyBindingAction.OpenPrevFile] = CmdOpenPrevFile.Execute,\n [CustomKeyBindingAction.OpenCurrentPath] = CmdOpenCurrentPath.Execute,\n\n [CustomKeyBindingAction.SubsPositionUp] = CmdSubsPositionUp.Execute,\n [CustomKeyBindingAction.SubsPositionDown] = CmdSubsPositionDown.Execute,\n [CustomKeyBindingAction.SubsSizeIncrease] = CmdSubsSizeIncrease.Execute,\n [CustomKeyBindingAction.SubsSizeDecrease] = CmdSubsSizeDecrease.Execute,\n [CustomKeyBindingAction.SubsPrimarySizeIncrease] = CmdSubsPrimarySizeIncrease.Execute,\n [CustomKeyBindingAction.SubsPrimarySizeDecrease] = CmdSubsPrimarySizeDecrease.Execute,\n [CustomKeyBindingAction.SubsSecondarySizeIncrease] = CmdSubsSecondarySizeIncrease.Execute,\n [CustomKeyBindingAction.SubsSecondarySizeDecrease] = CmdSubsSecondarySizeDecrease.Execute,\n [CustomKeyBindingAction.SubsDistanceIncrease] = CmdSubsDistanceIncrease.Execute,\n [CustomKeyBindingAction.SubsDistanceDecrease] = CmdSubsDistanceDecrease.Execute,\n\n [CustomKeyBindingAction.SubsTextCopy] = () => CmdSubsTextCopy.Execute(false),\n [CustomKeyBindingAction.SubsPrimaryTextCopy] = () => CmdSubsPrimaryTextCopy.Execute(false),\n [CustomKeyBindingAction.SubsSecondaryTextCopy] = () => CmdSubsSecondaryTextCopy.Execute(false),\n [CustomKeyBindingAction.ToggleSubsAutoTextCopy] = CmdToggleSubsAutoTextCopy.Execute,\n [CustomKeyBindingAction.ToggleSidebarShowSecondary] = CmdToggleSidebarShowSecondary.Execute,\n [CustomKeyBindingAction.ToggleSidebarShowOriginalText] = CmdToggleSidebarShowOriginalText.Execute,\n [CustomKeyBindingAction.ActivateSubsSearch] = CmdActivateSubsSearch.Execute,\n\n [CustomKeyBindingAction.ToggleSidebar] = CmdToggleSidebar.Execute,\n [CustomKeyBindingAction.ToggleDebugOverlay] = CmdToggleDebugOverlay.Execute,\n [CustomKeyBindingAction.ToggleAlwaysOnTop] = CmdToggleAlwaysOnTop.Execute,\n\n [CustomKeyBindingAction.OpenWindowSettings] = CmdOpenWindowSettings.Execute,\n [CustomKeyBindingAction.OpenWindowSubsDownloader] = CmdOpenWindowSubsDownloader.Execute,\n [CustomKeyBindingAction.OpenWindowSubsExporter] = CmdOpenWindowSubsExporter.Execute,\n [CustomKeyBindingAction.OpenWindowCheatSheet] = CmdOpenWindowCheatSheet.Execute,\n\n [CustomKeyBindingAction.AppNew] = CmdAppNew.Execute,\n [CustomKeyBindingAction.AppClone] = CmdAppClone.Execute,\n [CustomKeyBindingAction.AppRestart] = CmdAppRestart.Execute,\n [CustomKeyBindingAction.AppExit] = CmdAppExit.Execute,\n };\n }\n\n public static List DefaultCustomActionsMap()\n {\n return\n [\n new() { ActionName = nameof(CustomKeyBindingAction.OpenNextFile), Key = Key.Right, Alt = true, Shift = true, IsKeyUp = true },\n new() { ActionName = nameof(CustomKeyBindingAction.OpenPrevFile), Key = Key.Left, Alt = true, Shift = true, IsKeyUp = true },\n new() { ActionName = nameof(CustomKeyBindingAction.SubsPositionUp), Key = Key.Up, Shift = true },\n new() { ActionName = nameof(CustomKeyBindingAction.SubsPositionDown), Key = Key.Down, Shift = true },\n new() { ActionName = nameof(CustomKeyBindingAction.SubsSizeIncrease), Key = Key.Right, Shift = true },\n new() { ActionName = nameof(CustomKeyBindingAction.SubsSizeDecrease), Key = Key.Left, Shift = true },\n new() { ActionName = nameof(CustomKeyBindingAction.SubsSecondarySizeIncrease), Key = Key.Right, Ctrl = true, Shift = true },\n new() { ActionName = nameof(CustomKeyBindingAction.SubsSecondarySizeDecrease), Key = Key.Left, Ctrl = true, Shift = true },\n new() { ActionName = nameof(CustomKeyBindingAction.SubsDistanceIncrease), Key = Key.Up, Ctrl = true, Shift = true },\n new() { ActionName = nameof(CustomKeyBindingAction.SubsDistanceDecrease), Key = Key.Down, Ctrl = true, Shift = true },\n new() { ActionName = nameof(CustomKeyBindingAction.SubsPrimaryTextCopy), Key = Key.C, Ctrl = true, IsKeyUp = true },\n new() { ActionName = nameof(CustomKeyBindingAction.ToggleSubsAutoTextCopy), Key = Key.A, Ctrl = true, IsKeyUp = true },\n new() { ActionName = nameof(CustomKeyBindingAction.ActivateSubsSearch), Key = Key.F, Ctrl = true, IsKeyUp = true },\n new() { ActionName = nameof(CustomKeyBindingAction.ToggleSidebar), Key = Key.B, Ctrl = true, IsKeyUp = true },\n new() { ActionName = nameof(CustomKeyBindingAction.ToggleDebugOverlay), Key = Key.D, Ctrl = true, Shift = true, IsKeyUp = true },\n new() { ActionName = nameof(CustomKeyBindingAction.ToggleAlwaysOnTop), Key = Key.T, Ctrl = true, IsKeyUp = true },\n new() { ActionName = nameof(CustomKeyBindingAction.OpenWindowSettings), Key = Key.OemComma, Ctrl = true, IsKeyUp = true },\n new() { ActionName = nameof(CustomKeyBindingAction.OpenWindowCheatSheet), Key = Key.F1, IsKeyUp = true },\n new() { ActionName = nameof(CustomKeyBindingAction.AppNew), Key = Key.N, Ctrl = true, IsKeyUp = true },\n ];\n }\n\n // ReSharper disable NullCoalescingConditionIsAlwaysNotNullAccordingToAPIContract\n\n #region Command used in key\n\n public DelegateCommand CmdOpenNextFile => field ??= new(() =>\n {\n OpenNextPrevInternal(isNext: true);\n });\n\n public DelegateCommand CmdOpenPrevFile => field ??= new(() =>\n {\n OpenNextPrevInternal(isNext: false);\n });\n\n private void OpenNextPrevInternal(bool isNext)\n {\n var playlist = _player.Playlist;\n if (playlist.Url == null)\n return;\n\n string url = playlist.Url;\n\n try\n {\n (string? prev, string? next) = FileHelper.GetNextAndPreviousFile(url);\n if (isNext && next != null)\n {\n _player.OpenAsync(next);\n }\n else if (!isNext && prev != null)\n {\n _player.OpenAsync(prev);\n }\n }\n catch (Exception ex)\n {\n MessageBox.Show($\"OpenNextPrevFile is failed: {ex.Message}\");\n }\n }\n\n public DelegateCommand CmdOpenCurrentPath => field ??= new(() =>\n {\n var playlist = _player.Playlist;\n if (playlist.Selected == null)\n return;\n\n string url = playlist.Url;\n\n bool isFile = File.Exists(url);\n bool isUrl = url.StartsWith(\"http:\", StringComparison.OrdinalIgnoreCase) ||\n url.StartsWith(\"https:\", StringComparison.OrdinalIgnoreCase);\n\n if (!isFile && !isUrl)\n {\n return;\n }\n\n if (isUrl)\n {\n // fix url\n url = playlist.Selected.DirectUrl;\n }\n\n // Open folder or URL\n string? fileName = isFile ? Path.GetDirectoryName(url) : url;\n\n Process.Start(new ProcessStartInfo\n {\n FileName = fileName,\n UseShellExecute = true,\n Verb = \"open\"\n });\n });\n\n public DelegateCommand CmdSubsPositionUp => field ??= new(() =>\n {\n SubsPositionUpActionInternal(true);\n });\n\n public DelegateCommand CmdSubsPositionDown => field ??= new(() =>\n {\n SubsPositionUpActionInternal(false);\n });\n\n public DelegateCommand CmdSubsSizeIncrease => field ??= new(() =>\n {\n SubsSizeActionInternal(SubsSizeActionType.All, increase: true);\n });\n\n public DelegateCommand CmdSubsSizeDecrease => field ??= new(() =>\n {\n SubsSizeActionInternal(SubsSizeActionType.All, increase: false);\n });\n\n public DelegateCommand CmdSubsPrimarySizeIncrease => field ??= new(() =>\n {\n SubsSizeActionInternal(SubsSizeActionType.Primary, increase: true);\n });\n\n public DelegateCommand CmdSubsPrimarySizeDecrease => field ??= new(() =>\n {\n SubsSizeActionInternal(SubsSizeActionType.Primary, increase: false);\n });\n\n public DelegateCommand CmdSubsSecondarySizeIncrease => field ??= new(() =>\n {\n SubsSizeActionInternal(SubsSizeActionType.Secondary, increase: true);\n });\n\n public DelegateCommand CmdSubsSecondarySizeDecrease => field ??= new(() =>\n {\n SubsSizeActionInternal(SubsSizeActionType.Secondary, increase: false);\n });\n\n private void SubsSizeActionInternal(SubsSizeActionType type, bool increase)\n {\n var primary = _player.Subtitles[0];\n var secondary = _player.Subtitles[1];\n\n if (type is SubsSizeActionType.All or SubsSizeActionType.Primary)\n {\n // TODO: L: Match scaling ratios in text and bitmap subtitles\n if (primary.Enabled && (!primary.IsBitmap || !string.IsNullOrEmpty(primary.Data.Text)))\n {\n _config.Subs.SubsFontSize += _config.Subs.SubsFontSizeOffset * (increase ? 1 : -1);\n }\n else if (primary.Enabled && primary.IsBitmap)\n {\n _player.Subtitles[0].Data.BitmapPosition.ConfScale += _config.Subs.SubsBitmapScaleOffset / 100.0 * (increase ? 1.0 : -1.0);\n }\n }\n\n if (type is SubsSizeActionType.All or SubsSizeActionType.Secondary)\n {\n if (secondary.Enabled && (!secondary.IsBitmap || !string.IsNullOrEmpty(secondary.Data.Text)))\n {\n _config.Subs.SubsFontSize2 += _config.Subs.SubsFontSizeOffset * (increase ? 1 : -1);\n }\n else if (secondary.Enabled && secondary.IsBitmap)\n {\n _player.Subtitles[1].Data.BitmapPosition.ConfScale += _config.Subs.SubsBitmapScaleOffset / 100.0 * (increase ? 1.0 : -1.0);\n }\n }\n }\n\n public DelegateCommand CmdSubsDistanceIncrease => field ??= new(() =>\n {\n SubsDistanceActionInternal(true);\n });\n\n public DelegateCommand CmdSubsDistanceDecrease => field ??= new(() =>\n {\n SubsDistanceActionInternal(false);\n });\n\n private void SubsDistanceActionInternal(bool increase)\n {\n _config.Subs.SubsDistance += _config.Subs.SubsDistanceOffset * (increase ? 1 : -1);\n }\n\n public DelegateCommand CmdSubsTextCopy => field ??= new((suppressOsd) =>\n {\n if (!_player.Subtitles[0].Enabled && !_player.Subtitles[1].Enabled)\n {\n return;\n }\n\n string text = _player.Subtitles[0].Data.Text;\n if (!string.IsNullOrEmpty(_player.Subtitles[1].Data.Text))\n {\n text += Environment.NewLine + \"( \" + _player.Subtitles[1].Data.Text + \" )\";\n }\n\n if (!string.IsNullOrEmpty(text))\n {\n try\n {\n WindowsClipboard.SetText(text);\n if (!suppressOsd.HasValue || !suppressOsd.Value)\n {\n _player.OSDMessage = \"Copy All Subtitle Text\";\n }\n }\n catch\n {\n // ignored\n }\n }\n });\n\n public DelegateCommand CmdSubsPrimaryTextCopy => field ??= new((suppressOsd) =>\n {\n SubsTextCopyInternal(0, suppressOsd);\n });\n\n public DelegateCommand CmdSubsSecondaryTextCopy => field ??= new((suppressOsd) =>\n {\n SubsTextCopyInternal(1, suppressOsd);\n });\n\n private void SubsTextCopyInternal(int subIndex, bool? suppressOsd)\n {\n if (!_player.Subtitles[subIndex].Enabled)\n {\n return;\n }\n\n string text = _player.Subtitles[subIndex].Data.Text;\n\n if (!string.IsNullOrEmpty(text))\n {\n try\n {\n WindowsClipboard.SetText(text);\n if (!suppressOsd.HasValue || !suppressOsd.Value)\n {\n _player.OSDMessage = $\"Copy {(subIndex == 0 ? \"Primary\" : \"Secondary\")} Subtitle Text\";\n }\n }\n catch\n {\n // ignored\n }\n }\n }\n\n public DelegateCommand CmdToggleSubsAutoTextCopy => field ??= new(() =>\n {\n _config.Subs.SubsAutoTextCopy = !_config.Subs.SubsAutoTextCopy;\n });\n\n public DelegateCommand CmdActivateSubsSearch => field ??= new(() =>\n {\n if (_flyleafHost is { IsFullScreen: true })\n {\n return;\n }\n\n _config.ShowSidebar = true;\n\n // for getting focus to TextBox\n _config.SidebarSearchActive = false;\n _config.SidebarSearchActive = true;\n });\n\n public DelegateCommand CmdToggleSidebarShowSecondary => field ??= new(() =>\n {\n _config.SidebarShowSecondary = !_config.SidebarShowSecondary;\n });\n\n public DelegateCommand CmdToggleSidebarShowOriginalText => field ??= new(() =>\n {\n _config.SidebarShowOriginalText = !_config.SidebarShowOriginalText;\n });\n\n public DelegateCommand CmdToggleSidebar => field ??= new(() =>\n {\n _config.ShowSidebar = !_config.ShowSidebar;\n });\n\n public DelegateCommand CmdToggleDebugOverlay => field ??= new(() =>\n {\n _config.ShowDebug = !_config.ShowDebug;\n });\n\n public DelegateCommand CmdToggleAlwaysOnTop => field ??= new(() =>\n {\n _config.AlwaysOnTop = !_config.AlwaysOnTop;\n });\n\n public DelegateCommand CmdOpenWindowSettings => field ??= new(() =>\n {\n if (_player.IsPlaying)\n {\n _player.Pause();\n }\n\n // Detects configuration changes necessary for restart\n // TODO: L: refactor\n bool requiredRestart = false;\n\n _config.PropertyChanged += ConfigOnPropertyChanged;\n _player.Config.Subtitles.WhisperCppConfig.PropertyChanged += ConfigOnPropertyChanged;\n\n void ConfigOnPropertyChanged(object? sender, PropertyChangedEventArgs e)\n {\n switch (e.PropertyName)\n {\n case nameof(_config.IsDarkTitlebar):\n case nameof(_player.Config.Subtitles.WhisperCppConfig.RuntimeLibraries):\n requiredRestart = true;\n break;\n }\n }\n\n _player.Activity.ForceFullActive();\n _dialogService.ShowSingleton(nameof(SettingsDialog), result =>\n {\n // Activate as it may be minimized for some reason\n if (!Application.Current.MainWindow!.IsActive)\n {\n Application.Current.MainWindow!.Activate();\n }\n\n _config.PropertyChanged -= ConfigOnPropertyChanged;\n _player.Config.Subtitles.WhisperCppConfig.PropertyChanged += ConfigOnPropertyChanged;\n\n if (result.Result == ButtonResult.OK)\n {\n SaveAllConfig();\n\n if (requiredRestart)\n {\n // Show confirmation dialog\n MessageBoxResult confirm = MessageBox.Show(\n \"A restart is required for the settings to take effect. Do you want to restart?\",\n \"Confirm to restart\",\n MessageBoxButton.YesNo,\n MessageBoxImage.Question\n );\n\n if (confirm == MessageBoxResult.Yes)\n {\n CmdAppRestart.Execute();\n }\n }\n }\n }, false);\n });\n\n public DelegateCommand CmdOpenWindowSubsDownloader => field ??= new(() =>\n {\n _player.Activity.ForceFullActive();\n _dialogService.ShowSingleton(nameof(SubtitlesDownloaderDialog), true);\n });\n\n public DelegateCommand CmdOpenWindowSubsExporter => field ??= new(() =>\n {\n _player.Activity.ForceFullActive();\n _dialogService.ShowSingleton(nameof(SubtitlesExportDialog), _ =>\n {\n // Activate as it may be minimized for some reason\n if (!Application.Current.MainWindow!.IsActive)\n {\n Application.Current.MainWindow!.Activate();\n }\n }, false);\n });\n\n public DelegateCommand CmdOpenWindowCheatSheet => field ??= new(() =>\n {\n _player.Activity.ForceFullActive();\n _dialogService.ShowSingleton(nameof(CheatSheetDialog), true);\n });\n\n public DelegateCommand CmdAppNew => field ??= new(() =>\n {\n string exePath = Process.GetCurrentProcess().MainModule!.FileName;\n Process.Start(exePath);\n });\n\n public DelegateCommand CmdAppClone => field ??= new(() =>\n {\n string exePath = Process.GetCurrentProcess().MainModule!.FileName;\n\n ProcessStartInfo startInfo = new()\n {\n FileName = exePath,\n UseShellExecute = false\n };\n\n // Launch New App with current url if opened\n var prevPlaylist = _player.Playlist.Selected;\n if (prevPlaylist != null)\n {\n startInfo.ArgumentList.Add(prevPlaylist.DirectUrl);\n }\n\n Process.Start(startInfo);\n });\n\n public DelegateCommand CmdAppRestart => field ??= new(() =>\n {\n // Clone\n CmdAppClone.Execute();\n\n // Exit\n CmdAppExit.Execute();\n });\n\n public DelegateCommand CmdAppExit => field ??= new(() =>\n {\n Application.Current.Shutdown();\n });\n #endregion\n\n #region Command not used in key\n private static FontWeightConverter _fontWeightConv = new();\n private static FontStyleConverter _fontStyleConv = new();\n private static FontStretchConverter _fontStretchConv = new();\n\n public DelegateCommand CmdSetSubtitlesFont => field ??= new(() =>\n {\n ColorFontDialog dialog = new();\n\n dialog.Topmost = _config.AlwaysOnTop;\n dialog.Font = new FontInfo(new FontFamily(_config.Subs.SubsFontFamily), _config.Subs.SubsFontSize, (FontStyle)_fontStyleConv.ConvertFromString(_config.Subs.SubsFontStyle)!, (FontStretch)_fontStretchConv.ConvertFromString(_config.Subs.SubsFontStretch)!, (FontWeight)_fontWeightConv.ConvertFromString(_config.Subs.SubsFontWeight)!, new SolidColorBrush(Colors.Black));\n\n _player.Activity.ForceFullActive();\n\n double prevFontSize = dialog.Font.Size;\n\n if (dialog.ShowDialog() == true && dialog.Font != null)\n {\n _config.Subs.SubsFontFamily = dialog.Font.Family.ToString();\n _config.Subs.SubsFontWeight = dialog.Font.Weight.ToString();\n _config.Subs.SubsFontStretch = dialog.Font.Stretch.ToString();\n _config.Subs.SubsFontStyle = dialog.Font.Style.ToString();\n\n if (prevFontSize != dialog.Font.Size)\n {\n _config.Subs.SubsFontSize = dialog.Font.Size;\n _config.Subs.SubsFontSize2 = dialog.Font.Size; // change secondary as well\n }\n\n // update display of secondary subtitles\n _config.Subs.UpdateSecondaryFonts();\n }\n });\n\n public DelegateCommand CmdSetSubtitlesFont2 => field ??= new(() =>\n {\n ColorFontDialog dialog = new();\n\n dialog.Topmost = _config.AlwaysOnTop;\n dialog.Font = new FontInfo(new FontFamily(_config.Subs.SubsFontFamily2), _config.Subs.SubsFontSize2, (FontStyle)_fontStyleConv.ConvertFromString(_config.Subs.SubsFontStyle2)!, (FontStretch)_fontStretchConv.ConvertFromString(_config.Subs.SubsFontStretch2)!, (FontWeight)_fontWeightConv.ConvertFromString(_config.Subs.SubsFontWeight2)!, new SolidColorBrush(Colors.Black));\n\n _player.Activity.ForceFullActive();\n\n if (dialog.ShowDialog() == true && dialog.Font != null)\n {\n _config.Subs.SubsFontFamily2 = dialog.Font.Family.ToString();\n _config.Subs.SubsFontWeight2 = dialog.Font.Weight.ToString();\n _config.Subs.SubsFontStretch2 = dialog.Font.Stretch.ToString();\n _config.Subs.SubsFontStyle2 = dialog.Font.Style.ToString();\n\n _config.Subs.SubsFontSize2 = dialog.Font.Size;\n\n // update display of secondary subtitles\n _config.Subs.UpdateSecondaryFonts();\n }\n });\n\n public DelegateCommand CmdSetSubtitlesFontSidebar => field ??= new(() =>\n {\n ColorFontDialog dialog = new();\n\n dialog.Topmost = _config.AlwaysOnTop;\n dialog.Font = new FontInfo(new FontFamily(_config.SidebarFontFamily), _config.SidebarFontSize, FontStyles.Normal, FontStretches.Normal, (FontWeight)_fontWeightConv.ConvertFromString(_config.SidebarFontWeight)!, new SolidColorBrush(Colors.Black));\n\n _player.Activity.ForceFullActive();\n\n if (dialog.ShowDialog() == true && dialog.Font != null)\n {\n _config.SidebarFontFamily = dialog.Font.Family.ToString();\n _config.SidebarFontSize = dialog.Font.Size;\n _config.SidebarFontWeight = dialog.Font.Weight.ToString();\n }\n });\n\n public DelegateCommand CmdResetSubsPosition => field ??= new(() =>\n {\n // TODO: L: Reset bitmap as well\n _config.Subs.ResetSubsPosition();\n });\n\n public DelegateCommand CmdChangeAspectRatio => field ??= new((ratio) =>\n {\n if (!ratio.HasValue)\n return;\n\n _player.Config.Video.AspectRatio = ratio.Value;\n });\n\n public DelegateCommand CmdSetSubPositionAlignment => field ??= new((alignment) =>\n {\n if (!alignment.HasValue)\n return;\n\n _config.Subs.SubsPositionAlignment = alignment.Value;\n });\n\n public DelegateCommand CmdSetSubPositionAlignmentWhenDual => field ??= new((alignment) =>\n {\n if (!alignment.HasValue)\n return;\n\n _config.Subs.SubsPositionAlignmentWhenDual = alignment.Value;\n });\n\n #endregion\n\n // ReSharper restore NullCoalescingConditionIsAlwaysNotNullAccordingToAPIContract\n\n // TODO: L: make it command?\n public void SaveAllConfig()\n {\n _config.Save(App.AppConfigPath);\n\n var opts = AppConfig.GetJsonSerializerOptions();\n _player.Config.Version = App.Version;\n _player.Config.Save(App.PlayerConfigPath, opts);\n\n Engine.Config.Version = App.Version;\n Engine.Config.Save(App.EngineConfigPath, opts);\n }\n\n private enum SubsSizeActionType\n {\n All,\n Primary,\n Secondary\n }\n\n private void SubsPositionUpActionInternal(bool up)\n {\n var primary = _player.Subtitles[0];\n var secondary = _player.Subtitles[1];\n\n bool bothEnabled = primary.Enabled && secondary.Enabled;\n\n if (bothEnabled || // both enabled\n primary.Enabled && !primary.IsBitmap || // When text subtitles are enabled\n secondary.Enabled && !secondary.IsBitmap || !string.IsNullOrEmpty(primary.Data.Text) || // If OCR subtitles are available\n !string.IsNullOrEmpty(secondary.Data.Text))\n {\n _config.Subs.SubsPosition += _config.Subs.SubsPositionOffset * (up ? -1 : 1);\n }\n else if (primary.IsBitmap || secondary.IsBitmap)\n {\n // For bitmap subtitles (absolute position)\n for (int i = 0; i < _player.Config.Subtitles.Max; i++)\n {\n _player.Subtitles[i].Data.BitmapPosition.ConfPos += _config.Subs.SubsPositionOffset * (up ? -1 : 1);\n }\n }\n }\n}\n\n// List of key actions to be added from the app side\npublic enum CustomKeyBindingAction\n{\n [Description(\"Open Next File\")]\n OpenNextFile,\n [Description(\"Open Previous File\")]\n OpenPrevFile,\n [Description(\"Open Folder or URL of the currently opened file\")]\n OpenCurrentPath,\n\n [Description(\"Subtitles Position Up\")]\n SubsPositionUp,\n [Description(\"Subtitles Position Down\")]\n SubsPositionDown,\n [Description(\"Subtitles Size Increase\")]\n SubsSizeIncrease,\n [Description(\"Subtitles Size Decrease\")]\n SubsSizeDecrease,\n [Description(\"Primary Subtitles Size Increase\")]\n SubsPrimarySizeIncrease,\n [Description(\"Primary Subtitles Size Decrease\")]\n SubsPrimarySizeDecrease,\n [Description(\"Secondary Subtitles Size Increase\")]\n SubsSecondarySizeIncrease,\n [Description(\"Secondary Subtitles Size Decrease\")]\n SubsSecondarySizeDecrease,\n [Description(\"Primary/Secondary Subtitles Distance Increase\")]\n SubsDistanceIncrease,\n [Description(\"Primary/Secondary Subtitles Distance Decrease\")]\n SubsDistanceDecrease,\n\n [Description(\"Copy All Subtiltes Text\")]\n SubsTextCopy,\n [Description(\"Copy Primary Subtiltes Text\")]\n SubsPrimaryTextCopy,\n [Description(\"Copy Secondary Subtiltes Text\")]\n SubsSecondaryTextCopy,\n [Description(\"Toggle Auto Subtitles Text Copy\")]\n ToggleSubsAutoTextCopy,\n\n [Description(\"Toggle Primary / Secondary in Subtitles Sidebar\")]\n ToggleSidebarShowSecondary,\n [Description(\"Toggle to show original text in Subtitles Sidebar\")]\n ToggleSidebarShowOriginalText,\n [Description(\"Activate Subtitles Search in Sidebar\")]\n ActivateSubsSearch,\n\n [Description(\"Toggle Subitltes Sidebar\")]\n ToggleSidebar,\n [Description(\"Toggle Debug Overlay\")]\n ToggleDebugOverlay,\n [Description(\"Toggle Always On Top\")]\n ToggleAlwaysOnTop,\n\n [Description(\"Open Settings Window\")]\n OpenWindowSettings,\n [Description(\"Open Subtitles Downloader Window\")]\n OpenWindowSubsDownloader,\n [Description(\"Open Subtitles Exporter Window\")]\n OpenWindowSubsExporter,\n [Description(\"Open Cheat Sheet Window\")]\n OpenWindowCheatSheet,\n\n [Description(\"Launch New Application\")]\n AppNew,\n [Description(\"Launch Clone Application\")]\n AppClone,\n [Description(\"Restart Application\")]\n AppRestart,\n [Description(\"Exit Application\")]\n AppExit,\n}\n\npublic enum KeyBindingActionGroup\n{\n Playback,\n Player,\n Audio,\n Video,\n Subtitles,\n SubtitlesPosition,\n Window,\n Other\n}\n\npublic static class KeyBindingActionExtensions\n{\n public static string ToString(this KeyBindingActionGroup group)\n {\n var str = group.ToString();\n if (group == KeyBindingActionGroup.SubtitlesPosition)\n {\n str = \"Subtitles Position\";\n }\n\n return str;\n }\n\n public static KeyBindingActionGroup ToGroup(this CustomKeyBindingAction action)\n {\n switch (action)\n {\n case CustomKeyBindingAction.OpenNextFile:\n case CustomKeyBindingAction.OpenPrevFile:\n case CustomKeyBindingAction.OpenCurrentPath:\n return KeyBindingActionGroup.Player; // TODO: L: ?\n\n case CustomKeyBindingAction.SubsPositionUp:\n case CustomKeyBindingAction.SubsPositionDown:\n case CustomKeyBindingAction.SubsSizeIncrease:\n case CustomKeyBindingAction.SubsSizeDecrease:\n case CustomKeyBindingAction.SubsPrimarySizeIncrease:\n case CustomKeyBindingAction.SubsPrimarySizeDecrease:\n case CustomKeyBindingAction.SubsSecondarySizeIncrease:\n case CustomKeyBindingAction.SubsSecondarySizeDecrease:\n case CustomKeyBindingAction.SubsDistanceIncrease:\n case CustomKeyBindingAction.SubsDistanceDecrease:\n return KeyBindingActionGroup.SubtitlesPosition;\n\n case CustomKeyBindingAction.SubsTextCopy:\n case CustomKeyBindingAction.SubsPrimaryTextCopy:\n case CustomKeyBindingAction.SubsSecondaryTextCopy:\n case CustomKeyBindingAction.ToggleSubsAutoTextCopy:\n case CustomKeyBindingAction.ToggleSidebarShowSecondary:\n case CustomKeyBindingAction.ToggleSidebarShowOriginalText:\n case CustomKeyBindingAction.ActivateSubsSearch:\n return KeyBindingActionGroup.Subtitles;\n\n case CustomKeyBindingAction.ToggleSidebar:\n case CustomKeyBindingAction.ToggleDebugOverlay:\n case CustomKeyBindingAction.ToggleAlwaysOnTop:\n case CustomKeyBindingAction.OpenWindowSettings:\n case CustomKeyBindingAction.OpenWindowSubsDownloader:\n case CustomKeyBindingAction.OpenWindowSubsExporter:\n case CustomKeyBindingAction.OpenWindowCheatSheet:\n return KeyBindingActionGroup.Window;\n\n // TODO: L: review group\n case CustomKeyBindingAction.AppNew:\n case CustomKeyBindingAction.AppClone:\n case CustomKeyBindingAction.AppRestart:\n case CustomKeyBindingAction.AppExit:\n return KeyBindingActionGroup.Other;\n\n default:\n return KeyBindingActionGroup.Other;\n }\n }\n\n public static KeyBindingActionGroup ToGroup(this KeyBindingAction action)\n {\n switch (action)\n {\n // TODO: L: review order and grouping\n case KeyBindingAction.ForceIdle:\n case KeyBindingAction.ForceActive:\n case KeyBindingAction.ForceFullActive:\n return KeyBindingActionGroup.Player;\n\n case KeyBindingAction.AudioDelayAdd:\n case KeyBindingAction.AudioDelayAdd2:\n case KeyBindingAction.AudioDelayRemove:\n case KeyBindingAction.AudioDelayRemove2:\n case KeyBindingAction.ToggleAudio:\n case KeyBindingAction.ToggleMute:\n case KeyBindingAction.VolumeUp:\n case KeyBindingAction.VolumeDown:\n return KeyBindingActionGroup.Audio;\n\n case KeyBindingAction.SubsDelayAddPrimary:\n case KeyBindingAction.SubsDelayAdd2Primary:\n case KeyBindingAction.SubsDelayRemovePrimary:\n case KeyBindingAction.SubsDelayRemove2Primary:\n case KeyBindingAction.SubsDelayAddSecondary:\n case KeyBindingAction.SubsDelayAdd2Secondary:\n case KeyBindingAction.SubsDelayRemoveSecondary:\n case KeyBindingAction.SubsDelayRemove2Secondary:\n return KeyBindingActionGroup.SubtitlesPosition;\n case KeyBindingAction.ToggleSubtitlesVisibility:\n case KeyBindingAction.ToggleSubtitlesVisibilityPrimary:\n case KeyBindingAction.ToggleSubtitlesVisibilitySecondary:\n return KeyBindingActionGroup.Subtitles;\n\n case KeyBindingAction.CopyToClipboard:\n case KeyBindingAction.CopyItemToClipboard:\n return KeyBindingActionGroup.Other; // TODO: L: ?\n\n case KeyBindingAction.OpenFromClipboard:\n case KeyBindingAction.OpenFromClipboardSafe:\n case KeyBindingAction.OpenFromFileDialog:\n return KeyBindingActionGroup.Player; // TODO: L: ?\n\n case KeyBindingAction.Stop:\n case KeyBindingAction.Pause:\n case KeyBindingAction.Play:\n case KeyBindingAction.TogglePlayPause:\n case KeyBindingAction.ToggleReversePlayback:\n case KeyBindingAction.ToggleLoopPlayback:\n case KeyBindingAction.SeekForward:\n case KeyBindingAction.SeekBackward:\n case KeyBindingAction.SeekForward2:\n case KeyBindingAction.SeekBackward2:\n case KeyBindingAction.SeekForward3:\n case KeyBindingAction.SeekBackward3:\n case KeyBindingAction.SeekForward4:\n case KeyBindingAction.SeekBackward4:\n return KeyBindingActionGroup.Playback;\n\n case KeyBindingAction.Flush:\n case KeyBindingAction.NormalScreen:\n case KeyBindingAction.FullScreen:\n case KeyBindingAction.ToggleFullScreen:\n return KeyBindingActionGroup.Player;\n\n case KeyBindingAction.ToggleVideo:\n case KeyBindingAction.ToggleKeepRatio:\n case KeyBindingAction.ToggleVideoAcceleration:\n case KeyBindingAction.TakeSnapshot:\n case KeyBindingAction.ToggleRecording:\n return KeyBindingActionGroup.Video;\n\n case KeyBindingAction.SubsPrevSeek:\n case KeyBindingAction.SubsCurSeek:\n case KeyBindingAction.SubsNextSeek:\n case KeyBindingAction.SubsPrevSeekFallback:\n case KeyBindingAction.SubsNextSeekFallback:\n case KeyBindingAction.SubsPrevSeek2:\n case KeyBindingAction.SubsCurSeek2:\n case KeyBindingAction.SubsNextSeek2:\n case KeyBindingAction.SubsPrevSeekFallback2:\n case KeyBindingAction.SubsNextSeekFallback2:\n return KeyBindingActionGroup.Subtitles;\n\n case KeyBindingAction.ShowNextFrame:\n case KeyBindingAction.ShowPrevFrame:\n case KeyBindingAction.SpeedAdd:\n case KeyBindingAction.SpeedAdd2:\n case KeyBindingAction.SpeedRemove:\n case KeyBindingAction.SpeedRemove2:\n case KeyBindingAction.ToggleSeekAccurate:\n return KeyBindingActionGroup.Playback;\n\n case KeyBindingAction.ResetAll:\n case KeyBindingAction.ResetSpeed:\n case KeyBindingAction.ResetRotation:\n case KeyBindingAction.ResetZoom:\n case KeyBindingAction.ZoomIn:\n case KeyBindingAction.ZoomOut:\n return KeyBindingActionGroup.Player;\n\n default:\n return KeyBindingActionGroup.Other;\n }\n }\n\n /// \n /// Gets the value of the Description attribute assigned to the Enum member.\n /// \n /// \n /// \n public static string GetDescription(this Enum value)\n {\n ArgumentNullException.ThrowIfNull(value);\n\n Type type = value.GetType();\n\n string name = value.ToString();\n\n MemberInfo[] member = type.GetMember(name);\n\n if (member.Length > 0)\n {\n if (Attribute.GetCustomAttribute(member[0], typeof(DescriptionAttribute)) is DescriptionAttribute attr)\n {\n return attr.Description;\n }\n }\n\n return name;\n }\n}\n"], ["/LLPlayer/FlyleafLib/MediaFramework/MediaDecoder/VideoDecoder.cs", "using System.Collections.Concurrent;\nusing System.Collections.Generic;\nusing System.Runtime.InteropServices;\nusing System.Threading;\n\nusing Vortice.DXGI;\nusing Vortice.Direct3D11;\n\nusing ID3D11Texture2D = Vortice.Direct3D11.ID3D11Texture2D;\n\nusing FlyleafLib.MediaFramework.MediaStream;\nusing FlyleafLib.MediaFramework.MediaFrame;\nusing FlyleafLib.MediaFramework.MediaRenderer;\nusing FlyleafLib.MediaFramework.MediaRemuxer;\n\nusing static FlyleafLib.Logger;\n\nnamespace FlyleafLib.MediaFramework.MediaDecoder;\n\npublic unsafe class VideoDecoder : DecoderBase\n{\n public ConcurrentQueue\n Frames { get; protected set; } = new ConcurrentQueue();\n public Renderer Renderer { get; private set; }\n public bool VideoAccelerated { get; internal set; }\n public bool ZeroCopy { get; internal set; }\n\n public VideoStream VideoStream => (VideoStream) Stream;\n\n public long StartTime { get; internal set; } = AV_NOPTS_VALUE;\n public long StartRecordTime { get; internal set; } = AV_NOPTS_VALUE;\n\n const AVPixelFormat PIX_FMT_HWACCEL = AVPixelFormat.D3d11;\n const SwsFlags SCALING_HQ = SwsFlags.AccurateRnd | SwsFlags.Bitexact | SwsFlags.Lanczos | SwsFlags.FullChrHInt | SwsFlags.FullChrHInp;\n const SwsFlags SCALING_LQ = SwsFlags.Bicublin;\n\n internal SwsContext* swsCtx;\n IntPtr swsBufferPtr;\n internal byte_ptrArray4 swsData;\n internal int_array4 swsLineSize;\n\n internal bool swFallback;\n internal bool keyPacketRequired;\n internal long lastFixedPts;\n\n bool checkExtraFrames; // DecodeFrameNext\n\n // Reverse Playback\n ConcurrentStack>\n curReverseVideoStack = new();\n List curReverseVideoPackets = new();\n List curReverseVideoFrames = new();\n int curReversePacketPos = 0;\n\n // Drop frames if FPS is higher than allowed\n int curSpeedFrame = 9999; // don't skip first frame (on start/after seek-flush)\n double skipSpeedFrames = 0;\n\n public VideoDecoder(Config config, int uniqueId = -1) : base(config, uniqueId)\n => getHWformat = new AVCodecContext_get_format(get_format);\n\n protected override void OnSpeedChanged(double value)\n {\n if (VideoStream == null) return;\n speed = value;\n skipSpeedFrames = speed * VideoStream.FPS / Config.Video.MaxOutputFps;\n }\n\n /// \n /// Prevents to get the first frame after seek/flush\n /// \n public void ResetSpeedFrame()\n => curSpeedFrame = 0;\n\n public void CreateRenderer() // TBR: It should be in the constructor but DecoderContext will not work with null VideoDecoder for AudioOnly\n {\n if (Renderer == null)\n Renderer = new Renderer(this, IntPtr.Zero, UniqueId);\n else if (Renderer.Disposed)\n Renderer.Initialize();\n }\n public void DestroyRenderer() => Renderer?.Dispose();\n public void CreateSwapChain(IntPtr handle)\n {\n CreateRenderer();\n Renderer.InitializeSwapChain(handle);\n }\n public void CreateSwapChain(Action swapChainWinUIClbk)\n {\n Renderer.SwapChainWinUIClbk = swapChainWinUIClbk;\n if (Renderer.SwapChainWinUIClbk != null)\n Renderer.InitializeWinUISwapChain();\n\n }\n public void DestroySwapChain() => Renderer?.DisposeSwapChain();\n\n #region Video Acceleration (Should be disposed seperately)\n const int AV_CODEC_HW_CONFIG_METHOD_HW_DEVICE_CTX = 0x01;\n const AVHWDeviceType HW_DEVICE = AVHWDeviceType.D3d11va;\n\n internal ID3D11Texture2D\n textureFFmpeg;\n AVCodecContext_get_format\n getHWformat;\n AVBufferRef* hwframes;\n AVBufferRef* hw_device_ctx;\n\n internal static bool CheckCodecSupport(AVCodec* codec)\n {\n for (int i = 0; ; i++)\n {\n var config = avcodec_get_hw_config(codec, i);\n if (config == null) break;\n if ((config->methods & AVCodecHwConfigMethod.HwDeviceCtx) == 0 || config->pix_fmt == AVPixelFormat.None) continue;\n\n if (config->device_type == HW_DEVICE && config->pix_fmt == PIX_FMT_HWACCEL) return true;\n }\n\n return false;\n }\n internal int InitVA()\n {\n int ret;\n AVHWDeviceContext* device_ctx;\n AVD3D11VADeviceContext* d3d11va_device_ctx;\n\n if (Renderer.Device == null || hw_device_ctx != null) return -1;\n\n hw_device_ctx = av_hwdevice_ctx_alloc(HW_DEVICE);\n\n device_ctx = (AVHWDeviceContext*) hw_device_ctx->data;\n d3d11va_device_ctx = (AVD3D11VADeviceContext*) device_ctx->hwctx;\n d3d11va_device_ctx->device\n = (Flyleaf.FFmpeg.ID3D11Device*) Renderer.Device.NativePointer;\n\n ret = av_hwdevice_ctx_init(hw_device_ctx);\n if (ret != 0)\n {\n Log.Error($\"VA Failed - {FFmpegEngine.ErrorCodeToMsg(ret)} ({ret})\");\n\n fixed(AVBufferRef** ptr = &hw_device_ctx)\n av_buffer_unref(ptr);\n\n hw_device_ctx = null;\n }\n\n Renderer.Device.AddRef(); // Important to give another reference for FFmpeg so we can dispose without issues\n\n return ret;\n }\n\n private AVPixelFormat get_format(AVCodecContext* avctx, AVPixelFormat* pix_fmts)\n {\n if (CanDebug)\n {\n Log.Debug($\"Codec profile '{VideoStream.Codec} {avcodec_profile_name(codecCtx->codec_id, codecCtx->profile)}'\");\n\n if (CanTrace)\n {\n var save = pix_fmts;\n while (*pix_fmts != AVPixelFormat.None)\n {\n Log.Trace($\"{*pix_fmts}\");\n pix_fmts++;\n }\n pix_fmts = save;\n }\n }\n\n bool foundHWformat = false;\n\n while (*pix_fmts != AVPixelFormat.None)\n {\n if ((*pix_fmts) == PIX_FMT_HWACCEL)\n {\n foundHWformat = true;\n break;\n }\n\n pix_fmts++;\n }\n\n int ret = ShouldAllocateNew();\n\n if (foundHWformat && ret == 0)\n {\n if (codecCtx->hw_frames_ctx == null && hwframes != null)\n codecCtx->hw_frames_ctx = av_buffer_ref(hwframes);\n\n return PIX_FMT_HWACCEL;\n }\n\n lock (lockCodecCtx)\n {\n if (!foundHWformat || !VideoAccelerated || AllocateHWFrames() != 0)\n {\n if (CanWarn)\n Log.Warn(\"HW format not found. Fallback to sw format\");\n\n swFallback = true;\n return avcodec_default_get_format(avctx, pix_fmts);\n }\n\n if (CanDebug)\n Log.Debug(\"HW frame allocation completed\");\n\n // TBR: Catch codec changed on live streams (check codec/profiles and check even on sw frames)\n if (ret == 2)\n {\n Log.Warn($\"Codec changed {VideoStream.CodecID} {VideoStream.Width}x{VideoStream.Height} => {codecCtx->codec_id} {codecCtx->width}x{codecCtx->height}\");\n filledFromCodec = false;\n }\n\n return PIX_FMT_HWACCEL;\n }\n }\n private int ShouldAllocateNew() // 0: No, 1: Yes, 2: Yes+Codec Changed\n {\n if (hwframes == null)\n return 1;\n\n AVHWFramesContext* t2 = (AVHWFramesContext*) hwframes->data;\n\n if (codecCtx->coded_width != t2->width)\n return 2;\n\n if (codecCtx->coded_height != t2->height)\n return 2;\n\n // TBR: Codec changed (seems ffmpeg changes codecCtx by itself\n //if (codecCtx->codec_id != VideoStream.CodecID)\n // return 2;\n\n //var fmt = codecCtx->sw_pix_fmt == (AVPixelFormat)AV_PIX_FMT_YUV420P10LE ? (AVPixelFormat)AV_PIX_FMT_P010LE : (codecCtx->sw_pix_fmt == (AVPixelFormat)AV_PIX_FMT_P010BE ? (AVPixelFormat)AV_PIX_FMT_P010BE : AVPixelFormat.AV_PIX_FMT_NV12);\n //if (fmt != t2->sw_format)\n // return 2;\n\n return 0;\n }\n\n private int AllocateHWFrames()\n {\n if (hwframes != null)\n fixed(AVBufferRef** ptr = &hwframes)\n av_buffer_unref(ptr);\n\n hwframes = null;\n\n if (codecCtx->hw_frames_ctx != null)\n av_buffer_unref(&codecCtx->hw_frames_ctx);\n\n if (avcodec_get_hw_frames_parameters(codecCtx, codecCtx->hw_device_ctx, PIX_FMT_HWACCEL, &codecCtx->hw_frames_ctx) != 0)\n return -1;\n\n AVHWFramesContext* hw_frames_ctx = (AVHWFramesContext*)codecCtx->hw_frames_ctx->data;\n //hw_frames_ctx->initial_pool_size += Config.Decoder.MaxVideoFrames; // TBR: Texture 2D Array seems to have up limit to 128 (total=17+MaxVideoFrames)? (should use extra hw frames instead**)\n\n AVD3D11VAFramesContext *va_frames_ctx = (AVD3D11VAFramesContext *)hw_frames_ctx->hwctx;\n va_frames_ctx->BindFlags |= (uint)BindFlags.Decoder | (uint)BindFlags.ShaderResource;\n\n hwframes = av_buffer_ref(codecCtx->hw_frames_ctx);\n\n int ret = av_hwframe_ctx_init(codecCtx->hw_frames_ctx);\n if (ret == 0)\n {\n lock (Renderer.lockDevice)\n {\n textureFFmpeg = new ID3D11Texture2D((IntPtr) va_frames_ctx->texture);\n ZeroCopy = Config.Decoder.ZeroCopy == FlyleafLib.ZeroCopy.Enabled || (Config.Decoder.ZeroCopy == FlyleafLib.ZeroCopy.Auto && codecCtx->width == textureFFmpeg.Description.Width && codecCtx->height == textureFFmpeg.Description.Height);\n filledFromCodec = false;\n }\n }\n\n return ret;\n }\n internal void RecalculateZeroCopy()\n {\n lock (Renderer.lockDevice)\n {\n bool save = ZeroCopy;\n ZeroCopy = VideoAccelerated && (Config.Decoder.ZeroCopy == FlyleafLib.ZeroCopy.Enabled || (Config.Decoder.ZeroCopy == FlyleafLib.ZeroCopy.Auto && codecCtx->width == textureFFmpeg.Description.Width && codecCtx->height == textureFFmpeg.Description.Height));\n if (save != ZeroCopy)\n {\n Renderer?.ConfigPlanes();\n CodecChanged?.Invoke(this);\n }\n }\n }\n #endregion\n\n protected override int Setup(AVCodec* codec)\n {\n // Ensures we have a renderer (no swap chain is required)\n CreateRenderer();\n\n VideoAccelerated = false;\n\n if (!swFallback && Config.Video.VideoAcceleration && Renderer.Device.FeatureLevel >= Vortice.Direct3D.FeatureLevel.Level_10_0)\n {\n if (CheckCodecSupport(codec))\n {\n if (InitVA() == 0)\n {\n codecCtx->hw_device_ctx = av_buffer_ref(hw_device_ctx);\n VideoAccelerated = true;\n Log.Debug(\"VA Success\");\n }\n }\n else\n Log.Info($\"VA {codec->id} not supported\");\n }\n else\n Log.Debug(\"VA Disabled\");\n\n // Can't get data from here?\n //var t1 = av_stream_get_side_data(VideoStream.AVStream, AVPacketSideDataType.AV_PKT_DATA_MASTERING_DISPLAY_METADATA, null);\n //var t2 = av_stream_get_side_data(VideoStream.AVStream, AVPacketSideDataType.AV_PKT_DATA_CONTENT_LIGHT_LEVEL, null);\n\n // TBR: during swFallback (keyFrameRequiredPacket should not reset, currenlty saved in SWFallback)\n keyPacketRequired = false; // allow no key packet after open (lot of videos missing this)\n ZeroCopy = false;\n filledFromCodec = false;\n\n lastFixedPts = 0; // TBR: might need to set this to first known pts/dts\n\n if (VideoAccelerated)\n {\n codecCtx->thread_count = 1;\n codecCtx->hwaccel_flags |= HWAccelFlags.IgnoreLevel;\n if (Config.Decoder.AllowProfileMismatch)\n codecCtx->hwaccel_flags|= HWAccelFlags.AllowProfileMismatch;\n\n codecCtx->get_format = getHWformat;\n codecCtx->extra_hw_frames = Config.Decoder.MaxVideoFrames;\n }\n else\n codecCtx->thread_count = Math.Min(Config.Decoder.VideoThreads, codecCtx->codec_id == AVCodecID.Hevc ? 32 : 16);\n\n return 0;\n }\n internal bool SetupSws()\n {\n Marshal.FreeHGlobal(swsBufferPtr);\n var fmt = AVPixelFormat.Rgba;\n swsData = new byte_ptrArray4();\n swsLineSize = new int_array4();\n int outBufferSize\n = av_image_get_buffer_size(fmt, codecCtx->width, codecCtx->height, 1);\n swsBufferPtr = Marshal.AllocHGlobal(outBufferSize);\n av_image_fill_arrays(ref swsData, ref swsLineSize, (byte*) swsBufferPtr, fmt, codecCtx->width, codecCtx->height, 1);\n swsCtx = sws_getContext(codecCtx->coded_width, codecCtx->coded_height, codecCtx->pix_fmt, codecCtx->width, codecCtx->height, fmt, Config.Video.SwsHighQuality ? SCALING_HQ : SCALING_LQ, null, null, null);\n\n if (swsCtx == null)\n {\n Log.Error($\"Failed to allocate SwsContext\");\n return false;\n }\n\n return true;\n }\n internal void Flush()\n {\n lock (lockActions)\n lock (lockCodecCtx)\n {\n if (Disposed) return;\n\n if (Status == Status.Ended)\n Status = Status.Stopped;\n else if (Status == Status.Draining)\n Status = Status.Stopping;\n\n DisposeFrames();\n avcodec_flush_buffers(codecCtx);\n\n keyPacketRequired\n = true;\n StartTime = AV_NOPTS_VALUE;\n curSpeedFrame = 9999;\n }\n }\n\n protected override void RunInternal()\n {\n if (demuxer.IsReversePlayback)\n {\n RunInternalReverse();\n return;\n }\n\n int ret = 0;\n int allowedErrors = Config.Decoder.MaxErrors;\n int sleepMs = Config.Decoder.MaxVideoFrames > 2 && Config.Player.MaxLatency == 0 ? 10 : 2;\n AVPacket *packet;\n\n do\n {\n // Wait until Queue not Full or Stopped\n if (Frames.Count >= Config.Decoder.MaxVideoFrames)\n {\n lock (lockStatus)\n if (Status == Status.Running) Status = Status.QueueFull;\n\n while (Frames.Count >= Config.Decoder.MaxVideoFrames && Status == Status.QueueFull)\n Thread.Sleep(sleepMs);\n\n lock (lockStatus)\n {\n if (Status != Status.QueueFull) break;\n Status = Status.Running;\n }\n }\n\n // While Packets Queue Empty (Drain | Quit if Demuxer stopped | Wait until we get packets)\n if (demuxer.VideoPackets.Count == 0)\n {\n CriticalArea = true;\n\n lock (lockStatus)\n if (Status == Status.Running) Status = Status.QueueEmpty;\n\n while (demuxer.VideoPackets.Count == 0 && Status == Status.QueueEmpty)\n {\n if (demuxer.Status == Status.Ended)\n {\n lock (lockStatus)\n {\n // TODO: let the demuxer push the draining packet\n Log.Debug(\"Draining\");\n Status = Status.Draining;\n var drainPacket = av_packet_alloc();\n drainPacket->data = null;\n drainPacket->size = 0;\n demuxer.VideoPackets.Enqueue(drainPacket);\n }\n\n break;\n }\n else if (!demuxer.IsRunning)\n {\n if (CanDebug) Log.Debug($\"Demuxer is not running [Demuxer Status: {demuxer.Status}]\");\n\n int retries = 5;\n\n while (retries > 0)\n {\n retries--;\n Thread.Sleep(10);\n if (demuxer.IsRunning) break;\n }\n\n lock (demuxer.lockStatus)\n lock (lockStatus)\n {\n if (demuxer.Status == Status.Pausing || demuxer.Status == Status.Paused)\n Status = Status.Pausing;\n else if (demuxer.Status != Status.Ended)\n Status = Status.Stopping;\n else\n continue;\n }\n\n break;\n }\n\n Thread.Sleep(sleepMs);\n }\n\n lock (lockStatus)\n {\n CriticalArea = false;\n if (Status != Status.QueueEmpty && Status != Status.Draining) break;\n if (Status != Status.Draining) Status = Status.Running;\n }\n }\n\n lock (lockCodecCtx)\n {\n if (Status == Status.Stopped)\n continue;\n\n packet = demuxer.VideoPackets.Dequeue();\n\n if (packet == null)\n continue;\n\n if (isRecording)\n {\n if (!recKeyPacketRequired && (packet->flags & PktFlags.Key) != 0)\n {\n recKeyPacketRequired = true;\n StartRecordTime = (long)(packet->pts * VideoStream.Timebase) - demuxer.StartTime;\n }\n\n if (recKeyPacketRequired)\n curRecorder.Write(av_packet_clone(packet));\n }\n\n if (keyPacketRequired)\n {\n if (packet->flags.HasFlag(PktFlags.Key))\n keyPacketRequired = false;\n else\n {\n if (CanWarn) Log.Warn(\"Ignoring non-key packet\");\n av_packet_unref(packet);\n continue;\n }\n }\n\n // TBR: AVERROR(EAGAIN) means avcodec_receive_frame but after resend the same packet\n ret = avcodec_send_packet(codecCtx, packet);\n\n if (swFallback) // Should use 'global' packet to reset it in get_format (same packet should use also from DecoderContext)\n {\n SWFallback();\n ret = avcodec_send_packet(codecCtx, packet);\n }\n\n if (ret != 0 && ret != AVERROR(EAGAIN))\n {\n // TBR: Possible check for VA failed here (normally this will happen during get_format)\n av_packet_free(&packet);\n\n if (ret == AVERROR_EOF)\n {\n if (demuxer.VideoPackets.Count > 0) { avcodec_flush_buffers(codecCtx); continue; } // TBR: Happens on HLS while switching video streams\n Status = Status.Ended;\n break;\n }\n else\n {\n allowedErrors--;\n if (CanWarn) Log.Warn($\"{FFmpegEngine.ErrorCodeToMsg(ret)} ({ret})\");\n\n if (allowedErrors == 0) { Log.Error(\"Too many errors!\"); Status = Status.Stopping; break; }\n\n continue;\n }\n }\n\n while (true)\n {\n ret = avcodec_receive_frame(codecCtx, frame);\n if (ret != 0) { av_frame_unref(frame); break; }\n\n // GetFormat checks already for this but only for hardware accelerated (should also check for codec/fps* and possible reset sws if required)\n // Might use AVERROR_INPUT_CHANGED to let ffmpeg check for those (requires a flag to be set*)\n if (frame->height != VideoStream.Height || frame->width != VideoStream.Width)\n {\n // THIS IS Wrong and can cause filledFromCodec all the time. comparing frame<->videostream dimensions but we update the videostream from codecparam dimensions (which we pass from codecCtx w/h)\n // Related with display dimensions / coded dimensions / frame-crop dimensions (and apply_cropping) - it could happen when frame->crop... are not 0\n Log.Warn($\"Codec changed {VideoStream.CodecID} {VideoStream.Width}x{VideoStream.Height} => {codecCtx->codec_id} {frame->width}x{frame->height}\");\n filledFromCodec = false;\n }\n\n if (frame->best_effort_timestamp != AV_NOPTS_VALUE)\n frame->pts = frame->best_effort_timestamp;\n\n else if (frame->pts == AV_NOPTS_VALUE)\n {\n if (!VideoStream.FixTimestamps && VideoStream.Duration > TimeSpan.FromSeconds(1).Ticks)\n {\n // TBR: it is possible to have a single frame / image with no dts/pts which actually means pts = 0 ? (ticket_3449.264) - GenPts will not affect it\n // TBR: first frame might no have dts/pts which probably means pts = 0 (and not start time!)\n av_frame_unref(frame);\n continue;\n }\n\n // Create timestamps for h264/hevc raw streams (Needs also to handle this with the remuxer / no recording currently supported!)\n frame->pts = lastFixedPts + VideoStream.StartTimePts;\n lastFixedPts += av_rescale_q(VideoStream.FrameDuration / 10, Engine.FFmpeg.AV_TIMEBASE_Q, VideoStream.AVStream->time_base);\n }\n\n if (StartTime == NoTs)\n StartTime = (long)(frame->pts * VideoStream.Timebase) - demuxer.StartTime;\n\n if (!filledFromCodec) // Ensures we have a proper frame before filling from codec\n {\n ret = FillFromCodec(frame);\n if (ret == -1234)\n {\n Status = Status.Stopping;\n break;\n }\n }\n\n if (skipSpeedFrames > 1)\n {\n curSpeedFrame++;\n if (curSpeedFrame < skipSpeedFrames)\n {\n av_frame_unref(frame);\n continue;\n }\n curSpeedFrame = 0;\n }\n\n var mFrame = Renderer.FillPlanes(frame);\n if (mFrame != null) Frames.Enqueue(mFrame); // TBR: Does not respect Config.Decoder.MaxVideoFrames\n\n if (!Config.Video.PresentFlags.HasFlag(PresentFlags.DoNotWait) && Frames.Count > 2)\n Thread.Sleep(10);\n }\n\n av_packet_free(&packet);\n }\n\n } while (Status == Status.Running);\n\n checkExtraFrames = true;\n\n if (isRecording) { StopRecording(); recCompleted(MediaType.Video); }\n\n if (Status == Status.Draining) Status = Status.Ended;\n }\n\n internal int FillFromCodec(AVFrame* frame)\n {\n lock (Renderer.lockDevice)\n {\n int ret = 0;\n\n filledFromCodec = true;\n\n avcodec_parameters_from_context(Stream.AVStream->codecpar, codecCtx);\n VideoStream.AVStream->time_base = codecCtx->pkt_timebase;\n VideoStream.Refresh(VideoAccelerated && codecCtx->sw_pix_fmt != AVPixelFormat.None ? codecCtx->sw_pix_fmt : codecCtx->pix_fmt, frame);\n\n if (!(VideoStream.FPS > 0)) // NaN\n {\n VideoStream.FPS = av_q2d(codecCtx->framerate) > 0 ? av_q2d(codecCtx->framerate) : 0;\n VideoStream.FrameDuration = VideoStream.FPS > 0 ? (long) (10000000 / VideoStream.FPS) : 0;\n if (VideoStream.FrameDuration > 0)\n VideoStream.Demuxer.VideoPackets.frameDuration = VideoStream.FrameDuration;\n }\n\n skipSpeedFrames = speed * VideoStream.FPS / Config.Video.MaxOutputFps;\n CodecChanged?.Invoke(this);\n\n if (VideoStream.PixelFormat == AVPixelFormat.None || !Renderer.ConfigPlanes())\n {\n Log.Error(\"[Pixel Format] Unknown\");\n return -1234;\n }\n\n return ret;\n }\n }\n\n internal string SWFallback()\n {\n lock (Renderer.lockDevice)\n {\n string ret;\n\n DisposeInternal();\n if (codecCtx != null)\n fixed (AVCodecContext** ptr = &codecCtx)\n avcodec_free_context(ptr);\n\n codecCtx = null;\n swFallback = true;\n bool oldKeyFrameRequiredPacket\n = keyPacketRequired;\n ret = Open2(Stream, null, false); // TBR: Dispose() on failure could cause a deadlock\n keyPacketRequired\n = oldKeyFrameRequiredPacket;\n swFallback = false;\n filledFromCodec = false;\n\n return ret;\n }\n }\n\n private void RunInternalReverse()\n {\n // Bug with B-frames, we should not remove the ref packets (we miss frames each time we restart decoding the gop)\n\n int ret = 0;\n int allowedErrors = Config.Decoder.MaxErrors;\n AVPacket *packet;\n\n do\n {\n // While Packets Queue Empty (Drain | Quit if Demuxer stopped | Wait until we get packets)\n if (demuxer.VideoPacketsReverse.IsEmpty && curReverseVideoStack.IsEmpty && curReverseVideoPackets.Count == 0)\n {\n CriticalArea = true;\n\n lock (lockStatus)\n if (Status == Status.Running) Status = Status.QueueEmpty;\n\n while (demuxer.VideoPacketsReverse.IsEmpty && Status == Status.QueueEmpty)\n {\n if (demuxer.Status == Status.Ended) // TODO\n {\n lock (lockStatus) Status = Status.Ended;\n\n break;\n }\n else if (!demuxer.IsRunning)\n {\n if (CanDebug) Log.Debug($\"Demuxer is not running [Demuxer Status: {demuxer.Status}]\");\n\n int retries = 5;\n\n while (retries > 0)\n {\n retries--;\n Thread.Sleep(10);\n if (demuxer.IsRunning) break;\n }\n\n lock (demuxer.lockStatus)\n lock (lockStatus)\n {\n if (demuxer.Status == Status.Pausing || demuxer.Status == Status.Paused)\n Status = Status.Pausing;\n else if (demuxer.Status != Status.Ended)\n Status = Status.Stopping;\n else\n continue;\n }\n\n break;\n }\n\n Thread.Sleep(20);\n }\n\n lock (lockStatus)\n {\n CriticalArea = false;\n if (Status != Status.QueueEmpty) break;\n Status = Status.Running;\n }\n }\n\n if (curReverseVideoPackets.Count == 0)\n {\n if (curReverseVideoStack.IsEmpty)\n demuxer.VideoPacketsReverse.TryDequeue(out curReverseVideoStack);\n\n curReverseVideoStack.TryPop(out curReverseVideoPackets);\n curReversePacketPos = 0;\n }\n\n while (curReverseVideoPackets.Count > 0 && Status == Status.Running)\n {\n // Wait until Queue not Full or Stopped\n if (Frames.Count + curReverseVideoFrames.Count >= Config.Decoder.MaxVideoFrames)\n {\n lock (lockStatus)\n if (Status == Status.Running) Status = Status.QueueFull;\n\n while (Frames.Count + curReverseVideoFrames.Count >= Config.Decoder.MaxVideoFrames && Status == Status.QueueFull) Thread.Sleep(20);\n\n lock (lockStatus)\n {\n if (Status != Status.QueueFull) break;\n Status = Status.Running;\n }\n }\n\n lock (lockCodecCtx)\n {\n if (keyPacketRequired == true)\n {\n keyPacketRequired = false;\n curReversePacketPos = 0;\n break;\n }\n\n packet = (AVPacket*)curReverseVideoPackets[curReversePacketPos++];\n ret = avcodec_send_packet(codecCtx, packet);\n\n if (ret != 0 && ret != AVERROR(EAGAIN))\n {\n if (ret == AVERROR_EOF) { Status = Status.Ended; break; }\n\n if (CanWarn) Log.Warn($\"{FFmpegEngine.ErrorCodeToMsg(ret)} ({ret})\");\n\n allowedErrors--;\n if (allowedErrors == 0) { Log.Error(\"Too many errors!\"); Status = Status.Stopping; break; }\n\n for (int i=curReverseVideoPackets.Count-1; i>=curReversePacketPos-1; i--)\n {\n packet = (AVPacket*)curReverseVideoPackets[i];\n av_packet_free(&packet);\n curReverseVideoPackets[curReversePacketPos - 1] = IntPtr.Zero;\n curReverseVideoPackets.RemoveAt(i);\n }\n\n avcodec_flush_buffers(codecCtx);\n curReversePacketPos = 0;\n\n for (int i=curReverseVideoFrames.Count -1; i>=0; i--)\n Frames.Enqueue(curReverseVideoFrames[i]);\n\n curReverseVideoFrames.Clear();\n\n continue;\n }\n\n while (true)\n {\n ret = avcodec_receive_frame(codecCtx, frame);\n if (ret != 0) { av_frame_unref(frame); break; }\n\n if (frame->best_effort_timestamp != AV_NOPTS_VALUE)\n frame->pts = frame->best_effort_timestamp;\n else if (frame->pts == AV_NOPTS_VALUE)\n { av_frame_unref(frame); continue; }\n\n bool shouldProcess = curReverseVideoPackets.Count - curReversePacketPos < Config.Decoder.MaxVideoFrames;\n\n if (shouldProcess)\n {\n av_packet_free(&packet);\n curReverseVideoPackets[curReversePacketPos - 1] = IntPtr.Zero;\n var mFrame = Renderer.FillPlanes(frame);\n if (mFrame != null) curReverseVideoFrames.Add(mFrame);\n }\n else\n av_frame_unref(frame);\n }\n\n if (curReversePacketPos == curReverseVideoPackets.Count)\n {\n curReverseVideoPackets.RemoveRange(Math.Max(0, curReverseVideoPackets.Count - Config.Decoder.MaxVideoFrames), Math.Min(curReverseVideoPackets.Count, Config.Decoder.MaxVideoFrames) );\n avcodec_flush_buffers(codecCtx);\n curReversePacketPos = 0;\n\n for (int i=curReverseVideoFrames.Count -1; i>=0; i--)\n Frames.Enqueue(curReverseVideoFrames[i]);\n\n curReverseVideoFrames.Clear();\n\n break; // force recheck for max queues etc...\n }\n\n } // Lock CodecCtx\n\n // Import Sleep required to prevent delay during Renderer.Present for waitable swap chains\n if (!Config.Video.PresentFlags.HasFlag(PresentFlags.DoNotWait) && Frames.Count > 2)\n Thread.Sleep(10);\n\n } // while curReverseVideoPackets.Count > 0\n\n } while (Status == Status.Running);\n\n if (Status != Status.Pausing && Status != Status.Paused)\n curReversePacketPos = 0;\n }\n\n public void RefreshMaxVideoFrames()\n {\n lock (lockActions)\n {\n if (VideoStream == null)\n return;\n\n bool wasRunning = IsRunning;\n\n var stream = Stream;\n\n Dispose();\n Open(stream);\n\n if (wasRunning)\n Start();\n }\n }\n\n public int GetFrameNumber(long timestamp)\n {\n // Incoming timestamps are zero-base from demuxer start time (not from video stream start time)\n timestamp -= VideoStream.StartTime - demuxer.StartTime;\n\n if (timestamp < 1)\n return 0;\n\n // offset 2ms\n return (int) ((timestamp + 20000) / VideoStream.FrameDuration);\n }\n\n /// \n /// Performs accurate seeking to the requested VideoFrame and returns it\n /// \n /// Zero based frame index\n /// The requested VideoFrame or null on failure\n public VideoFrame GetFrame(int index)\n {\n int ret;\n\n // Calculation of FrameX timestamp (based on fps/avgFrameDuration) | offset 2ms\n long frameTimestamp = VideoStream.StartTime + (index * VideoStream.FrameDuration) - 20000;\n //Log.Debug($\"Searching for {Utils.TicksToTime(frameTimestamp)}\");\n\n demuxer.Pause();\n Pause();\n\n // TBR\n //if (demuxer.FormatContext->pb != null)\n // avio_flush(demuxer.FormatContext->pb);\n //avformat_flush(demuxer.FormatContext);\n\n // Seeking at frameTimestamp or previous I/Key frame and flushing codec | Temp fix (max I/distance 3sec) for ffmpeg bug that fails to seek on keyframe with HEVC\n // More issues with mpegts seeking backwards (those should be used also in the reverse playback in the demuxer)\n demuxer.Interrupter.SeekRequest();\n ret = codecCtx->codec_id == AVCodecID.Hevc|| (demuxer.FormatContext->iformat != null) // TBR: this is on FFInputFormat now -> && demuxer.FormatContext->iformat-> read_seek.Pointer == IntPtr.Zero)\n ? av_seek_frame(demuxer.FormatContext, -1, Math.Max(0, frameTimestamp - Config.Player.SeekGetFrameFixMargin) / 10, SeekFlags.Any)\n : av_seek_frame(demuxer.FormatContext, -1, frameTimestamp / 10, SeekFlags.Frame | SeekFlags.Backward);\n\n demuxer.DisposePackets();\n\n if (demuxer.Status == Status.Ended) demuxer.Status = Status.Stopped;\n if (ret < 0) return null; // handle seek error\n Flush();\n checkExtraFrames = false;\n\n while (DecodeFrameNext() == 0)\n {\n // Skip frames before our actual requested frame\n if ((long)(frame->pts * VideoStream.Timebase) < frameTimestamp)\n {\n //Log.Debug($\"[Skip] [pts: {frame->pts}] [time: {Utils.TicksToTime((long)(frame->pts * VideoStream.Timebase))}] | [fltime: {Utils.TicksToTime(((long)(frame->pts * VideoStream.Timebase) - demuxer.StartTime))}]\");\n av_frame_unref(frame);\n continue;\n }\n\n //Log.Debug($\"[Found] [pts: {frame->pts}] [time: {Utils.TicksToTime((long)(frame->pts * VideoStream.Timebase))}] | {Utils.TicksToTime(VideoStream.StartTime + (index * VideoStream.FrameDuration))} | [fltime: {Utils.TicksToTime(((long)(frame->pts * VideoStream.Timebase) - demuxer.StartTime))}]\");\n return Renderer.FillPlanes(frame);\n }\n\n return null;\n }\n\n /// \n /// Gets next VideoFrame (Decoder/Demuxer must not be running)\n /// \n /// The next VideoFrame\n public VideoFrame GetFrameNext()\n => DecodeFrameNext() == 0 ? Renderer.FillPlanes(frame) : null;\n\n /// \n /// Pushes the decoder to the next available VideoFrame (Decoder/Demuxer must not be running)\n /// \n /// \n public int DecodeFrameNext()\n {\n int ret;\n int allowedErrors = Config.Decoder.MaxErrors;\n\n if (checkExtraFrames)\n {\n if (Status == Status.Ended)\n return AVERROR_EOF;\n\n if (DecodeFrameNextInternal() == 0)\n return 0;\n\n if (Demuxer.Status == Status.Ended && demuxer.VideoPackets.Count == 0 && Frames.IsEmpty)\n {\n Stop();\n Status = Status.Ended;\n return AVERROR_EOF;\n }\n\n checkExtraFrames = false;\n }\n\n while (true)\n {\n ret = demuxer.GetNextVideoPacket();\n if (ret != 0)\n {\n if (demuxer.Status != Status.Ended)\n return ret;\n\n // Drain\n ret = avcodec_send_packet(codecCtx, demuxer.packet);\n av_packet_unref(demuxer.packet);\n\n if (ret != 0)\n return AVERROR_EOF;\n\n checkExtraFrames = true;\n return DecodeFrameNext();\n }\n\n if (keyPacketRequired)\n {\n if (demuxer.packet->flags.HasFlag(PktFlags.Key))\n keyPacketRequired = false;\n else\n {\n if (CanWarn) Log.Warn(\"Ignoring non-key packet\");\n av_packet_unref(demuxer.packet);\n continue;\n }\n }\n\n ret = avcodec_send_packet(codecCtx, demuxer.packet);\n\n if (swFallback) // Should use 'global' packet to reset it in get_format (same packet should use also from DecoderContext)\n {\n SWFallback();\n ret = avcodec_send_packet(codecCtx, demuxer.packet);\n }\n\n av_packet_unref(demuxer.packet);\n\n if (ret != 0 && ret != AVERROR(EAGAIN))\n {\n if (CanWarn) Log.Warn($\"{FFmpegEngine.ErrorCodeToMsg(ret)} ({ret})\");\n\n if (allowedErrors-- < 1)\n { Log.Error(\"Too many errors!\"); return ret; }\n\n continue;\n }\n\n if (DecodeFrameNextInternal() == 0)\n {\n checkExtraFrames = true;\n return 0;\n }\n }\n\n }\n private int DecodeFrameNextInternal()\n {\n int ret = avcodec_receive_frame(codecCtx, frame);\n if (ret != 0) { av_frame_unref(frame); return ret; }\n\n if (frame->best_effort_timestamp != AV_NOPTS_VALUE)\n frame->pts = frame->best_effort_timestamp;\n\n else if (frame->pts == AV_NOPTS_VALUE)\n {\n if (!VideoStream.FixTimestamps)\n {\n av_frame_unref(frame);\n\n return DecodeFrameNextInternal();\n }\n\n frame->pts = lastFixedPts + VideoStream.StartTimePts;\n lastFixedPts += av_rescale_q(VideoStream.FrameDuration / 10, Engine.FFmpeg.AV_TIMEBASE_Q, VideoStream.AVStream->time_base);\n }\n\n if (StartTime == NoTs)\n StartTime = (long)(frame->pts * VideoStream.Timebase) - demuxer.StartTime;\n\n if (!filledFromCodec) // Ensures we have a proper frame before filling from codec\n {\n ret = FillFromCodec(frame);\n if (ret == -1234)\n return -1;\n }\n\n return 0;\n }\n\n #region Dispose\n public void DisposeFrames()\n {\n while (!Frames.IsEmpty)\n {\n Frames.TryDequeue(out var frame);\n DisposeFrame(frame);\n }\n\n DisposeFramesReverse();\n }\n private void DisposeFramesReverse()\n {\n while (!curReverseVideoStack.IsEmpty)\n {\n curReverseVideoStack.TryPop(out var t2);\n for (int i = 0; i recCompleted;\n Remuxer curRecorder;\n bool recKeyPacketRequired;\n internal bool isRecording;\n\n internal void StartRecording(Remuxer remuxer)\n {\n if (Disposed || isRecording) return;\n\n StartRecordTime = AV_NOPTS_VALUE;\n curRecorder = remuxer;\n recKeyPacketRequired= false;\n isRecording = true;\n }\n internal void StopRecording() => isRecording = false;\n #endregion\n\n #region TODO Decoder Profiles\n\n /* Use the same as FFmpeg\n * https://github.com/FFmpeg/FFmpeg/blob/master/libavcodec/dxva2.c\n * https://github.com/FFmpeg/FFmpeg/blob/master/libavcodec/avcodec.h\n */\n\n //internal enum DecoderProfiles\n //{\n // DXVA_ModeMPEG2and1_VLD,\n // DXVA_ModeMPEG1_VLD,\n // DXVA2_ModeMPEG2_VLD,\n // DXVA2_ModeMPEG2_IDCT,\n // DXVA2_ModeMPEG2_MoComp,\n // DXVA_ModeH264_A,\n // DXVA_ModeH264_B,\n // DXVA_ModeH264_C,\n // DXVA_ModeH264_D,\n // DXVA_ModeH264_E,\n // DXVA_ModeH264_F,\n // DXVA_ModeH264_VLD_Stereo_Progressive_NoFGT,\n // DXVA_ModeH264_VLD_Stereo_NoFGT,\n // DXVA_ModeH264_VLD_Multiview_NoFGT,\n // DXVA_ModeWMV8_A,\n // DXVA_ModeWMV8_B,\n // DXVA_ModeWMV9_A,\n // DXVA_ModeWMV9_B,\n // DXVA_ModeWMV9_C,\n // DXVA_ModeVC1_A,\n // DXVA_ModeVC1_B,\n // DXVA_ModeVC1_C,\n // DXVA_ModeVC1_D,\n // DXVA_ModeVC1_D2010,\n // DXVA_ModeMPEG4pt2_VLD_Simple,\n // DXVA_ModeMPEG4pt2_VLD_AdvSimple_NoGMC,\n // DXVA_ModeMPEG4pt2_VLD_AdvSimple_GMC,\n // DXVA_ModeHEVC_VLD_Main,\n // DXVA_ModeHEVC_VLD_Main10,\n // DXVA_ModeVP8_VLD,\n // DXVA_ModeVP9_VLD_Profile0,\n // DXVA_ModeVP9_VLD_10bit_Profile2,\n // DXVA_ModeMPEG1_A,\n // DXVA_ModeMPEG2_A,\n // DXVA_ModeMPEG2_B,\n // DXVA_ModeMPEG2_C,\n // DXVA_ModeMPEG2_D,\n // DXVA_ModeH261_A,\n // DXVA_ModeH261_B,\n // DXVA_ModeH263_A,\n // DXVA_ModeH263_B,\n // DXVA_ModeH263_C,\n // DXVA_ModeH263_D,\n // DXVA_ModeH263_E,\n // DXVA_ModeH263_F,\n // DXVA_ModeH264_VLD_WithFMOASO_NoFGT,\n // DXVA_ModeH264_VLD_Multiview,\n // DXVADDI_Intel_ModeH264_A,\n // DXVADDI_Intel_ModeH264_C,\n // DXVA_Intel_H264_NoFGT_ClearVideo,\n // DXVA_ModeH264_VLD_NoFGT_Flash,\n // DXVA_Intel_VC1_ClearVideo,\n // DXVA_Intel_VC1_ClearVideo_2,\n // DXVA_nVidia_MPEG4_ASP,\n // DXVA_ModeMPEG4pt2_VLD_AdvSimple_Avivo,\n // DXVA_ModeHEVC_VLD_Main_Intel,\n // DXVA_ModeHEVC_VLD_Main10_Intel,\n // DXVA_ModeHEVC_VLD_Main12_Intel,\n // DXVA_ModeHEVC_VLD_Main422_10_Intel,\n // DXVA_ModeHEVC_VLD_Main422_12_Intel,\n // DXVA_ModeHEVC_VLD_Main444_Intel,\n // DXVA_ModeHEVC_VLD_Main444_10_Intel,\n // DXVA_ModeHEVC_VLD_Main444_12_Intel,\n // DXVA_ModeH264_VLD_SVC_Scalable_Baseline,\n // DXVA_ModeH264_VLD_SVC_Restricted_Scalable_Baseline,\n // DXVA_ModeH264_VLD_SVC_Scalable_High,\n // DXVA_ModeH264_VLD_SVC_Restricted_Scalable_High_Progressive,\n // DXVA_ModeVP9_VLD_Intel,\n // DXVA_ModeAV1_VLD_Profile0,\n // DXVA_ModeAV1_VLD_Profile1,\n // DXVA_ModeAV1_VLD_Profile2,\n // DXVA_ModeAV1_VLD_12bit_Profile2,\n // DXVA_ModeAV1_VLD_12bit_Profile2_420\n //}\n //internal static Dictionary DXVADecoderProfiles = new()\n //{\n // { new(0x86695f12, 0x340e, 0x4f04, 0x9f, 0xd3, 0x92, 0x53, 0xdd, 0x32, 0x74, 0x60), DecoderProfiles.DXVA_ModeMPEG2and1_VLD },\n // { new(0x6f3ec719, 0x3735, 0x42cc, 0x80, 0x63, 0x65, 0xcc, 0x3c, 0xb3, 0x66, 0x16), DecoderProfiles.DXVA_ModeMPEG1_VLD },\n // { new(0xee27417f, 0x5e28,0x4e65, 0xbe, 0xea, 0x1d, 0x26, 0xb5, 0x08, 0xad, 0xc9), DecoderProfiles.DXVA2_ModeMPEG2_VLD },\n // { new(0xbf22ad00, 0x03ea,0x4690, 0x80, 0x77, 0x47, 0x33, 0x46, 0x20, 0x9b, 0x7e), DecoderProfiles.DXVA2_ModeMPEG2_IDCT },\n // { new(0xe6a9f44b, 0x61b0,0x4563, 0x9e, 0xa4, 0x63, 0xd2, 0xa3, 0xc6, 0xfe, 0x66), DecoderProfiles.DXVA2_ModeMPEG2_MoComp },\n // { new(0x1b81be64, 0xa0c7,0x11d3, 0xb9, 0x84, 0x00, 0xc0, 0x4f, 0x2e, 0x73, 0xc5), DecoderProfiles.DXVA_ModeH264_A },\n // { new(0x1b81be65, 0xa0c7,0x11d3, 0xb9, 0x84, 0x00, 0xc0, 0x4f, 0x2e, 0x73, 0xc5), DecoderProfiles.DXVA_ModeH264_B },\n // { new(0x1b81be66, 0xa0c7,0x11d3, 0xb9, 0x84, 0x00, 0xc0, 0x4f, 0x2e, 0x73, 0xc5), DecoderProfiles.DXVA_ModeH264_C },\n // { new(0x1b81be67, 0xa0c7,0x11d3, 0xb9, 0x84, 0x00, 0xc0, 0x4f, 0x2e, 0x73, 0xc5), DecoderProfiles.DXVA_ModeH264_D },\n // { new(0x1b81be68, 0xa0c7,0x11d3, 0xb9, 0x84, 0x00, 0xc0, 0x4f, 0x2e, 0x73, 0xc5), DecoderProfiles.DXVA_ModeH264_E },\n // { new(0x1b81be69, 0xa0c7,0x11d3, 0xb9, 0x84, 0x00, 0xc0, 0x4f, 0x2e, 0x73, 0xc5), DecoderProfiles.DXVA_ModeH264_F },\n // { new(0xd79be8da, 0x0cf1,0x4c81, 0xb8, 0x2a, 0x69, 0xa4, 0xe2, 0x36, 0xf4, 0x3d), DecoderProfiles.DXVA_ModeH264_VLD_Stereo_Progressive_NoFGT },\n // { new(0xf9aaccbb, 0xc2b6,0x4cfc, 0x87, 0x79, 0x57, 0x07, 0xb1, 0x76, 0x05, 0x52), DecoderProfiles.DXVA_ModeH264_VLD_Stereo_NoFGT },\n // { new(0x705b9d82, 0x76cf,0x49d6, 0xb7, 0xe6, 0xac, 0x88, 0x72, 0xdb, 0x01, 0x3c), DecoderProfiles.DXVA_ModeH264_VLD_Multiview_NoFGT },\n // { new(0x1b81be80, 0xa0c7,0x11d3, 0xb9, 0x84, 0x00, 0xc0, 0x4f, 0x2e, 0x73, 0xc5), DecoderProfiles.DXVA_ModeWMV8_A },\n // { new(0x1b81be81, 0xa0c7,0x11d3, 0xb9, 0x84, 0x00, 0xc0, 0x4f, 0x2e, 0x73, 0xc5), DecoderProfiles.DXVA_ModeWMV8_B },\n // { new(0x1b81be90, 0xa0c7,0x11d3, 0xb9, 0x84, 0x00, 0xc0, 0x4f, 0x2e, 0x73, 0xc5), DecoderProfiles.DXVA_ModeWMV9_A },\n // { new(0x1b81be91, 0xa0c7,0x11d3, 0xb9, 0x84, 0x00, 0xc0, 0x4f, 0x2e, 0x73, 0xc5), DecoderProfiles.DXVA_ModeWMV9_B },\n // { new(0x1b81be94, 0xa0c7,0x11d3, 0xb9, 0x84, 0x00, 0xc0, 0x4f, 0x2e, 0x73, 0xc5), DecoderProfiles.DXVA_ModeWMV9_C },\n // { new(0x1b81beA0, 0xa0c7,0x11d3, 0xb9, 0x84, 0x00, 0xc0, 0x4f, 0x2e, 0x73, 0xc5), DecoderProfiles.DXVA_ModeVC1_A },\n // { new(0x1b81beA1, 0xa0c7,0x11d3, 0xb9, 0x84, 0x00, 0xc0, 0x4f, 0x2e, 0x73, 0xc5), DecoderProfiles.DXVA_ModeVC1_B },\n // { new(0x1b81beA2, 0xa0c7,0x11d3, 0xb9, 0x84, 0x00, 0xc0, 0x4f, 0x2e, 0x73, 0xc5), DecoderProfiles.DXVA_ModeVC1_C },\n // { new(0x1b81beA3, 0xa0c7,0x11d3, 0xb9, 0x84, 0x00, 0xc0, 0x4f, 0x2e, 0x73, 0xc5), DecoderProfiles.DXVA_ModeVC1_D },\n // { new(0x1b81bea4, 0xa0c7,0x11d3, 0xb9, 0x84, 0x00, 0xc0, 0x4f, 0x2e, 0x73, 0xc5), DecoderProfiles.DXVA_ModeVC1_D2010 },\n // { new(0xefd64d74, 0xc9e8,0x41d7, 0xa5, 0xe9, 0xe9, 0xb0, 0xe3, 0x9f, 0xa3, 0x19), DecoderProfiles.DXVA_ModeMPEG4pt2_VLD_Simple },\n // { new(0xed418a9f, 0x010d,0x4eda, 0x9a, 0xe3, 0x9a, 0x65, 0x35, 0x8d, 0x8d, 0x2e), DecoderProfiles.DXVA_ModeMPEG4pt2_VLD_AdvSimple_NoGMC },\n // { new(0xab998b5b, 0x4258,0x44a9, 0x9f, 0xeb, 0x94, 0xe5, 0x97, 0xa6, 0xba, 0xae), DecoderProfiles.DXVA_ModeMPEG4pt2_VLD_AdvSimple_GMC },\n // { new(0x5b11d51b, 0x2f4c,0x4452, 0xbc, 0xc3, 0x09, 0xf2, 0xa1, 0x16, 0x0c, 0xc0), DecoderProfiles.DXVA_ModeHEVC_VLD_Main },\n // { new(0x107af0e0, 0xef1a,0x4d19, 0xab, 0xa8, 0x67, 0xa1, 0x63, 0x07, 0x3d, 0x13), DecoderProfiles.DXVA_ModeHEVC_VLD_Main10 },\n // { new(0x90b899ea, 0x3a62,0x4705, 0x88, 0xb3, 0x8d, 0xf0, 0x4b, 0x27, 0x44, 0xe7), DecoderProfiles.DXVA_ModeVP8_VLD },\n // { new(0x463707f8, 0xa1d0,0x4585, 0x87, 0x6d, 0x83, 0xaa, 0x6d, 0x60, 0xb8, 0x9e), DecoderProfiles.DXVA_ModeVP9_VLD_Profile0 },\n // { new(0xa4c749ef, 0x6ecf,0x48aa, 0x84, 0x48, 0x50, 0xa7, 0xa1, 0x16, 0x5f, 0xf7), DecoderProfiles.DXVA_ModeVP9_VLD_10bit_Profile2 },\n // { new(0x1b81be09, 0xa0c7, 0x11d3, 0xb9, 0x84, 0x00, 0xc0, 0x4f, 0x2e, 0x73, 0xc5), DecoderProfiles.DXVA_ModeMPEG1_A },\n // { new(0x1b81be0A, 0xa0c7, 0x11d3, 0xb9, 0x84, 0x00, 0xc0, 0x4f, 0x2e, 0x73, 0xc5), DecoderProfiles.DXVA_ModeMPEG2_A },\n // { new(0x1b81be0B, 0xa0c7, 0x11d3, 0xb9, 0x84, 0x00, 0xc0, 0x4f, 0x2e, 0x73, 0xc5), DecoderProfiles.DXVA_ModeMPEG2_B },\n // { new(0x1b81be0C, 0xa0c7, 0x11d3, 0xb9, 0x84, 0x00, 0xc0, 0x4f, 0x2e, 0x73, 0xc5), DecoderProfiles.DXVA_ModeMPEG2_C },\n // { new(0x1b81be0D, 0xa0c7, 0x11d3, 0xb9, 0x84, 0x00, 0xc0, 0x4f, 0x2e, 0x73, 0xc5), DecoderProfiles.DXVA_ModeMPEG2_D },\n // { new(0x1b81be01, 0xa0c7, 0x11d3, 0xb9, 0x84, 0x00, 0xc0, 0x4f, 0x2e, 0x73, 0xc5), DecoderProfiles.DXVA_ModeH261_A },\n // { new(0x1b81be02, 0xa0c7, 0x11d3, 0xb9, 0x84, 0x00, 0xc0, 0x4f, 0x2e, 0x73, 0xc5), DecoderProfiles.DXVA_ModeH261_B },\n // { new(0x1b81be03, 0xa0c7, 0x11d3, 0xb9, 0x84, 0x00, 0xc0, 0x4f, 0x2e, 0x73, 0xc5), DecoderProfiles.DXVA_ModeH263_A },\n // { new(0x1b81be04, 0xa0c7, 0x11d3, 0xb9, 0x84, 0x00, 0xc0, 0x4f, 0x2e, 0x73, 0xc5), DecoderProfiles.DXVA_ModeH263_B },\n // { new(0x1b81be05, 0xa0c7, 0x11d3, 0xb9, 0x84, 0x00, 0xc0, 0x4f, 0x2e, 0x73, 0xc5), DecoderProfiles.DXVA_ModeH263_C },\n // { new(0x1b81be06, 0xa0c7, 0x11d3, 0xb9, 0x84, 0x00, 0xc0, 0x4f, 0x2e, 0x73, 0xc5), DecoderProfiles.DXVA_ModeH263_D },\n // { new(0x1b81be07, 0xa0c7, 0x11d3, 0xb9, 0x84, 0x00, 0xc0, 0x4f, 0x2e, 0x73, 0xc5), DecoderProfiles.DXVA_ModeH263_E },\n // { new(0x1b81be08, 0xa0c7, 0x11d3, 0xb9, 0x84, 0x00, 0xc0, 0x4f, 0x2e, 0x73, 0xc5), DecoderProfiles.DXVA_ModeH263_F },\n // { new(0xd5f04ff9, 0x3418, 0x45d8, 0x95, 0x61, 0x32, 0xa7, 0x6a, 0xae, 0x2d, 0xdd), DecoderProfiles.DXVA_ModeH264_VLD_WithFMOASO_NoFGT },\n // { new(0x9901CCD3, 0xca12, 0x4b7e, 0x86, 0x7a, 0xe2, 0x22, 0x3d, 0x92, 0x55, 0xc3), DecoderProfiles.DXVA_ModeH264_VLD_Multiview },\n // { new(0x604F8E64, 0x4951, 0x4c54, 0x88, 0xFE, 0xAB, 0xD2, 0x5C, 0x15, 0xB3, 0xD6), DecoderProfiles.DXVADDI_Intel_ModeH264_A },\n // { new(0x604F8E66, 0x4951, 0x4c54, 0x88, 0xFE, 0xAB, 0xD2, 0x5C, 0x15, 0xB3, 0xD6), DecoderProfiles.DXVADDI_Intel_ModeH264_C },\n // { new(0x604F8E68, 0x4951, 0x4c54, 0x88, 0xFE, 0xAB, 0xD2, 0x5C, 0x15, 0xB3, 0xD6), DecoderProfiles.DXVA_Intel_H264_NoFGT_ClearVideo },\n // { new(0x4245F676, 0x2BBC, 0x4166, 0xa0, 0xBB, 0x54, 0xE7, 0xB8, 0x49, 0xC3, 0x80), DecoderProfiles.DXVA_ModeH264_VLD_NoFGT_Flash },\n // { new(0xBCC5DB6D, 0xA2B6, 0x4AF0, 0xAC, 0xE4, 0xAD, 0xB1, 0xF7, 0x87, 0xBC, 0x89), DecoderProfiles.DXVA_Intel_VC1_ClearVideo },\n // { new(0xE07EC519, 0xE651, 0x4CD6, 0xAC, 0x84, 0x13, 0x70, 0xCC, 0xEE, 0xC8, 0x51), DecoderProfiles.DXVA_Intel_VC1_ClearVideo_2 },\n // { new(0x9947EC6F, 0x689B, 0x11DC, 0xA3, 0x20, 0x00, 0x19, 0xDB, 0xBC, 0x41, 0x84), DecoderProfiles.DXVA_nVidia_MPEG4_ASP },\n // { new(0x7C74ADC6, 0xe2ba, 0x4ade, 0x86, 0xde, 0x30, 0xbe, 0xab, 0xb4, 0x0c, 0xc1), DecoderProfiles.DXVA_ModeMPEG4pt2_VLD_AdvSimple_Avivo },\n // { new(0x8c56eb1e, 0x2b47, 0x466f, 0x8d, 0x33, 0x7d, 0xbc, 0xd6, 0x3f, 0x3d, 0xf2), DecoderProfiles.DXVA_ModeHEVC_VLD_Main_Intel },\n // { new(0x75fc75f7, 0xc589, 0x4a07, 0xa2, 0x5b, 0x72, 0xe0, 0x3b, 0x03, 0x83, 0xb3), DecoderProfiles.DXVA_ModeHEVC_VLD_Main10_Intel },\n // { new(0x8ff8a3aa, 0xc456, 0x4132, 0xb6, 0xef, 0x69, 0xd9, 0xdd, 0x72, 0x57, 0x1d), DecoderProfiles.DXVA_ModeHEVC_VLD_Main12_Intel },\n // { new(0xe484dcb8, 0xcac9, 0x4859, 0x99, 0xf5, 0x5c, 0x0d, 0x45, 0x06, 0x90, 0x89), DecoderProfiles.DXVA_ModeHEVC_VLD_Main422_10_Intel },\n // { new(0xc23dd857, 0x874b, 0x423c, 0xb6, 0xe0, 0x82, 0xce, 0xaa, 0x9b, 0x11, 0x8a), DecoderProfiles.DXVA_ModeHEVC_VLD_Main422_12_Intel },\n // { new(0x41a5af96, 0xe415, 0x4b0c, 0x9d, 0x03, 0x90, 0x78, 0x58, 0xe2, 0x3e, 0x78), DecoderProfiles.DXVA_ModeHEVC_VLD_Main444_Intel },\n // { new(0x6a6a81ba, 0x912a, 0x485d, 0xb5, 0x7f, 0xcc, 0xd2, 0xd3, 0x7b, 0x8d, 0x94), DecoderProfiles.DXVA_ModeHEVC_VLD_Main444_10_Intel },\n // { new(0x5b08e35d, 0x0c66, 0x4c51, 0xa6, 0xf1, 0x89, 0xd0, 0x0c, 0xb2, 0xc1, 0x97), DecoderProfiles.DXVA_ModeHEVC_VLD_Main444_12_Intel },\n // { new(0xc30700c4, 0xe384, 0x43e0, 0xb9, 0x82, 0x2d, 0x89, 0xee, 0x7f, 0x77, 0xc4), DecoderProfiles.DXVA_ModeH264_VLD_SVC_Scalable_Baseline },\n // { new(0x9b8175d4, 0xd670, 0x4cf2, 0xa9, 0xf0, 0xfa, 0x56, 0xdf, 0x71, 0xa1, 0xae), DecoderProfiles.DXVA_ModeH264_VLD_SVC_Restricted_Scalable_Baseline },\n // { new(0x728012c9, 0x66a8, 0x422f, 0x97, 0xe9, 0xb5, 0xe3, 0x9b, 0x51, 0xc0, 0x53), DecoderProfiles.DXVA_ModeH264_VLD_SVC_Scalable_High },\n // { new(0x8efa5926, 0xbd9e, 0x4b04, 0x8b, 0x72, 0x8f, 0x97, 0x7d, 0xc4, 0x4c, 0x36), DecoderProfiles.DXVA_ModeH264_VLD_SVC_Restricted_Scalable_High_Progressive },\n // { new(0x76988a52, 0xdf13, 0x419a, 0x8e, 0x64, 0xff, 0xcf, 0x4a, 0x33, 0x6c, 0xf5), DecoderProfiles.DXVA_ModeVP9_VLD_Intel },\n // { new(0xb8be4ccb, 0xcf53, 0x46ba, 0x8d, 0x59, 0xd6, 0xb8, 0xa6, 0xda, 0x5d, 0x2a), DecoderProfiles.DXVA_ModeAV1_VLD_Profile0 },\n // { new(0x6936ff0f, 0x45b1, 0x4163, 0x9c, 0xc1, 0x64, 0x6e, 0xf6, 0x94, 0x61, 0x08), DecoderProfiles.DXVA_ModeAV1_VLD_Profile1 },\n // { new(0x0c5f2aa1, 0xe541, 0x4089, 0xbb, 0x7b, 0x98, 0x11, 0x0a, 0x19, 0xd7, 0xc8), DecoderProfiles.DXVA_ModeAV1_VLD_Profile2 },\n // { new(0x17127009, 0xa00f, 0x4ce1, 0x99, 0x4e, 0xbf, 0x40, 0x81, 0xf6, 0xf3, 0xf0), DecoderProfiles.DXVA_ModeAV1_VLD_12bit_Profile2 },\n // { new(0x2d80bed6, 0x9cac, 0x4835, 0x9e, 0x91, 0x32, 0x7b, 0xbc, 0x4f, 0x9e, 0xe8), DecoderProfiles.DXVA_ModeAV1_VLD_12bit_Profile2_420 },\n\n\n //};\n //internal static Dictionary DXVADecoderProfilesDesc = new()\n //{\n // { DecoderProfiles.DXVA_ModeMPEG1_A, \"MPEG-1 decoder, restricted profile A\" },\n // { DecoderProfiles.DXVA_ModeMPEG2_A, \"MPEG-2 decoder, restricted profile A\" },\n // { DecoderProfiles.DXVA_ModeMPEG2_B, \"MPEG-2 decoder, restricted profile B\" },\n // { DecoderProfiles.DXVA_ModeMPEG2_C, \"MPEG-2 decoder, restricted profile C\" },\n // { DecoderProfiles.DXVA_ModeMPEG2_D, \"MPEG-2 decoder, restricted profile D\" },\n // { DecoderProfiles.DXVA2_ModeMPEG2_VLD, \"MPEG-2 variable-length decoder\" },\n // { DecoderProfiles.DXVA_ModeMPEG2and1_VLD, \"MPEG-2 & MPEG-1 variable-length decoder\" },\n // { DecoderProfiles.DXVA2_ModeMPEG2_MoComp, \"MPEG-2 motion compensation\" },\n // { DecoderProfiles.DXVA2_ModeMPEG2_IDCT, \"MPEG-2 inverse discrete cosine transform\" },\n // { DecoderProfiles.DXVA_ModeMPEG1_VLD, \"MPEG-1 variable-length decoder, no D pictures\" },\n // { DecoderProfiles.DXVA_ModeH264_F, \"H.264 variable-length decoder, film grain technology\" },\n // { DecoderProfiles.DXVA_ModeH264_E, \"H.264 variable-length decoder, no film grain technology\" },\n // { DecoderProfiles.DXVA_Intel_H264_NoFGT_ClearVideo, \"H.264 variable-length decoder, no film grain technology (Intel ClearVideo)\" },\n // { DecoderProfiles.DXVA_ModeH264_VLD_WithFMOASO_NoFGT, \"H.264 variable-length decoder, no film grain technology, FMO/ASO\" },\n // { DecoderProfiles.DXVA_ModeH264_VLD_NoFGT_Flash, \"H.264 variable-length decoder, no film grain technology, Flash\" },\n // { DecoderProfiles.DXVA_ModeH264_D, \"H.264 inverse discrete cosine transform, film grain technology\" },\n // { DecoderProfiles.DXVA_ModeH264_C, \"H.264 inverse discrete cosine transform, no film grain technology\" },\n // { DecoderProfiles.DXVADDI_Intel_ModeH264_C, \"H.264 inverse discrete cosine transform, no film grain technology (Intel)\" },\n // { DecoderProfiles.DXVA_ModeH264_B, \"H.264 motion compensation, film grain technology\" },\n // { DecoderProfiles.DXVA_ModeH264_A, \"H.264 motion compensation, no film grain technology\" },\n // { DecoderProfiles.DXVADDI_Intel_ModeH264_A, \"H.264 motion compensation, no film grain technology (Intel)\" },\n // { DecoderProfiles.DXVA_ModeH264_VLD_Stereo_Progressive_NoFGT, \"H.264 stereo high profile, mbs flag set\" },\n // { DecoderProfiles.DXVA_ModeH264_VLD_Stereo_NoFGT, \"H.264 stereo high profile\" },\n // { DecoderProfiles.DXVA_ModeH264_VLD_Multiview_NoFGT, \"H.264 multiview high profile\" },\n // { DecoderProfiles.DXVA_ModeH264_VLD_SVC_Scalable_Baseline, \"H.264 scalable video coding, Scalable Baseline Profile\" },\n // { DecoderProfiles.DXVA_ModeH264_VLD_SVC_Restricted_Scalable_Baseline, \"H.264 scalable video coding, Scalable Constrained Baseline Profile\" },\n // { DecoderProfiles.DXVA_ModeH264_VLD_SVC_Scalable_High, \"H.264 scalable video coding, Scalable High Profile\" },\n // { DecoderProfiles.DXVA_ModeH264_VLD_SVC_Restricted_Scalable_High_Progressive, \"H.264 scalable video coding, Scalable Constrained High Profile\" },\n // { DecoderProfiles.DXVA_ModeWMV8_B, \"Windows Media Video 8 motion compensation\" },\n // { DecoderProfiles.DXVA_ModeWMV8_A, \"Windows Media Video 8 post processing\" },\n // { DecoderProfiles.DXVA_ModeWMV9_C, \"Windows Media Video 9 IDCT\" },\n // { DecoderProfiles.DXVA_ModeWMV9_B, \"Windows Media Video 9 motion compensation\" },\n // { DecoderProfiles.DXVA_ModeWMV9_A, \"Windows Media Video 9 post processing\" },\n // { DecoderProfiles.DXVA_ModeVC1_D, \"VC-1 variable-length decoder\" },\n // { DecoderProfiles.DXVA_ModeVC1_D2010, \"VC-1 variable-length decoder\" },\n // { DecoderProfiles.DXVA_Intel_VC1_ClearVideo_2, \"VC-1 variable-length decoder 2 (Intel)\" },\n // { DecoderProfiles.DXVA_Intel_VC1_ClearVideo, \"VC-1 variable-length decoder (Intel)\" },\n // { DecoderProfiles.DXVA_ModeVC1_C, \"VC-1 inverse discrete cosine transform\" },\n // { DecoderProfiles.DXVA_ModeVC1_B, \"VC-1 motion compensation\" },\n // { DecoderProfiles.DXVA_ModeVC1_A, \"VC-1 post processing\" },\n // { DecoderProfiles.DXVA_nVidia_MPEG4_ASP, \"MPEG-4 Part 2 nVidia bitstream decoder\" },\n // { DecoderProfiles.DXVA_ModeMPEG4pt2_VLD_Simple, \"MPEG-4 Part 2 variable-length decoder, Simple Profile\" },\n // { DecoderProfiles.DXVA_ModeMPEG4pt2_VLD_AdvSimple_NoGMC, \"MPEG-4 Part 2 variable-length decoder, Simple&Advanced Profile, no GMC\" },\n // { DecoderProfiles.DXVA_ModeMPEG4pt2_VLD_AdvSimple_GMC, \"MPEG-4 Part 2 variable-length decoder, Simple&Advanced Profile, GMC\" },\n // { DecoderProfiles.DXVA_ModeMPEG4pt2_VLD_AdvSimple_Avivo, \"MPEG-4 Part 2 variable-length decoder, Simple&Advanced Profile, Avivo\" },\n // { DecoderProfiles.DXVA_ModeHEVC_VLD_Main_Intel, \"HEVC Main profile (Intel)\" },\n // { DecoderProfiles.DXVA_ModeHEVC_VLD_Main10_Intel, \"HEVC Main 10 profile (Intel)\" },\n // { DecoderProfiles.DXVA_ModeHEVC_VLD_Main12_Intel, \"HEVC Main profile 4:2:2 Range Extension (Intel)\" },\n // { DecoderProfiles.DXVA_ModeHEVC_VLD_Main422_10_Intel, \"HEVC Main 10 profile 4:2:2 Range Extension (Intel)\" },\n // { DecoderProfiles.DXVA_ModeHEVC_VLD_Main422_12_Intel, \"HEVC Main 12 profile 4:2:2 Range Extension (Intel)\" },\n // { DecoderProfiles.DXVA_ModeHEVC_VLD_Main444_Intel, \"HEVC Main profile 4:4:4 Range Extension (Intel)\" },\n // { DecoderProfiles.DXVA_ModeHEVC_VLD_Main444_10_Intel, \"HEVC Main 10 profile 4:4:4 Range Extension (Intel)\" },\n // { DecoderProfiles.DXVA_ModeHEVC_VLD_Main444_12_Intel, \"HEVC Main 12 profile 4:4:4 Range Extension (Intel)\" },\n // { DecoderProfiles.DXVA_ModeHEVC_VLD_Main, \"HEVC Main profile\" },\n // { DecoderProfiles.DXVA_ModeHEVC_VLD_Main10, \"HEVC Main 10 profile\" },\n // { DecoderProfiles.DXVA_ModeH261_A, \"H.261 decoder, restricted profile A\" },\n // { DecoderProfiles.DXVA_ModeH261_B, \"H.261 decoder, restricted profile B\" },\n // { DecoderProfiles.DXVA_ModeH263_A, \"H.263 decoder, restricted profile A\" },\n // { DecoderProfiles.DXVA_ModeH263_B, \"H.263 decoder, restricted profile B\" },\n // { DecoderProfiles.DXVA_ModeH263_C, \"H.263 decoder, restricted profile C\" },\n // { DecoderProfiles.DXVA_ModeH263_D, \"H.263 decoder, restricted profile D\" },\n // { DecoderProfiles.DXVA_ModeH263_E, \"H.263 decoder, restricted profile E\" },\n // { DecoderProfiles.DXVA_ModeH263_F, \"H.263 decoder, restricted profile F\" },\n // { DecoderProfiles.DXVA_ModeVP8_VLD, \"VP8\" },\n // { DecoderProfiles.DXVA_ModeVP9_VLD_Profile0, \"VP9 profile 0\" },\n // { DecoderProfiles.DXVA_ModeVP9_VLD_10bit_Profile2, \"VP9 profile\" },\n // { DecoderProfiles.DXVA_ModeVP9_VLD_Intel, \"VP9 profile Intel\" },\n // { DecoderProfiles.DXVA_ModeAV1_VLD_Profile0, \"AV1 Main profile\" },\n // { DecoderProfiles.DXVA_ModeAV1_VLD_Profile1, \"AV1 High profile\" },\n //};\n #endregion\n}\n"], ["/LLPlayer/FlyleafLib/MediaFramework/MediaDemuxer/Demuxer.cs", "using System.Collections.Concurrent;\nusing System.Collections.Generic;\nusing System.Collections.ObjectModel;\nusing System.IO;\nusing System.Runtime.InteropServices;\nusing System.Text;\nusing System.Threading;\nusing System.Threading.Tasks;\nusing System.Windows.Data;\n\nusing FlyleafLib.MediaFramework.MediaProgram;\nusing FlyleafLib.MediaFramework.MediaStream;\nusing FlyleafLib.MediaPlayer;\nusing static FlyleafLib.Config;\nusing static FlyleafLib.Logger;\n\nnamespace FlyleafLib.MediaFramework.MediaDemuxer;\n\npublic unsafe class Demuxer : RunThreadBase\n{\n /* TODO\n * 1) Review lockFmtCtx on Enable/Disable Streams causes delay and is not fully required\n * 2) Include AV_DISPOSITION_ATTACHED_PIC images in streams as VideoStream with flag\n * Possible introduce ImageStream and include also video streams with < 1 sec duration (eg. mjpeg etc)\n */\n\n #region Properties\n public MediaType Type { get; private set; }\n public DemuxerConfig Config { get; set; }\n\n // Format Info\n public string Url { get; private set; }\n public string Name { get; private set; }\n public string LongName { get; private set; }\n public string Extensions { get; private set; }\n public string Extension { get; private set; }\n public long StartTime { get; private set; }\n public long StartRealTime { get; private set; }\n public long Duration { get; internal set; }\n public void ForceDuration(long duration) { Duration = duration; IsLive = duration != 0; }\n\n public Dictionary\n Metadata { get; internal set; } = new Dictionary();\n\n /// \n /// The time of first packet in the queue (zero based, substracts start time)\n /// \n public long CurTime => CurPackets.CurTime != 0 ? CurPackets.CurTime : lastSeekTime;\n\n /// \n /// The buffered time in the queue (last packet time - first packet time)\n /// \n public long BufferedDuration=> CurPackets.BufferedDuration;\n\n public bool IsLive { get; private set; }\n public bool IsHLSLive { get; private set; }\n\n public AVFormatContext* FormatContext => fmtCtx;\n public CustomIOContext CustomIOContext { get; private set; }\n\n // Media Programs\n public ObservableCollection\n Programs { get; private set; } = new ObservableCollection();\n\n // Media Streams\n public ObservableCollection\n AudioStreams { get; private set; } = new ObservableCollection();\n public ObservableCollection\n VideoStreams { get; private set; } = new ObservableCollection();\n public ObservableCollection\n SubtitlesStreamsAll\n { get; private set; } = new ObservableCollection();\n public ObservableCollection\n DataStreams { get; private set; } = new ObservableCollection();\n readonly object lockStreams = new();\n\n public List EnabledStreams { get; private set; } = new List();\n public Dictionary\n AVStreamToStream{ get; private set; }\n\n public AudioStream AudioStream { get; private set; }\n public VideoStream VideoStream { get; private set; }\n // In the case of the secondary external subtitle, there is only one stream, but it goes into index=1 and index = 0 is null.\n public SubtitlesStream[] SubtitlesStreams\n { get; private set; }\n public DataStream DataStream { get; private set; }\n\n // Audio/Video Stream's HLSPlaylist\n internal playlist* HLSPlaylist { get; private set; }\n\n // Media Packets\n public PacketQueue Packets { get; private set; }\n public PacketQueue AudioPackets { get; private set; }\n public PacketQueue VideoPackets { get; private set; }\n public PacketQueue[] SubtitlesPackets\n { get; private set; }\n public PacketQueue DataPackets { get; private set; }\n public PacketQueue CurPackets { get; private set; }\n\n public bool UseAVSPackets { get; private set; }\n\n public PacketQueue GetPacketsPtr(StreamBase stream)\n {\n if (!UseAVSPackets)\n {\n return Packets;\n }\n\n switch (stream.Type)\n {\n case MediaType.Audio:\n return AudioPackets;\n case MediaType.Video:\n return VideoPackets;\n case MediaType.Subs:\n return SubtitlesPackets[SubtitlesSelectedHelper.CurIndex];\n default:\n return DataPackets;\n }\n }\n\n public ConcurrentQueue>>\n VideoPacketsReverse\n { get; private set; } = new ConcurrentQueue>>();\n\n public bool IsReversePlayback\n { get; private set; }\n\n public long TotalBytes { get; private set; } = 0;\n\n // Interrupt\n public Interrupter Interrupter { get; private set; }\n\n public ObservableCollection\n Chapters { get; private set; } = new ObservableCollection();\n public class Chapter\n {\n public long StartTime { get; set; }\n public long EndTime { get; set; }\n public string Title { get; set; }\n }\n\n public event EventHandler AudioLimit;\n bool audioBufferLimitFired;\n void OnAudioLimit()\n => Task.Run(() => AudioLimit?.Invoke(this, new EventArgs()));\n\n public event EventHandler TimedOut;\n internal void OnTimedOut()\n => Task.Run(() => TimedOut?.Invoke(this, new EventArgs()));\n #endregion\n\n #region Constructor / Declaration\n public AVPacket* packet;\n public AVFormatContext* fmtCtx;\n internal HLSContext* hlsCtx;\n\n long hlsPrevSeqNo = AV_NOPTS_VALUE; // Identifies the change of the m3u8 playlist (wraped)\n internal long hlsStartTime = AV_NOPTS_VALUE; // Calculation of first timestamp (lastPacketTs - hlsCurDuration)\n long hlsCurDuration; // Duration until the start of the current segment\n long lastSeekTime; // To set CurTime while no packets are available\n\n public object lockFmtCtx = new();\n internal bool allowReadInterrupts;\n\n /* Reverse Playback\n *\n * Video Packets Queue (FIFO) ConcurrentQueue>>\n * Video Packets Seek Stacks (FILO) ConcurrentStack>\n * Video Packets List Keyframe (List) List\n */\n\n long curReverseStopPts = AV_NOPTS_VALUE;\n long curReverseStopRequestedPts\n = AV_NOPTS_VALUE;\n long curReverseStartPts = AV_NOPTS_VALUE;\n List curReverseVideoPackets = new();\n ConcurrentStack>\n curReverseVideoStack = new();\n long curReverseSeekOffset;\n\n // Required for passing AV Options and HTTP Query params to the underlying contexts\n AVFormatContext_io_open ioopen;\n AVFormatContext_io_open ioopenDefault;\n AVDictionary* avoptCopy;\n Dictionary\n queryParams;\n byte[] queryCachedBytes;\n\n // for TEXT subtitles buffer\n byte* inputData;\n int inputDataSize;\n internal AVIOContext* avioCtx;\n\n int subNum => Config.config.Subtitles.Max;\n\n public Demuxer(DemuxerConfig config, MediaType type = MediaType.Video, int uniqueId = -1, bool useAVSPackets = true) : base(uniqueId)\n {\n Config = config;\n Type = type;\n UseAVSPackets = useAVSPackets;\n Interrupter = new Interrupter(this);\n CustomIOContext = new CustomIOContext(this);\n\n Packets = new PacketQueue(this);\n AudioPackets = new PacketQueue(this);\n VideoPackets = new PacketQueue(this);\n SubtitlesPackets = new PacketQueue[subNum];\n for (int i = 0; i < subNum; i++)\n {\n SubtitlesPackets[i] = new PacketQueue(this);\n }\n SubtitlesStreams = new SubtitlesStream[subNum];\n\n DataPackets = new PacketQueue(this);\n CurPackets = Packets; // Will be updated on stream switch in case of AVS\n\n string typeStr = Type == MediaType.Video ? \"Main\" : Type.ToString();\n threadName = $\"Demuxer: {typeStr,5}\";\n\n Utils.UIInvokeIfRequired(() =>\n {\n BindingOperations.EnableCollectionSynchronization(Programs, lockStreams);\n BindingOperations.EnableCollectionSynchronization(AudioStreams, lockStreams);\n BindingOperations.EnableCollectionSynchronization(VideoStreams, lockStreams);\n BindingOperations.EnableCollectionSynchronization(SubtitlesStreamsAll, lockStreams);\n BindingOperations.EnableCollectionSynchronization(DataStreams, lockStreams);\n\n BindingOperations.EnableCollectionSynchronization(Chapters, lockStreams);\n });\n\n ioopen = IOOpen;\n }\n #endregion\n\n #region Dispose / Dispose Packets\n public void DisposePackets()\n {\n if (UseAVSPackets)\n {\n AudioPackets.Clear();\n VideoPackets.Clear();\n for (int i = 0; i < subNum; i++)\n {\n SubtitlesPackets[i].Clear();\n }\n DataPackets.Clear();\n\n DisposePacketsReverse();\n }\n else\n Packets.Clear();\n\n hlsStartTime = AV_NOPTS_VALUE;\n }\n\n public void DisposePacketsReverse()\n {\n while (!VideoPacketsReverse.IsEmpty)\n {\n VideoPacketsReverse.TryDequeue(out var t1);\n while (!t1.IsEmpty)\n {\n t1.TryPop(out var t2);\n for (int i = 0; i < t2.Count; i++)\n {\n if (t2[i] == IntPtr.Zero) continue;\n AVPacket* packet = (AVPacket*)t2[i];\n av_packet_free(&packet);\n }\n }\n }\n\n while (!curReverseVideoStack.IsEmpty)\n {\n curReverseVideoStack.TryPop(out var t2);\n for (int i = 0; i < t2.Count; i++)\n {\n if (t2[i] == IntPtr.Zero) continue;\n AVPacket* packet = (AVPacket*)t2[i];\n av_packet_free(&packet);\n }\n }\n }\n public void Dispose()\n {\n if (Disposed)\n return;\n\n lock (lockActions)\n {\n if (Disposed)\n return;\n\n Stop();\n\n Url = null;\n hlsCtx = null;\n\n IsReversePlayback = false;\n curReverseStopPts = AV_NOPTS_VALUE;\n curReverseStartPts = AV_NOPTS_VALUE;\n hlsPrevSeqNo = AV_NOPTS_VALUE;\n lastSeekTime = 0;\n\n // Free Streams\n lock (lockStreams)\n {\n AudioStreams.Clear();\n VideoStreams.Clear();\n SubtitlesStreamsAll.Clear();\n DataStreams.Clear();\n Programs.Clear();\n\n Chapters.Clear();\n }\n EnabledStreams.Clear();\n AudioStream = null;\n VideoStream = null;\n for (int i = 0; i < subNum; i++)\n {\n SubtitlesStreams[i] = null;\n }\n DataStream = null;\n queryParams = null;\n queryCachedBytes = null;\n\n DisposePackets();\n\n if (fmtCtx != null)\n {\n Interrupter.CloseRequest();\n fixed (AVFormatContext** ptr = &fmtCtx) { avformat_close_input(ptr); fmtCtx = null; }\n }\n\n if (avoptCopy != null) fixed (AVDictionary** ptr = &avoptCopy) av_dict_free(ptr);\n if (packet != null) fixed (AVPacket** ptr = &packet) av_packet_free(ptr);\n\n CustomIOContext.Dispose();\n\n if (avioCtx != null)\n {\n av_free(avioCtx->buffer);\n fixed (AVIOContext** ptr = &avioCtx)\n {\n avio_context_free(ptr);\n }\n\n inputData = null;\n inputDataSize = 0;\n }\n\n TotalBytes = 0;\n Status = Status.Stopped;\n Disposed = true;\n\n Log.Info(\"Disposed\");\n }\n }\n #endregion\n\n #region Open / Seek / Run\n public string Open(string url) => Open(url, null);\n public string Open(Stream stream) => Open(null, stream);\n public string Open(string url, Stream stream)\n {\n bool gotLockActions = false;\n bool gotLockFmtCtx = false;\n string error = null;\n\n try\n {\n Monitor.Enter(lockActions,ref gotLockActions);\n Dispose();\n Monitor.Enter(lockFmtCtx, ref gotLockFmtCtx);\n Url = url;\n\n if (string.IsNullOrEmpty(url) && stream == null)\n return \"Invalid empty/null input\";\n\n Dictionary\n fmtOptExtra = null;\n AVInputFormat* inFmt = null;\n int ret = -1;\n\n Disposed = false;\n Status = Status.Opening;\n\n // Allocate / Prepare Format Context\n fmtCtx = avformat_alloc_context();\n if (Config.AllowInterrupts)\n fmtCtx->interrupt_callback.callback = Interrupter.interruptClbk;\n\n fmtCtx->flags |= (FmtFlags2)Config.FormatFlags;\n\n // Force Format (url as input and Config.FormatOpt for options)\n if (Config.ForceFormat != null)\n {\n inFmt = av_find_input_format(Config.ForceFormat);\n if (inFmt == null)\n return error = $\"[av_find_input_format] {Config.ForceFormat} not found\";\n }\n\n // Force Custom IO Stream Context (url should be null)\n if (stream != null)\n {\n CustomIOContext.Initialize(stream);\n stream.Seek(0, SeekOrigin.Begin);\n url = null;\n }\n\n /* Force Format with Url syntax to support format, url and options within the input url\n *\n * fmt://$format$[/]?$input$&$options$\n *\n * deprecate support for device://\n *\n * Examples:\n * See: https://ffmpeg.org/ffmpeg-devices.html for devices formats and options\n *\n * 1. fmt://gdigrab?title=Command Prompt&framerate=2\n * 2. fmt://gdigrab?desktop\n * 3. fmt://dshow?audio=Microphone (Relatek):video=Lenovo Camera\n * 4. fmt://rawvideo?C:\\root\\dev\\Flyleaf\\VideoSamples\\rawfile.raw&pixel_format=uyvy422&video_size=1920x1080&framerate=60\n *\n */\n else if (url.StartsWith(\"fmt://\") || url.StartsWith(\"device://\"))\n {\n string urlFromUrl = null;\n string fmtStr = \"\";\n int fmtStarts = url.IndexOf('/') + 2;\n int queryStarts = url.IndexOf('?');\n\n if (queryStarts == -1)\n fmtStr = url[fmtStarts..];\n else\n {\n fmtStr = url[fmtStarts..queryStarts];\n\n string query = url[(queryStarts + 1)..];\n int inputEnds = query.IndexOf('&');\n\n if (inputEnds == -1)\n urlFromUrl = query;\n else\n {\n urlFromUrl = query[..inputEnds];\n query = query[(inputEnds + 1)..];\n\n fmtOptExtra = Utils.ParseQueryString(query);\n }\n }\n\n url = urlFromUrl;\n fmtStr = fmtStr.Replace(\"/\", \"\");\n inFmt = av_find_input_format(fmtStr);\n if (inFmt == null)\n return error = $\"[av_find_input_format] {fmtStr} not found\";\n }\n else if (url.StartsWith(\"srt://\"))\n {\n ReadOnlySpan urlSpan = url.AsSpan();\n int queryPos = urlSpan.IndexOf('?');\n\n if (queryPos != -1)\n {\n fmtOptExtra = Utils.ParseQueryString(urlSpan.Slice(queryPos + 1));\n url = urlSpan[..queryPos].ToString();\n }\n }\n\n if (Config.FormatOptToUnderlying && url != null && (url.StartsWith(\"http://\") || url.StartsWith(\"https://\")))\n {\n queryParams = [];\n if (Config.DefaultHTTPQueryToUnderlying)\n {\n int queryStarts = url.IndexOf('?');\n if (queryStarts != -1)\n {\n var qp = Utils.ParseQueryString(url.AsSpan()[(queryStarts + 1)..]);\n foreach (var kv in qp)\n queryParams[kv.Key] = kv.Value;\n }\n }\n\n foreach (var kv in Config.ExtraHTTPQueryParamsToUnderlying)\n queryParams[kv.Key] = kv.Value;\n\n if (queryParams.Count > 0)\n {\n var queryCachedStr = \"?\";\n foreach (var kv in queryParams)\n queryCachedStr += kv.Value == null ? $\"{kv.Key}&\" : $\"{kv.Key}={kv.Value}&\";\n\n queryCachedStr = queryCachedStr[..^1];\n queryCachedBytes = Encoding.UTF8.GetBytes(queryCachedStr);\n }\n else\n queryParams = null;\n }\n\n if (Type == MediaType.Subs &&\n Utils.ExtensionsSubtitlesText.Contains(Utils.GetUrlExtention(url)) &&\n File.Exists(url))\n {\n // If the files can be read with text subtitles, load them all into memory and convert them to UTF8.\n // Because ffmpeg expects UTF8 text.\n try\n {\n FileInfo file = new(url);\n if (file.Length >= 10 * 1024 * 1024)\n {\n throw new InvalidOperationException($\"TEXT subtitle is too big (>=10MB) to load: {file.Length}\");\n }\n\n // Detects character encoding, reads text and converts to UTF8\n Encoding encoding = Encoding.UTF8;\n\n Encoding detected = TextEncodings.DetectEncoding(url);\n if (detected != null)\n {\n encoding = detected;\n }\n\n string content = File.ReadAllText(url, encoding);\n byte[] contentBytes = Encoding.UTF8.GetBytes(content);\n\n inputDataSize = contentBytes.Length;\n inputData = (byte*)av_malloc((nuint)inputDataSize);\n\n Span src = new(contentBytes);\n Span dst = new(inputData, inputDataSize);\n src.CopyTo(dst);\n\n avioCtx = avio_alloc_context(inputData, inputDataSize, 0, null, null, null, null);\n if (avioCtx == null)\n {\n throw new InvalidOperationException(\"avio_alloc_context\");\n }\n\n // Pass to ffmpeg by on-memory\n fmtCtx->pb = avioCtx;\n fmtCtx->flags |= FmtFlags2.CustomIo;\n }\n catch (Exception ex)\n {\n Log.Warn($\"Could not load text subtitles to memory: {ex.Message}\");\n }\n }\n\n // Some devices required to be opened from a UI or STA thread | after 20-40 sec. of demuxing -> [gdigrab @ 0000019affe3f2c0] Failed to capture image (error 6) or (error 8)\n bool isDevice = inFmt != null && inFmt->priv_class != null && (\n inFmt->priv_class->category.HasFlag(AVClassCategory.DeviceAudioInput) ||\n inFmt->priv_class->category.HasFlag(AVClassCategory.DeviceAudioOutput) ||\n inFmt->priv_class->category.HasFlag(AVClassCategory.DeviceInput) ||\n inFmt->priv_class->category.HasFlag(AVClassCategory.DeviceOutput) ||\n inFmt->priv_class->category.HasFlag(AVClassCategory.DeviceVideoInput) ||\n inFmt->priv_class->category.HasFlag(AVClassCategory.DeviceVideoOutput)\n );\n\n // Open Format Context\n allowReadInterrupts = true; // allow Open interrupts always\n Interrupter.OpenRequest();\n\n // Nesting the io_open (to pass the options to the underlying formats)\n if (Config.FormatOptToUnderlying)\n {\n ioopenDefault = (AVFormatContext_io_open)Marshal.GetDelegateForFunctionPointer(fmtCtx->io_open.Pointer, typeof(AVFormatContext_io_open));\n fmtCtx->io_open = ioopen;\n }\n\n if (isDevice)\n {\n string fmtName = Utils.BytePtrToStringUTF8(inFmt->name);\n\n if (fmtName == \"decklink\") // avoid using UI thread for decklink (STA should be enough for CoInitialize/CoCreateInstance)\n Utils.STAInvoke(() => OpenFormat(url, inFmt, fmtOptExtra, out ret));\n else\n Utils.UIInvoke(() => OpenFormat(url, inFmt, fmtOptExtra, out ret));\n }\n else\n OpenFormat(url, inFmt, fmtOptExtra, out ret);\n\n if ((ret == AVERROR_EXIT && !Interrupter.Timedout) || Status != Status.Opening || Interrupter.ForceInterrupt == 1) { if (ret < 0) fmtCtx = null; return error = \"Cancelled\"; }\n if (ret < 0) { fmtCtx = null; return error = Interrupter.Timedout ? \"[avformat_open_input] Timeout\" : $\"[avformat_open_input] {FFmpegEngine.ErrorCodeToMsg(ret)} ({ret})\"; }\n\n // Find Streams Info\n if (Config.AllowFindStreamInfo)\n {\n /* For some reason HdmvPgsSubtitle requires more analysis (even when it has already all the information)\n *\n * Increases delay & memory and it will not free it after analysis (fmtctx internal buffer)\n * - avformat_flush will release it but messes with the initial seek position (possible seek to start to force it releasing it but still we have the delay)\n *\n * Consider\n * - DVD/Blu-ray/mpegts only? (possible HLS -> mpegts?*)\n * - Re-open in case of \"Consider increasing the value for the 'analyzeduration'\" (catch from ffmpeg log)\n *\n * https://github.com/SuRGeoNix/Flyleaf/issues/502\n */\n\n if (Utils.BytePtrToStringUTF8(fmtCtx->iformat->name) == \"mpegts\")\n {\n bool requiresMoreAnalyse = false;\n\n for (int i = 0; i < fmtCtx->nb_streams; i++)\n if (fmtCtx->streams[i]->codecpar->codec_id == AVCodecID.HdmvPgsSubtitle ||\n fmtCtx->streams[i]->codecpar->codec_id == AVCodecID.DvdSubtitle\n )\n { requiresMoreAnalyse = true; break; }\n\n if (requiresMoreAnalyse)\n {\n fmtCtx->probesize = Math.Max(fmtCtx->probesize, 5000 * (long)1024 * 1024); // Bytes\n fmtCtx->max_analyze_duration = Math.Max(fmtCtx->max_analyze_duration, 1000 * (long)1000 * 1000); // Mcs\n }\n }\n\n ret = avformat_find_stream_info(fmtCtx, null);\n if (ret == AVERROR_EXIT || Status != Status.Opening || Interrupter.ForceInterrupt == 1) return error = \"Cancelled\";\n if (ret < 0) return error = $\"[avformat_find_stream_info] {FFmpegEngine.ErrorCodeToMsg(ret)} ({ret})\";\n }\n\n // Prevent Multiple Immediate exit requested on eof (maybe should not use avio_feof() to test for the end)\n if (fmtCtx->pb != null)\n fmtCtx->pb->eof_reached = 0;\n\n bool hasVideo = FillInfo();\n\n if (Type == MediaType.Video && !hasVideo && AudioStreams.Count == 0)\n return error = $\"No audio / video stream found\";\n else if (Type == MediaType.Audio && AudioStreams.Count == 0)\n return error = $\"No audio stream found\";\n else if (Type == MediaType.Subs && SubtitlesStreamsAll.Count == 0)\n return error = $\"No subtitles stream found\";\n\n packet = av_packet_alloc();\n Status = Status.Stopped;\n allowReadInterrupts = Config.AllowReadInterrupts && !Config.ExcludeInterruptFmts.Contains(Name);\n\n return error = null;\n }\n catch (Exception ex)\n {\n return error = $\"Unknown: {ex.Message}\";\n }\n finally\n {\n if (error != null)\n Dispose();\n\n if (gotLockFmtCtx) Monitor.Exit(lockFmtCtx);\n if (gotLockActions) Monitor.Exit(lockActions);\n }\n }\n\n int IOOpen(AVFormatContext* s, AVIOContext** pb, byte* urlb, IOFlags flags, AVDictionary** avFmtOpts)\n {\n int ret;\n AVDictionaryEntry *t = null;\n\n if (avoptCopy != null)\n {\n while ((t = av_dict_get(avoptCopy, \"\", t, DictReadFlags.IgnoreSuffix)) != null)\n _ = av_dict_set(avFmtOpts, Utils.BytePtrToStringUTF8(t->key), Utils.BytePtrToStringUTF8(t->value), 0);\n }\n\n if (queryParams == null)\n ret = ioopenDefault(s, pb, urlb, flags, avFmtOpts);\n else\n {\n int urlLength = 0;\n int queryPos = -1;\n while (urlb[urlLength] != '\\0')\n {\n if (urlb[urlLength] == '?' && queryPos == -1 && urlb[urlLength + 1] != '\\0')\n queryPos = urlLength;\n\n urlLength++;\n }\n\n // urlNoQuery + ? + queryCachedBytes\n if (queryPos == -1)\n {\n ReadOnlySpan urlNoQuery = new(urlb, urlLength);\n int newLength = urlLength + queryCachedBytes.Length + 1;\n Span urlSpan = newLength < 1024 ? stackalloc byte[newLength] : new byte[newLength];// new(urlPtr, newLength);\n urlNoQuery.CopyTo(urlSpan);\n queryCachedBytes.AsSpan().CopyTo(urlSpan[urlNoQuery.Length..]);\n\n fixed(byte* urlPtr = urlSpan)\n ret = ioopenDefault(s, pb, urlPtr, flags, avFmtOpts);\n }\n\n // urlNoQuery + ? + existingParams/queryParams combined\n else\n {\n ReadOnlySpan urlNoQuery = new(urlb, queryPos);\n ReadOnlySpan urlQuery = new(urlb + queryPos + 1, urlLength - queryPos - 1);\n var qps = Utils.ParseQueryString(Encoding.UTF8.GetString(urlQuery));\n\n foreach (var kv in queryParams)\n if (!qps.ContainsKey(kv.Key))\n qps[kv.Key] = kv.Value;\n\n string newQuery = \"?\";\n foreach (var kv in qps)\n newQuery += kv.Value == null ? $\"{kv.Key}&\" : $\"{kv.Key}={kv.Value}&\";\n\n int newLength = urlNoQuery.Length + newQuery.Length + 1;\n Span urlSpan = newLength < 1024 ? stackalloc byte[newLength] : new byte[newLength];// new(urlPtr, newLength);\n urlNoQuery.CopyTo(urlSpan);\n Encoding.UTF8.GetBytes(newQuery).AsSpan().CopyTo(urlSpan[urlNoQuery.Length..]);\n\n fixed(byte* urlPtr = urlSpan)\n ret = ioopenDefault(s, pb, urlPtr, flags, avFmtOpts);\n }\n }\n\n return ret;\n }\n\n private void OpenFormat(string url, AVInputFormat* inFmt, Dictionary opt, out int ret)\n {\n AVDictionary* avopt = null;\n var curOpt = Type == MediaType.Video ? Config.FormatOpt : (Type == MediaType.Audio ? Config.AudioFormatOpt : Config.SubtitlesFormatOpt);\n\n if (curOpt != null)\n foreach (var optKV in curOpt)\n av_dict_set(&avopt, optKV.Key, optKV.Value, 0);\n\n if (opt != null)\n foreach (var optKV in opt)\n av_dict_set(&avopt, optKV.Key, optKV.Value, 0);\n\n if (Config.FormatOptToUnderlying)\n fixed(AVDictionary** ptr = &avoptCopy)\n av_dict_copy(ptr, avopt, 0);\n\n fixed(AVFormatContext** fmtCtxPtr = &fmtCtx)\n ret = avformat_open_input(fmtCtxPtr, url, inFmt, avopt == null ? null : &avopt);\n\n if (avopt != null)\n {\n if (ret >= 0)\n {\n AVDictionaryEntry *t = null;\n\n while ((t = av_dict_get(avopt, \"\", t, DictReadFlags.IgnoreSuffix)) != null)\n Log.Debug($\"Ignoring format option {Utils.BytePtrToStringUTF8(t->key)}\");\n }\n\n av_dict_free(&avopt);\n }\n }\n private bool FillInfo()\n {\n Name = Utils.BytePtrToStringUTF8(fmtCtx->iformat->name);\n LongName = Utils.BytePtrToStringUTF8(fmtCtx->iformat->long_name);\n Extensions = Utils.BytePtrToStringUTF8(fmtCtx->iformat->extensions);\n\n StartTime = fmtCtx->start_time != AV_NOPTS_VALUE ? fmtCtx->start_time * 10 : 0;\n StartRealTime = fmtCtx->start_time_realtime != AV_NOPTS_VALUE ? fmtCtx->start_time_realtime * 10 : 0;\n Duration = fmtCtx->duration > 0 ? fmtCtx->duration * 10 : 0;\n\n // TBR: Possible we can get Apple HTTP Live Streaming/hls with HLSPlaylist->finished with Duration != 0\n if (Engine.Config.FFmpegHLSLiveSeek && Duration == 0 && Name == \"hls\" && Environment.Is64BitProcess) // HLSContext cast is not safe\n {\n hlsCtx = (HLSContext*) fmtCtx->priv_data;\n StartTime = 0;\n //UpdateHLSTime(); Maybe with default 0 playlist\n }\n\n if (fmtCtx->nb_streams == 1 && fmtCtx->streams[0]->codecpar->codec_type == AVMediaType.Subtitle) // External Streams (mainly for .sub will have as start time the first subs timestamp)\n StartTime = 0;\n\n IsLive = Duration == 0 || hlsCtx != null;\n\n bool hasVideo = false;\n AVStreamToStream = new Dictionary();\n\n Metadata.Clear();\n AVDictionaryEntry* b = null;\n while (true)\n {\n b = av_dict_get(fmtCtx->metadata, \"\", b, DictReadFlags.IgnoreSuffix);\n if (b == null) break;\n Metadata.Add(Utils.BytePtrToStringUTF8(b->key), Utils.BytePtrToStringUTF8(b->value));\n }\n\n Chapters.Clear();\n string dump = \"\";\n for (int i=0; inb_chapters; i++)\n {\n var chp = fmtCtx->chapters[i];\n double tb = av_q2d(chp->time_base) * 10000.0 * 1000.0;\n string title = \"\";\n\n b = null;\n while (true)\n {\n b = av_dict_get(chp->metadata, \"\", b, DictReadFlags.IgnoreSuffix);\n if (b == null) break;\n if (Utils.BytePtrToStringUTF8(b->key).ToLower() == \"title\")\n title = Utils.BytePtrToStringUTF8(b->value);\n }\n\n if (CanDebug)\n dump += $\"[Chapter {i+1,-2}] {Utils.TicksToTime((long)(chp->start * tb) - StartTime)} - {Utils.TicksToTime((long)(chp->end * tb) - StartTime)} | {title}\\r\\n\";\n\n Chapters.Add(new Chapter()\n {\n StartTime = (long)((chp->start * tb) - StartTime),\n EndTime = (long)((chp->end * tb) - StartTime),\n Title = title\n });\n }\n\n if (CanDebug && dump != \"\") Log.Debug($\"Chapters\\r\\n\\r\\n{dump}\");\n\n bool audioHasEng = false;\n bool subsHasEng = false;\n\n lock (lockStreams)\n {\n for (int i=0; inb_streams; i++)\n {\n fmtCtx->streams[i]->discard = AVDiscard.All;\n\n switch (fmtCtx->streams[i]->codecpar->codec_type)\n {\n case AVMediaType.Audio:\n AudioStreams.Add(new AudioStream(this, fmtCtx->streams[i]));\n AVStreamToStream.Add(fmtCtx->streams[i]->index, AudioStreams[^1]);\n audioHasEng = AudioStreams[^1].Language == Language.English;\n\n break;\n\n case AVMediaType.Video:\n if ((fmtCtx->streams[i]->disposition & DispositionFlags.AttachedPic) != 0)\n { Log.Info($\"Excluding image stream #{i}\"); continue; }\n\n // TBR: When AllowFindStreamInfo = false we can get valid pixel format during decoding (in case of remuxing only this might crash, possible check if usedecoders?)\n if (((AVPixelFormat)fmtCtx->streams[i]->codecpar->format) == AVPixelFormat.None && Config.AllowFindStreamInfo)\n {\n Log.Info($\"Excluding invalid video stream #{i}\");\n continue;\n }\n VideoStreams.Add(new VideoStream(this, fmtCtx->streams[i]));\n AVStreamToStream.Add(fmtCtx->streams[i]->index, VideoStreams[^1]);\n hasVideo |= !Config.AllowFindStreamInfo || VideoStreams[^1].PixelFormat != AVPixelFormat.None;\n\n break;\n\n case AVMediaType.Subtitle:\n SubtitlesStreamsAll.Add(new SubtitlesStream(this, fmtCtx->streams[i]));\n AVStreamToStream.Add(fmtCtx->streams[i]->index, SubtitlesStreamsAll[^1]);\n subsHasEng = SubtitlesStreamsAll[^1].Language == Language.English;\n break;\n\n case AVMediaType.Data:\n DataStreams.Add(new DataStream(this, fmtCtx->streams[i]));\n AVStreamToStream.Add(fmtCtx->streams[i]->index, DataStreams[^1]);\n\n break;\n\n default:\n Log.Info($\"#[Unknown #{i}] {fmtCtx->streams[i]->codecpar->codec_type}\");\n break;\n }\n }\n\n if (!audioHasEng)\n for (int i=0; inb_programs > 0)\n {\n for (int i = 0; i < fmtCtx->nb_programs; i++)\n {\n fmtCtx->programs[i]->discard = AVDiscard.All;\n Program program = new(fmtCtx->programs[i], this);\n Programs.Add(program);\n }\n }\n\n Extension = GetValidExtension();\n }\n\n PrintDump();\n return hasVideo;\n }\n\n public int SeekInQueue(long ticks, bool forward = false)\n {\n lock (lockActions)\n {\n if (Disposed) return -1;\n\n /* Seek within current bufffered queue\n *\n * 10 seconds because of video keyframe distances or 1 seconds for other (can be fixed also with CurTime+X seek instead of timestamps)\n * For subtitles it should keep (prev packet) the last presented as it can have a lot of distance with CurTime (cur packet)\n * It doesn't work for HLS live streams\n * It doesn't work for decoders buffered queue (which is small only subs might be an issue if we have large decoder queue)\n */\n\n long startTime = StartTime;\n\n if (hlsCtx != null)\n {\n ticks += hlsStartTime - (hlsCtx->first_timestamp * 10);\n startTime = hlsStartTime;\n }\n\n if (ticks + (VideoStream != null && forward ? (10000 * 10000) : 1000 * 10000) > CurTime + startTime && ticks < CurTime + startTime + BufferedDuration)\n {\n bool found = false;\n while (VideoPackets.Count > 0)\n {\n var packet = VideoPackets.Peek();\n if (packet->pts != AV_NOPTS_VALUE && ticks < packet->pts * VideoStream.Timebase && (packet->flags & PktFlags.Key) != 0)\n {\n found = true;\n ticks = (long) (packet->pts * VideoStream.Timebase);\n\n break;\n }\n\n VideoPackets.Dequeue();\n av_packet_free(&packet);\n }\n\n while (AudioPackets.Count > 0)\n {\n var packet = AudioPackets.Peek();\n if (packet->pts != AV_NOPTS_VALUE && (packet->pts + packet->duration) * AudioStream.Timebase >= ticks)\n {\n if (Type == MediaType.Audio || VideoStream == null)\n found = true;\n\n break;\n }\n\n AudioPackets.Dequeue();\n av_packet_free(&packet);\n }\n\n for (int i = 0; i < subNum; i++)\n {\n while (SubtitlesPackets[i].Count > 0)\n {\n var packet = SubtitlesPackets[i].Peek();\n if (packet->pts != AV_NOPTS_VALUE && ticks < (packet->pts + packet->duration) * SubtitlesStreams[i].Timebase)\n {\n if (Type == MediaType.Subs)\n {\n found = true;\n }\n\n break;\n }\n\n SubtitlesPackets[i].Dequeue();\n av_packet_free(&packet);\n }\n }\n\n while (DataPackets.Count > 0)\n {\n var packet = DataPackets.Peek();\n if (packet->pts != AV_NOPTS_VALUE && ticks < (packet->pts + packet->duration) * DataStream.Timebase)\n {\n if (Type == MediaType.Data)\n found = true;\n\n break;\n }\n\n DataPackets.Dequeue();\n av_packet_free(&packet);\n }\n\n if (found)\n {\n Log.Debug(\"[Seek] Found in Queue\");\n return 0;\n }\n }\n\n return -1;\n }\n }\n public int Seek(long ticks, bool forward = false)\n {\n /* Current Issues\n *\n * HEVC/MPEG-TS: Fails to seek to keyframe https://blog.csdn.net/Annie_heyeqq/article/details/113649501 | https://trac.ffmpeg.org/ticket/9412\n * AVSEEK_FLAG_BACKWARD will not work on .dav even if it returns 0 (it will work after it fills the index table)\n * Strange delay (could be 200ms!) after seek on HEVC/yuv420p10le (10-bits) while trying to Present on swapchain (possible recreates texturearray?)\n * AVFMT_NOTIMESTAMPS unknown duration (can be calculated?) should perform byte seek instead (percentage based on total pb size)\n */\n\n lock (lockActions)\n {\n if (Disposed) return -1;\n\n int ret;\n long savedPbPos = 0;\n\n Interrupter.ForceInterrupt = 1;\n lock (lockFmtCtx)\n {\n Interrupter.ForceInterrupt = 0;\n\n // Flush required because of the interrupt\n if (fmtCtx->pb != null)\n {\n savedPbPos = fmtCtx->pb->pos;\n avio_flush(fmtCtx->pb);\n fmtCtx->pb->error = 0; // AVERROR_EXIT will stay forever and will cause the demuxer to go in Status Stopped instead of Ended (after interrupted seeks)\n fmtCtx->pb->eof_reached = 0;\n }\n avformat_flush(fmtCtx);\n\n // Forces seekable HLS\n if (hlsCtx != null)\n fmtCtx->ctx_flags &= ~FmtCtxFlags.Unseekable;\n\n Interrupter.SeekRequest();\n if (VideoStream != null)\n {\n if (CanDebug) Log.Debug($\"[Seek({(forward ? \"->\" : \"<-\")})] Requested at {new TimeSpan(ticks)}\");\n\n // TODO: After proper calculation of Duration\n //if (VideoStream.FixTimestamps && Duration > 0)\n //ret = av_seek_frame(fmtCtx, -1, (long)((ticks/(double)Duration) * avio_size(fmtCtx->pb)), AVSEEK_FLAG_BYTE);\n //else\n ret = ticks == StartTime // we should also call this if we seek anywhere within the first Gop\n ? avformat_seek_file(fmtCtx, -1, 0, 0, 0, 0)\n : av_seek_frame(fmtCtx, -1, ticks / 10, forward ? SeekFlags.Frame : SeekFlags.Backward);\n\n curReverseStopPts = AV_NOPTS_VALUE;\n curReverseStartPts= AV_NOPTS_VALUE;\n }\n else\n {\n if (CanDebug) Log.Debug($\"[Seek({(forward ? \"->\" : \"<-\")})] Requested at {new TimeSpan(ticks)} | ANY\");\n ret = forward ?\n avformat_seek_file(fmtCtx, -1, ticks / 10 , ticks / 10, long.MaxValue , SeekFlags.Any):\n avformat_seek_file(fmtCtx, -1, long.MinValue, ticks / 10, ticks / 10 , SeekFlags.Any);\n }\n\n if (ret < 0)\n {\n if (hlsCtx != null) fmtCtx->ctx_flags &= ~FmtCtxFlags.Unseekable;\n Log.Info($\"Seek failed 1/2 (retrying) {FFmpegEngine.ErrorCodeToMsg(ret)} ({ret})\");\n\n ret = VideoStream != null\n ? av_seek_frame(fmtCtx, -1, ticks / 10, forward ? SeekFlags.Backward : SeekFlags.Frame)\n : forward ?\n avformat_seek_file(fmtCtx, -1, long.MinValue, ticks / 10, ticks / 10 , SeekFlags.Any):\n avformat_seek_file(fmtCtx, -1, ticks / 10 , ticks / 10, long.MaxValue , SeekFlags.Any);\n\n if (ret < 0)\n {\n Log.Warn($\"Seek failed 2/2 {FFmpegEngine.ErrorCodeToMsg(ret)} ({ret})\");\n\n // Flush required because of seek failure (reset pb to last pos otherwise will be eof) - Mainly for NoTimestamps (TODO: byte seek/calc dur/percentage)\n if (fmtCtx->pb != null)\n {\n avio_flush(fmtCtx->pb);\n fmtCtx->pb->error = 0;\n fmtCtx->pb->eof_reached = 0;\n avio_seek(fmtCtx->pb, savedPbPos, 0);\n }\n avformat_flush(fmtCtx);\n }\n else\n lastSeekTime = ticks - StartTime - (hlsCtx != null ? hlsStartTime : 0);\n }\n else\n lastSeekTime = ticks - StartTime - (hlsCtx != null ? hlsStartTime : 0);\n\n DisposePackets();\n lock (lockStatus) if (Status == Status.Ended) Status = Status.Stopped;\n }\n\n return ret; // >= 0 for success\n }\n }\n\n protected override void RunInternal()\n {\n if (IsReversePlayback)\n {\n RunInternalReverse();\n return;\n }\n\n int ret = 0;\n int allowedErrors = Config.MaxErrors;\n bool gotAVERROR_EXIT = false;\n audioBufferLimitFired = false;\n long lastVideoPacketPts = 0;\n\n do\n {\n // Wait until not QueueFull\n if (BufferedDuration > Config.BufferDuration || (Config.BufferPackets != 0 && CurPackets.Count > Config.BufferPackets))\n {\n lock (lockStatus)\n if (Status == Status.Running) Status = Status.QueueFull;\n\n while (!PauseOnQueueFull && (BufferedDuration > Config.BufferDuration || (Config.BufferPackets != 0 && CurPackets.Count > Config.BufferPackets)) && Status == Status.QueueFull)\n Thread.Sleep(20);\n\n lock (lockStatus)\n {\n if (PauseOnQueueFull) { PauseOnQueueFull = false; Status = Status.Pausing; }\n if (Status != Status.QueueFull) break;\n Status = Status.Running;\n }\n }\n\n // Wait possible someone asks for lockFmtCtx\n else if (gotAVERROR_EXIT)\n {\n gotAVERROR_EXIT = false;\n Thread.Sleep(5);\n }\n\n // Demux Packet\n lock (lockFmtCtx)\n {\n Interrupter.ReadRequest();\n ret = av_read_frame(fmtCtx, packet);\n if (Interrupter.ForceInterrupt != 0)\n {\n av_packet_unref(packet);\n gotAVERROR_EXIT = true;\n continue;\n }\n\n // Possible check if interrupt/timeout and we dont seek to reset the backend pb->pos = 0?\n if (ret != 0)\n {\n av_packet_unref(packet);\n\n if (ret == AVERROR_EOF)\n {\n Status = Status.Ended;\n break;\n }\n\n if (Interrupter.Timedout)\n {\n Status = Status.Stopping;\n break;\n }\n\n allowedErrors--;\n if (CanWarn) Log.Warn($\"{FFmpegEngine.ErrorCodeToMsg(ret)} ({ret})\");\n\n if (allowedErrors == 0) { Log.Error(\"Too many errors!\"); Status = Status.Stopping; break; }\n\n gotAVERROR_EXIT = true;\n continue;\n }\n\n TotalBytes += packet->size;\n\n // Skip Disabled Streams | TODO: It's possible that the streams will changed (add/remove or even update/change of codecs)\n if (!EnabledStreams.Contains(packet->stream_index)) { av_packet_unref(packet); continue; }\n\n if (IsHLSLive)\n UpdateHLSTime();\n\n if (CanTrace)\n {\n var stream = AVStreamToStream[packet->stream_index];\n long dts = packet->dts == AV_NOPTS_VALUE ? -1 : (long)(packet->dts * stream.Timebase);\n long pts = packet->pts == AV_NOPTS_VALUE ? -1 : (long)(packet->pts * stream.Timebase);\n Log.Trace($\"[{stream.Type}] DTS: {(dts == -1 ? \"-\" : Utils.TicksToTime(dts))} PTS: {(pts == -1 ? \"-\" : Utils.TicksToTime(pts))} | FLPTS: {(pts == -1 ? \"-\" : Utils.TicksToTime(pts - StartTime))} | CurTime: {Utils.TicksToTime(CurTime)} | Buffered: {Utils.TicksToTime(BufferedDuration)}\");\n }\n\n // Enqueue Packet (AVS Queue or Single Queue)\n if (UseAVSPackets)\n {\n switch (fmtCtx->streams[packet->stream_index]->codecpar->codec_type)\n {\n case AVMediaType.Audio:\n //Log($\"Audio => {Utils.TicksToTime((long)(packet->pts * AudioStream.Timebase))} | {Utils.TicksToTime(CurTime)}\");\n\n // Handles A/V de-sync and ffmpeg bug with 2^33 timestamps wrapping\n if (Config.MaxAudioPackets != 0 && AudioPackets.Count > Config.MaxAudioPackets)\n {\n av_packet_unref(packet);\n packet = av_packet_alloc();\n\n if (!audioBufferLimitFired)\n {\n audioBufferLimitFired = true;\n OnAudioLimit();\n }\n\n break;\n }\n\n AudioPackets.Enqueue(packet);\n packet = av_packet_alloc();\n\n break;\n\n case AVMediaType.Video:\n //Log($\"Video => {Utils.TicksToTime((long)(packet->pts * VideoStream.Timebase))} | {Utils.TicksToTime(CurTime)}\");\n lastVideoPacketPts = packet->pts;\n VideoPackets.Enqueue(packet);\n packet = av_packet_alloc();\n\n break;\n\n case AVMediaType.Subtitle:\n for (int i = 0; i < subNum; i++)\n {\n // Clone packets to support simultaneous display of the same subtitle\n if (packet->stream_index == SubtitlesStreams[i]?.StreamIndex)\n {\n SubtitlesPackets[i].Enqueue(av_packet_clone(packet));\n }\n }\n\n // cloned, so free packet\n av_packet_unref(packet);\n\n break;\n\n case AVMediaType.Data:\n // Some data streams only have nopts, set pts to last video packet pts\n if (packet->pts == AV_NOPTS_VALUE)\n packet->pts = lastVideoPacketPts;\n DataPackets.Enqueue(packet);\n packet = av_packet_alloc();\n\n break;\n\n default:\n av_packet_unref(packet);\n break;\n }\n }\n else\n {\n Packets.Enqueue(packet);\n packet = av_packet_alloc();\n }\n }\n } while (Status == Status.Running);\n }\n private void RunInternalReverse()\n {\n int ret = 0;\n int allowedErrors = Config.MaxErrors;\n bool gotAVERROR_EXIT = false;\n\n // To demux further for buffering (related to BufferDuration)\n int maxQueueSize = 2;\n curReverseSeekOffset = av_rescale_q(3 * 1000 * 10000 / 10, Engine.FFmpeg.AV_TIMEBASE_Q, VideoStream.AVStream->time_base);\n\n do\n {\n // Wait until not QueueFull\n if (VideoPacketsReverse.Count > maxQueueSize)\n {\n lock (lockStatus)\n if (Status == Status.Running) Status = Status.QueueFull;\n\n while (!PauseOnQueueFull && VideoPacketsReverse.Count > maxQueueSize && Status == Status.QueueFull) { Thread.Sleep(20); }\n\n lock (lockStatus)\n {\n if (PauseOnQueueFull) { PauseOnQueueFull = false; Status = Status.Pausing; }\n if (Status != Status.QueueFull) break;\n Status = Status.Running;\n }\n }\n\n // Wait possible someone asks for lockFmtCtx\n else if (gotAVERROR_EXIT)\n {\n gotAVERROR_EXIT = false;\n Thread.Sleep(5);\n }\n\n // Demux Packet\n lock (lockFmtCtx)\n {\n Interrupter.ReadRequest();\n ret = av_read_frame(fmtCtx, packet);\n if (Interrupter.ForceInterrupt != 0)\n {\n av_packet_unref(packet); gotAVERROR_EXIT = true;\n continue;\n }\n\n // Possible check if interrupt/timeout and we dont seek to reset the backend pb->pos = 0?\n if (ret != 0)\n {\n av_packet_unref(packet);\n\n if (ret == AVERROR_EOF)\n {\n if (curReverseVideoPackets.Count > 0)\n {\n var drainPacket = av_packet_alloc();\n drainPacket->data = null;\n drainPacket->size = 0;\n curReverseVideoPackets.Add((IntPtr)drainPacket);\n curReverseVideoStack.Push(curReverseVideoPackets);\n curReverseVideoPackets = new List();\n }\n\n if (!curReverseVideoStack.IsEmpty)\n {\n VideoPacketsReverse.Enqueue(curReverseVideoStack);\n curReverseVideoStack = new ConcurrentStack>();\n }\n\n if (curReverseStartPts != AV_NOPTS_VALUE && curReverseStartPts <= VideoStream.StartTimePts)\n {\n Status = Status.Ended;\n break;\n }\n\n //Log($\"[][][SEEK END] {curReverseStartPts} | {Utils.TicksToTime((long) (curReverseStartPts * VideoStream.Timebase))}\");\n Interrupter.SeekRequest();\n ret = av_seek_frame(fmtCtx, VideoStream.StreamIndex, Math.Max(curReverseStartPts - curReverseSeekOffset, VideoStream.StartTimePts), SeekFlags.Backward);\n\n if (ret != 0)\n {\n Status = Status.Stopping;\n break;\n }\n\n curReverseStopPts = curReverseStartPts;\n curReverseStartPts = AV_NOPTS_VALUE;\n continue;\n }\n\n allowedErrors--;\n if (CanWarn) Log.Warn($\"{ FFmpegEngine.ErrorCodeToMsg(ret)} ({ret})\");\n\n if (allowedErrors == 0) { Log.Error(\"Too many errors!\"); Status = Status.Stopping; break; }\n\n gotAVERROR_EXIT = true;\n continue;\n }\n\n if (VideoStream.StreamIndex != packet->stream_index) { av_packet_unref(packet); continue; }\n\n if ((packet->flags & PktFlags.Key) != 0)\n {\n if (curReverseStartPts == AV_NOPTS_VALUE)\n curReverseStartPts = packet->pts;\n\n if (curReverseVideoPackets.Count > 0)\n {\n var drainPacket = av_packet_alloc();\n drainPacket->data = null;\n drainPacket->size = 0;\n curReverseVideoPackets.Add((IntPtr)drainPacket);\n curReverseVideoStack.Push(curReverseVideoPackets);\n curReverseVideoPackets = new List();\n }\n }\n\n if (packet->pts != AV_NOPTS_VALUE && (\n (curReverseStopRequestedPts != AV_NOPTS_VALUE && curReverseStopRequestedPts <= packet->pts) ||\n (curReverseStopPts == AV_NOPTS_VALUE && (packet->flags & PktFlags.Key) != 0 && packet->pts != curReverseStartPts) ||\n (packet->pts == curReverseStopPts)\n ))\n {\n if (curReverseStartPts == AV_NOPTS_VALUE || curReverseStopPts == curReverseStartPts)\n {\n curReverseSeekOffset *= 2;\n if (curReverseStartPts == AV_NOPTS_VALUE) curReverseStartPts = curReverseStopPts;\n if (curReverseStartPts == AV_NOPTS_VALUE) curReverseStartPts = curReverseStopRequestedPts;\n }\n\n curReverseStopRequestedPts = AV_NOPTS_VALUE;\n\n if ((packet->flags & PktFlags.Key) == 0 && curReverseVideoPackets.Count > 0)\n {\n var drainPacket = av_packet_alloc();\n drainPacket->data = null;\n drainPacket->size = 0;\n curReverseVideoPackets.Add((IntPtr)drainPacket);\n curReverseVideoStack.Push(curReverseVideoPackets);\n curReverseVideoPackets = new List();\n }\n\n if (!curReverseVideoStack.IsEmpty)\n {\n VideoPacketsReverse.Enqueue(curReverseVideoStack);\n curReverseVideoStack = new ConcurrentStack>();\n }\n\n av_packet_unref(packet);\n\n if (curReverseStartPts != AV_NOPTS_VALUE && curReverseStartPts <= VideoStream.StartTimePts)\n {\n Status = Status.Ended;\n break;\n }\n\n //Log($\"[][][SEEK] {curReverseStartPts} | {Utils.TicksToTime((long) (curReverseStartPts * VideoStream.Timebase))}\");\n Interrupter.SeekRequest();\n ret = av_seek_frame(fmtCtx, VideoStream.StreamIndex, Math.Max(curReverseStartPts - curReverseSeekOffset, 0), SeekFlags.Backward);\n\n if (ret != 0)\n {\n Status = Status.Stopping;\n break;\n }\n\n curReverseStopPts = curReverseStartPts;\n curReverseStartPts = AV_NOPTS_VALUE;\n }\n else\n {\n if (curReverseStartPts != AV_NOPTS_VALUE)\n {\n curReverseVideoPackets.Add((IntPtr)packet);\n packet = av_packet_alloc();\n }\n else\n av_packet_unref(packet);\n }\n }\n\n } while (Status == Status.Running);\n }\n\n public void EnableReversePlayback(long timestamp)\n {\n IsReversePlayback = true;\n Seek(StartTime + timestamp);\n curReverseStopRequestedPts = av_rescale_q((StartTime + timestamp) / 10, Engine.FFmpeg.AV_TIMEBASE_Q, VideoStream.AVStream->time_base);\n }\n public void DisableReversePlayback() => IsReversePlayback = false;\n #endregion\n\n #region Switch Programs / Streams\n public bool IsProgramEnabled(StreamBase stream)\n {\n for (int i=0; iprograms[i]->discard != AVDiscard.All)\n return true;\n\n return false;\n }\n public void EnableProgram(StreamBase stream)\n {\n if (IsProgramEnabled(stream))\n {\n if (CanDebug) Log.Debug($\"[Stream #{stream.StreamIndex}] Program already enabled\");\n return;\n }\n\n for (int i=0; iprograms[i]->discard = AVDiscard.Default;\n return;\n }\n }\n public void DisableProgram(StreamBase stream)\n {\n for (int i=0; iprograms[i]->discard != AVDiscard.All)\n {\n bool isNeeded = false;\n for (int l2=0; l2programs[i]->discard = AVDiscard.All;\n }\n else if (CanDebug)\n Log.Debug($\"[Stream #{stream.StreamIndex}] Program #{i} is needed\");\n }\n }\n\n public void EnableStream(StreamBase stream)\n {\n lock (lockFmtCtx)\n {\n if (Disposed || stream == null || EnabledStreams.Contains(stream.StreamIndex))\n {\n // If it detects that the primary and secondary are trying to select the same subtitle\n // Put the same instance in SubtitlesStreams and return.\n if (stream != null && stream.Type == MediaType.Subs && EnabledStreams.Contains(stream.StreamIndex))\n {\n SubtitlesStreams[SubtitlesSelectedHelper.CurIndex] = (SubtitlesStream)stream;\n // Necessary to update UI immediately\n stream.Enabled = stream.Enabled;\n }\n return;\n };\n\n EnabledStreams.Add(stream.StreamIndex);\n fmtCtx->streams[stream.StreamIndex]->discard = AVDiscard.Default;\n stream.Enabled = true;\n EnableProgram(stream);\n\n switch (stream.Type)\n {\n case MediaType.Audio:\n AudioStream = (AudioStream) stream;\n if (VideoStream == null)\n {\n if (AudioStream.HLSPlaylist != null)\n {\n IsHLSLive = true;\n HLSPlaylist = AudioStream.HLSPlaylist;\n UpdateHLSTime();\n }\n else\n {\n HLSPlaylist = null;\n IsHLSLive = false;\n }\n }\n\n break;\n\n case MediaType.Video:\n VideoStream = (VideoStream) stream;\n VideoPackets.frameDuration = VideoStream.FrameDuration > 0 ? VideoStream.FrameDuration : 30 * 1000 * 10000;\n if (VideoStream.HLSPlaylist != null)\n {\n IsHLSLive = true;\n HLSPlaylist = VideoStream.HLSPlaylist;\n UpdateHLSTime();\n }\n else\n {\n HLSPlaylist = null;\n IsHLSLive = false;\n }\n\n break;\n\n case MediaType.Subs:\n SubtitlesStreams[SubtitlesSelectedHelper.CurIndex] = (SubtitlesStream)stream;\n\n break;\n\n case MediaType.Data:\n DataStream = (DataStream) stream;\n\n break;\n }\n\n if (UseAVSPackets)\n CurPackets = VideoStream != null ? VideoPackets : (AudioStream != null ? AudioPackets : (SubtitlesStreams[0] != null ? SubtitlesPackets[0] : DataPackets));\n\n if (CanInfo) Log.Info($\"[{stream.Type} #{stream.StreamIndex}] Enabled\");\n }\n }\n public void DisableStream(StreamBase stream)\n {\n lock (lockFmtCtx)\n {\n if (Disposed || stream == null || !EnabledStreams.Contains(stream.StreamIndex)) return;\n\n // If it is the same subtitle, do not disable it.\n if (stream.Type == MediaType.Subs && SubtitlesStreams[0] != null && SubtitlesStreams[0] == SubtitlesStreams[1])\n {\n // clear only what is needed\n SubtitlesStreams[SubtitlesSelectedHelper.CurIndex] = null;\n SubtitlesPackets[SubtitlesSelectedHelper.CurIndex].Clear();\n // Necessary to update UI immediately\n stream.Enabled = stream.Enabled;\n return;\n }\n\n /* AVDISCARD_ALL causes syncing issues between streams (TBR: bandwidth?)\n * 1) While switching video streams will not switch at the same timestamp\n * 2) By disabling video stream after a seek, audio will not seek properly\n * 3) HLS needs to update hlsCtx->first_time and read at least on package before seek to be accurate\n */\n\n fmtCtx->streams[stream.StreamIndex]->discard = AVDiscard.All;\n EnabledStreams.Remove(stream.StreamIndex);\n stream.Enabled = false;\n DisableProgram(stream);\n\n switch (stream.Type)\n {\n case MediaType.Audio:\n AudioStream = null;\n if (VideoStream != null)\n {\n if (VideoStream.HLSPlaylist != null)\n {\n IsHLSLive = true;\n HLSPlaylist = VideoStream.HLSPlaylist;\n UpdateHLSTime();\n }\n else\n {\n HLSPlaylist = null;\n IsHLSLive = false;\n }\n }\n\n AudioPackets.Clear();\n\n break;\n\n case MediaType.Video:\n VideoStream = null;\n if (AudioStream != null)\n {\n if (AudioStream.HLSPlaylist != null)\n {\n IsHLSLive = true;\n HLSPlaylist = AudioStream.HLSPlaylist;\n UpdateHLSTime();\n }\n else\n {\n HLSPlaylist = null;\n IsHLSLive = false;\n }\n }\n\n VideoPackets.Clear();\n break;\n\n case MediaType.Subs:\n SubtitlesStreams[SubtitlesSelectedHelper.CurIndex] = null;\n SubtitlesPackets[SubtitlesSelectedHelper.CurIndex].Clear();\n\n break;\n\n case MediaType.Data:\n DataStream = null;\n DataPackets.Clear();\n\n break;\n }\n\n if (UseAVSPackets)\n CurPackets = VideoStream != null ? VideoPackets : (AudioStream != null ? AudioPackets : SubtitlesPackets[0]);\n\n if (CanInfo) Log.Info($\"[{stream.Type} #{stream.StreamIndex}] Disabled\");\n }\n }\n public void SwitchStream(StreamBase stream)\n {\n lock (lockFmtCtx)\n {\n if (stream.Type == MediaType.Audio)\n DisableStream(AudioStream);\n else if (stream.Type == MediaType.Video)\n DisableStream(VideoStream);\n else if (stream.Type == MediaType.Subs)\n DisableStream(SubtitlesStreams[SubtitlesSelectedHelper.CurIndex]);\n else\n DisableStream(DataStream);\n\n EnableStream(stream);\n }\n }\n #endregion\n\n #region Misc\n internal void UpdateHLSTime()\n {\n // TBR: Access Violation\n // [hls @ 00000269f9cdb400] Media sequence changed unexpectedly: 150070 -> 0\n\n if (hlsPrevSeqNo != HLSPlaylist->cur_seq_no)\n {\n hlsPrevSeqNo = HLSPlaylist->cur_seq_no;\n hlsStartTime = AV_NOPTS_VALUE;\n\n hlsCurDuration = 0;\n long duration = 0;\n\n for (long i=0; icur_seq_no - HLSPlaylist->start_seq_no; i++)\n {\n hlsCurDuration += HLSPlaylist->segments[i]->duration;\n duration += HLSPlaylist->segments[i]->duration;\n }\n\n for (long i=HLSPlaylist->cur_seq_no - HLSPlaylist->start_seq_no; in_segments; i++)\n duration += HLSPlaylist->segments[i]->duration;\n\n hlsCurDuration *= 10;\n duration *= 10;\n Duration = duration;\n }\n\n if (hlsStartTime == AV_NOPTS_VALUE && CurPackets.LastTimestamp != AV_NOPTS_VALUE)\n {\n hlsStartTime = CurPackets.LastTimestamp - hlsCurDuration;\n CurPackets.UpdateCurTime();\n }\n }\n\n private string GetValidExtension()\n {\n // TODO\n // Should check for all supported output formats (there is no list in ffmpeg.autogen ?)\n // Should check for inner input format (not outer protocol eg. hls/rtsp)\n // Should check for raw codecs it can be mp4/mov but it will not work in mp4 only in mov (or avi for raw)\n\n if (Name == \"mpegts\")\n return \"ts\";\n else if (Name == \"mpeg\")\n return \"mpeg\";\n\n List supportedOutput = new() { \"mp4\", \"avi\", \"flv\", \"flac\", \"mpeg\", \"mpegts\", \"mkv\", \"ogg\", \"ts\"};\n string defaultExtenstion = \"mp4\";\n bool hasPcm = false;\n bool isRaw = false;\n\n foreach (var stream in AudioStreams)\n if (stream.Codec.Contains(\"pcm\")) hasPcm = true;\n\n foreach (var stream in VideoStreams)\n if (stream.Codec.Contains(\"raw\")) isRaw = true;\n\n if (isRaw) defaultExtenstion = \"avi\";\n\n // MP4 container doesn't support PCM\n if (hasPcm) defaultExtenstion = \"mkv\";\n\n // TODO\n // Check also shortnames\n //if (Name == \"mpegts\") return \"ts\";\n //if ((fmtCtx->iformat->flags & AVFMT_TS_DISCONT) != 0) should be mp4 or container that supports segments\n\n if (string.IsNullOrEmpty(Extensions)) return defaultExtenstion;\n string[] extensions = Extensions.Split(',');\n if (extensions == null || extensions.Length < 1) return defaultExtenstion;\n\n // Try to set the output container same as input\n for (int i=0; istart_time * 10)}/{Utils.TicksToTime(fmtCtx->duration * 10)} | {Utils.TicksToTime(StartTime)}/{Utils.TicksToTime(Duration)}\";\n\n foreach(var stream in VideoStreams) dump += \"\\r\\n\" + stream.GetDump();\n foreach(var stream in AudioStreams) dump += \"\\r\\n\" + stream.GetDump();\n foreach(var stream in SubtitlesStreamsAll) dump += \"\\r\\n\" + stream.GetDump();\n\n if (fmtCtx->nb_programs > 0)\n dump += $\"\\r\\n[Programs] {fmtCtx->nb_programs}\";\n\n for (int i=0; inb_programs; i++)\n {\n dump += $\"\\r\\n\\tProgram #{i}\";\n\n if (fmtCtx->programs[i]->nb_stream_indexes > 0)\n dump += $\"\\r\\n\\t\\tStreams [{fmtCtx->programs[i]->nb_stream_indexes}]: \";\n\n for (int l=0; lprograms[i]->nb_stream_indexes; l++)\n dump += $\"{fmtCtx->programs[i]->stream_index[l]},\";\n\n if (fmtCtx->programs[i]->nb_stream_indexes > 0)\n dump = dump[..^1];\n }\n\n if (CanInfo) Log.Info($\"Format Context Info {dump}\\r\\n\");\n }\n\n /// \n /// Gets next VideoPacket from the existing queue or demuxes it if required (Demuxer must not be running)\n /// \n /// 0 on success\n public int GetNextVideoPacket()\n {\n if (VideoPackets.Count > 0)\n {\n packet = VideoPackets.Dequeue();\n return 0;\n }\n else\n return GetNextPacket(VideoStream.StreamIndex);\n }\n\n /// \n /// Pushes the demuxer to the next available packet (Demuxer must not be running)\n /// \n /// Packet's stream index\n /// 0 on success\n public int GetNextPacket(int streamIndex = -1)\n {\n int ret;\n\n while (true)\n {\n Interrupter.ReadRequest();\n ret = av_read_frame(fmtCtx, packet);\n\n if (ret != 0)\n {\n av_packet_unref(packet);\n\n if ((ret == AVERROR_EXIT && fmtCtx->pb != null && fmtCtx->pb->eof_reached != 0) || ret == AVERROR_EOF)\n {\n packet = av_packet_alloc();\n packet->data = null;\n packet->size = 0;\n\n Stop();\n Status = Status.Ended;\n }\n\n return ret;\n }\n\n if (streamIndex != -1)\n {\n if (packet->stream_index == streamIndex)\n return 0;\n }\n else if (EnabledStreams.Contains(packet->stream_index))\n return 0;\n\n av_packet_unref(packet);\n }\n }\n #endregion\n}\n\npublic unsafe class PacketQueue\n{\n // TODO: DTS might not be available without avformat_find_stream_info (should changed based on packet->duration and fallback should be removed)\n readonly Demuxer demuxer;\n readonly ConcurrentQueue packets = new();\n public long frameDuration = 30 * 1000 * 10000; // in case of negative buffer duration calculate it based on packets count / FPS\n\n public long Bytes { get; private set; }\n public long BufferedDuration { get; private set; }\n public long CurTime { get; private set; }\n public int Count => packets.Count;\n public bool IsEmpty => packets.IsEmpty;\n\n public long FirstTimestamp { get; private set; } = AV_NOPTS_VALUE;\n public long LastTimestamp { get; private set; } = AV_NOPTS_VALUE;\n\n public PacketQueue(Demuxer demuxer)\n => this.demuxer = demuxer;\n\n public void Clear()\n {\n lock(packets)\n {\n while (!packets.IsEmpty)\n {\n packets.TryDequeue(out IntPtr packetPtr);\n if (packetPtr == IntPtr.Zero) continue;\n AVPacket* packet = (AVPacket*)packetPtr;\n av_packet_free(&packet);\n }\n\n FirstTimestamp = AV_NOPTS_VALUE;\n LastTimestamp = AV_NOPTS_VALUE;\n Bytes = 0;\n BufferedDuration = 0;\n CurTime = 0;\n }\n }\n\n public void Enqueue(AVPacket* packet)\n {\n lock (packets)\n {\n packets.Enqueue((IntPtr)packet);\n\n if (packet->dts != AV_NOPTS_VALUE || packet->pts != AV_NOPTS_VALUE)\n {\n LastTimestamp = packet->dts != AV_NOPTS_VALUE ?\n (long)(packet->dts * demuxer.AVStreamToStream[packet->stream_index].Timebase):\n (long)(packet->pts * demuxer.AVStreamToStream[packet->stream_index].Timebase);\n\n if (FirstTimestamp == AV_NOPTS_VALUE)\n {\n FirstTimestamp = LastTimestamp;\n UpdateCurTime();\n }\n else\n {\n BufferedDuration = LastTimestamp - FirstTimestamp;\n if (BufferedDuration < 0)\n BufferedDuration = packets.Count * frameDuration;\n }\n }\n else\n BufferedDuration = packets.Count * frameDuration;\n\n Bytes += packet->size;\n }\n }\n\n public AVPacket* Dequeue()\n {\n lock(packets)\n if (packets.TryDequeue(out IntPtr packetPtr))\n {\n AVPacket* packet = (AVPacket*)packetPtr;\n\n if (packet->dts != AV_NOPTS_VALUE || packet->pts != AV_NOPTS_VALUE)\n {\n FirstTimestamp = packet->dts != AV_NOPTS_VALUE ?\n (long)(packet->dts * demuxer.AVStreamToStream[packet->stream_index].Timebase):\n (long)(packet->pts * demuxer.AVStreamToStream[packet->stream_index].Timebase);\n UpdateCurTime();\n }\n else\n BufferedDuration = packets.Count * frameDuration;\n\n return (AVPacket*)packetPtr;\n }\n\n return null;\n }\n\n public AVPacket* Peek()\n => packets.TryPeek(out IntPtr packetPtr)\n ? (AVPacket*)packetPtr\n : (AVPacket*)null;\n\n internal void UpdateCurTime()\n {\n if (demuxer.hlsCtx != null)\n {\n if (demuxer.hlsStartTime != AV_NOPTS_VALUE)\n {\n if (FirstTimestamp < demuxer.hlsStartTime)\n {\n demuxer.Duration += demuxer.hlsStartTime - FirstTimestamp;\n demuxer.hlsStartTime = FirstTimestamp;\n CurTime = 0;\n }\n else\n CurTime = FirstTimestamp - demuxer.hlsStartTime;\n }\n }\n else\n CurTime = FirstTimestamp - demuxer.StartTime;\n\n if (CurTime < 0)\n CurTime = 0;\n\n BufferedDuration = LastTimestamp - FirstTimestamp;\n\n if (BufferedDuration < 0)\n BufferedDuration = packets.Count * frameDuration;\n }\n}\n"], ["/LLPlayer/FlyleafLib/MediaFramework/MediaRenderer/Renderer.SwapChain.cs", "using System.Windows;\n\nusing Vortice;\nusing Vortice.Direct3D;\nusing Vortice.Direct3D11;\nusing Vortice.DirectComposition;\nusing Vortice.DXGI;\n\nusing static FlyleafLib.Utils.NativeMethods;\nusing ID3D11Texture2D = Vortice.Direct3D11.ID3D11Texture2D;\n\nnamespace FlyleafLib.MediaFramework.MediaRenderer;\n\npublic partial class Renderer\n{\n ID3D11Texture2D backBuffer;\n ID3D11RenderTargetView backBufferRtv;\n IDXGISwapChain1 swapChain;\n IDCompositionDevice dCompDevice;\n IDCompositionVisual dCompVisual;\n IDCompositionTarget dCompTarget;\n\n const Int32 WM_NCDESTROY= 0x0082;\n const Int32 WM_SIZE = 0x0005;\n const Int32 WS_EX_NOREDIRECTIONBITMAP\n = 0x00200000;\n SubclassWndProc wndProcDelegate;\n IntPtr wndProcDelegatePtr;\n\n // Support Windows 8+\n private SwapChainDescription1 GetSwapChainDesc(int width, int height, bool isComp = false, bool alpha = false)\n {\n if (Device.FeatureLevel < FeatureLevel.Level_10_0 || (!string.IsNullOrWhiteSpace(Config.Video.GPUAdapter) && Config.Video.GPUAdapter.ToUpper() == \"WARP\"))\n {\n return new()\n {\n BufferUsage = Usage.RenderTargetOutput,\n Format = Config.Video.Swap10Bit ? Format.R10G10B10A2_UNorm : Format.B8G8R8A8_UNorm,\n Width = (uint)width,\n Height = (uint)height,\n AlphaMode = AlphaMode.Ignore,\n SwapEffect = isComp ? SwapEffect.FlipSequential : SwapEffect.Discard, // will this work for warp?\n Scaling = Scaling.Stretch,\n BufferCount = 1,\n SampleDescription = new SampleDescription(1, 0)\n };\n }\n else\n {\n SwapEffect swapEffect = isComp ? SwapEffect.FlipSequential : Environment.OSVersion.Version.Major >= 10 ? SwapEffect.FlipDiscard : SwapEffect.FlipSequential;\n\n return new()\n {\n BufferUsage = Usage.RenderTargetOutput,\n Format = Config.Video.Swap10Bit ? Format.R10G10B10A2_UNorm : (Config.Video.SwapForceR8G8B8A8 ? Format.R8G8B8A8_UNorm : Format.B8G8R8A8_UNorm),\n Width = (uint)width,\n Height = (uint)height,\n AlphaMode = alpha ? AlphaMode.Premultiplied : AlphaMode.Ignore,\n SwapEffect = swapEffect,\n Scaling = isComp ? Scaling.Stretch : Scaling.None,\n BufferCount = swapEffect == SwapEffect.FlipDiscard ? Math.Min(Config.Video.SwapBuffers, 2) : Config.Video.SwapBuffers,\n SampleDescription = new SampleDescription(1, 0),\n };\n }\n }\n\n internal void InitializeSwapChain(IntPtr handle)\n {\n lock (lockDevice)\n {\n if (!SCDisposed)\n DisposeSwapChain();\n\n if (Disposed && parent == null)\n Initialize(false);\n\n ControlHandle = handle;\n RECT rect = new();\n GetWindowRect(ControlHandle,ref rect);\n ControlWidth = rect.Right - rect.Left;\n ControlHeight = rect.Bottom - rect.Top;\n\n try\n {\n if (cornerRadius == zeroCornerRadius)\n {\n Log.Info($\"Initializing {(Config.Video.Swap10Bit ? \"10-bit\" : \"8-bit\")} swap chain with {Config.Video.SwapBuffers} buffers [Handle: {handle}]\");\n swapChain = Engine.Video.Factory.CreateSwapChainForHwnd(Device, handle, GetSwapChainDesc(ControlWidth, ControlHeight));\n }\n else\n {\n Log.Info($\"Initializing {(Config.Video.Swap10Bit ? \"10-bit\" : \"8-bit\")} composition swap chain with {Config.Video.SwapBuffers} buffers [Handle: {handle}]\");\n swapChain = Engine.Video.Factory.CreateSwapChainForComposition(Device, GetSwapChainDesc(ControlWidth, ControlHeight, true, true));\n using (var dxgiDevice = Device.QueryInterface())\n dCompDevice = DComp.DCompositionCreateDevice(dxgiDevice);\n dCompDevice.CreateTargetForHwnd(handle, false, out dCompTarget).CheckError();\n dCompDevice.CreateVisual(out dCompVisual).CheckError();\n dCompVisual.SetContent(swapChain).CheckError();\n dCompTarget.SetRoot(dCompVisual).CheckError();\n dCompDevice.Commit().CheckError();\n\n int styleEx = GetWindowLong(handle, (int)WindowLongFlags.GWL_EXSTYLE).ToInt32() | WS_EX_NOREDIRECTIONBITMAP;\n SetWindowLong(handle, (int)WindowLongFlags.GWL_EXSTYLE, new IntPtr(styleEx));\n }\n }\n catch (Exception e)\n {\n if (string.IsNullOrWhiteSpace(Config.Video.GPUAdapter) || Config.Video.GPUAdapter.ToUpper() != \"WARP\")\n {\n try { if (Device != null) Log.Warn($\"Device Remove Reason = {Device.DeviceRemovedReason.Description}\"); } catch { } // For troubleshooting\n\n Log.Warn($\"[SwapChain] Initialization failed ({e.Message}). Failling back to WARP device.\");\n Config.Video.GPUAdapter = \"WARP\";\n Flush();\n }\n else\n {\n ControlHandle = IntPtr.Zero;\n Log.Error($\"[SwapChain] Initialization failed ({e.Message})\");\n }\n\n return;\n }\n\n backBuffer = swapChain.GetBuffer(0);\n backBufferRtv = Device.CreateRenderTargetView(backBuffer);\n SCDisposed = false;\n\n if (!isFlushing) // avoid calling UI thread during Player.Stop\n {\n // SetWindowSubclass seems to require UI thread when RemoveWindowSubclass does not (docs are not mentioning this?)\n if (System.Threading.Thread.CurrentThread.ManagedThreadId == System.Windows.Application.Current.Dispatcher.Thread.ManagedThreadId)\n SetWindowSubclass(ControlHandle, wndProcDelegatePtr, UIntPtr.Zero, UIntPtr.Zero);\n else\n Utils.UI(() => SetWindowSubclass(ControlHandle, wndProcDelegatePtr, UIntPtr.Zero, UIntPtr.Zero));\n }\n\n Engine.Video.Factory.MakeWindowAssociation(ControlHandle, WindowAssociationFlags.IgnoreAll);\n\n ResizeBuffers(ControlWidth, ControlHeight); // maybe not required (only for vp)?\n }\n }\n internal void InitializeWinUISwapChain() // TODO: width/height directly here\n {\n lock (lockDevice)\n {\n if (!SCDisposed)\n DisposeSwapChain();\n\n if (Disposed)\n Initialize(false);\n\n Log.Info($\"Initializing {(Config.Video.Swap10Bit ? \"10-bit\" : \"8-bit\")} swap chain with {Config.Video.SwapBuffers} buffers\");\n\n try\n {\n swapChain = Engine.Video.Factory.CreateSwapChainForComposition(Device, GetSwapChainDesc(1, 1, true));\n }\n catch (Exception e)\n {\n Log.Error($\"Initialization failed [{e.Message}]\");\n\n // TODO fallback to WARP?\n\n SwapChainWinUIClbk?.Invoke(null);\n return;\n }\n\n backBuffer = swapChain.GetBuffer(0);\n backBufferRtv = Device.CreateRenderTargetView(backBuffer);\n SCDisposed = false;\n ResizeBuffers(1, 1);\n\n SwapChainWinUIClbk?.Invoke(swapChain.QueryInterface());\n }\n }\n\n public void DisposeSwapChain()\n {\n lock (lockDevice)\n {\n if (SCDisposed)\n return;\n\n SCDisposed = true;\n\n // Clear Screan\n if (!Disposed && swapChain != null)\n {\n try\n {\n context.ClearRenderTargetView(backBufferRtv, Config.Video._BackgroundColor);\n swapChain.Present(Config.Video.VSync, PresentFlags.None);\n }\n catch { }\n }\n\n Log.Info($\"Destroying swap chain [Handle: {ControlHandle}]\");\n\n // Unassign renderer's WndProc if still there and re-assign the old one\n if (ControlHandle != IntPtr.Zero)\n {\n if (!isFlushing) // SetWindowSubclass requires UI thread so avoid calling it on flush (Player.Stop)\n RemoveWindowSubclass(ControlHandle, wndProcDelegatePtr, UIntPtr.Zero);\n ControlHandle = IntPtr.Zero;\n }\n\n if (SwapChainWinUIClbk != null)\n {\n SwapChainWinUIClbk.Invoke(null);\n SwapChainWinUIClbk = null;\n swapChain?.Release(); // TBR: SwapChainPanel (SCP) should be disposed and create new instance instead (currently used from Template)\n }\n\n dCompVisual?.Dispose();\n dCompTarget?.Dispose();\n dCompDevice?.Dispose();\n dCompVisual = null;\n dCompTarget = null;\n dCompDevice = null;\n\n vpov?.Dispose();\n backBufferRtv?.Dispose();\n backBuffer?.Dispose();\n swapChain?.Dispose();\n\n if (Device != null)\n context?.Flush();\n }\n }\n\n public void RemoveViewportOffsets(ref Point p)\n {\n p.X -= (SideXPixels / 2 + PanXOffset);\n p.Y -= (SideYPixels / 2 + PanYOffset);\n }\n public bool IsPointWithInViewPort(Point p)\n => p.X >= GetViewport.X && p.X < GetViewport.X + GetViewport.Width && p.Y >= GetViewport.Y && p.Y < GetViewport.Y + GetViewport.Height;\n\n public static double GetCenterPoint(double zoom, double offset)\n => zoom == 1 ? offset : offset / (zoom - 1); // possible bug when zoom = 1 (noticed in out of bounds zoom out)\n\n /// \n /// Zooms in a way that the specified point before zoom will be at the same position after zoom\n /// \n /// \n /// \n public void ZoomWithCenterPoint(Point p, double zoom)\n {\n /* Notes\n *\n * Zoomed Point (ZP) // the current point in a -possible- zoomed viewport\n * Zoom (Z)\n * Unzoomed Point (UP) // the actual pixel of the current point\n * Viewport Point (VP)\n * Center Point (CP)\n *\n * UP = (VP + ZP) / Z =>\n * ZP = (UP * Z) - VP\n * CP = VP / (ZP - 1) (when UP = ZP)\n */\n\n if (!IsPointWithInViewPort(p))\n {\n SetZoom(zoom);\n return;\n }\n\n Point viewport = new(GetViewport.X, GetViewport.Y);\n RemoveViewportOffsets(ref viewport);\n RemoveViewportOffsets(ref p);\n\n // Finds the required center point so that p will have the same pixel after zoom\n Point zoomCenter = new(\n GetCenterPoint(zoom, ((p.X - viewport.X) / (this.zoom / zoom)) - p.X) / (GetViewport.Width / this.zoom),\n GetCenterPoint(zoom, ((p.Y - viewport.Y) / (this.zoom / zoom)) - p.Y) / (GetViewport.Height / this.zoom));\n\n SetZoomAndCenter(zoom, zoomCenter);\n }\n\n public void SetViewport(bool refresh = true)\n {\n float ratio;\n int x, y, newWidth, newHeight, xZoomPixels, yZoomPixels;\n\n if (Config.Video.AspectRatio == AspectRatio.Keep)\n ratio = curRatio;\n else ratio = Config.Video.AspectRatio == AspectRatio.Fill\n ? ControlWidth / (float)ControlHeight\n : Config.Video.AspectRatio == AspectRatio.Custom ? Config.Video.CustomAspectRatio.Value : Config.Video.AspectRatio.Value;\n\n if (ratio <= 0)\n ratio = 1;\n\n if (actualRotation == 90 || actualRotation == 270)\n ratio = 1 / ratio;\n\n if (ratio < ControlWidth / (float) ControlHeight)\n {\n newHeight = (int)(ControlHeight * zoom);\n newWidth = (int)(newHeight * ratio);\n\n SideXPixels = newWidth > ControlWidth && false ? 0 : (int) (ControlWidth - (ControlHeight * ratio)); // TBR\n SideYPixels = 0;\n\n y = PanYOffset;\n x = PanXOffset + SideXPixels / 2;\n\n yZoomPixels = newHeight - ControlHeight;\n xZoomPixels = newWidth - (ControlWidth - SideXPixels);\n }\n else\n {\n newWidth = (int)(ControlWidth * zoom);\n newHeight = (int)(newWidth / ratio);\n\n SideYPixels = newHeight > ControlHeight && false ? 0 : (int) (ControlHeight - (ControlWidth / ratio));\n SideXPixels = 0;\n\n x = PanXOffset;\n y = PanYOffset + SideYPixels / 2;\n\n xZoomPixels = newWidth - ControlWidth;\n yZoomPixels = newHeight - (ControlHeight - SideYPixels);\n }\n\n GetViewport = new(x - xZoomPixels * (float)zoomCenter.X, y - yZoomPixels * (float)zoomCenter.Y, newWidth, newHeight);\n ViewportChanged?.Invoke(this, new());\n\n if (videoProcessor == VideoProcessors.D3D11)\n {\n RawRect src, dst;\n\n if (GetViewport.Width < 1 || GetViewport.X + GetViewport.Width <= 0 || GetViewport.X >= ControlWidth || GetViewport.Y + GetViewport.Height <= 0 || GetViewport.Y >= ControlHeight)\n { // Out of screen\n src = new RawRect();\n dst = new RawRect();\n }\n else\n {\n int cropLeft = GetViewport.X < 0 ? (int) GetViewport.X * -1 : 0;\n int cropRight = GetViewport.X + GetViewport.Width > ControlWidth ? (int) (GetViewport.X + GetViewport.Width - ControlWidth) : 0;\n int cropTop = GetViewport.Y < 0 ? (int) GetViewport.Y * -1 : 0;\n int cropBottom = GetViewport.Y + GetViewport.Height > ControlHeight ? (int) (GetViewport.Y + GetViewport.Height - ControlHeight) : 0;\n\n dst = new RawRect(Math.Max((int)GetViewport.X, 0), Math.Max((int)GetViewport.Y, 0), Math.Min((int)GetViewport.Width + (int)GetViewport.X, ControlWidth), Math.Min((int)GetViewport.Height + (int)GetViewport.Y, ControlHeight));\n\n if (_RotationAngle == 90)\n {\n src = new RawRect(\n (int) (cropTop * (VideoRect.Right / GetViewport.Height)),\n (int) (cropRight * (VideoRect.Bottom / GetViewport.Width)),\n VideoRect.Right - (int) (cropBottom * VideoRect.Right / GetViewport.Height),\n VideoRect.Bottom - (int) (cropLeft * VideoRect.Bottom / GetViewport.Width));\n }\n else if (_RotationAngle == 270)\n {\n src = new RawRect(\n (int) (cropBottom * VideoRect.Right / GetViewport.Height),\n (int) (cropLeft * VideoRect.Bottom / GetViewport.Width),\n VideoRect.Right - (int) (cropTop * VideoRect.Right / GetViewport.Height),\n VideoRect.Bottom - (int) (cropRight * VideoRect.Bottom / GetViewport.Width));\n }\n else if (_RotationAngle == 180)\n {\n src = new RawRect(\n (int) (cropRight * VideoRect.Right / GetViewport.Width),\n (int) (cropBottom * VideoRect.Bottom /GetViewport.Height),\n VideoRect.Right - (int) (cropLeft * VideoRect.Right / GetViewport.Width),\n VideoRect.Bottom - (int) (cropTop * VideoRect.Bottom / GetViewport.Height));\n }\n else\n {\n src = new RawRect(\n (int) (cropLeft * VideoRect.Right / GetViewport.Width),\n (int) (cropTop * VideoRect.Bottom / GetViewport.Height),\n VideoRect.Right - (int) (cropRight * VideoRect.Right / GetViewport.Width),\n VideoRect.Bottom - (int) (cropBottom * VideoRect.Bottom / GetViewport.Height));\n }\n }\n\n vc.VideoProcessorSetStreamSourceRect(vp, 0, true, src);\n vc.VideoProcessorSetStreamDestRect (vp, 0, true, dst);\n vc.VideoProcessorSetOutputTargetRect(vp, true, new RawRect(0, 0, ControlWidth, ControlHeight));\n }\n\n if (refresh)\n Present();\n }\n public void ResizeBuffers(int width, int height)\n {\n lock (lockDevice)\n {\n if (SCDisposed)\n return;\n\n ControlWidth = width;\n ControlHeight = height;\n\n backBufferRtv.Dispose();\n vpov?.Dispose();\n backBuffer.Dispose();\n swapChain.ResizeBuffers(0, (uint)ControlWidth, (uint)ControlHeight, Format.Unknown, SwapChainFlags.None);\n UpdateCornerRadius();\n backBuffer = swapChain.GetBuffer(0);\n backBufferRtv = Device.CreateRenderTargetView(backBuffer);\n if (videoProcessor == VideoProcessors.D3D11)\n vd1.CreateVideoProcessorOutputView(backBuffer, vpe, vpovd, out vpov);\n\n SetViewport();\n }\n }\n\n internal void UpdateCornerRadius()\n {\n if (dCompDevice == null)\n return;\n\n dCompDevice.CreateRectangleClip(out var clip).CheckError();\n clip.SetLeft(0);\n clip.SetRight(ControlWidth);\n clip.SetTop(0);\n clip.SetBottom(ControlHeight);\n clip.SetTopLeftRadiusX((float)cornerRadius.TopLeft);\n clip.SetTopLeftRadiusY((float)cornerRadius.TopLeft);\n clip.SetTopRightRadiusX((float)cornerRadius.TopRight);\n clip.SetTopRightRadiusY((float)cornerRadius.TopRight);\n clip.SetBottomLeftRadiusX((float)cornerRadius.BottomLeft);\n clip.SetBottomLeftRadiusY((float)cornerRadius.BottomLeft);\n clip.SetBottomRightRadiusX((float)cornerRadius.BottomRight);\n clip.SetBottomRightRadiusY((float)cornerRadius.BottomRight);\n dCompVisual.SetClip(clip).CheckError();\n clip.Dispose();\n dCompDevice.Commit().CheckError();\n }\n\n private IntPtr WndProc(IntPtr hWnd, uint msg, IntPtr wParam, IntPtr lParam, IntPtr uIdSubclass, IntPtr dwRefData)\n {\n switch (msg)\n {\n case WM_NCDESTROY:\n if (SCDisposed)\n RemoveWindowSubclass(ControlHandle, wndProcDelegatePtr, UIntPtr.Zero);\n else\n DisposeSwapChain();\n break;\n\n case WM_SIZE:\n ResizeBuffers(SignedLOWORD(lParam), SignedHIWORD(lParam));\n break;\n }\n\n return DefSubclassProc(hWnd, msg, wParam, lParam);\n }\n}\n"], ["/LLPlayer/FlyleafLib/MediaPlayer/Player.Extra.cs", "using System;\nusing System.Drawing.Imaging;\nusing System.IO;\nusing System.Windows;\n\nusing FlyleafLib.MediaFramework.MediaDecoder;\nusing FlyleafLib.MediaFramework.MediaDemuxer;\nusing FlyleafLib.MediaFramework.MediaFrame;\nusing FlyleafLib.MediaFramework.MediaRenderer;\n\nusing static FlyleafLib.Utils;\nusing static FlyleafLib.Logger;\n\nnamespace FlyleafLib.MediaPlayer;\n\nunsafe partial class Player\n{\n public bool IsOpenFileDialogOpen { get; private set; }\n\n\n public void SeekBackward() => SeekBackward_(Config.Player.SeekOffset, Config.Player.SeekOffsetAccurate);\n public void SeekBackward2() => SeekBackward_(Config.Player.SeekOffset2, Config.Player.SeekOffsetAccurate2);\n public void SeekBackward3() => SeekBackward_(Config.Player.SeekOffset3, Config.Player.SeekOffsetAccurate3);\n public void SeekBackward4() => SeekBackward_(Config.Player.SeekOffset4, Config.Player.SeekOffsetAccurate4);\n public void SeekBackward_(long offset, bool accurate)\n {\n if (!CanPlay)\n return;\n\n long seekTs = CurTime - (CurTime % offset) - offset;\n\n if (Config.Player.SeekAccurate || accurate)\n SeekAccurate(Math.Max((int) (seekTs / 10000), 0));\n else\n Seek(Math.Max((int) (seekTs / 10000), 0), false);\n }\n\n public void SeekForward() => SeekForward_(Config.Player.SeekOffset, Config.Player.SeekOffsetAccurate);\n public void SeekForward2() => SeekForward_(Config.Player.SeekOffset2, Config.Player.SeekOffsetAccurate2);\n public void SeekForward3() => SeekForward_(Config.Player.SeekOffset3, Config.Player.SeekOffsetAccurate3);\n public void SeekForward4() => SeekForward_(Config.Player.SeekOffset4, Config.Player.SeekOffsetAccurate4);\n public void SeekForward_(long offset, bool accurate)\n {\n if (!CanPlay)\n return;\n\n long seekTs = CurTime - (CurTime % offset) + offset;\n\n if (seekTs > Duration && !isLive)\n return;\n\n if (Config.Player.SeekAccurate || accurate)\n SeekAccurate((int)(seekTs / 10000));\n else\n Seek((int)(seekTs / 10000), true);\n }\n\n public void SeekToChapter(Demuxer.Chapter chapter) =>\n /* TODO\n* Accurate pts required (backward/forward check)\n* Get current chapter implementation + next/prev\n*/\n Seek((int)(chapter.StartTime / 10000.0), true);\n\n public void CopyToClipboard()\n {\n var url = decoder.Playlist.Url;\n if (url == null)\n return;\n\n Clipboard.SetText(url);\n OSDMessage = $\"Copy {url}\";\n }\n public void CopyItemToClipboard()\n {\n if (decoder.Playlist.Selected == null || decoder.Playlist.Selected.DirectUrl == null)\n return;\n\n string url = decoder.Playlist.Selected.DirectUrl;\n\n Clipboard.SetText(url);\n OSDMessage = $\"Copy {url}\";\n }\n public void OpenFromClipboard()\n {\n string text = Clipboard.GetText();\n if (!string.IsNullOrWhiteSpace(text))\n {\n OpenAsync(text);\n }\n }\n\n public void OpenFromClipboardSafe()\n {\n if (decoder.Playlist.Selected != null)\n {\n return;\n }\n\n OpenFromClipboard();\n }\n\n public void OpenFromFileDialog()\n {\n int prevTimeout = Activity.Timeout;\n Activity.IsEnabled = false;\n Activity.Timeout = 0;\n IsOpenFileDialogOpen = true;\n\n System.Windows.Forms.OpenFileDialog openFileDialog = new();\n\n // If there is currently an open file, set that folder as the base folder\n if (decoder.Playlist.Url != null && File.Exists(decoder.Playlist.Url))\n {\n var folder = Path.GetDirectoryName(decoder.Playlist.Url);\n if (folder != null)\n openFileDialog.InitialDirectory = folder;\n }\n\n var res = openFileDialog.ShowDialog();\n\n if (res == System.Windows.Forms.DialogResult.OK)\n OpenAsync(openFileDialog.FileName);\n\n Activity.Timeout = prevTimeout;\n Activity.IsEnabled = true;\n IsOpenFileDialogOpen = false;\n }\n\n public void ShowFrame(int frameIndex)\n {\n if (!Video.IsOpened || !CanPlay || VideoDemuxer.IsHLSLive) return;\n\n lock (lockActions)\n {\n Pause();\n dFrame = null;\n for (int i = 0; i < subNum; i++)\n {\n sFrames[i] = null;\n SubtitleClear(i);\n }\n\n decoder.Flush();\n decoder.RequiresResync = true;\n\n vFrame = VideoDecoder.GetFrame(frameIndex);\n if (vFrame == null) return;\n\n if (CanDebug) Log.Debug($\"SFI: {VideoDecoder.GetFrameNumber(vFrame.timestamp)}\");\n\n curTime = vFrame.timestamp;\n renderer.Present(vFrame);\n reversePlaybackResync = true;\n vFrame = null;\n\n UI(() => UpdateCurTime());\n }\n }\n\n // Whether video queue should be flushed as it could have opposite direction frames\n bool shouldFlushNext;\n bool shouldFlushPrev;\n public void ShowFrameNext()\n {\n if (!Video.IsOpened || !CanPlay || VideoDemuxer.IsHLSLive)\n return;\n\n lock (lockActions)\n {\n Pause();\n\n if (Status == Status.Ended)\n {\n status = Status.Paused;\n UI(() => Status = Status);\n }\n\n shouldFlushPrev = true;\n decoder.RequiresResync = true;\n\n if (shouldFlushNext)\n {\n decoder.StopThreads();\n decoder.Flush();\n shouldFlushNext = false;\n\n var vFrame = VideoDecoder.GetFrame(VideoDecoder.GetFrameNumber(CurTime));\n VideoDecoder.DisposeFrame(vFrame);\n }\n\n for (int i = 0; i < subNum; i++)\n {\n sFrames[i] = null;\n SubtitleClear(i);\n }\n\n if (VideoDecoder.Frames.IsEmpty)\n vFrame = VideoDecoder.GetFrameNext();\n else\n VideoDecoder.Frames.TryDequeue(out vFrame);\n\n if (vFrame == null)\n return;\n\n if (CanDebug) Log.Debug($\"SFN: {VideoDecoder.GetFrameNumber(vFrame.timestamp)}\");\n\n curTime = curTime = vFrame.timestamp;\n renderer.Present(vFrame);\n reversePlaybackResync = true;\n vFrame = null;\n\n UI(() => UpdateCurTime());\n }\n }\n public void ShowFramePrev()\n {\n if (!Video.IsOpened || !CanPlay || VideoDemuxer.IsHLSLive)\n return;\n\n lock (lockActions)\n {\n Pause();\n\n if (Status == Status.Ended)\n {\n status = Status.Paused;\n UI(() => Status = Status);\n }\n\n shouldFlushNext = true;\n decoder.RequiresResync = true;\n\n if (shouldFlushPrev)\n {\n decoder.StopThreads();\n decoder.Flush();\n shouldFlushPrev = false;\n }\n\n for (int i = 0; i < subNum; i++)\n {\n sFrames[i] = null;\n SubtitleClear(i);\n }\n\n if (VideoDecoder.Frames.IsEmpty)\n {\n // Temp fix for previous timestamps until we seperate GetFrame for Extractor and the Player\n reversePlaybackResync = true;\n int askedFrame = VideoDecoder.GetFrameNumber(CurTime) - 1;\n //Log.Debug($\"CurTime1: {TicksToTime(CurTime)}, Asked: {askedFrame}\");\n vFrame = VideoDecoder.GetFrame(askedFrame);\n if (vFrame == null) return;\n\n int recvFrame = VideoDecoder.GetFrameNumber(vFrame.timestamp);\n //Log.Debug($\"CurTime2: {TicksToTime(vFrame.timestamp)}, Got: {recvFrame}\");\n if (askedFrame != recvFrame)\n {\n VideoDecoder.DisposeFrame(vFrame);\n vFrame = null;\n vFrame = askedFrame > recvFrame\n ? VideoDecoder.GetFrame(VideoDecoder.GetFrameNumber(CurTime))\n : VideoDecoder.GetFrame(VideoDecoder.GetFrameNumber(CurTime) - 2);\n }\n }\n else\n VideoDecoder.Frames.TryDequeue(out vFrame);\n\n if (vFrame == null)\n return;\n\n if (CanDebug) Log.Debug($\"SFB: {VideoDecoder.GetFrameNumber(vFrame.timestamp)}\");\n\n curTime = vFrame.timestamp;\n renderer.Present(vFrame);\n vFrame = null;\n UI(() => UpdateCurTime()); // For some strange reason this will not be updated on KeyDown (only on KeyUp) which doesn't happen on ShowFrameNext (GPU overload? / Thread.Sleep underlying in UI thread?)\n }\n }\n\n public void SpeedUp() => Speed += Config.Player.SpeedOffset;\n public void SpeedUp2() => Speed += Config.Player.SpeedOffset2;\n public void SpeedDown() => Speed -= Config.Player.SpeedOffset;\n public void SpeedDown2() => Speed -= Config.Player.SpeedOffset2;\n\n public void RotateRight() => renderer.Rotation = (renderer.Rotation + 90) % 360;\n public void RotateLeft() => renderer.Rotation = renderer.Rotation < 90 ? 360 + renderer.Rotation - 90 : renderer.Rotation - 90;\n\n public void FullScreen() => Host?.Player_SetFullScreen(true);\n public void NormalScreen() => Host?.Player_SetFullScreen(false);\n public void ToggleFullScreen()\n {\n if (Host == null)\n return;\n\n if (Host.Player_GetFullScreen())\n Host.Player_SetFullScreen(false);\n else\n Host.Player_SetFullScreen(true);\n }\n\n /// \n /// Starts recording (uses Config.Player.FolderRecordings and default filename title_curTime)\n /// \n public void StartRecording()\n {\n if (!CanPlay)\n return;\n try\n {\n if (!Directory.Exists(Config.Player.FolderRecordings))\n Directory.CreateDirectory(Config.Player.FolderRecordings);\n\n string filename = GetValidFileName(string.IsNullOrEmpty(Playlist.Selected.Title) ? \"Record\" : Playlist.Selected.Title) + $\"_{new TimeSpan(CurTime):hhmmss}.\" + decoder.Extension;\n filename = FindNextAvailableFile(Path.Combine(Config.Player.FolderRecordings, filename));\n StartRecording(ref filename, false);\n } catch { }\n }\n\n /// \n /// Starts recording\n /// \n /// Path of the new recording file\n /// You can force the output container's format or use the recommended one to avoid incompatibility\n public void StartRecording(ref string filename, bool useRecommendedExtension = true)\n {\n if (!CanPlay)\n return;\n\n OSDMessage = $\"Start recording to {Path.GetFileName(filename)}\";\n decoder.StartRecording(ref filename, useRecommendedExtension);\n IsRecording = decoder.IsRecording;\n }\n\n /// \n /// Stops recording\n /// \n public void StopRecording()\n {\n decoder.StopRecording();\n IsRecording = decoder.IsRecording;\n OSDMessage = \"Stop recording\";\n }\n public void ToggleRecording()\n {\n if (!CanPlay) return;\n\n if (IsRecording)\n StopRecording();\n else\n StartRecording();\n }\n\n /// \n /// Saves the current video frame (encoding based on file extention .bmp, .png, .jpg)\n /// If filename not specified will use Config.Player.FolderSnapshots and with default filename title_frameNumber.ext (ext from Config.Player.SnapshotFormat)\n /// If width/height not specified will use the original size. If one of them will be set, the other one will be set based on original ratio\n /// If frame not specified will use the current/last frame\n /// \n /// Specify the filename (null: will use Config.Player.FolderSnapshots and with default filename title_frameNumber.ext (ext from Config.Player.SnapshotFormat)\n /// Specify the width (-1: will keep the ratio based on height)\n /// Specify the height (-1: will keep the ratio based on width)\n /// Specify the frame (null: will use the current/last frame)\n /// \n public void TakeSnapshotToFile(string filename = null, int width = -1, int height = -1, VideoFrame frame = null)\n {\n if (!CanPlay)\n return;\n\n if (filename == null)\n {\n try\n {\n if (!Directory.Exists(Config.Player.FolderSnapshots))\n Directory.CreateDirectory(Config.Player.FolderSnapshots);\n\n // TBR: if frame is specified we don't know the frame's number\n filename = GetValidFileName(string.IsNullOrEmpty(Playlist.Selected.Title) ? \"Snapshot\" : Playlist.Selected.Title) + $\"_{(frame == null ? VideoDecoder.GetFrameNumber(CurTime).ToString() : \"X\")}.{Config.Player.SnapshotFormat}\";\n filename = FindNextAvailableFile(Path.Combine(Config.Player.FolderSnapshots, filename));\n } catch { return; }\n }\n\n string ext = GetUrlExtention(filename);\n\n ImageFormat imageFormat;\n\n switch (ext)\n {\n case \"bmp\":\n imageFormat = ImageFormat.Bmp;\n break;\n\n case \"png\":\n imageFormat = ImageFormat.Png;\n break;\n\n case \"jpg\":\n case \"jpeg\":\n imageFormat = ImageFormat.Jpeg;\n break;\n\n default:\n throw new Exception($\"Invalid snapshot extention '{ext}' (valid .bmp, .png, .jpeg, .jpg\");\n }\n\n if (renderer == null)\n return;\n\n var snapshotBitmap = renderer.GetBitmap(width, height, frame);\n if (snapshotBitmap == null)\n return;\n\n Exception e = null;\n try\n {\n snapshotBitmap.Save(filename, imageFormat);\n\n UI(() =>\n {\n OSDMessage = $\"Save snapshot to {Path.GetFileName(filename)}\";\n });\n }\n catch (Exception e2)\n {\n e = e2;\n }\n snapshotBitmap.Dispose();\n\n if (e != null)\n throw e;\n }\n\n /// \n /// Returns a bitmap of the current or specified video frame\n /// If width/height not specified will use the original size. If one of them will be set, the other one will be set based on original ratio\n /// If frame not specified will use the current/last frame\n /// \n /// Specify the width (-1: will keep the ratio based on height)\n /// Specify the height (-1: will keep the ratio based on width)\n /// Specify the frame (null: will use the current/last frame)\n /// \n public System.Drawing.Bitmap TakeSnapshotToBitmap(int width = -1, int height = -1, VideoFrame frame = null) => renderer?.GetBitmap(width, height, frame);\n\n public void ZoomIn() => Zoom += Config.Player.ZoomOffset;\n public void ZoomOut() { if (Zoom - Config.Player.ZoomOffset < 1) return; Zoom -= Config.Player.ZoomOffset; }\n\n /// \n /// Pan zoom in with center point\n /// \n /// \n public void ZoomIn(Point p) { renderer.ZoomWithCenterPoint(p, renderer.Zoom + Config.Player.ZoomOffset / 100.0); RaiseUI(nameof(Zoom)); }\n\n /// \n /// Pan zoom out with center point\n /// \n /// \n public void ZoomOut(Point p){ double zoom = renderer.Zoom - Config.Player.ZoomOffset / 100.0; if (zoom < 0.001) return; renderer.ZoomWithCenterPoint(p, zoom); RaiseUI(nameof(Zoom)); }\n\n /// \n /// Pan zoom (no raise)\n /// \n /// \n public void SetZoom(double zoom) => renderer.SetZoom(zoom);\n /// \n /// Pan zoom's center point (no raise, no center point change)\n /// \n /// \n public void SetZoomCenter(Point p) => renderer.SetZoomCenter(p);\n /// \n /// Pan zoom and center point (no raise)\n /// \n /// \n /// \n public void SetZoomAndCenter(double zoom, Point p) => renderer.SetZoomAndCenter(zoom, p);\n\n public void ResetAll()\n {\n ResetSpeed();\n ResetRotation();\n ResetZoom();\n }\n\n public void ResetSpeed()\n {\n Speed = 1;\n }\n\n public void ResetRotation()\n {\n Rotation = 0;\n }\n\n public void ResetZoom()\n {\n bool npx = renderer.PanXOffset != 0;\n bool npy = renderer.PanYOffset != 0;\n bool npz = renderer.Zoom != 1;\n renderer.SetPanAll(0, 0, Rotation, 1, Renderer.ZoomCenterPoint, true); // Pan X/Y, Rotation, Zoom, Zoomcenter, Refresh\n\n UI(() =>\n {\n if (npx) Raise(nameof(PanXOffset));\n if (npy) Raise(nameof(PanYOffset));\n if (npz) Raise(nameof(Zoom));\n });\n }\n}\n"], ["/LLPlayer/FlyleafLib/MediaPlayer/SubtitlesManager.cs", "using System.Collections.Generic;\nusing System.Collections.ObjectModel;\nusing System.Collections.Specialized;\nusing System.ComponentModel;\nusing System.Diagnostics;\nusing System.Linq;\nusing System.Runtime.CompilerServices;\nusing System.Runtime.InteropServices;\nusing System.Threading;\nusing System.Windows;\nusing System.Windows.Data;\nusing System.Windows.Media;\nusing System.Windows.Media.Imaging;\nusing FlyleafLib.MediaFramework.MediaDecoder;\nusing FlyleafLib.MediaFramework.MediaDemuxer;\nusing FlyleafLib.MediaFramework.MediaFrame;\nusing FlyleafLib.MediaFramework.MediaRenderer;\nusing FlyleafLib.MediaFramework.MediaStream;\nusing FlyleafLib.MediaPlayer.Translation;\nusing static FlyleafLib.Logger;\n\nnamespace FlyleafLib.MediaPlayer;\n\n#nullable enable\n\npublic class SubtitlesManager\n{\n private readonly SubManager[] _subManagers;\n public SubManager this[int subIndex] => _subManagers[subIndex];\n private readonly int _subNum;\n\n public SubtitlesManager(Config config, int subNum)\n {\n _subNum = subNum;\n _subManagers = new SubManager[subNum];\n for (int i = 0; i < subNum; i++)\n {\n _subManagers[i] = new SubManager(config, i);\n }\n }\n\n /// \n /// Open a file and read all subtitle data by streaming\n /// \n /// 0: Primary, 1: Secondary\n /// subtitle file path or video file path\n /// streamIndex of subtitle\n /// demuxer media type\n /// Use bitmap subtitles or immediately release bitmap if not used\n /// subtitle language\n public void Open(int subIndex, string url, int streamIndex, MediaType type, bool useBitmap, Language lang)\n {\n // TODO: L: Add caching subtitle data for the same stream and URL?\n this[subIndex].Open(url, streamIndex, type, useBitmap, lang);\n }\n\n public void SetCurrentTime(TimeSpan currentTime)\n {\n for (int i = 0; i < _subNum; i++)\n {\n this[i].SetCurrentTime(currentTime);\n }\n }\n}\n\npublic class SubManager : INotifyPropertyChanged\n{\n private readonly Lock _locker = new();\n private CancellationTokenSource? _cts;\n public SubtitleData? SelectedSub { get; set => Set(ref field, value); }\n public int CurrentIndex { get; private set => Set(ref field, value); } = -1;\n\n public PositionState State\n {\n get;\n private set\n {\n bool prevIsDisplaying = IsDisplaying;\n if (Set(ref field, value) && prevIsDisplaying != IsDisplaying)\n {\n OnPropertyChanged(nameof(IsDisplaying));\n }\n }\n } = PositionState.First;\n\n public bool IsDisplaying => State == PositionState.Showing;\n\n /// \n /// List of subtitles that can be bound to ItemsControl\n /// Must be sorted with timestamp to perform binary search.\n /// \n public BulkObservableCollection Subs { get; } = new();\n\n /// \n /// True when addition to Subs is running... (Reading all subtitles, OCR, ASR)\n /// \n public bool IsLoading { get; private set => Set(ref field, value); }\n\n // LanguageSource with fallback\n public Language? Language\n {\n get\n {\n if (LanguageSource == Language.Unknown)\n {\n // fallback to user set language\n return _subIndex == 0 ? _config.Subtitles.LanguageFallbackPrimary : _config.Subtitles.LanguageFallbackSecondary;\n }\n\n return LanguageSource;\n }\n }\n\n public Language? LanguageSource\n {\n get;\n set\n {\n if (Set(ref field, value))\n {\n OnPropertyChanged(nameof(Language));\n }\n }\n }\n\n // For displaying bitmap subtitles, manage video width and height\n public int Width { get; internal set; }\n public int Height { get; internal set; }\n\n private readonly object _subsLocker = new();\n private readonly Config _config;\n private readonly int _subIndex;\n private readonly SubTranslator _subTranslator;\n private readonly LogHandler Log;\n\n public SubManager(Config config, int subIndex, bool enableSync = true)\n {\n _config = config;\n _subIndex = subIndex;\n // TODO: L: Review whether to initialize it here.\n _subTranslator = new SubTranslator(this, config.Subtitles, subIndex);\n Log = new LogHandler((\"[#1]\").PadRight(8, ' ') + $\" [SubManager{subIndex + 1} ] \");\n\n if (enableSync)\n {\n // Enable binding to ItemsControl\n Utils.UIInvokeIfRequired(() =>\n {\n BindingOperations.EnableCollectionSynchronization(Subs, _subsLocker);\n });\n }\n }\n\n public enum PositionState\n {\n First, // still haven't reached the first subtitle\n Showing, // currently displaying\n Around, // not displayed and can seek before and after\n Last // After the last subtitle\n }\n\n /// \n /// Force UI refresh\n /// \n internal void Refresh()\n {\n // NOTE: If it is not executed in the main thread, the following error occurs.\n // System.NotSupportedException: 'This type of CollectionView does not support'\n Utils.UI(() =>\n {\n CollectionViewSource.GetDefaultView(Subs).Refresh();\n OnPropertyChanged(nameof(CurrentIndex)); // required for translating current sub\n });\n }\n\n /// \n /// This must be called when doing heavy operation\n /// \n /// \n internal IDisposable StartLoading()\n {\n IsLoading = true;\n\n return Disposable.Create(() =>\n {\n IsLoading = false;\n });\n }\n\n public void Load(IEnumerable items)\n {\n lock (_subsLocker)\n {\n CurrentIndex = -1;\n SelectedSub = null;\n Subs.Clear();\n Subs.AddRange(items);\n }\n }\n\n public void Add(SubtitleData sub)\n {\n lock (_subsLocker)\n {\n sub.Index = Subs.Count;\n Subs.Add(sub);\n }\n }\n\n public void AddRange(IEnumerable items)\n {\n lock (_subsLocker)\n {\n Subs.AddRange(items);\n }\n }\n\n public SubtitleData? GetCurrent()\n {\n lock (_subsLocker)\n {\n if (Subs.Count == 0 || CurrentIndex == -1)\n {\n return null;\n }\n\n Debug.Assert(CurrentIndex < Subs.Count);\n\n if (State == PositionState.Showing)\n {\n return Subs[CurrentIndex];\n }\n\n return null;\n }\n }\n\n public SubtitleData? GetNext()\n {\n lock (_subsLocker)\n {\n if (Subs.Count == 0)\n {\n return null;\n }\n\n switch (State)\n {\n case PositionState.First:\n return Subs[0];\n\n case PositionState.Showing:\n if (CurrentIndex < Subs.Count - 1)\n return Subs[CurrentIndex + 1];\n break;\n\n case PositionState.Around:\n if (CurrentIndex < Subs.Count - 1)\n return Subs[CurrentIndex + 1];\n break;\n }\n\n return null;\n }\n }\n\n public SubtitleData? GetPrev()\n {\n lock (_subsLocker)\n {\n if (Subs.Count == 0 || CurrentIndex == -1)\n return null;\n\n switch (State)\n {\n case PositionState.Showing:\n if (CurrentIndex > 0)\n return Subs[CurrentIndex - 1];\n break;\n\n case PositionState.Around:\n if (CurrentIndex >= 0)\n return Subs[CurrentIndex];\n break;\n\n case PositionState.Last:\n return Subs[^1];\n }\n }\n\n return null;\n }\n\n private readonly SubtitleData _searchSub = new();\n\n public SubManager SetCurrentTime(TimeSpan currentTime)\n {\n // Adjust the display timing of subtitles by adjusting the timestamp of the video\n currentTime = currentTime.Subtract(new TimeSpan(_config.Subtitles[_subIndex].Delay));\n\n lock (_subsLocker)\n {\n // If no subtitle data is loaded, nothing is done.\n if (Subs.Count == 0)\n return this;\n\n // If it is a subtitle that is displaying, it does nothing.\n var curSub = GetCurrent();\n if (curSub != null && curSub.StartTime < currentTime && curSub.EndTime > currentTime)\n {\n return this;\n }\n\n _searchSub.StartTime = currentTime;\n\n int ret = Subs.BinarySearch(_searchSub, SubtitleTimeStartComparer.Instance);\n int cur = -1;\n\n if (~ret == 0)\n {\n CurrentIndex = -1;\n SelectedSub = null;\n State = PositionState.First;\n return this;\n }\n\n if (ret < 0)\n {\n // The reason subtracting 1 is that the result of the binary search is the next big index.\n cur = (~ret) - 1;\n }\n else\n {\n // If the starting position is matched, it is unlikely\n cur = ret;\n }\n\n Debug.Assert(cur >= 0, \"negative index detected\");\n Debug.Assert(cur < Subs.Count, \"out of bounds detected\");\n\n if (cur == Subs.Count - 1)\n {\n if (Subs[cur].EndTime < currentTime)\n {\n CurrentIndex = cur;\n SelectedSub = Subs[cur];\n State = PositionState.Last;\n }\n else\n {\n CurrentIndex = cur;\n SelectedSub = Subs[cur];\n State = PositionState.Showing;\n }\n }\n else\n {\n if (Subs[cur].StartTime <= currentTime && Subs[cur].EndTime >= currentTime)\n {\n // Show subtitles\n CurrentIndex = cur;\n SelectedSub = Subs[cur];\n State = PositionState.Showing;\n }\n else if (Subs[cur].StartTime <= currentTime)\n {\n // Almost there to display in currentIndex.\n CurrentIndex = cur;\n SelectedSub = Subs[cur];\n State = PositionState.Around;\n }\n }\n }\n\n return this;\n }\n\n public void Sort()\n {\n lock (_subsLocker)\n {\n if (Subs.Count == 0)\n return;\n\n Subs.Sort(SubtitleTimeStartComparer.Instance);\n }\n }\n\n public void DeleteAfter(TimeSpan time)\n {\n lock (_subsLocker)\n {\n if (Subs.Count == 0)\n return;\n\n int index = Subs.BinarySearch(new SubtitleData { EndTime = time }, new SubtitleTimeEndComparer());\n\n if (index < 0)\n {\n index = ~index;\n }\n\n if (index < Subs.Count)\n {\n var newSubs = Subs.GetRange(0, index).ToList();\n var deleteSubs = Subs.GetRange(index, Subs.Count - index).ToList();\n Load(newSubs);\n\n foreach (var sub in deleteSubs)\n {\n sub.Dispose();\n }\n }\n }\n }\n\n public void Open(string url, int streamIndex, MediaType type, bool useBitmap, Language lang)\n {\n // Asynchronously read subtitle timestamps and text\n\n // Cancel if already executed\n TryCancelWait();\n\n lock (_locker)\n {\n using var loading = StartLoading();\n\n List subChunk = new();\n\n try\n {\n _cts = new CancellationTokenSource();\n using SubtitleReader reader = new(this, _config, _subIndex);\n reader.Open(url, streamIndex, type, _cts.Token);\n\n _cts.Token.ThrowIfCancellationRequested();\n\n bool isFirst = true;\n int subCnt = 0;\n\n Stopwatch refreshSw = new();\n refreshSw.Start();\n\n reader.ReadAll(useBitmap, data =>\n {\n if (isFirst)\n {\n isFirst = false;\n // Set the language at the timing of the first subtitle data set.\n LanguageSource = lang;\n\n Log.Info($\"Start loading subs... (lang:{lang.TopEnglishName})\");\n }\n\n data.Index = subCnt++;\n subChunk.Add(data);\n\n // Large files and network files take time to load to the end.\n // To prevent frequent UI updates, use AddRange to group files to some extent before adding them.\n if (subChunk.Count >= 2 && refreshSw.Elapsed > TimeSpan.FromMilliseconds(500))\n {\n AddRange(subChunk);\n subChunk.Clear();\n refreshSw.Restart();\n }\n }, _cts.Token);\n\n // Process remaining\n if (subChunk.Count > 0)\n {\n AddRange(subChunk);\n }\n refreshSw.Stop();\n Log.Info(\"End loading subs\");\n }\n catch (OperationCanceledException)\n {\n foreach (var sub in subChunk)\n {\n sub.Dispose();\n }\n\n Clear();\n }\n }\n }\n\n public void TryCancelWait()\n {\n if (_cts != null)\n {\n // If it has already been executed, cancel it and wait until the preceding process is finished.\n // (It waits because it has a lock)\n _cts.Cancel();\n lock (_locker)\n {\n // dispose after it is no longer used.\n _cts.Dispose();\n _cts = null;\n }\n }\n }\n\n public void Clear()\n {\n lock (_subsLocker)\n {\n CurrentIndex = -1;\n SelectedSub = null;\n foreach (var sub in Subs)\n {\n sub.Dispose();\n }\n Subs.Clear();\n State = PositionState.First;\n LanguageSource = null;\n IsLoading = false;\n Width = 0;\n Height = 0;\n }\n }\n\n public void Reset()\n {\n TryCancelWait();\n Clear();\n }\n\n #region INotifyPropertyChanged\n public event PropertyChangedEventHandler? PropertyChanged;\n\n protected virtual void OnPropertyChanged([CallerMemberName] string? propertyName = null)\n {\n PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));\n }\n\n protected bool Set(ref T field, T value, [CallerMemberName] string? propertyName = null)\n {\n if (EqualityComparer.Default.Equals(field, value))\n return false;\n field = value;\n OnPropertyChanged(propertyName);\n return true;\n }\n #endregion\n}\n\npublic unsafe class SubtitleReader : IDisposable\n{\n private readonly SubManager _manager;\n private readonly Config _config;\n private readonly LogHandler Log;\n private readonly int _subIndex;\n\n private Demuxer? _demuxer;\n private SubtitlesDecoder? _decoder;\n private SubtitlesStream? _stream;\n\n private AVPacket* _packet = null;\n\n public SubtitleReader(SubManager manager, Config config, int subIndex)\n {\n _manager = manager;\n _config = config;\n Log = new LogHandler((\"[#1]\").PadRight(8, ' ') + $\" [SubReader{subIndex + 1} ] \");\n\n _subIndex = subIndex;\n }\n\n public void Open(string url, int streamIndex, MediaType type, CancellationToken token)\n {\n _demuxer = new Demuxer(_config.Demuxer, type, _subIndex + 1, false);\n\n token.Register(() =>\n {\n if (_demuxer != null)\n _demuxer.Interrupter.ForceInterrupt = 1;\n });\n\n _demuxer.Log.Prefix = _demuxer.Log.Prefix.Replace(\"Demuxer: \", \"DemuxerS:\");\n string? error = _demuxer.Open(url);\n\n if (error != null)\n {\n token.ThrowIfCancellationRequested(); // if canceled\n\n throw new InvalidOperationException($\"demuxer open error: {error}\");\n }\n\n _stream = (SubtitlesStream)_demuxer.AVStreamToStream[streamIndex];\n\n if (type == MediaType.Subs)\n {\n\n _stream.ExternalStream = new ExternalSubtitlesStream()\n {\n Url = url,\n IsBitmap = _stream.IsBitmap\n };\n\n _stream.ExternalStreamAdded();\n }\n\n _decoder = new SubtitlesDecoder(_config, _subIndex + 1);\n _decoder.Log.Prefix = _decoder.Log.Prefix.Replace(\"Decoder: \", \"DecoderS:\");\n error = _decoder.Open(_stream);\n\n if (error != null)\n {\n token.ThrowIfCancellationRequested(); // if canceled\n\n throw new InvalidOperationException($\"decoder open error: {error}\");\n }\n }\n\n /// \n /// Read subtitle stream to the end and get all subtitle data\n /// \n /// \n /// \n /// \n /// The token has had cancellation requested.\n public void ReadAll(bool useBitmap, Action addSub, CancellationToken token)\n {\n if (_demuxer == null || _decoder == null || _stream == null)\n throw new InvalidOperationException(\"Open() is not called\");\n\n SubtitleData? prevSub = null;\n\n _packet = av_packet_alloc();\n\n int demuxErrors = 0;\n int decodeErrors = 0;\n\n while (!token.IsCancellationRequested)\n {\n _demuxer.Interrupter.ReadRequest();\n int ret = av_read_frame(_demuxer.fmtCtx, _packet);\n\n if (ret != 0)\n {\n av_packet_unref(_packet);\n\n if (_demuxer.Interrupter.Timedout)\n {\n if (token.IsCancellationRequested)\n break;\n\n ret.ThrowExceptionIfError(\"av_read_frame (timed out)\");\n }\n\n if (ret == AVERROR_EOF || token.IsCancellationRequested)\n {\n break;\n }\n\n // demux error\n if (CanWarn) Log.Warn($\"av_read_frame: {FFmpegEngine.ErrorCodeToMsg(ret)} ({ret})\");\n\n if (++demuxErrors == _config.Demuxer.MaxErrors)\n {\n ret.ThrowExceptionIfError(\"av_read_frame\");\n }\n\n continue;\n }\n\n // Discard all but the subtitle stream.\n if (_packet->stream_index != _stream.StreamIndex)\n {\n av_packet_unref(_packet);\n continue;\n }\n\n SubtitleData subData = new();\n int gotSub = 0;\n AVSubtitle sub = default;\n\n ret = avcodec_decode_subtitle2(_decoder.CodecCtx, &sub, &gotSub, _packet);\n if (ret < 0)\n {\n // decode error\n av_packet_unref(_packet);\n if (CanWarn) Log.Warn($\"avcodec_decode_subtitle2: {FFmpegEngine.ErrorCodeToMsg(ret)} ({ret})\");\n if (++decodeErrors == _config.Decoder.MaxErrors)\n {\n ret.ThrowExceptionIfError(\"avcodec_decode_subtitle2\");\n }\n\n continue;\n }\n\n if (gotSub == 0)\n {\n av_packet_unref(_packet);\n continue;\n }\n\n long pts = AV_NOPTS_VALUE; // 0.1us\n if (sub.pts != AV_NOPTS_VALUE)\n {\n pts = sub.pts /*us*/ * 10;\n }\n else if (_packet->pts != AV_NOPTS_VALUE)\n {\n pts = (long)(_packet->pts * _stream.Timebase);\n }\n\n av_packet_unref(_packet);\n\n if (pts == AV_NOPTS_VALUE)\n {\n continue;\n }\n\n if (_stream.IsBitmap)\n {\n // Cache the width and height of the video for use in displaying bitmap subtitles\n // width and height may be 0 unless after decoding the subtitles\n // In this case, bitmap subtitles cannot be displayed correctly, so the size should be cached here\n if (_manager.Width != _decoder.CodecCtx->width)\n _manager.Width = _decoder.CodecCtx->width;\n if (_manager.Height != _decoder.CodecCtx->height)\n _manager.Height = _decoder.CodecCtx->height;\n }\n\n // Bitmap PGS has a special format.\n if (_stream.IsBitmap && prevSub != null\n /*&& _stream->codecpar->codec_id == AVCodecID.AV_CODEC_ID_HDMV_PGS_SUBTITLE*/)\n {\n if (sub.num_rects < 1)\n {\n // Support for special format bitmap subtitles.\n // In the case of bitmap subtitles, num_rects = 0 and 1 may alternate.\n // In this case sub->start_display_time and sub->end_display_time are always fixed at 0 and\n // AVPacket->duration is also always 0.\n // This indicates the end of the previous subtitle, and the time in pts is the end time of the previous subtitle.\n\n // Note that not all bitmap subtitles have this behavior.\n\n // Assign pts as the end time of the previous subtitle\n prevSub.EndTime = new TimeSpan(pts - _demuxer.StartTime);\n addSub(prevSub);\n prevSub = null;\n\n avsubtitle_free(&sub);\n continue;\n }\n\n // There are cases where num_rects = 1 is consecutive.\n // In this case, the previous subtitle end time is corrected by pts, and a new subtitle is started with the same pts.\n if (prevSub.Bitmap?.Sub.end_display_time == uint.MaxValue) // 4294967295\n {\n prevSub.EndTime = new TimeSpan(pts - _demuxer.StartTime);\n addSub(prevSub);\n prevSub = null;\n }\n }\n\n subData.StartTime = new TimeSpan(pts - _demuxer.StartTime);\n subData.EndTime = subData.StartTime.Add(TimeSpan.FromMilliseconds(sub.end_display_time));\n\n switch (sub.rects[0]->type)\n {\n case AVSubtitleType.Text:\n subData.Text = Utils.BytePtrToStringUTF8(sub.rects[0]->text).Trim();\n avsubtitle_free(&sub);\n\n if (string.IsNullOrEmpty(subData.Text))\n {\n continue;\n }\n\n break;\n case AVSubtitleType.Ass:\n string text = Utils.BytePtrToStringUTF8(sub.rects[0]->ass).Trim();\n avsubtitle_free(&sub);\n\n subData.Text = ParseSubtitles.SSAtoSubStyles(text, out var subStyles).Trim();\n subData.SubStyles = subStyles;\n\n if (string.IsNullOrEmpty(subData.Text))\n {\n continue;\n }\n\n break;\n\n case AVSubtitleType.Bitmap:\n subData.IsBitmap = true;\n\n if (useBitmap)\n {\n // Save subtitle data for (OCR or subtitle cache)\n subData.Bitmap = new SubtitleBitmapData(sub);\n }\n else\n {\n // Only subtitle timestamp information is used, so bitmap is released\n avsubtitle_free(&sub);\n }\n\n break;\n }\n\n if (prevSub != null)\n {\n addSub(prevSub);\n }\n\n prevSub = subData;\n }\n\n if (token.IsCancellationRequested)\n {\n prevSub?.Dispose();\n token.ThrowIfCancellationRequested();\n }\n\n // Process last\n if (prevSub != null)\n {\n addSub(prevSub);\n }\n }\n\n private bool _isDisposed;\n public void Dispose()\n {\n if (_isDisposed)\n return;\n\n // av_packet_alloc\n if (_packet != null)\n {\n fixed (AVPacket** ptr = &_packet)\n {\n av_packet_free(ptr);\n }\n }\n\n _decoder?.Dispose();\n if (_demuxer != null)\n {\n _demuxer.Interrupter.ForceInterrupt = 0;\n _demuxer.Dispose();\n }\n\n _isDisposed = true;\n }\n}\n\npublic class SubtitleBitmapData : IDisposable\n{\n public SubtitleBitmapData(AVSubtitle sub)\n {\n Sub = sub;\n }\n\n private readonly ReaderWriterLockSlim _rwLock = new();\n private bool _isDisposed;\n\n public AVSubtitle Sub;\n\n public WriteableBitmap SubToWritableBitmap(bool isGrey)\n {\n (byte[] data, AVSubtitleRect rect) = SubToBitmap(isGrey);\n\n WriteableBitmap wb = new(\n rect.w, rect.h,\n Utils.NativeMethods.DpiXSource, Utils.NativeMethods.DpiYSource,\n PixelFormats.Bgra32, null\n );\n Int32Rect dirtyRect = new(0, 0, rect.w, rect.h);\n wb.Lock();\n\n Marshal.Copy(data, 0, wb.BackBuffer, data.Length);\n\n wb.AddDirtyRect(dirtyRect);\n wb.Unlock();\n wb.Freeze();\n\n return wb;\n }\n\n public unsafe (byte[] data, AVSubtitleRect rect) SubToBitmap(bool isGrey)\n {\n if (_isDisposed)\n throw new InvalidOperationException(\"already disposed\");\n\n try\n {\n // Prevent from disposing\n _rwLock.EnterReadLock();\n\n AVSubtitleRect rect = *Sub.rects[0];\n byte[] data = Renderer.ConvertBitmapSub(Sub, isGrey);\n\n return (data, rect);\n }\n finally\n {\n _rwLock.ExitReadLock();\n }\n }\n\n public void Dispose()\n {\n if (_isDisposed)\n return;\n\n _rwLock.EnterWriteLock();\n\n if (Sub.num_rects > 0)\n {\n unsafe\n {\n fixed (AVSubtitle* subPtr = &Sub)\n {\n avsubtitle_free(subPtr);\n }\n }\n }\n\n _isDisposed = true;\n _rwLock.ExitWriteLock();\n\n#if DEBUG\n GC.SuppressFinalize(this);\n#endif\n }\n\n#if DEBUG\n ~SubtitleBitmapData()\n {\n System.Diagnostics.Debug.Fail(\"Dispose is not called\");\n }\n#endif\n}\n\npublic class SubtitleData : IDisposable, INotifyPropertyChanged\n{\n public int Index { get; set; }\n\n public string? Text\n {\n get;\n set\n {\n var prevIsText = IsText;\n if (Set(ref field, value))\n {\n if (prevIsText != IsText)\n OnPropertyChanged(nameof(IsText));\n OnPropertyChanged(nameof(DisplayText));\n }\n }\n }\n\n public string? TranslatedText\n {\n get;\n set\n {\n var prevUseTranslated = UseTranslated;\n if (Set(ref field, value))\n {\n if (prevUseTranslated != UseTranslated)\n {\n OnPropertyChanged(nameof(UseTranslated));\n }\n OnPropertyChanged(nameof(DisplayText));\n }\n }\n }\n\n public bool IsText => !string.IsNullOrEmpty(Text);\n\n public bool IsTranslated => TranslatedText != null;\n public bool UseTranslated => EnabledTranslated && IsTranslated;\n\n public bool EnabledTranslated = true;\n\n public string? DisplayText => UseTranslated ? TranslatedText : Text;\n\n public List? SubStyles;\n public TimeSpan StartTime { get; set; }\n public TimeSpan EndTime { get; set; }\n#if DEBUG\n public int ChunkNo { get; set => Set(ref field, value); }\n public TimeSpan StartTimeChunk { get; set => Set(ref field, value); }\n public TimeSpan EndTimeChunk { get; set => Set(ref field, value); }\n#endif\n public TimeSpan Duration => EndTime - StartTime;\n\n public SubtitleBitmapData? Bitmap { get; set; }\n\n public bool IsBitmap { get; set; }\n\n private bool _isDisposed;\n\n public void Dispose()\n {\n if (_isDisposed)\n return;\n\n if (IsBitmap && Bitmap != null)\n {\n Bitmap.Dispose();\n Bitmap = null;\n }\n\n _isDisposed = true;\n }\n\n public SubtitleData Clone()\n {\n return new SubtitleData()\n {\n Index = Index,\n Text = Text,\n TranslatedText = TranslatedText,\n EnabledTranslated = EnabledTranslated,\n StartTime = StartTime,\n EndTime = EndTime,\n#if DEBUG\n ChunkNo = ChunkNo,\n StartTimeChunk = StartTimeChunk,\n EndTimeChunk = EndTimeChunk,\n#endif\n IsBitmap = IsBitmap,\n Bitmap = null,\n };\n }\n\n #region INotifyPropertyChanged\n public event PropertyChangedEventHandler? PropertyChanged;\n protected virtual void OnPropertyChanged([CallerMemberName] string? propertyName = null)\n {\n PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));\n }\n\n protected bool Set(ref T field, T value, [CallerMemberName] string? propertyName = null)\n {\n if (EqualityComparer.Default.Equals(field, value))\n return false;\n field = value;\n OnPropertyChanged(propertyName);\n return true;\n }\n #endregion\n}\n\npublic class SubtitleTimeStartComparer : Comparer\n{\n public static SubtitleTimeStartComparer Instance { get; } = new();\n private SubtitleTimeStartComparer() { }\n static SubtitleTimeStartComparer() { }\n\n public override int Compare(SubtitleData? x, SubtitleData? y)\n {\n if (object.Equals(x, y)) return 0;\n if (x == null) return -1;\n if (y == null) return 1;\n\n return x.StartTime.CompareTo(y.StartTime);\n }\n}\n\npublic class SubtitleTimeEndComparer : Comparer\n{\n public override int Compare(SubtitleData? x, SubtitleData? y)\n {\n if (object.Equals(x, y)) return 0;\n if (x == null) return -1;\n if (y == null) return 1;\n\n return x.EndTime.CompareTo(y.EndTime);\n }\n}\n\ninternal static class WrapperHelper\n{\n public static int ThrowExceptionIfError(this int error, string message)\n {\n if (error < 0)\n {\n string errStr = AvErrorStr(error);\n throw new InvalidOperationException($\"{message}: {errStr} ({error})\");\n }\n\n return error;\n }\n\n public static unsafe string AvErrorStr(this int error)\n {\n int bufSize = 1024;\n byte* buf = stackalloc byte[bufSize];\n\n if (av_strerror(error, buf, (nuint)bufSize) == 0)\n {\n string errStr = Marshal.PtrToStringAnsi((IntPtr)buf)!;\n return errStr;\n }\n\n return \"unknown error\";\n }\n}\n\npublic static class ObservableCollectionExtensions\n{\n public static int FindIndex(this ObservableCollection collection, Predicate match)\n {\n ArgumentNullException.ThrowIfNull(collection);\n ArgumentNullException.ThrowIfNull(match);\n\n for (int i = 0; i < collection.Count; i++)\n {\n if (match(collection[i]))\n return i;\n }\n return -1;\n }\n\n public static int BinarySearch(this ObservableCollection collection, T item, IComparer comparer)\n {\n ArgumentNullException.ThrowIfNull(collection);\n\n //comparer ??= Comparer.Default;\n int low = 0;\n int high = collection.Count - 1;\n\n while (low <= high)\n {\n int mid = low + ((high - low) / 2);\n int comparison = comparer.Compare(collection[mid], item);\n\n if (comparison == 0)\n return mid;\n if (comparison < 0)\n low = mid + 1;\n else\n high = mid - 1;\n }\n\n return ~low;\n }\n\n public static IEnumerable GetRange(this ObservableCollection collection, int index, int count)\n {\n ArgumentNullException.ThrowIfNull(collection);\n if (index < 0 || count < 0 || (index + count) > collection.Count)\n throw new ArgumentOutOfRangeException();\n\n return collection.Skip(index).Take(count);\n }\n\n public static void Sort(this ObservableCollection collection, IComparer comparer)\n {\n ArgumentNullException.ThrowIfNull(collection);\n ArgumentNullException.ThrowIfNull(comparer);\n\n List sortedList = collection.ToList();\n sortedList.Sort(comparer);\n\n collection.Clear();\n foreach (var item in sortedList)\n {\n collection.Add(item);\n }\n }\n}\n\npublic class BulkObservableCollection : ObservableCollection\n{\n private bool _suppressNotification;\n\n protected override void OnCollectionChanged(NotifyCollectionChangedEventArgs e)\n {\n if (!_suppressNotification)\n base.OnCollectionChanged(e);\n }\n\n public void AddRange(IEnumerable list)\n {\n ArgumentNullException.ThrowIfNull(list);\n\n _suppressNotification = true;\n\n foreach (T item in list)\n {\n Add(item);\n }\n _suppressNotification = false;\n\n OnCollectionChanged(new NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction.Reset));\n }\n}\n"], ["/LLPlayer/FlyleafLib/MediaFramework/MediaRenderer/Renderer.cs", "using System.Collections.Generic;\nusing System.Runtime.InteropServices;\nusing System.Windows;\n\nusing Vortice;\nusing Vortice.DXGI;\nusing Vortice.Direct3D11;\nusing Vortice.Mathematics;\n\nusing FlyleafLib.MediaFramework.MediaDecoder;\nusing FlyleafLib.MediaFramework.MediaFrame;\nusing FlyleafLib.MediaFramework.MediaStream;\n\nusing ID3D11Device = Vortice.Direct3D11.ID3D11Device;\n\nnamespace FlyleafLib.MediaFramework.MediaRenderer;\n\n/* TODO\n * 1) Attach on every frame video output configuration so we will not have to worry for video codec change etc.\n * this will fix also dynamic video stream change\n * we might have issue with bufRef / ffmpeg texture array on zero copy\n *\n * 2) Use different context/video processor for off rendering so we dont have to reset pixel shaders/viewports etc (review also rtvs for extractor)\n *\n * 3) Add Crop (Left/Right/Top/Bottom) -on Source- support per pixels (easy implemantation with D3D11VP, FlyleafVP requires more research)\n *\n * 4) Improve A/V Sync\n *\n * a. vsync / vblack\n * b. Present can cause a delay (based on device load), consider using more buffers for high frame rates that could minimize the delay\n * c. display refresh rate vs input rate, consider using max latency > 1 ?\n * d. frame drops\n *\n * swapChain.GetFrameStatistics(out var stats);\n * swapChain.LastPresentCount - stats.PresentCount;\n */\n\npublic partial class Renderer : NotifyPropertyChanged, IDisposable\n{\n public Config Config { get; private set;}\n public int ControlWidth { get; private set; }\n public int ControlHeight { get; private set; }\n internal IntPtr ControlHandle;\n\n internal Action\n SwapChainWinUIClbk;\n\n public ID3D11Device Device { get; private set; }\n public bool D3D11VPFailed => vc == null;\n public GPUAdapter GPUAdapter { get; private set; }\n public bool Disposed { get; private set; } = true;\n public bool SCDisposed { get; private set; } = true;\n public int MaxOffScreenTextures\n { get; set; } = 20;\n public VideoDecoder VideoDecoder { get; internal set; }\n public VideoStream VideoStream => VideoDecoder.VideoStream;\n\n public Viewport GetViewport { get; private set; }\n public event EventHandler ViewportChanged;\n\n public CornerRadius CornerRadius { get => cornerRadius; set { if (cornerRadius == value) return; cornerRadius = value; UpdateCornerRadius(); } }\n CornerRadius cornerRadius = new(0);\n CornerRadius zeroCornerRadius = new(0);\n\n public bool IsHDR { get => isHDR; private set { SetUI(ref _IsHDR, value); isHDR = value; } }\n bool _IsHDR, isHDR;\n\n public int SideXPixels { get; private set; }\n public int SideYPixels { get; private set; }\n\n public int PanXOffset { get => panXOffset; set => SetPanX(value); }\n int panXOffset;\n public void SetPanX(int panX, bool refresh = true)\n {\n lock(lockDevice)\n {\n panXOffset = panX;\n\n if (Disposed)\n return;\n\n SetViewport(refresh);\n }\n }\n\n public int PanYOffset { get => panYOffset; set => SetPanY(value); }\n int panYOffset;\n public void SetPanY(int panY, bool refresh = true)\n {\n lock(lockDevice)\n {\n panYOffset = panY;\n\n if (Disposed)\n return;\n\n SetViewport(refresh);\n }\n }\n\n public uint Rotation { get => _RotationAngle;set { lock (lockDevice) UpdateRotation(value); } }\n uint _RotationAngle;\n VideoProcessorRotation _d3d11vpRotation = VideoProcessorRotation.Identity;\n bool rotationLinesize; // if negative should be vertically flipped\n\n public bool HFlip { get => _HFlip;set { _HFlip = value; lock (lockDevice) UpdateRotation(_RotationAngle); } }\n bool _HFlip;\n\n public bool VFlip { get => _VFlip;set { _VFlip = value; lock (lockDevice) UpdateRotation(_RotationAngle); } }\n bool _VFlip;\n\n public VideoProcessors VideoProcessor { get => videoProcessor; private set => SetUI(ref videoProcessor, value); }\n VideoProcessors videoProcessor = VideoProcessors.Flyleaf;\n\n /// \n /// Zoom percentage (100% equals to 1.0)\n /// \n public double Zoom { get => zoom; set => SetZoom(value); }\n double zoom = 1;\n public void SetZoom(double zoom, bool refresh = true)\n {\n lock(lockDevice)\n {\n this.zoom = zoom;\n\n if (Disposed)\n return;\n\n SetViewport(refresh);\n }\n }\n\n public Point ZoomCenter { get => zoomCenter; set => SetZoomCenter(value); }\n Point zoomCenter = ZoomCenterPoint;\n public static Point ZoomCenterPoint = new(0.5, 0.5);\n public void SetZoomCenter(Point p, bool refresh = true)\n {\n lock(lockDevice)\n {\n zoomCenter = p;\n\n if (Disposed)\n return;\n\n if (refresh)\n SetViewport();\n }\n }\n public void SetZoomAndCenter(double zoom, Point p, bool refresh = true)\n {\n lock(lockDevice)\n {\n this.zoom = zoom;\n zoomCenter = p;\n\n if (Disposed)\n return;\n\n if (refresh)\n SetViewport();\n }\n }\n public void SetPanAll(int panX, int panY, uint rotation, double zoom, Point p, bool refresh = true)\n {\n lock(lockDevice)\n {\n panXOffset = panX;\n panYOffset = panY;\n this.zoom = zoom;\n zoomCenter = p;\n UpdateRotation(rotation, false);\n\n if (Disposed)\n return;\n\n if (refresh)\n SetViewport();\n }\n }\n\n public int UniqueId { get; private set; }\n\n public Dictionary\n Filters { get; set; }\n public VideoFrame LastFrame { get; set; }\n public RawRect VideoRect { get; set; }\n\n LogHandler Log;\n\n public Renderer(VideoDecoder videoDecoder, IntPtr handle = new IntPtr(), int uniqueId = -1)\n {\n UniqueId = uniqueId == -1 ? Utils.GetUniqueId() : uniqueId;\n VideoDecoder= videoDecoder;\n Config = videoDecoder.Config;\n Log = new LogHandler((\"[#\" + UniqueId + \"]\").PadRight(8, ' ') + \" [Renderer ] \");\n\n overlayTextureDesc = new()\n {\n Usage = ResourceUsage.Default,\n Width = 0,\n Height = 0,\n Format = Format.B8G8R8A8_UNorm,\n ArraySize = 1,\n MipLevels = 1,\n BindFlags = BindFlags.ShaderResource,\n SampleDescription = new SampleDescription(1, 0)\n };\n\n singleStageDesc = new Texture2DDescription()\n {\n Usage = ResourceUsage.Staging,\n Format = Format.B8G8R8A8_UNorm,\n ArraySize = 1,\n MipLevels = 1,\n BindFlags = BindFlags.None,\n CPUAccessFlags = CpuAccessFlags.Read,\n SampleDescription = new SampleDescription(1, 0),\n\n Width = 0,\n Height = 0\n };\n\n singleGpuDesc = new Texture2DDescription()\n {\n Usage = ResourceUsage.Default,\n Format = Format.B8G8R8A8_UNorm,\n ArraySize = 1,\n MipLevels = 1,\n BindFlags = BindFlags.RenderTarget | BindFlags.ShaderResource,\n SampleDescription = new SampleDescription(1, 0)\n };\n\n wndProcDelegate = new(WndProc);\n wndProcDelegatePtr = Marshal.GetFunctionPointerForDelegate(wndProcDelegate);\n ControlHandle = handle;\n Initialize();\n }\n\n #region Replica Renderer (Expiremental)\n public Renderer child; // allow access to child renderer (not safe)\n Renderer parent;\n public Renderer(Renderer renderer, IntPtr handle, int uniqueId = -1)\n {\n UniqueId = uniqueId == -1 ? Utils.GetUniqueId() : uniqueId;\n Log = new LogHandler((\"[#\" + UniqueId + \"]\").PadRight(8, ' ') + \" [Renderer Repl] \");\n\n renderer.child = this;\n parent = renderer;\n Config = renderer.Config;\n wndProcDelegate = new(WndProc);\n wndProcDelegatePtr = Marshal.GetFunctionPointerForDelegate(wndProcDelegate);\n ControlHandle = handle;\n }\n\n public void SetChildHandle(IntPtr handle)\n {\n lock (lockDevice)\n {\n if (child != null)\n DisposeChild();\n\n if (handle == IntPtr.Zero)\n return;\n\n child = new(this, handle, UniqueId);\n InitializeChildSwapChain();\n }\n }\n #endregion\n}\n"], ["/LLPlayer/FlyleafLib/MediaFramework/MediaRenderer/ShaderCompiler.cs", "using System.Collections.Generic;\nusing System.Text;\nusing System.Threading;\n\nusing Vortice.D3DCompiler;\nusing Vortice.Direct3D;\nusing Vortice.Direct3D11;\n\nusing ID3D11Device = Vortice.Direct3D11.ID3D11Device;\nusing static FlyleafLib.Utils;\n\nnamespace FlyleafLib.MediaFramework.MediaRenderer;\n\ninternal class BlobWrapper\n{\n public Blob blob;\n public BlobWrapper(Blob blob) => this.blob = blob;\n public BlobWrapper() { }\n}\n\ninternal static class ShaderCompiler\n{\n internal static Blob VSBlob = Compile(VS, false); // TODO Embedded?\n\n const int MAXSIZE = 64;\n static Dictionary cache = new();\n\n internal static ID3D11PixelShader CompilePS(ID3D11Device device, string uniqueId, string hlslSample, List defines = null)\n {\n BlobWrapper bw;\n\n lock (cache)\n {\n if (cache.Count > MAXSIZE)\n {\n Engine.Log.Trace($\"[ShaderCompiler] Clears cache\");\n foreach (var bw1 in cache.Values)\n bw1.blob.Dispose();\n\n cache.Clear();\n }\n\n cache.TryGetValue(uniqueId, out var bw2);\n if (bw2 != null)\n {\n Engine.Log.Trace($\"[ShaderCompiler] Found in cache {uniqueId}\");\n lock(bw2)\n return device.CreatePixelShader(bw2.blob);\n }\n\n bw = new();\n Monitor.Enter(bw);\n cache.Add(uniqueId, bw);\n }\n\n var blob = Compile(PS_HEADER + hlslSample + PS_FOOTER, true, defines);\n bw.blob = blob;\n var ps = device.CreatePixelShader(bw.blob);\n Monitor.Exit(bw);\n\n Engine.Log.Trace($\"[ShaderCompiler] Compiled {uniqueId}\");\n return ps;\n }\n internal static Blob Compile(string hlsl, bool isPS = true, List defines = null)\n {\n ShaderMacro[] definesMacro = null;\n\n if (defines != null)\n {\n definesMacro = new ShaderMacro[defines.Count + 1];\n for(int i=0; i GetUrlExtention(x) == \"hlsl\").ToArray();\n\n // foreach (string shader in shaders)\n // using (Stream stream = assembly.GetManifestResourceStream(shader))\n // {\n // string shaderName = shader.Substring(0, shader.Length - 5);\n // shaderName = shaderName.Substring(shaderName.LastIndexOf('.') + 1);\n\n // byte[] bytes = new byte[stream.Length];\n // stream.Read(bytes, 0, bytes.Length);\n\n // CompileShader(bytes, shaderName);\n // }\n //}\n\n //private unsafe static void CompileFileShaders()\n //{\n // List shaders = Directory.EnumerateFiles(EmbeddedShadersFolder, \"*.hlsl\").ToList();\n // foreach (string shader in shaders)\n // {\n // string shaderName = shader.Substring(0, shader.Length - 5);\n // shaderName = shaderName.Substring(shaderName.LastIndexOf('\\\\') + 1);\n\n // CompileShader(File.ReadAllBytes(shader), shaderName);\n // }\n //}\n\n // Loads compiled blob shaders\n //private static void LoadShaders()\n //{\n // Assembly assembly = Assembly.GetExecutingAssembly();\n // string[] shaders = assembly.GetManifestResourceNames().Where(x => GetUrlExtention(x) == \"blob\").ToArray();\n // string tempFile = Path.GetTempFileName();\n\n // foreach (string shader in shaders)\n // {\n // using (Stream stream = assembly.GetManifestResourceStream(shader))\n // {\n // var shaderName = shader.Substring(0, shader.Length - 5);\n // shaderName = shaderName.Substring(shaderName.LastIndexOf('.') + 1);\n\n // byte[] bytes = new byte[stream.Length];\n // stream.Read(bytes, 0, bytes.Length);\n\n // Dictionary curShaders = shaderName.Substring(0, 2).ToLower() == \"vs\" ? VSShaderBlobs : PSShaderBlobs;\n\n // File.WriteAllBytes(tempFile, bytes);\n // curShaders.Add(shaderName, Compiler.ReadFileToBlob(tempFile));\n // }\n // }\n //}\n\n // Should work at least from main Samples => FlyleafPlayer (WPF Control) (WPF)\n //static string EmbeddedShadersFolder = @\"..\\..\\..\\..\\..\\..\\FlyleafLib\\MediaFramework\\MediaRenderer\\Shaders\";\n //static Assembly ASSEMBLY = Assembly.GetExecutingAssembly();\n //static string SHADERS_NS = typeof(Renderer).Namespace + \".Shaders.\";\n\n //static byte[] GetEmbeddedShaderResource(string shaderName)\n //{\n // using (Stream stream = ASSEMBLY.GetManifestResourceStream(SHADERS_NS + shaderName + \".hlsl\"))\n // {\n // byte[] bytes = new byte[stream.Length];\n // stream.Read(bytes, 0, bytes.Length);\n\n // return bytes;\n // }\n //}\n\n const string PS_HEADER = @\"\n#pragma warning( disable: 3571 )\nTexture2D\t\tTexture1\t\t: register(t0);\nTexture2D\t\tTexture2\t\t: register(t1);\nTexture2D\t\tTexture3\t\t: register(t2);\nTexture2D\t\tTexture4\t\t: register(t3);\n\ncbuffer Config : register(b0)\n{\n int coefsIndex;\n int hdrmethod;\n\n float brightness;\n float contrast;\n\n float g_luminance;\n float g_toneP1;\n float g_toneP2;\n\n float texWidth;\n};\n\nSamplerState Sampler : IMMUTABLE\n{\n Filter = MIN_MAG_MIP_LINEAR;\n AddressU = CLAMP;\n AddressV = CLAMP;\n AddressW = CLAMP;\n ComparisonFunc = NEVER;\n MinLOD = 0;\n};\n\n#if defined(YUV)\n// YUV to RGB matrix coefficients\nstatic const float4x4 coefs[] =\n{\n // Limited -> Full\n {\n // BT2020 (srcBits = 10)\n { 1.16438353, 1.16438353, 1.16438353, 0 },\n { 0, -0.187326103, 2.14177227, 0 },\n { 1.67867422, -0.650424361, 0, 0 },\n { -0.915688038, 0.347458541, -1.14814520, 1 }\n },\n\n // BT709\n {\n { 1.16438341, 1.16438341, 1.16438341, 0 },\n { 0, -0.213248596, 2.11240149, 0 },\n { 1.79274082, -0.532909214, 0, 0 },\n { -0.972944975, 0.301482648, -1.13340211, 1 }\n },\n // BT601\n {\n { 1.16438341, 1.16438341, 1.16438341, 0 },\n { 0, -0.391762286, 2.01723194, 0 },\n { 1.59602666, -0.812967658, 0, 0 },\n { -0.874202192, 0.531667829, -1.08563077, 1 },\n }\n};\n#endif\n\n#if defined(HDR)\n// hdrmethod enum\nstatic const int Aces = 1;\nstatic const int Hable = 2;\nstatic const int Reinhard = 3;\n\n// HDR to SDR color convert (Thanks to KODI community https://github.com/thexai/xbmc)\nstatic const float ST2084_m1 = 2610.0f / (4096.0f * 4.0f);\nstatic const float ST2084_m2 = (2523.0f / 4096.0f) * 128.0f;\nstatic const float ST2084_c1 = 3424.0f / 4096.0f;\nstatic const float ST2084_c2 = (2413.0f / 4096.0f) * 32.0f;\nstatic const float ST2084_c3 = (2392.0f / 4096.0f) * 32.0f;\n\nstatic const float4x4 bt2020tobt709color =\n{\n { 1.6604f, -0.1245f, -0.0181f, 0 },\n { -0.5876f, 1.1329f, -0.10057f, 0 },\n { -0.07284f, -0.0083f, 1.1187f, 0 },\n { 0, 0, 0, 0 }\n};\n\nfloat3 inversePQ(float3 x)\n{\n x = pow(max(x, 0.0f), 1.0f / ST2084_m2);\n x = max(x - ST2084_c1, 0.0f) / (ST2084_c2 - ST2084_c3 * x);\n x = pow(x, 1.0f / ST2084_m1);\n return x;\n}\n\n#if defined(HLG)\nfloat3 inverseHLG(float3 x)\n{\n const float B67_a = 0.17883277f;\n const float B67_b = 0.28466892f;\n const float B67_c = 0.55991073f;\n const float B67_inv_r2 = 4.0f;\n x = (x <= 0.5f) ? x * x * B67_inv_r2 : exp((x - B67_c) / B67_a) + B67_b;\n return x;\n}\n\nfloat3 tranferPQ(float3 x)\n{\n x = pow(x / 1000.0f, ST2084_m1);\n x = (ST2084_c1 + ST2084_c2 * x) / (1.0f + ST2084_c3 * x);\n x = pow(x, ST2084_m2);\n return x;\n}\n\n#endif\nfloat3 aces(float3 x)\n{\n const float A = 2.51f;\n const float B = 0.03f;\n const float C = 2.43f;\n const float D = 0.59f;\n const float E = 0.14f;\n return (x * (A * x + B)) / (x * (C * x + D) + E);\n}\n\nfloat3 hable(float3 x)\n{\n const float A = 0.15f;\n const float B = 0.5f;\n const float C = 0.1f;\n const float D = 0.2f;\n const float E = 0.02f;\n const float F = 0.3f;\n return ((x * (A * x + C * B) + D * E) / (x * (A * x + B) + D * F)) - E / F;\n}\n\nstatic const float3 bt709coefs = { 0.2126f, 1.0f - 0.2126f - 0.0722f, 0.0722f };\nfloat reinhard(float x)\n{\n return x * (1.0f + x / (g_toneP1 * g_toneP1)) / (1.0f + x);\n}\n#endif\n\nstruct PSInput\n{\n float4 Position : SV_POSITION;\n float2 Texture : TEXCOORD;\n};\n\nfloat4 main(PSInput input) : SV_TARGET\n{\n float4 color;\n\n // Dynamic Sampling\n\n\";\n\n const string PS_FOOTER = @\"\n\n // YUV to RGB\n#if defined(YUV)\n color = mul(color, coefs[coefsIndex]);\n#endif\n\n\n // HDR\n#if defined(HDR)\n // BT2020 -> BT709\n color.rgb = pow(max(0.0, color.rgb), 2.4f);\n color.rgb = max(0.0, mul(color, bt2020tobt709color).rgb);\n color.rgb = pow(color.rgb, 1.0f / 2.2f);\n\n if (hdrmethod == Aces)\n {\n color.rgb = inversePQ(color.rgb);\n color.rgb *= (10000.0f / g_luminance) * (2.0f / g_toneP1);\n color.rgb = aces(color.rgb);\n color.rgb *= (1.24f / g_toneP1);\n color.rgb = pow(color.rgb, 0.27f);\n }\n else if (hdrmethod == Hable)\n {\n color.rgb = inversePQ(color.rgb);\n color.rgb *= g_toneP1;\n color.rgb = hable(color.rgb * g_toneP2) / hable(g_toneP2);\n color.rgb = pow(color.rgb, 1.0f / 2.2f);\n }\n else if (hdrmethod == Reinhard)\n {\n float luma = dot(color.rgb, bt709coefs);\n color.rgb *= reinhard(luma) / luma;\n }\n #if defined(HLG)\n // HLG\n color.rgb = inverseHLG(color.rgb);\n float3 ootf_2020 = float3(0.2627f, 0.6780f, 0.0593f);\n float ootf_ys = 2000.0f * dot(ootf_2020, color.rgb);\n color.rgb *= pow(ootf_ys, 0.2f);\n color.rgb = tranferPQ(color.rgb);\n #endif\n#endif\n\n // Contrast / Brightness / Saturate / Hue\n color *= contrast * 2.0f;\n color += brightness - 0.5f;\n\n return color;\n}\n\";\n\n const string VS = @\"\ncbuffer cBuf : register(b0)\n{\n matrix mat;\n}\n\nstruct VSInput\n{\n float4 Position : POSITION;\n float2 Texture : TEXCOORD;\n};\n\nstruct PSInput\n{\n float4 Position : SV_POSITION;\n float2 Texture : TEXCOORD;\n};\n\nPSInput main(VSInput vsi)\n{\n PSInput psi;\n\n psi.Position = mul(vsi.Position, mat);\n psi.Texture = vsi.Texture;\n\n return psi;\n}\n\";\n}\n"], ["/LLPlayer/LLPlayer/Services/AppConfig.cs", "using System.Collections.ObjectModel;\nusing System.ComponentModel;\nusing System.IO;\nusing System.Text.Json;\nusing System.Text.Json.Serialization;\nusing System.Windows;\nusing System.Windows.Input;\nusing System.Windows.Media;\nusing FlyleafLib;\nusing FlyleafLib.MediaPlayer;\nusing FlyleafLib.MediaPlayer.Translation.Services;\nusing LLPlayer.Extensions;\nusing MaterialDesignThemes.Wpf;\nusing Vortice.Mathematics;\nusing Color = System.Windows.Media.Color;\nusing Colors = System.Windows.Media.Colors;\nusing Size = System.Windows.Size;\n\nnamespace LLPlayer.Services;\n\npublic class AppConfig : Bindable\n{\n private FlyleafManager FL = null!;\n\n public void Initialize(FlyleafManager fl)\n {\n FL = fl;\n Loaded = true;\n\n Subs.Initialize(this, fl);\n }\n\n public string Version { get; set; } = \"\";\n\n /// \n /// State to skip the setter run when reading JSON\n /// \n [JsonIgnore]\n public bool Loaded { get; private set; }\n\n public void FlyleafHostLoaded()\n {\n Subs.FlyleafHostLoaded();\n\n // Ensure that FlyeafHost reflects the configuration values when restoring the configuration.\n FL.FlyleafHost!.ActivityTimeout = FL.Config.ActivityTimeout;\n }\n\n public AppConfigSubs Subs { get; set => Set(ref field, value); } = new();\n\n public static AppConfig Load(string path)\n {\n AppConfig config = JsonSerializer.Deserialize(File.ReadAllText(path), GetJsonSerializerOptions())!;\n\n return config;\n }\n\n public void Save(string path)\n {\n Version = App.Version;\n File.WriteAllText(path, JsonSerializer.Serialize(this, GetJsonSerializerOptions()));\n\n Subs.SaveAfter();\n }\n\n public AppConfigTheme Theme { get; set => Set(ref field, value); } = new();\n\n public bool AlwaysOnTop { get; set => Set(ref field, value); }\n\n [JsonIgnore]\n public double ScreenWidth\n {\n private get;\n set => Set(ref field, value);\n }\n\n // Video Screen Height (including black background), without titlebar height\n [JsonIgnore]\n public double ScreenHeight\n {\n internal get;\n set\n {\n if (Set(ref field, value))\n {\n Subs.UpdateSubsConfig();\n }\n }\n }\n\n public bool IsDarkTitlebar { get; set => Set(ref field, value); } = true;\n\n public int ActivityTimeout\n {\n get;\n set\n {\n if (Set(ref field, value))\n {\n if (Loaded && FL.FlyleafHost != null)\n {\n FL.FlyleafHost.ActivityTimeout = value;\n }\n }\n }\n } = 1200;\n\n public bool ShowSidebar { get; set => Set(ref field, value); } = true;\n\n [JsonIgnore]\n public bool ShowDebug\n {\n get;\n set\n {\n if (Set(ref field, value))\n {\n FL.PlayerConfig.Player.Stats = value;\n }\n }\n }\n\n\n #region FlyleafBar\n public bool SeekBarShowOnlyMouseOver { get; set => Set(ref field, value); } = false;\n public int SeekBarFadeInTimeMs { get; set => Set(ref field, value); } = 80;\n public int SeekBarFadeOutTimeMs { get; set => Set(ref field, value); } = 150;\n #endregion\n\n #region Mouse\n public bool MouseSingleClickToPlay { get; set => Set(ref field, value); } = true;\n public bool MouseDoubleClickToFullScreen { get; set => Set(ref field, value); }\n public bool MouseWheelToVolumeUpDown { get; set => Set(ref field, value); } = true;\n #endregion\n\n // TODO: L: should be move to AppConfigSubs?\n public bool SidebarLeft\n {\n get;\n set\n {\n if (Set(ref field, value))\n {\n OnPropertyChanged(nameof(SidebarFlowDirection));\n }\n }\n }\n\n [JsonIgnore]\n public FlowDirection SidebarFlowDirection => !SidebarLeft ? FlowDirection.LeftToRight : FlowDirection.RightToLeft;\n\n public int SidebarWidth { get; set => Set(ref field, value); } = 300;\n\n public int SidebarSubPadding { get; set => Set(ref field, value); } = 5;\n\n [JsonIgnore]\n public bool SidebarShowSecondary { get; set => Set(ref field, value); }\n\n public bool SidebarShowOriginalText { get; set => Set(ref field, value); }\n\n public bool SidebarTextMask { get; set => Set(ref field, value); }\n\n [JsonIgnore]\n public bool SidebarSearchActive { get; set => Set(ref field, value); }\n\n public string SidebarFontFamily { get; set => Set(ref field, value); } = \"Segoe UI\";\n\n public double SidebarFontSize { get; set => Set(ref field, value); } = 16;\n\n public string SidebarFontWeight { get; set => Set(ref field, value); } = FontWeights.Normal.ToString();\n\n public static JsonSerializerOptions GetJsonSerializerOptions()\n {\n Dictionary typeMappingMenuAction = new()\n {\n { nameof(ClipboardMenuAction), typeof(ClipboardMenuAction) },\n { nameof(ClipboardAllMenuAction), typeof(ClipboardAllMenuAction) },\n { nameof(SearchMenuAction), typeof(SearchMenuAction) },\n };\n\n Dictionary typeMappingTranslateSettings = new()\n {\n { nameof(GoogleV1TranslateSettings), typeof(GoogleV1TranslateSettings) },\n { nameof(DeepLTranslateSettings), typeof(DeepLTranslateSettings) },\n { nameof(DeepLXTranslateSettings), typeof(DeepLXTranslateSettings) },\n { nameof(OllamaTranslateSettings), typeof(OllamaTranslateSettings) },\n { nameof(LMStudioTranslateSettings), typeof(LMStudioTranslateSettings) },\n { nameof(KoboldCppTranslateSettings), typeof(KoboldCppTranslateSettings) },\n { nameof(OpenAITranslateSettings), typeof(OpenAITranslateSettings) },\n { nameof(OpenAILikeTranslateSettings), typeof(OpenAILikeTranslateSettings) },\n { nameof(ClaudeTranslateSettings), typeof(ClaudeTranslateSettings) },\n { nameof(LiteLLMTranslateSettings), typeof(LiteLLMTranslateSettings) }\n };\n\n JsonSerializerOptions jsonOptions = new()\n {\n WriteIndented = true,\n DefaultIgnoreCondition = JsonIgnoreCondition.WhenWritingNull,\n Converters =\n {\n new JsonStringEnumConverter(),\n // TODO: L: should separate converters for different types of config?\n new JsonInterfaceConcreteConverter(typeMappingMenuAction),\n new JsonInterfaceConcreteConverter(typeMappingTranslateSettings),\n new ColorHexJsonConverter()\n }\n };\n\n return jsonOptions;\n }\n}\n\npublic class AppConfigSubs : Bindable\n{\n private AppConfig _rootConfig = null!;\n private FlyleafManager FL = null!;\n\n [JsonIgnore]\n public bool Loaded { get; private set; }\n\n public void Initialize(AppConfig rootConfig, FlyleafManager fl)\n {\n _rootConfig = rootConfig;\n FL = fl;\n Loaded = true;\n\n // Save the initial value of the position for reset.\n _subsPositionInitial = SubsPosition;\n\n // register event handler\n var pSubsAutoCopy = SubsAutoTextCopy;\n SubsAutoTextCopy = false;\n SubsAutoTextCopy = pSubsAutoCopy;\n }\n\n public void FlyleafHostLoaded()\n {\n Viewport = FL.Player.renderer.GetViewport;\n\n FL.Player.renderer.ViewportChanged += (sender, args) =>\n {\n Utils.UIIfRequired(() =>\n {\n Viewport = FL.Player.renderer.GetViewport;\n });\n };\n }\n\n public void SaveAfter()\n {\n // Update initial value\n _subsPositionInitial = SubsPosition;\n }\n\n [JsonIgnore]\n public Viewport Viewport\n {\n get;\n private set\n {\n var prev = Viewport;\n if (Set(ref field, value))\n {\n if ((int)prev.Width != (int)value.Width)\n {\n // update font size if width changed\n OnPropertyChanged(nameof(SubsFontSizeFix));\n OnPropertyChanged(nameof(SubsFontSize2Fix));\n }\n\n if ((int)prev.Height != (int)value.Height ||\n (int)prev.Y != (int)value.Y)\n {\n // update font margin/distance if height/Y changed\n UpdateSubsConfig();\n }\n }\n }\n }\n\n public bool SubsUseSeparateFonts\n {\n get;\n set\n {\n if (Set(ref field, value))\n {\n // update subtitles\n UpdateSecondaryFonts();\n\n OnPropertyChanged(nameof(SubsFontColor2Fix));\n OnPropertyChanged(nameof(SubsBackgroundBrush2));\n }\n }\n }\n\n internal void UpdateSecondaryFonts()\n {\n // update subtitles display\n OnPropertyChanged(nameof(SubsFontFamily2Fix));\n OnPropertyChanged(nameof(SubsFontStretch2Fix));\n OnPropertyChanged(nameof(SubsFontWeight2Fix));\n OnPropertyChanged(nameof(SubsFontStyle2Fix));\n\n CmdResetSubsFont2!.RaiseCanExecuteChanged();\n }\n\n // Primary Subtitle Size\n public double SubsFontSize\n {\n get;\n set\n {\n if (value <= 0)\n {\n return;\n }\n\n if (Set(ref field, Math.Round(value)))\n {\n OnPropertyChanged(nameof(SubsFontSizeFix));\n CmdResetSubsFontSize2!.RaiseCanExecuteChanged();\n }\n }\n } = 44;\n\n [JsonIgnore]\n public double SubsFontSizeFix => GetFixFontSize(SubsFontSize);\n\n // Secondary Subtitle Size\n public double SubsFontSize2\n {\n get;\n set\n {\n if (value <= 0)\n {\n return;\n }\n\n if (Set(ref field, Math.Round(value)))\n {\n OnPropertyChanged(nameof(SubsFontSize2Fix));\n CmdResetSubsFontSize2!.RaiseCanExecuteChanged();\n }\n }\n } = 44;\n\n [JsonIgnore]\n public double SubsFontSize2Fix => GetFixFontSize(SubsFontSize2);\n\n private double GetFixFontSize(double fontSize)\n {\n double scaleFactor = Viewport.Width / 1920;\n double size = fontSize * scaleFactor;\n if (size > 0)\n {\n return size;\n }\n\n return fontSize;\n }\n\n private const string DefaultFont = \"Segoe UI\";\n public string SubsFontFamily { get; set => Set(ref field, value); } = DefaultFont;\n public string SubsFontStretch { get; set => Set(ref field, value); } = FontStretches.Normal.ToString();\n public string SubsFontWeight { get; set => Set(ref field, value); } = FontWeights.Bold.ToString();\n public string SubsFontStyle { get; set => Set(ref field, value); } = FontStyles.Normal.ToString();\n public Color SubsFontColor\n {\n get;\n set\n {\n if (Set(ref field, value))\n {\n OnPropertyChanged(nameof(SubsFontColor2Fix));\n CmdResetSubsFontColor2!.RaiseCanExecuteChanged();\n }\n }\n } = Colors.White;\n\n [JsonIgnore]\n public string SubsFontFamily2Fix => SubsUseSeparateFonts ? SubsFontFamily2 : SubsFontFamily;\n public string SubsFontFamily2 { get; set => Set(ref field, value); } = DefaultFont;\n\n [JsonIgnore]\n public string SubsFontStretch2Fix => SubsUseSeparateFonts ? SubsFontStretch2 : SubsFontStretch;\n public string SubsFontStretch2 { get; set => Set(ref field, value); } = FontStretches.Normal.ToString();\n\n [JsonIgnore]\n public string SubsFontWeight2Fix => SubsUseSeparateFonts ? SubsFontWeight2 : SubsFontWeight;\n public string SubsFontWeight2 { get; set => Set(ref field, value); } = FontWeights.SemiBold.ToString(); // change from bold\n\n [JsonIgnore]\n public string SubsFontStyle2Fix => SubsUseSeparateFonts ? SubsFontStyle2 : SubsFontStyle;\n public string SubsFontStyle2 { get; set => Set(ref field, value); } = FontStyles.Normal.ToString();\n\n [JsonIgnore]\n public Color SubsFontColor2Fix => SubsUseSeparateFonts ? SubsFontColor2 : SubsFontColor;\n public Color SubsFontColor2\n {\n get;\n set\n {\n if (Set(ref field, value))\n {\n OnPropertyChanged(nameof(SubsFontColor2Fix));\n CmdResetSubsFontColor2!.RaiseCanExecuteChanged();\n }\n }\n } = Color.FromRgb(231, 231, 231); // #E7E7E7\n\n public Color SubsStrokeColor { get; set => Set(ref field, value); } = Colors.Black;\n public double SubsStrokeThickness { get; set => Set(ref field, value); } = 3.2;\n\n public Color SubsBackgroundColor\n {\n get;\n set\n {\n if (Set(ref field, value))\n {\n OnPropertyChanged(nameof(SubsBackgroundBrush));\n OnPropertyChanged(nameof(SubsBackgroundBrush2));\n }\n }\n } = Colors.Black;\n\n public double SubsBackgroundOpacity\n {\n get;\n set\n {\n if (value < 0.0 || value > 1.0)\n {\n return;\n }\n\n if (Set(ref field, Math.Round(value, 2)))\n {\n OnPropertyChanged(nameof(SubsBackgroundBrush));\n OnPropertyChanged(nameof(SubsBackgroundBrush2));\n CmdResetSubsBackgroundOpacity2!.RaiseCanExecuteChanged();\n }\n }\n } = 0; // default no background\n\n [JsonIgnore]\n public SolidColorBrush SubsBackgroundBrush\n {\n get\n {\n byte alpha = (byte)(SubsBackgroundOpacity * 255);\n return new SolidColorBrush(Color.FromArgb(alpha, SubsBackgroundColor.R, SubsBackgroundColor.G, SubsBackgroundColor.B));\n }\n }\n\n [JsonIgnore]\n private double SubsBackgroundOpacity2Fix => SubsUseSeparateFonts ? SubsBackgroundOpacity2 : SubsBackgroundOpacity;\n public double SubsBackgroundOpacity2\n {\n get;\n set\n {\n if (value < 0.0 || value > 1.0)\n {\n return;\n }\n\n if (Set(ref field, Math.Round(value, 2)))\n {\n OnPropertyChanged(nameof(SubsBackgroundBrush2));\n CmdResetSubsBackgroundOpacity2!.RaiseCanExecuteChanged();\n }\n }\n } = 0;\n\n [JsonIgnore]\n public SolidColorBrush SubsBackgroundBrush2\n {\n get\n {\n byte alpha = (byte)(SubsBackgroundOpacity2Fix * 255);\n return new SolidColorBrush(Color.FromArgb(alpha, SubsBackgroundColor.R, SubsBackgroundColor.G, SubsBackgroundColor.B));\n }\n }\n\n [JsonIgnore]\n public DelegateCommand? CmdResetSubsFontSize2 => field ??= new(() =>\n {\n SubsFontSize2 = SubsFontSize;\n }, () => SubsFontSize2 != SubsFontSize);\n\n [JsonIgnore]\n public DelegateCommand? CmdResetSubsFont2 => field ??= new(() =>\n {\n SubsFontFamily2 = SubsFontFamily;\n SubsFontStretch2 = SubsFontStretch;\n SubsFontWeight2 = SubsFontWeight;\n SubsFontStyle2 = SubsFontStyle;\n\n UpdateSecondaryFonts();\n }, () =>\n SubsFontFamily2 != SubsFontFamily ||\n SubsFontStretch2 != SubsFontStretch ||\n SubsFontWeight2 != SubsFontWeight ||\n SubsFontStyle2 != SubsFontStyle\n );\n\n [JsonIgnore]\n public DelegateCommand? CmdResetSubsFontColor2 => field ??= new(() =>\n {\n SubsFontColor2 = SubsFontColor;\n }, () => SubsFontColor2 != SubsFontColor);\n\n [JsonIgnore]\n public DelegateCommand? CmdResetSubsBackgroundOpacity2 => field ??= new(() =>\n {\n SubsBackgroundOpacity2 = SubsBackgroundOpacity;\n }, () => SubsBackgroundOpacity2 != SubsBackgroundOpacity);\n\n [JsonIgnore]\n public Size SubsPanelSize\n {\n private get;\n set\n {\n if (Set(ref field, value))\n {\n UpdateSubsMargin();\n }\n }\n }\n\n private bool _isSubsOverflowBottom;\n\n [JsonIgnore]\n public Thickness SubsMargin\n {\n get;\n set => Set(ref field, value);\n }\n\n private double _subsPositionInitial;\n public void ResetSubsPosition()\n {\n SubsPosition = _subsPositionInitial;\n }\n\n #region Offsets\n\n public double SubsPositionOffset { get; set => Set(ref field, value); } = 2;\n public int SubsFontSizeOffset { get; set => Set(ref field, value); } = 2;\n public double SubsBitmapScaleOffset { get; set => Set(ref field, value); } = 4;\n public double SubsDistanceOffset { get; set => Set(ref field, value); } = 5;\n\n #endregion\n\n // -25%-150%\n // Allow some going up and down from ViewPort\n public double SubsPosition\n {\n get;\n set\n {\n if (_isSubsOverflowBottom && SubsPanelSize.Height > 0 && field < value)\n {\n // Prohibit going further down when it overflows below.\n return;\n }\n\n if (value < -25 || value > 150)\n {\n return;\n }\n\n if (Set(ref field, Math.Round(value)))\n {\n UpdateSubsMargin();\n }\n }\n } = 85;\n\n public SubPositionAlignment SubsPositionAlignment\n {\n get;\n set\n {\n if (Set(ref field, value))\n {\n UpdateSubsConfig();\n }\n }\n } = SubPositionAlignment.Center;\n\n public SubPositionAlignment SubsPositionAlignmentWhenDual\n {\n get;\n set\n {\n if (Set(ref field, value))\n {\n UpdateSubsConfig();\n }\n }\n } = SubPositionAlignment.Top;\n\n // 0%-100%\n public double SubsFixOverflowMargin\n {\n get;\n set\n {\n if (value < 0.0 || value > 100.0)\n {\n return;\n }\n\n Set(ref field, value);\n }\n } = 3.0;\n\n [JsonIgnore]\n public double SubsDistanceFix { get; set => Set(ref field, value); }\n\n public double SubsDistance\n {\n get;\n set\n {\n if (value < 1)\n {\n return;\n }\n\n if (Set(ref field, Math.Round(value)))\n {\n UpdateSubsDistance();\n }\n }\n } = 16;\n\n public double SubsSeparatorMaxWidth { get; set => Set(ref field, value); } = 280;\n public double SubsSeparatorOpacity\n {\n get;\n set\n {\n if (value < 0.0 || value > 1.0)\n {\n return;\n }\n\n Set(ref field, value);\n }\n } = 0.3;\n\n public double SubsWidthPercentage\n {\n get;\n set\n {\n if (value < 1.0 || value > 100.0)\n {\n return;\n }\n\n Set(ref field, value);\n }\n } = 66.0;\n\n public double SubsMaxWidth\n {\n get;\n set\n {\n if (value < 0)\n {\n return;\n }\n\n Set(ref field, value);\n }\n } = 0;\n\n public bool SubsIgnoreLineBreak { get; set => Set(ref field, value); }\n\n internal void UpdateSubsConfig()\n {\n if (!Loaded)\n return;\n\n UpdateSubsDistance();\n UpdateSubsMargin();\n }\n\n private void UpdateSubsDistance()\n {\n if (!Loaded)\n return;\n\n float scaleFactor = Viewport.Height / 1080;\n double newDistance = SubsDistance * scaleFactor;\n\n SubsDistanceFix = newDistance;\n }\n\n private void UpdateSubsMargin()\n {\n if (!Loaded)\n return;\n\n // Set the margin from the top based on Viewport, not Window\n // Allow going above or below the Viewport\n float offset = Viewport.Y;\n float height = Viewport.Height;\n\n double marginTop = height * (SubsPosition / 100.0);\n double marginTopFix = marginTop + offset;\n\n // Adjustment for vertical alignment of subtitles\n SubPositionAlignment alignment = SubsPositionAlignment;\n if (FL.Player.Subtitles[0].Enabled && FL.Player.Subtitles[1].Enabled)\n {\n alignment = SubsPositionAlignmentWhenDual;\n }\n\n if (alignment == SubPositionAlignment.Center)\n {\n marginTopFix -= SubsPanelSize.Height / 2;\n }\n else if (alignment == SubPositionAlignment.Bottom)\n {\n marginTopFix -= SubsPanelSize.Height;\n }\n\n // Corrects for off-screen subtitles if they are detected.\n marginTopFix = FixOverflowSubsPosition(marginTopFix);\n\n SubsMargin = new Thickness(SubsMargin.Left, marginTopFix, SubsMargin.Right, SubsMargin.Bottom);\n }\n\n /// \n /// Detects whether subtitles are placed off-screen and corrects them if they appear\n /// \n /// \n /// \n private double FixOverflowSubsPosition(double marginTop)\n {\n double subHeight = SubsPanelSize.Height;\n\n double bottomMargin = Viewport.Height * (SubsFixOverflowMargin / 100.0);\n\n if (subHeight + marginTop + bottomMargin > _rootConfig.ScreenHeight)\n {\n // It overflowed, so fix it.\n _isSubsOverflowBottom = true;\n double fixedMargin = _rootConfig.ScreenHeight - subHeight - bottomMargin;\n return fixedMargin;\n }\n\n _isSubsOverflowBottom = false;\n return marginTop;\n }\n\n public bool SubsExportUTF8WithBom { get; set => Set(ref field, value); } = true;\n\n public bool SubsAutoTextCopy\n {\n get;\n set\n {\n if (Set(ref field, value) && Loaded)\n {\n if (value)\n {\n FL.Player.Subtitles[0].Data.PropertyChanged += SubtitleTextOnPropertyChanged;\n FL.Player.Subtitles[1].Data.PropertyChanged += SubtitleTextOnPropertyChanged;\n }\n else\n {\n FL.Player.Subtitles[0].Data.PropertyChanged -= SubtitleTextOnPropertyChanged;\n FL.Player.Subtitles[1].Data.PropertyChanged -= SubtitleTextOnPropertyChanged;\n }\n }\n }\n }\n\n public SubAutoTextCopyTarget SubsAutoTextCopyTarget { get; set => Set(ref field, value); } = SubAutoTextCopyTarget.Primary;\n\n private void SubtitleTextOnPropertyChanged(object? sender, PropertyChangedEventArgs e)\n {\n if (e.PropertyName != nameof(SubsData.Text))\n return;\n\n switch (SubsAutoTextCopyTarget)\n {\n case SubAutoTextCopyTarget.All:\n if (FL.Player.Subtitles[0].Data.Text != \"\" ||\n FL.Player.Subtitles[1].Data.Text != \"\")\n {\n FL.Action.CmdSubsTextCopy.Execute(true);\n }\n break;\n case SubAutoTextCopyTarget.Primary:\n if (FL.Player.Subtitles[0].Data == sender && FL.Player.Subtitles[0].Data.Text != \"\")\n {\n FL.Action.CmdSubsPrimaryTextCopy.Execute(true);\n }\n break;\n case SubAutoTextCopyTarget.Secondary:\n if (FL.Player.Subtitles[1].Data == sender && FL.Player.Subtitles[1].Data.Text != \"\")\n {\n FL.Action.CmdSubsSecondaryTextCopy.Execute(true);\n }\n break;\n }\n }\n\n public WordClickAction WordClickActionMethod { get; set => Set(ref field, value); }\n public bool WordCopyOnSelected { get; set => Set(ref field, value); } = true;\n public bool WordLastSearchOnSelected { get; set => Set(ref field, value); } = true;\n\n public ModifierKeys WordLastSearchOnSelectedModifier { get; set => Set(ref field, value); } = ModifierKeys.Control;\n public ObservableCollection WordMenuActions { get; set => Set(ref field, value); } = new(\n [\n new ClipboardMenuAction(),\n new ClipboardAllMenuAction(),\n new SearchMenuAction{ Title = \"Search Google\", Url = \"https://www.google.com/search?q=%w\" },\n new SearchMenuAction{ Title = \"Search Wiktionary\", Url = \"https://en.wiktionary.org/wiki/Special:Search?search=%w&go=Look+up\" },\n new SearchMenuAction{ Title = \"Search Longman\", Url = \"https://www.ldoceonline.com/search/english/direct/?q=%w\" },\n ]);\n public string? PDICPipeExecutablePath { get; set => Set(ref field, value); }\n}\n\npublic enum SubAutoTextCopyTarget\n{\n Primary,\n Secondary,\n All\n}\n\npublic enum SubPositionAlignment\n{\n Top, // This is useful for dual subs because primary sub position is stayed\n Center, // Same as bitmap subs\n Bottom // Normal video players use this\n}\n\npublic class AppConfigTheme : Bindable\n{\n private readonly PaletteHelper _paletteHelper = new();\n\n public Color PrimaryColor\n {\n get;\n set\n {\n if (Set(ref field, value))\n {\n Theme cur = _paletteHelper.GetTheme();\n cur.SetPrimaryColor(value);\n _paletteHelper.SetTheme(cur);\n }\n }\n } = (Color)ColorConverter.ConvertFromString(\"#D23D6F\"); // Pink\n // Desaturate and lighten from material pink 500\n // https://m2.material.io/design/color/the-color-system.html#tools-for-picking-colors\n // $ pastel color E91E63 | pastel desaturate 0.2 | pastel lighten 0.015\n\n public Color SecondaryColor\n {\n get;\n set\n {\n if (Set(ref field, value))\n {\n Theme cur = _paletteHelper.GetTheme();\n cur.SetSecondaryColor(value);\n _paletteHelper.SetTheme(cur);\n }\n }\n } = (Color)ColorConverter.ConvertFromString(\"#00B8D4\"); // Cyan\n}\n\npublic interface IMenuAction : INotifyPropertyChanged, ICloneable\n{\n [JsonIgnore]\n string Type { get; }\n string Title { get; set; }\n bool IsEnabled { get; set; }\n}\n\npublic class SearchMenuAction : Bindable, IMenuAction\n{\n [JsonIgnore]\n public string Type => \"Search\";\n public required string Title { get; set; }\n public required string Url { get; set => Set(ref field, value); }\n public bool IsEnabled { get; set => Set(ref field, value); } = true;\n\n public object Clone()\n {\n return new SearchMenuAction\n {\n Title = Title,\n Url = Url,\n IsEnabled = IsEnabled\n };\n }\n}\n\npublic class ClipboardMenuAction : Bindable, IMenuAction\n{\n [JsonIgnore]\n public string Type => \"Clipboard\";\n public string Title { get; set; } = \"Copy\";\n public bool ToLower { get; set => Set(ref field, value); }\n public bool IsEnabled { get; set => Set(ref field, value); } = true;\n\n public object Clone()\n {\n return new ClipboardMenuAction\n {\n Title = Title,\n ToLower = ToLower,\n IsEnabled = IsEnabled\n };\n }\n}\n\npublic class ClipboardAllMenuAction : Bindable, IMenuAction\n{\n [JsonIgnore]\n public string Type => \"ClipboardAll\";\n public string Title { get; set; } = \"Copy All\";\n public bool ToLower { get; set => Set(ref field, value); }\n public bool IsEnabled { get; set => Set(ref field, value); } = true;\n\n public object Clone()\n {\n return new ClipboardAllMenuAction\n {\n Title = Title,\n ToLower = ToLower,\n IsEnabled = IsEnabled\n };\n }\n}\n\npublic enum WordClickAction\n{\n Translation,\n Clipboard,\n ClipboardAll,\n PDIC\n}\n"], ["/LLPlayer/FlyleafLib/MediaPlayer/SubtitlesOCR.cs", "using System.Collections.Generic;\nusing System.Drawing;\nusing System.Drawing.Drawing2D;\nusing System.Drawing.Imaging;\nusing System.IO;\nusing System.Linq;\nusing System.Runtime.InteropServices;\nusing System.Threading;\nusing System.Threading.Tasks;\nusing Windows.Graphics.Imaging;\nusing Windows.Media.Ocr;\nusing Windows.Storage.Streams;\nusing Color = System.Drawing.Color;\nusing ImageFormat = System.Drawing.Imaging.ImageFormat;\nusing PixelFormat = System.Drawing.Imaging.PixelFormat;\n\nnamespace FlyleafLib.MediaPlayer;\n\n#nullable enable\n\npublic unsafe class SubtitlesOCR\n{\n private readonly Config.SubtitlesConfig _config;\n private int _subNum;\n\n private readonly CancellationTokenSource?[] _ctss;\n private readonly object[] _lockers;\n private IOCRService? _ocrService;\n\n public SubtitlesOCR(Config.SubtitlesConfig config, int subNum)\n {\n _config = config;\n _subNum = subNum;\n\n _lockers = new object[subNum];\n _ctss = new CancellationTokenSource[subNum];\n for (int i = 0; i < subNum; i++)\n {\n _lockers[i] = new object();\n _ctss[i] = new CancellationTokenSource();\n }\n }\n\n /// \n /// Try to initialize OCR Engine\n /// \n /// OCR Language\n /// expected initialize error\n /// whether to success to initialize\n public bool TryInitialize(int subIndex, Language lang, out string err)\n {\n lang = GetLanguageWithFallback(subIndex, lang);\n\n // Retaining engines will increase memory usage, so they are created and discarded on the fly.\n IOCRService ocrService = _config[subIndex].OCREngine switch\n {\n SubOCREngineType.Tesseract => new TesseractOCRService(_config),\n SubOCREngineType.MicrosoftOCR => new MicrosoftOCRService(_config),\n _ => throw new InvalidOperationException(),\n };\n\n if (!ocrService.TryInitialize(lang, out err))\n {\n return false;\n }\n\n _ocrService = ocrService;\n\n err = \"\";\n return true;\n }\n\n /// \n /// Do OCR\n /// \n /// 0: Primary, 1: Secondary\n /// List of subtitle data for OCR\n /// Timestamp to start OCR\n public void Do(int subIndex, List subs, TimeSpan? startTime = null)\n {\n if (_ocrService == null)\n throw new InvalidOperationException(\"ocrService is not initialized. you must call TryInitialize() first\");\n\n if (subs.Count == 0 || !subs[0].IsBitmap)\n return;\n\n // Cancel preceding OCR\n TryCancelWait(subIndex);\n\n lock (_lockers[subIndex])\n {\n // NOTE: important to dispose inside lock\n using IOCRService ocrService = _ocrService;\n\n _ctss[subIndex] = new CancellationTokenSource();\n\n int startIndex = 0;\n // Start OCR from the current playback point\n if (startTime.HasValue)\n {\n int match = subs.FindIndex(s => s.StartTime >= startTime);\n if (match != -1)\n {\n // Do from 5 previous subtitles\n startIndex = Math.Max(0, match - 5);\n }\n }\n\n for (int i = 0; i < subs.Count; i++)\n {\n if (_ctss[subIndex]!.Token.IsCancellationRequested)\n {\n foreach (var sub in subs)\n {\n sub.Dispose();\n }\n\n break;\n }\n\n int index = (startIndex + i) % subs.Count;\n\n SubtitleBitmapData? bitmap = subs[index].Bitmap;\n if (bitmap == null)\n continue;\n\n // TODO: L: If it's disposed, do I need to cancel it later?\n subs[index].Text = Process(ocrService, subIndex, bitmap);\n if (!string.IsNullOrEmpty(subs[index].Text))\n {\n // If OCR succeeds, dispose of it (if it fails, leave it so that it can be displayed in the sidebar).\n subs[index].Dispose();\n }\n }\n\n if (!_ctss[subIndex]!.Token.IsCancellationRequested)\n {\n // TODO: L: Notify, express completion in some way\n Utils.PlayCompletionSound();\n }\n }\n }\n\n private Language GetLanguageWithFallback(int subIndex, Language lang)\n {\n if (lang == Language.Unknown)\n {\n // fallback to user set language\n lang = subIndex == 0 ? _config.LanguageFallbackPrimary : _config.LanguageFallbackSecondary;\n }\n\n return lang;\n }\n\n public void TryCancelWait(int subIndex)\n {\n if (_ctss[subIndex] != null)\n {\n // Cancel if preceding OCR is running\n _ctss[subIndex]!.Cancel();\n\n // Wait until it is canceled by taking a lock\n lock (_lockers[subIndex])\n {\n _ctss[subIndex]?.Dispose();\n _ctss[subIndex] = null;\n }\n }\n }\n\n public static string Process(IOCRService ocrService, int subIndex, SubtitleBitmapData sub)\n {\n (byte[] data, AVSubtitleRect rect) = sub.SubToBitmap(true);\n\n int width = rect.w;\n int height = rect.h;\n\n fixed (byte* ptr = data)\n {\n // TODO: L: Make it possible to set true here in config (should the bitmap itself have an invert function automatically?)\n Binarize(width, height, ptr, 4, true);\n }\n\n using Bitmap bitmap = new(width, height, PixelFormat.Format32bppArgb);\n BitmapData bitmapData = bitmap.LockBits(\n new Rectangle(0, 0, width, height),\n ImageLockMode.WriteOnly, bitmap.PixelFormat);\n Marshal.Copy(data, 0, bitmapData.Scan0, data.Length);\n bitmap.UnlockBits(bitmapData);\n\n // Perform preprocessing to improve accuracy before OCR (common processing independent of OCR method)\n using Bitmap ocrBitmap = Preprocess(bitmap);\n\n string ocrText = ocrService.RecognizeTextAsync(ocrBitmap).GetAwaiter().GetResult();\n string processedText = ocrService.PostProcess(ocrText);\n\n return processedText;\n }\n\n private static Bitmap Preprocess(Bitmap bitmap)\n {\n using Bitmap blackText = ImageProcessor.BlackText(bitmap);\n Bitmap padded = ImageProcessor.AddPadding(blackText, 20);\n\n return padded;\n }\n\n /// \n /// Perform binarization on bitmaps\n /// \n /// \n /// \n /// \n /// \n /// \n private static void Binarize(int width, int height, byte* buffer, int pixelByte, bool srcTextWhite)\n {\n // Black text on white background\n byte white = 255;\n byte black = 0;\n if (srcTextWhite)\n {\n // The text is white on a black background, so invert it to black text.\n white = 0;\n black = 255;\n }\n\n for (int y = 0; y < height; y++)\n {\n for (int x = 0; x < width; x++)\n {\n byte* pixel = buffer + (y * width + x) * pixelByte;\n // Take out the first R bits since they are already in grayscale\n int grayscale = pixel[0];\n byte binaryValue = grayscale < 128 ? black : white;\n pixel[0] = pixel[1] = pixel[2] = binaryValue;\n }\n }\n }\n\n public void Reset(int subIndex)\n {\n TryCancelWait(subIndex);\n }\n}\n\npublic interface IOCRService : IDisposable\n{\n bool TryInitialize(Language lang, out string err);\n Task RecognizeTextAsync(Bitmap bitmap);\n string PostProcess(string text);\n}\n\npublic class TesseractOCRService : IOCRService\n{\n private readonly Config.SubtitlesConfig _config;\n private TesseractOCR.Engine? _ocrEngine;\n private bool _disposed;\n private Language? _lang;\n\n public TesseractOCRService(Config.SubtitlesConfig config)\n {\n _config = config;\n }\n\n public bool TryInitialize(Language lang, out string err)\n {\n _lang = lang;\n\n string iso6391 = lang.ISO6391;\n\n if (iso6391 == \"nb\")\n {\n // Norwegian Bokmål to Norwegian\n iso6391 = \"no\";\n }\n\n Dictionary> tesseractModels = TesseractModelLoader.GetAvailableModels();\n\n if (!tesseractModels.TryGetValue(iso6391, out List? models))\n {\n err = $\"Language:{lang.TopEnglishName} ({iso6391}) is not available in Tesseract OCR, Please download a model in settings if available language.\";\n\n return false;\n }\n\n TesseractModel model = models.First();\n if (_config.TesseractOcrRegions != null && models.Count >= 2)\n {\n // choose zh-CN or zh-TW (for Chinese)\n if (_config.TesseractOcrRegions.TryGetValue(iso6391, out string? langCode))\n {\n TesseractModel? m = models.FirstOrDefault(m => m.LangCode == langCode);\n if (m != null)\n {\n model = m;\n }\n }\n }\n\n _ocrEngine = new TesseractOCR.Engine(\n TesseractModel.ModelsDirectory,\n model.Lang);\n\n bool isCJK = model.Lang is\n TesseractOCR.Enums.Language.Japanese or\n TesseractOCR.Enums.Language.Korean or\n TesseractOCR.Enums.Language.ChineseSimplified or\n TesseractOCR.Enums.Language.ChineseTraditional;\n\n if (isCJK)\n {\n // remove whitespace around word if CJK\n _ocrEngine.SetVariable(\"preserve_interword_spaces\", 1);\n }\n\n err = string.Empty;\n return true;\n }\n\n public Task RecognizeTextAsync(Bitmap bitmap)\n {\n if (_ocrEngine == null)\n throw new InvalidOperationException(\"ocrEngine is not initialized\");\n\n using MemoryStream stream = new();\n\n // 32bit -> 24bit conversion\n Bitmap converted = new Bitmap(bitmap.Width, bitmap.Height, PixelFormat.Format24bppRgb);\n using (Graphics g = Graphics.FromImage(converted))\n {\n g.DrawImage(bitmap, 0, 0);\n }\n\n converted.Save(stream, ImageFormat.Bmp);\n\n stream.Position = 0;\n\n using var img = TesseractOCR.Pix.Image.LoadFromMemory(stream);\n\n using var page = _ocrEngine.Process(img);\n return Task.FromResult(page.Text);\n }\n\n public string PostProcess(string text)\n {\n var processedText = text;\n\n if (_lang == Language.English)\n {\n processedText = processedText\n .Replace(\"|\", \"I\")\n .Replace(\"I1t's\", \"It's\")\n .Replace(\"’'\", \"'\");\n }\n\n // common\n processedText = processedText\n .Trim();\n\n return processedText;\n }\n\n public void Dispose()\n {\n if (_disposed)\n return;\n\n _ocrEngine?.Dispose();\n _disposed = true;\n }\n}\n\npublic class MicrosoftOCRService : IOCRService\n{\n private readonly Config.SubtitlesConfig _config;\n private OcrEngine? _ocrEngine;\n private bool _isCJK;\n private bool _disposed;\n\n public MicrosoftOCRService(Config.SubtitlesConfig config)\n {\n _config = config;\n }\n\n public bool TryInitialize(Language lang, out string err)\n {\n string iso6391 = lang.ISO6391;\n\n string? langTag = null;\n\n if (_config.MsOcrRegions.TryGetValue(iso6391, out string? tag))\n {\n // If there is a preferred language region in the settings, it is given priority.\n langTag = tag;\n }\n else\n {\n var availableLangs = OcrEngine.AvailableRecognizerLanguages.ToList();\n\n // full match\n var match = availableLangs.FirstOrDefault(l => l.LanguageTag == iso6391);\n\n if (match == null)\n {\n // left match\n match = availableLangs.FirstOrDefault(l => l.LanguageTag.StartsWith($\"{iso6391}-\"));\n }\n\n if (match != null)\n {\n langTag = match.LanguageTag;\n }\n }\n\n if (langTag == null)\n {\n err = $\"Language:{lang.TopEnglishName} ({iso6391}) is not available in Microsoft OCR, Please install an OCR engine if available language.\";\n return false;\n }\n\n var language = new Windows.Globalization.Language(langTag);\n\n OcrEngine ocrEngine = OcrEngine.TryCreateFromLanguage(language);\n if (ocrEngine == null)\n {\n err = $\"Language:{lang.TopEnglishName} ({iso6391}) is not available in Microsoft OCR (TryCreateFromLanguage), Please install an OCR engine if available language.\";\n return false;\n }\n\n _ocrEngine = ocrEngine;\n _isCJK = langTag.StartsWith(\"zh\", StringComparison.OrdinalIgnoreCase) || // Chinese\n langTag.StartsWith(\"ja\", StringComparison.OrdinalIgnoreCase); // Japanese\n\n err = string.Empty;\n return true;\n }\n\n public async Task RecognizeTextAsync(Bitmap bitmap)\n {\n if (_ocrEngine == null)\n throw new InvalidOperationException(\"ocrEngine is not initialized\");\n\n using MemoryStream ms = new();\n\n bitmap.Save(ms, ImageFormat.Bmp);\n ms.Position = 0;\n\n using IRandomAccessStream randomAccessStream = ms.AsRandomAccessStream();\n BitmapDecoder decoder = await BitmapDecoder.CreateAsync(randomAccessStream);\n using SoftwareBitmap softwareBitmap = await decoder.GetSoftwareBitmapAsync();\n\n OcrResult ocrResult = await _ocrEngine.RecognizeAsync(softwareBitmap);\n\n if (_isCJK)\n {\n // remove whitespace around word if CJK\n return string.Join(Environment.NewLine,\n ocrResult.Lines.Select(line => string.Concat(line.Words.Select(word => word.Text))));\n }\n\n return string.Join(Environment.NewLine, ocrResult.Lines.Select(l => l.Text));\n }\n\n public string PostProcess(string text)\n {\n return text;\n }\n\n public void Dispose()\n {\n if (_disposed)\n return;\n\n // do nothing\n _disposed = true;\n }\n}\n\npublic static class ImageProcessor\n{\n /// \n /// Converts to black text on a white background\n /// \n /// original bitmap\n /// processed bitmap\n public static Bitmap BlackText(Bitmap original)\n {\n Bitmap converted = new(original.Width, original.Height, original.PixelFormat);\n\n using (Graphics g = Graphics.FromImage(converted))\n {\n // Convert to black text on a white background\n g.Clear(Color.White);\n\n // Drawing images with alpha blending enabled\n g.CompositingMode = System.Drawing.Drawing2D.CompositingMode.SourceOver;\n\n g.DrawImage(original, 0, 0);\n }\n\n return converted;\n }\n\n /// \n /// Add white padding around the bitmap\n /// \n /// original bitmap\n /// Size of padding to be added (in pixels)\n /// padded bitmap\n public static Bitmap AddPadding(Bitmap original, int padding)\n {\n int newWidth = original.Width + padding * 2;\n int newHeight = original.Height + padding * 2;\n\n Bitmap paddedBitmap = new(newWidth, newHeight, original.PixelFormat);\n\n using (Graphics graphics = Graphics.FromImage(paddedBitmap))\n {\n // White background\n graphics.Clear(Color.White);\n\n graphics.InterpolationMode = InterpolationMode.HighQualityBicubic;\n graphics.CompositingQuality = CompositingQuality.HighQuality;\n graphics.SmoothingMode = SmoothingMode.HighQuality;\n graphics.PixelOffsetMode = PixelOffsetMode.HighQuality;\n\n // Draw the original image in the center\n graphics.DrawImage(original, padding, padding, original.Width, original.Height);\n }\n\n return paddedBitmap;\n }\n\n /// \n /// Enlarge the size of the bitmap while maintaining the aspect ratio.\n /// \n /// source bitmap\n /// processed bitmap\n private static Bitmap ResizeBitmap(Bitmap original, double scaleFactor)\n {\n // Calculate new size\n int newWidth = (int)(original.Width * scaleFactor);\n int newHeight = (int)(original.Height * scaleFactor);\n\n Bitmap resizedBitmap = new(newWidth, newHeight);\n\n using (Graphics graphics = Graphics.FromImage(resizedBitmap))\n {\n graphics.InterpolationMode = InterpolationMode.HighQualityBicubic;\n graphics.CompositingQuality = CompositingQuality.HighQuality;\n graphics.SmoothingMode = SmoothingMode.HighQuality;\n graphics.PixelOffsetMode = PixelOffsetMode.HighQuality;\n\n // resize\n graphics.DrawImage(original, 0, 0, newWidth, newHeight);\n }\n\n return resizedBitmap;\n }\n}\n"], ["/LLPlayer/FlyleafLib/MediaFramework/MediaRenderer/Renderer.PixelShader.cs", "using System.Collections.Generic;\nusing System.Threading;\n\nusing Vortice.Direct3D;\nusing Vortice.Direct3D11;\nusing Vortice.DXGI;\nusing Vortice.Mathematics;\nusing Vortice;\n\nusing FlyleafLib.MediaFramework.MediaDecoder;\nusing FlyleafLib.MediaFramework.MediaFrame;\n\nusing static FlyleafLib.Logger;\n\nusing ID3D11Texture2D = Vortice.Direct3D11.ID3D11Texture2D;\n\nnamespace FlyleafLib.MediaFramework.MediaRenderer;\n\nunsafe public partial class Renderer\n{\n static string[] pixelOffsets = new[] { \"r\", \"g\", \"b\", \"a\" };\n enum PSDefines { HDR, HLG, YUV }\n enum PSCase : int\n {\n None,\n HWD3D11VP,\n HWD3D11VPZeroCopy,\n HW,\n HWZeroCopy,\n\n RGBPacked,\n RGBPacked2,\n RGBPlanar,\n\n YUVPacked,\n YUVSemiPlanar,\n YUVPlanar,\n SwsScale\n }\n\n bool checkHDR;\n PSCase curPSCase;\n string curPSUniqueId;\n float curRatio = 1.0f;\n string prevPSUniqueId;\n internal bool forceNotExtractor; // TBR: workaround until we separate the Extractor?\n\n Texture2DDescription[] textDesc= new Texture2DDescription[4];\n ShaderResourceViewDescription[] srvDesc = new ShaderResourceViewDescription[4];\n SubresourceData[] subData = new SubresourceData[1];\n Box cropBox = new(0, 0, 0, 0, 0, 1);\n\n void InitPS()\n {\n for (int i=0; iflags & PixFmtFlags.Be) == 0) // We currently force SwsScale for BE (RGBA64/BGRA64 BE noted that could work as is?*)\n {\n if (videoProcessor == VideoProcessors.D3D11)\n {\n if (oldVP != videoProcessor)\n {\n VideoDecoder.DisposeFrames();\n Config.Video.Filters[VideoFilters.Brightness].Value = Config.Video.Filters[VideoFilters.Brightness].DefaultValue;\n Config.Video.Filters[VideoFilters.Contrast].Value = Config.Video.Filters[VideoFilters.Contrast].DefaultValue;\n }\n\n inputColorSpace = new()\n {\n Usage = 0,\n RGB_Range = VideoStream.AVStream->codecpar->color_range == AVColorRange.Jpeg ? (uint) 0 : 1,\n YCbCr_Matrix = VideoStream.ColorSpace != ColorSpace.BT601 ? (uint) 1 : 0,\n YCbCr_xvYCC = 0,\n Nominal_Range = VideoStream.AVStream->codecpar->color_range == AVColorRange.Jpeg ? (uint) 2 : 1\n };\n\n vpov?.Dispose();\n vd1.CreateVideoProcessorOutputView(backBuffer, vpe, vpovd, out vpov);\n vc.VideoProcessorSetStreamColorSpace(vp, 0, inputColorSpace);\n vc.VideoProcessorSetOutputColorSpace(vp, outputColorSpace);\n\n if (child != null)\n {\n child.vpov?.Dispose();\n vd1.CreateVideoProcessorOutputView(child.backBuffer, vpe, vpovd, out child.vpov);\n }\n\n if (VideoDecoder.ZeroCopy)\n curPSCase = PSCase.HWD3D11VPZeroCopy;\n else\n {\n curPSCase = PSCase.HWD3D11VP;\n\n textDesc[0].BindFlags |= BindFlags.RenderTarget;\n\n cropBox.Right = (int)VideoStream.Width;\n textDesc[0].Width = VideoStream.Width;\n cropBox.Bottom = (int)VideoStream.Height;\n textDesc[0].Height = VideoStream.Height;\n textDesc[0].Format = VideoDecoder.textureFFmpeg.Description.Format;\n }\n }\n else if (!Config.Video.SwsForce || VideoDecoder.VideoAccelerated) // FlyleafVP\n {\n List defines = new();\n\n if (oldVP != videoProcessor)\n {\n VideoDecoder.DisposeFrames();\n Config.Video.Filters[VideoFilters.Brightness].Value = Config.Video.Filters[VideoFilters.Brightness].Minimum + ((Config.Video.Filters[VideoFilters.Brightness].Maximum - Config.Video.Filters[VideoFilters.Brightness].Minimum) / 2);\n Config.Video.Filters[VideoFilters.Contrast].Value = Config.Video.Filters[VideoFilters.Contrast].Minimum + ((Config.Video.Filters[VideoFilters.Contrast].Maximum - Config.Video.Filters[VideoFilters.Contrast].Minimum) / 2);\n }\n\n if (IsHDR)\n {\n // TBR: It currently works better without it\n //if (VideoStream.ColorTransfer == AVColorTransferCharacteristic.AVCOL_TRC_ARIB_STD_B67)\n //{\n // defines.Add(PSDefines.HLG.ToString());\n // curPSUniqueId += \"g\";\n //}\n\n curPSUniqueId += \"h\";\n defines.Add(PSDefines.HDR.ToString());\n psBufferData.coefsIndex = 0;\n UpdateHDRtoSDR(false);\n }\n else\n psBufferData.coefsIndex = VideoStream.ColorSpace == ColorSpace.BT709 ? 1 : 2;\n\n for (int i=0; i 8)\n {\n srvDesc[0].Format = Format.R16_UNorm;\n srvDesc[1].Format = Format.R16G16_UNorm;\n }\n else\n {\n srvDesc[0].Format = Format.R8_UNorm;\n srvDesc[1].Format = Format.R8G8_UNorm;\n }\n\n if (VideoDecoder.ZeroCopy)\n {\n curPSCase = PSCase.HWZeroCopy;\n curPSUniqueId += ((int)curPSCase).ToString();\n\n for (int i=0; i 8)\n {\n curPSUniqueId += \"x\";\n textDesc[0].Format = srvDesc[0].Format = Format.R16G16B16A16_UNorm;\n }\n else if (VideoStream.PixelComp0Depth > 4)\n textDesc[0].Format = srvDesc[0].Format = Format.R8G8B8A8_UNorm; // B8G8R8X8_UNorm for 0[rgb]?\n\n string offsets = \"\";\n for (int i = 0; i < VideoStream.PixelComps.Length; i++)\n offsets += pixelOffsets[(int) (VideoStream.PixelComps[i].offset / Math.Ceiling(VideoStream.PixelComp0Depth / 8.0))];\n\n curPSUniqueId += offsets;\n\n if (VideoStream.PixelComps.Length > 3)\n SetPS(curPSUniqueId, $\"color = Texture1.Sample(Sampler, input.Texture).{offsets};\");\n else\n SetPS(curPSUniqueId, $\"color = float4(Texture1.Sample(Sampler, input.Texture).{offsets}, 1.0);\");\n }\n\n // [BGR/RGB]16\n else if (VideoStream.PixelPlanes == 1 && (\n VideoStream.PixelFormat == AVPixelFormat.Rgb444le||\n VideoStream.PixelFormat == AVPixelFormat.Bgr444le))\n {\n curPSCase = PSCase.RGBPacked2;\n curPSUniqueId += ((int)curPSCase).ToString();\n\n textDesc[0].Width = VideoStream.Width;\n textDesc[0].Height = VideoStream.Height;\n\n textDesc[0].Format = srvDesc[0].Format = Format.B4G4R4A4_UNorm;\n\n if (VideoStream.PixelFormat == AVPixelFormat.Rgb444le)\n {\n curPSUniqueId += \"a\";\n SetPS(curPSUniqueId, $\"color = float4(Texture1.Sample(Sampler, input.Texture).rgb, 1.0);\");\n }\n else\n {\n curPSUniqueId += \"b\";\n SetPS(curPSUniqueId, $\"color = float4(Texture1.Sample(Sampler, input.Texture).bgr, 1.0);\");\n }\n }\n\n // GBR(A) <=16\n else if (VideoStream.PixelPlanes > 2 && VideoStream.PixelComp0Depth <= 16)\n {\n curPSCase = PSCase.RGBPlanar;\n curPSUniqueId += ((int)curPSCase).ToString();\n\n for (int i=0; i 8)\n {\n curPSUniqueId += VideoStream.PixelComp0Depth;\n\n for (int i=0; i> 1);\n textDesc[0].Width = VideoStream.Width;\n textDesc[0].Height = VideoStream.Height;\n\n if (VideoStream.PixelComp0Depth > 8)\n {\n curPSUniqueId += $\"{VideoStream.Width}_\";\n textDesc[0].Format = Format.Y210;\n srvDesc[0].Format = Format.R16G16B16A16_UNorm;\n }\n else\n {\n curPSUniqueId += $\"{VideoStream.Width}\";\n textDesc[0].Format = Format.YUY2;\n srvDesc[0].Format = Format.R8G8B8A8_UNorm;\n }\n\n string header = @\"\n float posx = input.Texture.x - (texWidth * 0.25);\n float fx = frac(posx / texWidth);\n float pos1 = posx + ((0.5 - fx) * texWidth);\n float pos2 = posx + ((1.5 - fx) * texWidth);\n\n float4 c1 = Texture1.Sample(Sampler, float2(pos1, input.Texture.y));\n float4 c2 = Texture1.Sample(Sampler, float2(pos2, input.Texture.y));\n\n \";\n if (VideoStream.PixelFormat == AVPixelFormat.Yuyv422 ||\n VideoStream.PixelFormat == AVPixelFormat.Y210le)\n {\n curPSUniqueId += $\"a\";\n\n SetPS(curPSUniqueId, header + @\"\n float leftY = lerp(c1.r, c1.b, fx * 2);\n float rightY = lerp(c1.b, c2.r, fx * 2 - 1);\n float2 outUV = lerp(c1.ga, c2.ga, fx);\n float outY = lerp(leftY, rightY, step(0.5, fx));\n color = float4(outY, outUV, 1.0);\n \", defines);\n } else if (VideoStream.PixelFormat == AVPixelFormat.Yvyu422)\n {\n curPSUniqueId += $\"b\";\n\n SetPS(curPSUniqueId, header + @\"\n float leftY = lerp(c1.r, c1.b, fx * 2);\n float rightY = lerp(c1.b, c2.r, fx * 2 - 1);\n float2 outUV = lerp(c1.ag, c2.ag, fx);\n float outY = lerp(leftY, rightY, step(0.5, fx));\n color = float4(outY, outUV, 1.0);\n \", defines);\n } else if (VideoStream.PixelFormat == AVPixelFormat.Uyvy422)\n {\n curPSUniqueId += $\"c\";\n\n SetPS(curPSUniqueId, header + @\"\n float leftY = lerp(c1.g, c1.a, fx * 2);\n float rightY = lerp(c1.a, c2.g, fx * 2 - 1);\n float2 outUV = lerp(c1.rb, c2.rb, fx);\n float outY = lerp(leftY, rightY, step(0.5, fx));\n color = float4(outY, outUV, 1.0);\n \", defines);\n }\n }\n\n // Y_UV | nv12,nv21,nv24,nv42,p010le,p016le,p410le,p416le | (log2_chroma_w != log2_chroma_h / Interleaved) (? nv16,nv20le,p210le,p216le)\n // This covers all planes == 2 YUV (Semi-Planar)\n else if (VideoStream.PixelPlanes == 2) // && VideoStream.PixelSameDepth) && !VideoStream.PixelInterleaved)\n {\n curPSCase = PSCase.YUVSemiPlanar;\n curPSUniqueId += ((int)curPSCase).ToString();\n\n textDesc[0].Width = VideoStream.Width;\n textDesc[0].Height = VideoStream.Height;\n textDesc[1].Width = VideoStream.PixelFormatDesc->log2_chroma_w > 0 ? (VideoStream.Width + 1) >> VideoStream.PixelFormatDesc->log2_chroma_w : VideoStream.Width >> VideoStream.PixelFormatDesc->log2_chroma_w;\n textDesc[1].Height = VideoStream.PixelFormatDesc->log2_chroma_h > 0 ? (VideoStream.Height + 1) >> VideoStream.PixelFormatDesc->log2_chroma_h : VideoStream.Height >> VideoStream.PixelFormatDesc->log2_chroma_h;\n\n string offsets = VideoStream.PixelComps[1].offset > VideoStream.PixelComps[2].offset ? \"gr\" : \"rg\";\n\n if (VideoStream.PixelComp0Depth > 8)\n {\n curPSUniqueId += \"x\";\n textDesc[0].Format = srvDesc[0].Format = Format.R16_UNorm;\n textDesc[1].Format = srvDesc[1].Format = Format.R16G16_UNorm;\n }\n else\n {\n textDesc[0].Format = srvDesc[0].Format = Format.R8_UNorm;\n textDesc[1].Format = srvDesc[1].Format = Format.R8G8_UNorm;\n }\n\n SetPS(curPSUniqueId, @\"\n color = float4(\n Texture1.Sample(Sampler, input.Texture).r,\n Texture2.Sample(Sampler, input.Texture).\" + offsets + @\",\n 1.0);\n \", defines);\n }\n\n // Y_U_V\n else if (VideoStream.PixelPlanes > 2)\n {\n curPSCase = PSCase.YUVPlanar;\n curPSUniqueId += ((int)curPSCase).ToString();\n\n textDesc[0].Width = textDesc[3].Width = VideoStream.Width;\n textDesc[0].Height = textDesc[3].Height= VideoStream.Height;\n textDesc[1].Width = textDesc[2].Width = VideoStream.PixelFormatDesc->log2_chroma_w > 0 ? (VideoStream.Width + 1) >> VideoStream.PixelFormatDesc->log2_chroma_w : VideoStream.Width >> VideoStream.PixelFormatDesc->log2_chroma_w;\n textDesc[1].Height = textDesc[2].Height= VideoStream.PixelFormatDesc->log2_chroma_h > 0 ? (VideoStream.Height + 1) >> VideoStream.PixelFormatDesc->log2_chroma_h : VideoStream.Height >> VideoStream.PixelFormatDesc->log2_chroma_h;\n\n string shader = @\"\n color.r = Texture1.Sample(Sampler, input.Texture).r;\n color.g = Texture2.Sample(Sampler, input.Texture).r;\n color.b = Texture3.Sample(Sampler, input.Texture).r;\n \";\n\n if (VideoStream.PixelPlanes == 4)\n {\n curPSUniqueId += \"x\";\n\n shader += @\"\n color.a = Texture4.Sample(Sampler, input.Texture).r;\n \";\n }\n\n if (VideoStream.PixelComp0Depth > 8)\n {\n curPSUniqueId += VideoStream.PixelComp0Depth;\n\n for (int i=0; ipts * VideoStream.Timebase) - VideoDecoder.Demuxer.StartTime;\n if (CanTrace) Log.Trace($\"Processes {Utils.TicksToTime(mFrame.timestamp)}\");\n\n if (checkHDR)\n {\n // TODO Dolpy Vision / Vivid\n //var hdrSideDolpyDynamic = av_frame_get_side_data(frame, AVFrameSideDataType.AV_FRAME_DATA_DOVI_METADATA);\n\n var hdrSideDynamic = av_frame_get_side_data(frame, AVFrameSideDataType.DynamicHdrPlus);\n\n if (hdrSideDynamic != null && hdrSideDynamic->data != null)\n {\n hdrPlusData = (AVDynamicHDRPlus*) hdrSideDynamic->data;\n UpdateHDRtoSDR();\n }\n else\n {\n var lightSide = av_frame_get_side_data(frame, AVFrameSideDataType.ContentLightLevel);\n var displaySide = av_frame_get_side_data(frame, AVFrameSideDataType.MasteringDisplayMetadata);\n\n if (lightSide != null && lightSide->data != null && ((AVContentLightMetadata*)lightSide->data)->MaxCLL != 0)\n {\n lightData = *((AVContentLightMetadata*) lightSide->data);\n checkHDR = false;\n UpdateHDRtoSDR();\n }\n\n if (displaySide != null && displaySide->data != null && ((AVMasteringDisplayMetadata*)displaySide->data)->has_luminance != 0)\n {\n displayData = *((AVMasteringDisplayMetadata*) displaySide->data);\n checkHDR = false;\n UpdateHDRtoSDR();\n }\n }\n }\n\n if (curPSCase == PSCase.HWZeroCopy)\n {\n mFrame.srvs = new ID3D11ShaderResourceView[2];\n srvDesc[0].Texture2DArray.FirstArraySlice = srvDesc[1].Texture2DArray.FirstArraySlice = (uint) frame->data[1];\n\n mFrame.srvs[0] = Device.CreateShaderResourceView(VideoDecoder.textureFFmpeg, srvDesc[0]);\n mFrame.srvs[1] = Device.CreateShaderResourceView(VideoDecoder.textureFFmpeg, srvDesc[1]);\n\n mFrame.avFrame = av_frame_alloc();\n av_frame_move_ref(mFrame.avFrame, frame);\n return mFrame;\n }\n\n else if (curPSCase == PSCase.HW)\n {\n mFrame.textures = new ID3D11Texture2D[1];\n mFrame.srvs = new ID3D11ShaderResourceView[2];\n\n mFrame.textures[0] = Device.CreateTexture2D(textDesc[0]);\n context.CopySubresourceRegion(\n mFrame.textures[0], 0, 0, 0, 0, // dst\n VideoDecoder.textureFFmpeg, (uint) frame->data[1], // src\n cropBox); // crop decoder's padding\n\n mFrame.srvs[0] = Device.CreateShaderResourceView(mFrame.textures[0], srvDesc[0]);\n mFrame.srvs[1] = Device.CreateShaderResourceView(mFrame.textures[0], srvDesc[1]);\n }\n\n else if (curPSCase == PSCase.HWD3D11VPZeroCopy)\n {\n mFrame.avFrame = av_frame_alloc();\n av_frame_move_ref(mFrame.avFrame, frame);\n return mFrame;\n }\n\n else if (curPSCase == PSCase.HWD3D11VP)\n {\n mFrame.textures = new ID3D11Texture2D[1];\n mFrame.textures[0] = Device.CreateTexture2D(textDesc[0]);\n context.CopySubresourceRegion(\n mFrame.textures[0], 0, 0, 0, 0, // dst\n VideoDecoder.textureFFmpeg, (uint) frame->data[1], // src\n cropBox); // crop decoder's padding\n }\n\n else if (curPSCase == PSCase.SwsScale)\n {\n mFrame.textures = new ID3D11Texture2D[1];\n mFrame.srvs = new ID3D11ShaderResourceView[1];\n\n sws_scale(VideoDecoder.swsCtx, frame->data.ToRawArray(), frame->linesize.ToArray(), 0, frame->height, VideoDecoder.swsData.ToRawArray(), VideoDecoder.swsLineSize.ToArray());\n\n subData[0].DataPointer = VideoDecoder.swsData[0];\n subData[0].RowPitch = (uint)VideoDecoder.swsLineSize[0];\n\n mFrame.textures[0] = Device.CreateTexture2D(textDesc[0], subData);\n mFrame.srvs[0] = Device.CreateShaderResourceView(mFrame.textures[0], srvDesc[0]);\n }\n\n else\n {\n mFrame.textures = new ID3D11Texture2D[VideoStream.PixelPlanes];\n mFrame.srvs = new ID3D11ShaderResourceView[VideoStream.PixelPlanes];\n\n bool newRotationLinesize = false;\n for (int i = 0; i < VideoStream.PixelPlanes; i++)\n {\n if (frame->linesize[i] < 0)\n {\n // Negative linesize for vertical flipping [TBR: might required for HW as well? (SwsScale does that)] http://ffmpeg.org/doxygen/trunk/structAVFrame.html#aa52bfc6605f6a3059a0c3226cc0f6567\n newRotationLinesize = true;\n subData[0].RowPitch = (uint)(-1 * frame->linesize[i]);\n subData[0].DataPointer = frame->data[i];\n subData[0].DataPointer -= (nint)((subData[0].RowPitch * (VideoStream.Height - 1)));\n }\n else\n {\n newRotationLinesize = false;\n subData[0].RowPitch = (uint)frame->linesize[i];\n subData[0].DataPointer = frame->data[i];\n }\n\n if (subData[0].RowPitch < textDesc[i].Width) // Prevent reading more than the actual data (Access Violation #424)\n {\n av_frame_unref(frame);\n return null;\n }\n\n mFrame.textures[i] = Device.CreateTexture2D(textDesc[i], subData);\n mFrame.srvs[i] = Device.CreateShaderResourceView(mFrame.textures[i], srvDesc[i]);\n }\n\n if (newRotationLinesize != rotationLinesize)\n {\n rotationLinesize = newRotationLinesize;\n UpdateRotation(_RotationAngle);\n }\n }\n\n av_frame_unref(frame);\n return mFrame;\n }\n catch (Exception e)\n {\n av_frame_unref(frame);\n Log.Error($\"Failed to process frame ({e.Message})\");\n return null;\n }\n }\n\n void SetPS(string uniqueId, string sampleHLSL, List defines = null)\n {\n if (curPSUniqueId == prevPSUniqueId)\n return;\n\n ShaderPS?.Dispose();\n ShaderPS = ShaderCompiler.CompilePS(Device, uniqueId, sampleHLSL, defines);\n context.PSSetShader(ShaderPS);\n }\n}\n"], ["/LLPlayer/FlyleafLib/MediaPlayer/Player.Playback.cs", "using System;\nusing System.Runtime.InteropServices;\nusing System.Threading;\nusing System.Threading.Tasks;\nusing System.Windows;\nusing System.Windows.Media;\nusing System.Windows.Media.Imaging;\nusing FlyleafLib.MediaFramework.MediaDecoder;\nusing FlyleafLib.MediaFramework.MediaFrame;\nusing static FlyleafLib.Utils;\nusing static FlyleafLib.Logger;\n\nnamespace FlyleafLib.MediaPlayer;\n\npartial class Player\n{\n string stoppedWithError = null;\n\n /// \n /// Fires on playback stopped by an error or completed / ended successfully \n /// Warning: Uses Invoke and it comes from playback thread so you can't pause/stop etc. You need to use another thread if you have to.\n /// \n public event EventHandler PlaybackStopped;\n protected virtual void OnPlaybackStopped(string error = null)\n {\n if (error != null && LastError == null)\n {\n lastError = error;\n UI(() => LastError = LastError);\n }\n\n PlaybackStopped?.Invoke(this, new PlaybackStoppedArgs(error));\n }\n\n /// \n /// Fires on seek completed for the specified ms (ms will be -1 on failure)\n /// \n public event EventHandler SeekCompleted;\n\n /// \n /// Plays AVS streams\n /// \n public void Play()\n {\n lock (lockActions)\n {\n if (!CanPlay || Status == Status.Playing || Status == Status.Ended)\n return;\n\n status = Status.Playing;\n UI(() => Status = Status);\n }\n\n while (taskPlayRuns || taskSeekRuns) Thread.Sleep(5);\n taskPlayRuns = true;\n\n Thread t = new(() =>\n {\n try\n {\n Engine.TimeBeginPeriod1();\n NativeMethods.SetThreadExecutionState(NativeMethods.EXECUTION_STATE.ES_CONTINUOUS | NativeMethods.EXECUTION_STATE.ES_SYSTEM_REQUIRED | NativeMethods.EXECUTION_STATE.ES_DISPLAY_REQUIRED);\n\n onBufferingStarted = 0;\n onBufferingCompleted = 0;\n requiresBuffering = true;\n\n if (LastError != null)\n {\n lastError = null;\n UI(() => LastError = LastError);\n }\n\n if (Config.Player.Usage == Usage.Audio || !Video.IsOpened)\n ScreamerAudioOnly();\n else\n {\n if (ReversePlayback)\n {\n shouldFlushNext = true;\n ScreamerReverse();\n }\n else\n {\n shouldFlushPrev = true;\n Screamer();\n }\n\n }\n\n }\n catch (Exception ex)\n {\n Log.Error($\"Playback failed ({ex.Message})\");\n RaiseUnknownErrorOccurred($\"Playback failed: {ex.Message}\", UnknownErrorType.Playback, ex);\n }\n finally\n {\n VideoDecoder.DisposeFrame(vFrame);\n vFrame = null;\n for (int i = 0; i < subNum; i++)\n {\n sFrames[i] = null;\n }\n\n if (Status == Status.Stopped)\n decoder?.Initialize();\n else if (decoder != null)\n {\n decoder.PauseOnQueueFull();\n decoder.PauseDecoders();\n }\n\n Audio.ClearBuffer();\n Engine.TimeEndPeriod1();\n NativeMethods.SetThreadExecutionState(NativeMethods.EXECUTION_STATE.ES_CONTINUOUS);\n stoppedWithError = null;\n\n if (IsPlaying)\n {\n if (decoderHasEnded)\n status = Status.Ended;\n else\n {\n if (Video.IsOpened && VideoDemuxer.Interrupter.Timedout)\n stoppedWithError = \"Timeout\";\n else if (onBufferingStarted - 1 == onBufferingCompleted)\n {\n stoppedWithError = \"Playback stopped unexpectedly\";\n OnBufferingCompleted(\"Buffering failed\");\n }\n else\n {\n if (!ReversePlayback)\n {\n if (isLive || Math.Abs(Duration - CurTime) > 3 * 1000 * 10000)\n stoppedWithError = \"Playback stopped unexpectedly\";\n }\n else if (CurTime > 3 * 1000 * 10000)\n stoppedWithError = \"Playback stopped unexpectedly\";\n }\n\n status = Status.Paused;\n }\n }\n\n OnPlaybackStopped(stoppedWithError);\n if (CanDebug) Log.Debug($\"[SCREAMER] Finished (Status: {Status}, Error: {stoppedWithError})\");\n\n UI(() =>\n {\n Status = Status;\n UpdateCurTime();\n });\n\n taskPlayRuns = false;\n }\n });\n t.Priority = Config.Player.ThreadPriority;\n t.Name = $\"[#{PlayerId}] Playback\";\n t.IsBackground = true;\n t.Start();\n }\n\n /// \n /// Pauses AVS streams\n /// \n public void Pause()\n {\n lock (lockActions)\n {\n if (!CanPlay || Status == Status.Ended)\n return;\n\n status = Status.Paused;\n UI(() => Status = Status);\n\n while (taskPlayRuns) Thread.Sleep(5);\n }\n }\n\n public void TogglePlayPause()\n {\n if (IsPlaying)\n Pause();\n else\n Play();\n }\n\n public void ToggleReversePlayback()\n => ReversePlayback = !ReversePlayback;\n\n public void ToggleLoopPlayback()\n => LoopPlayback = !LoopPlayback;\n\n /// \n /// Seeks backwards or forwards based on the specified ms to the nearest keyframe\n /// \n /// \n /// \n public void Seek(int ms, bool forward = false) => Seek(ms, forward, false);\n\n /// \n /// Seeks at the exact timestamp (with half frame distance accuracy)\n /// \n /// \n /// \n public void SeekAccurate(TimeSpan time, int subIndex = -1)\n {\n int ms = (int)time.TotalMilliseconds;\n if (subIndex != -1 && time.Microseconds > 0)\n {\n // When seeking subtitles, rounding down the milliseconds or less will cause the previous subtitle\n // ASR subtitles are in microseconds, so if you truncate, you'll end up one before the current subtitle.\n ms += 1;\n }\n\n SeekAccurate(ms, subIndex);\n }\n\n /// \n /// Seeks at the exact timestamp (with half frame distance accuracy)\n /// \n /// \n /// \n public void SeekAccurate(int ms, int subIndex = -1)\n {\n if (subIndex >= 0)\n {\n ms += (int)(Config.Subtitles[subIndex].Delay / 10000);\n }\n\n Seek(ms, false, !IsLive);\n }\n\n public void ToggleSeekAccurate()\n => Config.Player.SeekAccurate = !Config.Player.SeekAccurate;\n\n private void Seek(int ms, bool forward, bool accurate)\n {\n if (!CanPlay)\n return;\n\n lock (seeks)\n {\n _CurTime = curTime = ms * (long)10000;\n seeks.Push(new SeekData(ms, forward, accurate));\n }\n\n // Set timestamp to Manager immediately after seek to enable continuous seek\n // (Without this, seek is called with the same timestamp on successive calls, so it will seek to the same subtitle.)\n SubtitlesManager.SetCurrentTime(new TimeSpan(curTime));\n\n Raise(nameof(CurTime));\n Raise(nameof(RemainingDuration));\n\n if (Status == Status.Playing)\n return;\n\n lock (seeks)\n {\n if (taskSeekRuns)\n return;\n\n taskSeekRuns = true;\n }\n\n Task.Run(() =>\n {\n int ret;\n bool wasEnded = false;\n SeekData seekData = null;\n\n try\n {\n Engine.TimeBeginPeriod1();\n\n while (true)\n {\n lock (seeks)\n {\n if (!(seeks.TryPop(out seekData) && CanPlay && !IsPlaying))\n {\n taskSeekRuns = false;\n break;\n }\n\n seeks.Clear();\n }\n\n if (Status == Status.Ended)\n {\n wasEnded = true;\n status = Status.Paused;\n UI(() => Status = Status);\n }\n\n for (int i = 0; i < subNum; i++)\n {\n // Display subtitles from cache when seeking while paused\n bool display = false;\n var cur = SubtitlesManager[i].GetCurrent();\n if (cur != null)\n {\n if (!string.IsNullOrEmpty(cur.DisplayText))\n {\n SubtitleDisplay(cur.DisplayText, i, cur.UseTranslated);\n display = true;\n }\n else if (cur.IsBitmap && cur.Bitmap != null)\n {\n SubtitleDisplay(cur.Bitmap, i);\n display = true;\n }\n\n if (display)\n {\n sFramesPrev[i] = new SubtitlesFrame\n {\n timestamp = cur.StartTime.Ticks + Config.Subtitles[i].Delay,\n duration = (uint)cur.Duration.TotalMilliseconds,\n isTranslated = cur.UseTranslated\n };\n }\n }\n\n // clear subtitles\n // but do not clear when cache hit\n if (!display && sFramesPrev[i] != null)\n {\n sFramesPrev[i] = null;\n SubtitleClear(i);\n }\n }\n\n if (!Video.IsOpened)\n {\n if (AudioDecoder.OnVideoDemuxer)\n {\n ret = decoder.Seek(seekData.ms, seekData.forward);\n if (CanWarn && ret < 0)\n Log.Warn(\"Seek failed 2\");\n\n VideoDemuxer.Start();\n SeekCompleted?.Invoke(this, -1);\n }\n else\n {\n ret = decoder.SeekAudio(seekData.ms, seekData.forward);\n if (CanWarn && ret < 0)\n Log.Warn(\"Seek failed 3\");\n\n AudioDemuxer.Start();\n SeekCompleted?.Invoke(this, -1);\n }\n\n decoder.PauseOnQueueFull();\n SeekCompleted?.Invoke(this, seekData.ms);\n }\n else\n {\n decoder.PauseDecoders();\n ret = decoder.Seek(seekData.accurate ? Math.Max(0, seekData.ms - (int) new TimeSpan(Config.Player.SeekAccurateFixMargin).TotalMilliseconds) : seekData.ms, seekData.forward, !seekData.accurate); // 3sec ffmpeg bug for seek accurate when fails to seek backwards (see videodecoder getframe)\n if (ret < 0)\n {\n if (CanWarn) Log.Warn(\"Seek failed\");\n SeekCompleted?.Invoke(this, -1);\n }\n else if (!ReversePlayback && CanPlay)\n {\n decoder.GetVideoFrame(seekData.accurate ? seekData.ms * (long)10000 : -1);\n ShowOneFrame();\n VideoDemuxer.Start();\n AudioDemuxer.Start();\n //for (int i = 0; i < subNum; i++)\n //{\n // SubtitlesDemuxers[i].Start();\n //}\n DataDemuxer.Start();\n decoder.PauseOnQueueFull();\n SeekCompleted?.Invoke(this, seekData.ms);\n }\n }\n\n Thread.Sleep(20);\n }\n }\n catch (Exception e)\n {\n lock (seeks) taskSeekRuns = false;\n Log.Error($\"Seek failed ({e.Message})\");\n }\n finally\n {\n decoder.OpenedPlugin?.OnBufferingCompleted();\n Engine.TimeEndPeriod1();\n if ((wasEnded && Config.Player.AutoPlay) || stoppedWithError != null) // TBR: Possible race condition with if (Status == Status.Playing)\n Play();\n }\n });\n }\n\n /// \n /// Flushes the buffer (demuxers (packets) and decoders (frames))\n /// This is useful mainly for live streams to push the playback at very end (low latency)\n /// \n public void Flush()\n {\n decoder.Flush();\n OSDMessage = \"Buffer Flushed\";\n }\n\n /// \n /// Stops and Closes AVS streams\n /// \n public void Stop()\n {\n lock (lockActions)\n {\n Initialize();\n renderer?.Flush();\n }\n }\n public void SubtitleClear()\n {\n for (int i = 0; i < subNum; i++)\n {\n SubtitleClear(i);\n }\n }\n\n public void SubtitleClear(int subIndex)\n {\n Subtitles[subIndex].Data.Clear();\n //renderer.ClearOverlayTexture();\n }\n\n /// \n /// Updated text format subtitle display\n /// \n /// \n /// \n /// \n public void SubtitleDisplay(string text, int subIndex, bool isTranslated)\n {\n UI(() =>\n {\n Subtitles[subIndex].Data.IsTranslated = isTranslated;\n Subtitles[subIndex].Data.Language = isTranslated\n ? Config.Subtitles.TranslateLanguage\n : SubtitlesManager[subIndex].Language;\n\n Subtitles[subIndex].Data.Text = text;\n Subtitles[subIndex].Data.Bitmap = null;\n });\n }\n\n public void SubtitleDisplay(SubtitleBitmapData bitmapData, int subIndex)\n {\n if (bitmapData.Sub.num_rects == 0)\n {\n return;\n }\n\n (byte[] data, AVSubtitleRect rect) = bitmapData.SubToBitmap(false);\n\n SubtitlesFrameBitmap bitmap = new()\n {\n data = data,\n width = rect.w,\n height = rect.h,\n x = rect.x,\n y = rect.y,\n };\n\n SubtitleDisplay(bitmap, subIndex);\n }\n\n /// \n /// Update bitmap format subtitle display\n /// \n /// \n /// \n public void SubtitleDisplay(SubtitlesFrameBitmap bitmap, int subIndex)\n {\n // TODO: L: refactor\n\n // Each subtitle has a different size and needs to be generated each time.\n WriteableBitmap wb = new(\n bitmap.width, bitmap.height,\n NativeMethods.DpiXSource, NativeMethods.DpiYSource,\n PixelFormats.Bgra32, null\n );\n Int32Rect rect = new(0, 0, bitmap.width, bitmap.height);\n wb.Lock();\n\n Marshal.Copy(bitmap.data, 0, wb.BackBuffer, bitmap.data.Length);\n\n wb.AddDirtyRect(rect);\n wb.Unlock();\n // Note that you will get a UI thread error if you don't call\n wb.Freeze();\n\n int x = bitmap.x;\n int y = bitmap.y;\n int w = bitmap.width;\n int h = bitmap.height;\n\n SubsBitmap subsBitmap = new()\n {\n X = x,\n Y = y,\n Width = w,\n Height = h,\n Source = wb,\n };\n\n UI(() =>\n {\n Subtitles[subIndex].Data.Bitmap = subsBitmap;\n Subtitles[subIndex].Data.Text = \"\";\n });\n }\n}\n\npublic class PlaybackStoppedArgs : EventArgs\n{\n public string Error { get; }\n public bool Success { get; }\n\n public PlaybackStoppedArgs(string error)\n {\n Error = error;\n Success = Error == null;\n }\n}\n\nclass SeekData\n{\n public int ms;\n public bool forward;\n public bool accurate;\n public SeekData(int ms, bool forward, bool accurate)\n { this.ms = ms; this.forward = forward && !accurate; this.accurate = accurate; }\n}\n"], ["/LLPlayer/FlyleafLib/MediaPlayer/Commands.cs", "using System.Threading.Tasks;\nusing System.Windows.Input;\n\nusing FlyleafLib.Controls.WPF;\nusing FlyleafLib.MediaFramework.MediaPlaylist;\nusing FlyleafLib.MediaFramework.MediaStream;\n\nnamespace FlyleafLib.MediaPlayer;\n\npublic class Commands\n{\n public ICommand AudioDelaySet { get; set; }\n public ICommand AudioDelaySet2 { get; set; }\n public ICommand AudioDelayAdd { get; set; }\n public ICommand AudioDelayAdd2 { get; set; }\n public ICommand AudioDelayRemove { get; set; }\n public ICommand AudioDelayRemove2 { get; set; }\n\n public ICommand SubtitlesDelaySetPrimary { get; set; }\n public ICommand SubtitlesDelaySet2Primary { get; set; }\n public ICommand SubtitlesDelayAddPrimary { get; set; }\n public ICommand SubtitlesDelayAdd2Primary { get; set; }\n public ICommand SubtitlesDelayRemovePrimary { get; set; }\n public ICommand SubtitlesDelayRemove2Primary { get; set; }\n\n public ICommand SubtitlesDelaySetSecondary { get; set; }\n public ICommand SubtitlesDelaySet2Secondary { get; set; }\n public ICommand SubtitlesDelayAddSecondary { get; set; }\n public ICommand SubtitlesDelayAdd2Secondary { get; set; }\n public ICommand SubtitlesDelayRemoveSecondary { get; set; }\n public ICommand SubtitlesDelayRemove2Secondary { get; set; }\n\n public ICommand OpenSubtitles { get; set; }\n public ICommand OpenSubtitlesASR { get; set; }\n public ICommand SubtitlesOff { get; set; }\n\n public ICommand Open { get; set; }\n public ICommand OpenFromClipboard { get; set; }\n public ICommand OpenFromFileDialog { get; set; }\n public ICommand Reopen { get; set; }\n public ICommand CopyToClipboard { get; set; }\n public ICommand CopyItemToClipboard { get; set; }\n\n public ICommand Play { get; set; }\n public ICommand Pause { get; set; }\n public ICommand Stop { get; set; }\n public ICommand TogglePlayPause { get; set; }\n\n public ICommand SeekBackward { get; set; }\n public ICommand SeekBackward2 { get; set; }\n public ICommand SeekBackward3 { get; set; }\n public ICommand SeekBackward4 { get; set; }\n public ICommand SeekForward { get; set; }\n public ICommand SeekForward2 { get; set; }\n public ICommand SeekForward3 { get; set; }\n public ICommand SeekForward4 { get; set; }\n public ICommand SeekToChapter { get; set; }\n\n public ICommand ShowFramePrev { get; set; }\n public ICommand ShowFrameNext { get; set; }\n\n public ICommand NormalScreen { get; set; }\n public ICommand FullScreen { get; set; }\n public ICommand ToggleFullScreen { get; set; }\n\n public ICommand ToggleReversePlayback { get; set; }\n public ICommand ToggleLoopPlayback { get; set; }\n public ICommand StartRecording { get; set; }\n public ICommand StopRecording { get; set; }\n public ICommand ToggleRecording { get; set; }\n\n public ICommand TakeSnapshot { get; set; }\n public ICommand ZoomIn { get; set; }\n public ICommand ZoomOut { get; set; }\n public ICommand RotationSet { get; set; }\n public ICommand RotateLeft { get; set; }\n public ICommand RotateRight { get; set; }\n public ICommand ResetAll { get; set; }\n public ICommand ResetSpeed { get; set; }\n public ICommand ResetRotation { get; set; }\n public ICommand ResetZoom { get; set; }\n\n public ICommand SpeedSet { get; set; }\n public ICommand SpeedUp { get; set; }\n public ICommand SpeedUp2 { get; set; }\n public ICommand SpeedDown { get; set; }\n public ICommand SpeedDown2 { get; set; }\n\n public ICommand VolumeUp { get; set; }\n public ICommand VolumeDown { get; set; }\n public ICommand ToggleMute { get; set; }\n\n public ICommand ForceIdle { get; set; }\n public ICommand ForceActive { get; set; }\n public ICommand ForceFullActive { get; set; }\n public ICommand RefreshActive { get; set; }\n public ICommand RefreshFullActive { get; set; }\n\n public ICommand ResetFilter { get; set; }\n\n Player player;\n\n public Commands(Player player)\n {\n this.player = player;\n\n Open = new RelayCommand(OpenAction);\n OpenFromClipboard = new RelayCommandSimple(player.OpenFromClipboard);\n OpenFromFileDialog = new RelayCommandSimple(player.OpenFromFileDialog);\n Reopen = new RelayCommand(ReopenAction);\n CopyToClipboard = new RelayCommandSimple(player.CopyToClipboard);\n CopyItemToClipboard = new RelayCommandSimple(player.CopyItemToClipboard);\n\n Play = new RelayCommandSimple(player.Play);\n Pause = new RelayCommandSimple(player.Pause);\n TogglePlayPause = new RelayCommandSimple(player.TogglePlayPause);\n Stop = new RelayCommandSimple(player.Stop);\n\n SeekBackward = new RelayCommandSimple(player.SeekBackward);\n SeekBackward2 = new RelayCommandSimple(player.SeekBackward2);\n SeekBackward3 = new RelayCommandSimple(player.SeekBackward3);\n SeekBackward4 = new RelayCommandSimple(player.SeekBackward4);\n SeekForward = new RelayCommandSimple(player.SeekForward);\n SeekForward2 = new RelayCommandSimple(player.SeekForward2);\n SeekForward3 = new RelayCommandSimple(player.SeekForward3);\n SeekForward4 = new RelayCommandSimple(player.SeekForward4);\n SeekToChapter = new RelayCommand(SeekToChapterAction);\n\n ShowFrameNext = new RelayCommandSimple(player.ShowFrameNext);\n ShowFramePrev = new RelayCommandSimple(player.ShowFramePrev);\n\n NormalScreen = new RelayCommandSimple(player.NormalScreen);\n FullScreen = new RelayCommandSimple(player.FullScreen);\n ToggleFullScreen = new RelayCommandSimple(player.ToggleFullScreen);\n\n ToggleReversePlayback = new RelayCommandSimple(player.ToggleReversePlayback);\n ToggleLoopPlayback = new RelayCommandSimple(player.ToggleLoopPlayback);\n StartRecording = new RelayCommandSimple(player.StartRecording);\n StopRecording = new RelayCommandSimple(player.StopRecording);\n ToggleRecording = new RelayCommandSimple(player.ToggleRecording);\n\n TakeSnapshot = new RelayCommandSimple(TakeSnapshotAction);\n ZoomIn = new RelayCommandSimple(player.ZoomIn);\n ZoomOut = new RelayCommandSimple(player.ZoomOut);\n RotationSet = new RelayCommand(RotationSetAction);\n RotateLeft = new RelayCommandSimple(player.RotateLeft);\n RotateRight = new RelayCommandSimple(player.RotateRight);\n ResetAll = new RelayCommandSimple(player.ResetAll);\n ResetSpeed = new RelayCommandSimple(player.ResetSpeed);\n ResetRotation = new RelayCommandSimple(player.ResetRotation);\n ResetZoom = new RelayCommandSimple(player.ResetZoom);\n\n SpeedSet = new RelayCommand(SpeedSetAction);\n SpeedUp = new RelayCommandSimple(player.SpeedUp);\n SpeedDown = new RelayCommandSimple(player.SpeedDown);\n SpeedUp2 = new RelayCommandSimple(player.SpeedUp2);\n SpeedDown2 = new RelayCommandSimple(player.SpeedDown2);\n\n VolumeUp = new RelayCommandSimple(player.Audio.VolumeUp);\n VolumeDown = new RelayCommandSimple(player.Audio.VolumeDown);\n ToggleMute = new RelayCommandSimple(player.Audio.ToggleMute);\n\n AudioDelaySet = new RelayCommand(AudioDelaySetAction);\n AudioDelaySet2 = new RelayCommand(AudioDelaySetAction2);\n AudioDelayAdd = new RelayCommandSimple(player.Audio.DelayAdd);\n AudioDelayAdd2 = new RelayCommandSimple(player.Audio.DelayAdd2);\n AudioDelayRemove = new RelayCommandSimple(player.Audio.DelayRemove);\n AudioDelayRemove2 = new RelayCommandSimple(player.Audio.DelayRemove2);\n\n SubtitlesDelaySetPrimary = new RelayCommand(SubtitlesDelaySetActionPrimary);\n SubtitlesDelaySet2Primary = new RelayCommand(SubtitlesDelaySetAction2Primary);\n SubtitlesDelayAddPrimary = new RelayCommandSimple(player.Subtitles.DelayAddPrimary);\n SubtitlesDelayAdd2Primary = new RelayCommandSimple(player.Subtitles.DelayAdd2Primary);\n SubtitlesDelayRemovePrimary = new RelayCommandSimple(player.Subtitles.DelayRemovePrimary);\n SubtitlesDelayRemove2Primary = new RelayCommandSimple(player.Subtitles.DelayRemove2Primary);\n\n SubtitlesDelaySetSecondary = new RelayCommand(SubtitlesDelaySetActionSecondary);\n SubtitlesDelaySet2Secondary = new RelayCommand(SubtitlesDelaySetAction2Secondary);\n SubtitlesDelayAddSecondary = new RelayCommandSimple(player.Subtitles.DelayAddSecondary);\n SubtitlesDelayAdd2Secondary = new RelayCommandSimple(player.Subtitles.DelayAdd2Secondary);\n SubtitlesDelayRemoveSecondary = new RelayCommandSimple(player.Subtitles.DelayRemoveSecondary);\n SubtitlesDelayRemove2Secondary = new RelayCommandSimple(player.Subtitles.DelayRemove2Secondary);\n\n OpenSubtitles = new RelayCommand(OpenSubtitlesAction);\n OpenSubtitlesASR = new RelayCommand(OpenSubtitlesASRAction);\n SubtitlesOff = new RelayCommand(SubtitlesOffAction);\n\n ForceIdle = new RelayCommandSimple(player.Activity.ForceIdle);\n ForceActive = new RelayCommandSimple(player.Activity.ForceActive);\n ForceFullActive = new RelayCommandSimple(player.Activity.ForceFullActive);\n RefreshActive = new RelayCommandSimple(player.Activity.RefreshActive);\n RefreshFullActive = new RelayCommandSimple(player.Activity.RefreshFullActive);\n\n ResetFilter = new RelayCommand(ResetFilterAction);\n }\n\n private void RotationSetAction(object obj)\n => player.Rotation = uint.Parse(obj.ToString());\n\n private void ResetFilterAction(object filter)\n => player.Config.Video.Filters[(VideoFilters)filter].Value = player.Config.Video.Filters[(VideoFilters)filter].DefaultValue;\n\n public void SpeedSetAction(object speed)\n {\n string speedstr = speed.ToString().Replace(',', '.');\n if (double.TryParse(speedstr, System.Globalization.NumberStyles.Any, System.Globalization.CultureInfo.InvariantCulture, out double value))\n player.Speed = value;\n }\n\n public void AudioDelaySetAction(object delay)\n => player.Config.Audio.Delay = int.Parse(delay.ToString()) * (long)10000;\n public void AudioDelaySetAction2(object delay)\n => player.Config.Audio.Delay += int.Parse(delay.ToString()) * (long)10000;\n\n public void SubtitlesDelaySetActionPrimary(object delay)\n => player.Config.Subtitles[0].Delay = int.Parse(delay.ToString()) * (long)10000;\n public void SubtitlesDelaySetAction2Primary(object delay)\n => player.Config.Subtitles[0].Delay += int.Parse(delay.ToString()) * (long)10000;\n\n // TODO: L: refactor\n public void SubtitlesDelaySetActionSecondary(object delay)\n => player.Config.Subtitles[1].Delay = int.Parse(delay.ToString()) * (long)10000;\n public void SubtitlesDelaySetAction2Secondary(object delay)\n => player.Config.Subtitles[1].Delay += int.Parse(delay.ToString()) * (long)10000;\n\n\n public void TakeSnapshotAction() => Task.Run(() => { try { player.TakeSnapshotToFile(); } catch { } });\n\n public void SeekToChapterAction(object chapter)\n {\n if (player.Chapters == null || player.Chapters.Count == 0)\n return;\n\n if (chapter is MediaFramework.MediaDemuxer.Demuxer.Chapter)\n player.SeekToChapter((MediaFramework.MediaDemuxer.Demuxer.Chapter)chapter);\n else if (int.TryParse(chapter.ToString(), out int chapterId) && chapterId < player.Chapters.Count)\n player.SeekToChapter(player.Chapters[chapterId]);\n }\n\n public void OpenSubtitlesAction(object input)\n {\n if (input is not ValueTuple tuple)\n {\n return;\n }\n\n if (tuple is { Item1: string, Item2: SubtitlesStream, Item3: SelectSubMethod })\n {\n var subIndex = int.Parse((string)tuple.Item1);\n var stream = (SubtitlesStream)tuple.Item2;\n var selectSubMethod = (SelectSubMethod)tuple.Item3;\n\n if (selectSubMethod == SelectSubMethod.OCR)\n {\n if (!TryInitializeOCR(subIndex, stream.Language))\n {\n return;\n }\n }\n\n SubtitlesSelectedHelper.Set(subIndex, (stream.StreamIndex, null));\n SubtitlesSelectedHelper.SetMethod(subIndex, selectSubMethod);\n SubtitlesSelectedHelper.CurIndex = subIndex;\n }\n else if (tuple is { Item1: string, Item2: ExternalSubtitlesStream, Item3: SelectSubMethod })\n {\n var subIndex = int.Parse((string)tuple.Item1);\n var stream = (ExternalSubtitlesStream)tuple.Item2;\n var selectSubMethod = (SelectSubMethod)tuple.Item3;\n\n if (selectSubMethod == SelectSubMethod.OCR)\n {\n if (!TryInitializeOCR(subIndex, stream.Language))\n {\n return;\n }\n }\n\n SubtitlesSelectedHelper.Set(subIndex, (null, stream));\n SubtitlesSelectedHelper.SetMethod(subIndex, selectSubMethod);\n SubtitlesSelectedHelper.CurIndex = subIndex;\n }\n\n OpenAction(tuple.Item2);\n return;\n\n bool TryInitializeOCR(int subIndex, Language lang)\n {\n if (!player.SubtitlesOCR.TryInitialize(subIndex, lang, out string err))\n {\n player.RaiseKnownErrorOccurred(err, KnownErrorType.Configuration);\n return false;\n }\n\n return true;\n }\n }\n\n public void OpenSubtitlesASRAction(object input)\n {\n if (!int.TryParse(input.ToString(), out var subIndex))\n {\n return;\n }\n\n if (!player.Audio.IsOpened)\n {\n // not opened\n return;\n }\n\n if (!player.SubtitlesASR.CanExecute(out string err))\n {\n player.RaiseKnownErrorOccurred(err, KnownErrorType.Configuration);\n return;\n }\n\n if (player.IsLive)\n {\n player.RaiseKnownErrorOccurred(\"Currently ASR is not available for live streams.\", KnownErrorType.ASR);\n return;\n }\n\n SubtitlesSelectedHelper.CurIndex = subIndex;\n\n // First, turn off existing subtitles (if not ASR)\n if (!player.Subtitles[subIndex].EnabledASR)\n {\n player.Subtitles[subIndex].Disable();\n }\n\n player.Subtitles[subIndex].EnableASR();\n }\n\n public void SubtitlesOffAction(object input)\n {\n if (int.TryParse(input.ToString(), out var subIndex))\n {\n SubtitlesSelectedHelper.CurIndex = subIndex;\n player.Subtitles[subIndex].Disable();\n }\n }\n\n public void OpenAction(object input)\n {\n if (input == null)\n return;\n\n if (input is StreamBase)\n player.OpenAsync((StreamBase)input);\n else if (input is PlaylistItem)\n player.OpenAsync((PlaylistItem)input);\n else if (input is ExternalStream)\n player.OpenAsync((ExternalStream)input);\n else if (input is System.IO.Stream)\n player.OpenAsync((System.IO.Stream)input);\n else\n player.OpenAsync(input.ToString());\n }\n\n public void ReopenAction(object playlistItem)\n {\n if (playlistItem == null)\n return;\n\n PlaylistItem item = (PlaylistItem)playlistItem;\n if (item.OpenedCounter > 0)\n {\n var session = player.GetSession(item);\n session.isReopen = true;\n session.CurTime = 0;\n\n // TBR: in case of disabled audio/video/subs it will save the session with them to be disabled\n\n // TBR: This can cause issues and it might not useful either\n //if (session.CurTime < 60 * (long)1000 * 10000)\n // session.CurTime = 0;\n\n player.OpenAsync(session);\n }\n else\n player.OpenAsync(item);\n }\n}\n"], ["/LLPlayer/FlyleafLib/MediaPlayer/Translation/Services/OpenAIBaseTranslateService.cs", "using System.Collections.Concurrent;\nusing System.Collections.Generic;\nusing System.Diagnostics;\nusing System.Linq;\nusing System.Net.Http;\nusing System.Text;\nusing System.Text.Encodings.Web;\nusing System.Text.Json;\nusing System.Text.Json.Nodes;\nusing System.Text.Json.Serialization;\nusing System.Threading;\nusing System.Threading.Tasks;\n\nnamespace FlyleafLib.MediaPlayer.Translation.Services;\n\n#nullable enable\n\n// All LLM translation use this class\n// Currently only supports OpenAI compatible API\npublic class OpenAIBaseTranslateService : ITranslateService\n{\n private readonly HttpClient _httpClient;\n private readonly OpenAIBaseTranslateSettings _settings;\n private readonly TranslateChatConfig _chatConfig;\n private readonly bool _wordMode;\n\n private ChatTranslateMethod TranslateMethod => _chatConfig.TranslateMethod;\n\n public OpenAIBaseTranslateService(OpenAIBaseTranslateSettings settings, TranslateChatConfig chatConfig, bool wordMode)\n {\n _httpClient = settings.GetHttpClient();\n _settings = settings;\n _chatConfig = chatConfig;\n _wordMode = wordMode;\n }\n\n private string? _basePrompt;\n private readonly ConcurrentQueue _messageQueue = new();\n\n private static readonly JsonSerializerOptions JsonOptions = new()\n {\n DefaultIgnoreCondition = JsonIgnoreCondition.WhenWritingNull,\n Encoder = JavaScriptEncoder.UnsafeRelaxedJsonEscaping\n };\n\n public TranslateServiceType ServiceType => _settings.ServiceType;\n\n public void Dispose()\n {\n _httpClient.Dispose();\n }\n\n public void Initialize(Language src, TargetLanguage target)\n {\n (TranslateLanguage srcLang, TranslateLanguage targetLang) = this.TryGetLanguage(src, target);\n\n // setup prompt\n string prompt = !_wordMode && TranslateMethod == ChatTranslateMethod.KeepContext\n ? _chatConfig.PromptKeepContext\n : _chatConfig.PromptOneByOne;\n\n string targetLangName = _chatConfig.IncludeTargetLangRegion\n ? target.DisplayName() : targetLang.Name;\n\n _basePrompt = prompt\n .Replace(\"{source_lang}\", srcLang.Name)\n .Replace(\"{target_lang}\", targetLangName);\n }\n\n public async Task TranslateAsync(string text, CancellationToken token)\n {\n if (!_wordMode && TranslateMethod == ChatTranslateMethod.KeepContext)\n {\n return await DoKeepContext(text, token);\n }\n\n return await DoOneByOne(text, token);\n }\n\n private async Task DoKeepContext(string text, CancellationToken token)\n {\n if (_basePrompt == null)\n throw new InvalidOperationException(\"must be initialized\");\n\n // Trim message history if required\n while (_messageQueue.Count / 2 > _chatConfig.SubtitleContextCount)\n {\n if (_chatConfig.ContextRetainPolicy == ChatContextRetainPolicy.KeepSize)\n {\n Debug.Assert(_messageQueue.Count >= 2);\n\n // user\n _messageQueue.TryDequeue(out _);\n // assistant\n _messageQueue.TryDequeue(out _);\n }\n else if (_chatConfig.ContextRetainPolicy == ChatContextRetainPolicy.Reset)\n {\n // clear\n _messageQueue.Clear();\n }\n }\n\n List messages = new(_messageQueue.Count + 2)\n {\n new OpenAIMessage { role = \"system\", content = _basePrompt },\n };\n\n // add history\n messages.AddRange(_messageQueue);\n\n // add new message\n OpenAIMessage newMessage = new() { role = \"user\", content = text };\n messages.Add(newMessage);\n\n string reply = await SendChatRequest(\n _httpClient, _settings, messages.ToArray(), token);\n\n // add to message history if success\n _messageQueue.Enqueue(newMessage);\n _messageQueue.Enqueue(new OpenAIMessage { role = \"assistant\", content = reply });\n\n return reply;\n }\n\n private async Task DoOneByOne(string text, CancellationToken token)\n {\n if (_basePrompt == null)\n throw new InvalidOperationException(\"must be initialized\");\n\n string prompt = _basePrompt.Replace(\"{source_text}\", text);\n\n OpenAIMessage[] messages =\n [\n new() { role = \"user\", content = prompt }\n ];\n\n return await SendChatRequest(_httpClient, _settings, messages, token);\n }\n\n public static async Task Hello(OpenAIBaseTranslateSettings settings)\n {\n using HttpClient client = settings.GetHttpClient();\n\n OpenAIMessage[] messages =\n [\n new() { role = \"user\", content = \"Hello\" }\n ];\n\n return await SendChatRequest(client, settings, messages, CancellationToken.None);\n }\n\n private static async Task SendChatRequest(\n HttpClient client,\n OpenAIBaseTranslateSettings settings,\n OpenAIMessage[] messages,\n CancellationToken token)\n {\n string jsonResultString = string.Empty;\n int statusCode = -1;\n\n // Create the request payload\n OpenAIRequest request = new()\n {\n model = settings.Model,\n stream = false,\n messages = messages,\n\n temperature = settings.TemperatureManual ? settings.Temperature : null,\n top_p = settings.TopPManual ? settings.TopP : null,\n max_completion_tokens = settings.MaxCompletionTokens,\n max_tokens = settings.MaxTokens,\n };\n\n if (!settings.ModelRequired && string.IsNullOrWhiteSpace(settings.Model))\n {\n request.model = null;\n }\n\n try\n {\n // Convert to JSON\n string jsonContent = JsonSerializer.Serialize(request, JsonOptions);\n using var content = new StringContent(jsonContent, Encoding.UTF8, \"application/json\");\n using var result = await client.PostAsync(settings.ChatPath, content, token);\n\n jsonResultString = await result.Content.ReadAsStringAsync(token);\n\n statusCode = (int)result.StatusCode;\n result.EnsureSuccessStatusCode();\n\n OpenAIResponse? chatResponse = JsonSerializer.Deserialize(jsonResultString);\n string reply = chatResponse!.choices[0].message.content;\n if (settings.ReasonStripRequired)\n {\n var stripped = ChatReplyParser.StripReasoning(reply);\n return stripped.Trim().ToString();\n }\n\n return reply.Trim();\n }\n // Distinguish between timeout and cancel errors\n catch (OperationCanceledException ex)\n when (!ex.Message.StartsWith(\"The request was canceled due to the configured HttpClient.Timeout\"))\n {\n // cancel\n throw;\n }\n catch (Exception ex)\n {\n // timeout and other error\n throw new TranslationException($\"Cannot request to {settings.ServiceType}: {ex.Message}\", ex)\n {\n Data =\n {\n [\"status_code\"] = statusCode.ToString(),\n [\"response\"] = jsonResultString\n }\n };\n }\n }\n\n public static async Task> GetLoadedModels(OpenAIBaseTranslateSettings settings)\n {\n using HttpClient client = settings.GetHttpClient(true);\n\n string jsonResultString = string.Empty;\n int statusCode = -1;\n\n // getting models\n try\n {\n using var result = await client.GetAsync(\"/v1/models\");\n\n jsonResultString = await result.Content.ReadAsStringAsync();\n\n statusCode = (int)result.StatusCode;\n result.EnsureSuccessStatusCode();\n\n JsonNode? node = JsonNode.Parse(jsonResultString);\n List models = node![\"data\"]!.AsArray()\n .Select(model => model![\"id\"]!.GetValue())\n .Order()\n .ToList();\n\n return models;\n }\n catch (Exception ex)\n {\n throw new InvalidOperationException($\"get models error: {ex.Message}\", ex)\n {\n Data =\n {\n [\"status_code\"] = statusCode.ToString(),\n [\"response\"] = jsonResultString\n }\n };\n }\n }\n}\n\npublic class OpenAIMessage\n{\n public required string role { get; init; }\n public required string content { get; init; }\n}\n\npublic class OpenAIRequest\n{\n public string? model { get; set; }\n public required OpenAIMessage[] messages { get; init; }\n public required bool stream { get; init; }\n public double? temperature { get; set; }\n public double? top_p { get; set; }\n public int? max_completion_tokens { get; set; }\n public int? max_tokens { get; set; }\n}\n\npublic class OpenAIResponse\n{\n public required OpenAIChoice[] choices { get; init; }\n}\n\npublic class OpenAIChoice\n{\n public required OpenAIMessage message { get; init; }\n}\n\npublic static class ChatReplyParser\n{\n // Target tag names to remove (lowercase)\n private static readonly string[] Tags = [\"think\", \"reason\", \"reasoning\", \"thought\"];\n\n // open/close tag strings from tag names\n private static readonly string[] OpenTags;\n private static readonly string[] CloseTags;\n\n static ChatReplyParser()\n {\n OpenTags = new string[Tags.Length];\n CloseTags = new string[Tags.Length];\n for (int i = 0; i < Tags.Length; i++)\n {\n OpenTags[i] = $\"<{Tags[i]}>\"; // e.g. \"\"\n CloseTags[i] = $\"\"; // e.g. \"\"\n }\n }\n\n /// \n /// Removes a leading reasoning tag if present and returns only the generated message portion.\n /// \n public static ReadOnlySpan StripReasoning(ReadOnlySpan input)\n {\n // Return immediately if it doesn't start with a tag\n if (input.Length == 0 || input[0] != '<')\n {\n return input;\n }\n\n for (int i = 0; i < OpenTags.Length; i++)\n {\n if (input.StartsWith(OpenTags[i], StringComparison.OrdinalIgnoreCase))\n {\n int endIdx = input.IndexOf(CloseTags[i], StringComparison.OrdinalIgnoreCase);\n if (endIdx >= 0)\n {\n int next = endIdx + CloseTags[i].Length;\n // Skip over any consecutive line breaks and whitespace\n while (next < input.Length && char.IsWhiteSpace(input[next]))\n {\n next++;\n }\n return input.Slice(next);\n }\n }\n }\n\n // Return original string if no tag matched\n return input;\n }\n}\n"], ["/LLPlayer/FlyleafLib/MediaPlayer/Translation/Services/ITranslateSettings.cs", "using System.Collections.Generic;\nusing System.Collections.ObjectModel;\nusing System.ComponentModel;\nusing System.Diagnostics;\nusing System.Linq;\nusing System.Net.Http;\nusing System.Text;\nusing System.Text.Json.Serialization;\nusing System.Threading.Tasks;\nusing FlyleafLib.Controls.WPF;\n\nnamespace FlyleafLib.MediaPlayer.Translation.Services;\n\npublic interface ITranslateSettings : INotifyPropertyChanged;\n\npublic class GoogleV1TranslateSettings : NotifyPropertyChanged, ITranslateSettings\n{\n private const string DefaultEndpoint = \"https://translate.googleapis.com\";\n\n public string Endpoint\n {\n get;\n set\n {\n if (Set(ref field, value))\n {\n CmdSetDefaultEndpoint.OnCanExecuteChanged();\n }\n }\n } = DefaultEndpoint;\n\n [JsonIgnore]\n public RelayCommand CmdSetDefaultEndpoint => field ??= new(_ =>\n {\n Endpoint = DefaultEndpoint;\n }, _ => Endpoint != DefaultEndpoint);\n\n public int TimeoutMs { get; set => Set(ref field, value); } = 10000;\n\n public Dictionary Regions { get; set; } = new(GoogleV1TranslateService.DefaultRegions);\n\n /// \n /// for Settings\n /// \n [JsonIgnore]\n public ObservableCollection LanguageRegions\n {\n get\n {\n if (field == null)\n {\n field = LoadLanguageRegions();\n\n foreach (var pref in field)\n {\n pref.PropertyChanged += (sender, args) =>\n {\n if (args.PropertyName == nameof(Services.LanguageRegions.SelectedRegionMember))\n {\n // Apply changes in setting\n Regions[pref.ISO6391] = pref.SelectedRegionMember.Code;\n }\n };\n }\n }\n\n return field;\n }\n }\n\n private ObservableCollection LoadLanguageRegions()\n {\n List preferences = [\n new()\n {\n Name = \"Chinese\",\n ISO6391 = \"zh\",\n Regions =\n [\n // priority to the above\n new LanguageRegionMember { Name = \"Chinese (Simplified)\", Code = \"zh-CN\" },\n new LanguageRegionMember { Name = \"Chinese (Traditional)\", Code = \"zh-TW\" }\n ],\n },\n new()\n {\n Name = \"French\",\n ISO6391 = \"fr\",\n Regions =\n [\n new LanguageRegionMember { Name = \"French (French)\", Code = \"fr-FR\" },\n new LanguageRegionMember { Name = \"French (Canadian)\", Code = \"fr-CA\" }\n ],\n },\n new()\n {\n Name = \"Portuguese\",\n ISO6391 = \"pt\",\n Regions =\n [\n new LanguageRegionMember { Name = \"Portuguese (Portugal)\", Code = \"pt-PT\" },\n new LanguageRegionMember { Name = \"Portuguese (Brazil)\", Code = \"pt-BR\" }\n ],\n }\n ];\n\n foreach (LanguageRegions p in preferences)\n {\n if (Regions.TryGetValue(p.ISO6391, out string code))\n {\n // loaded from config\n p.SelectedRegionMember = p.Regions.FirstOrDefault(r => r.Code == code);\n }\n else\n {\n // select first\n p.SelectedRegionMember = p.Regions.First();\n }\n }\n\n return new ObservableCollection(preferences);\n }\n}\n\npublic class DeepLTranslateSettings : NotifyPropertyChanged, ITranslateSettings\n{\n public string ApiKey { get; set => Set(ref field, value); }\n\n public int TimeoutMs { get; set => Set(ref field, value); } = 10000;\n}\n\npublic class DeepLXTranslateSettings : NotifyPropertyChanged, ITranslateSettings\n{\n public string Endpoint { get; set => Set(ref field, value); } = \"http://127.0.0.1:1188\";\n\n public int TimeoutMs { get; set => Set(ref field, value); } = 10000;\n}\n\npublic abstract class OpenAIBaseTranslateSettings : NotifyPropertyChanged, ITranslateSettings\n{\n protected OpenAIBaseTranslateSettings()\n {\n // ReSharper disable once VirtualMemberCallInConstructor\n Endpoint = DefaultEndpoint;\n }\n\n public abstract TranslateServiceType ServiceType { get; }\n public string Endpoint\n {\n get;\n set\n {\n if (Set(ref field, value))\n {\n CmdSetDefaultEndpoint.OnCanExecuteChanged();\n }\n }\n }\n [JsonIgnore]\n protected virtual bool ReuseConnection => true;\n\n public abstract string DefaultEndpoint { get; }\n\n [JsonIgnore]\n public virtual string ChatPath\n {\n get => \"/v1/chat/completions\";\n set => throw new NotImplementedException();\n }\n\n public string Model { get; set => Set(ref field, value); }\n\n [JsonIgnore]\n public virtual bool ModelRequired => true;\n\n [JsonIgnore]\n public virtual bool ReasonStripRequired => true;\n\n public int TimeoutMs { get; set => Set(ref field, value); } = 15000;\n public int TimeoutHealthMs { get; set => Set(ref field, value); } = 2000;\n\n #region LLM Parameters\n public double Temperature\n {\n get;\n set\n {\n if (value is >= 0.0 and <= 2.0)\n {\n Set(ref field, Math.Round(value, 2));\n }\n }\n } = 0.0;\n\n public bool TemperatureManual { get; set => Set(ref field, value); } = true;\n\n public double TopP\n {\n get;\n set\n {\n if (value is >= 0.0 and <= 1.0)\n {\n Set(ref field, Math.Round(value, 2));\n }\n }\n } = 1;\n\n public bool TopPManual { get; set => Set(ref field, value); }\n\n public int? MaxTokens\n {\n get;\n set => Set(ref field, value is <= 0 ? null : value);\n }\n\n public int? MaxCompletionTokens\n {\n get;\n set => Set(ref field, value is <= 0 ? null : value);\n }\n #endregion\n\n /// \n /// GetHttpClient\n /// \n /// \n /// \n /// \n internal virtual HttpClient GetHttpClient(bool healthCheck = false)\n {\n if (string.IsNullOrWhiteSpace(Endpoint))\n {\n throw new TranslationConfigException(\n $\"Endpoint for {ServiceType} is not configured.\");\n }\n\n if (!healthCheck)\n {\n if (ModelRequired && string.IsNullOrWhiteSpace(Model))\n {\n throw new TranslationConfigException(\n $\"Model for {ServiceType} is not configured.\");\n }\n }\n\n // In KoboldCpp, if this is not set, even if it is sent with Connection: close,\n // the connection will be reused and an error will occur.\n HttpMessageHandler handler = ReuseConnection ?\n new HttpClientHandler() :\n new SocketsHttpHandler\n {\n PooledConnectionLifetime = TimeSpan.Zero,\n PooledConnectionIdleTimeout = TimeSpan.Zero,\n };\n\n HttpClient client = new(handler);\n client.BaseAddress = new Uri(Endpoint);\n client.Timeout = TimeSpan.FromMilliseconds(healthCheck ? TimeoutHealthMs : TimeoutMs);\n if (!ReuseConnection)\n {\n client.DefaultRequestHeaders.ConnectionClose = true;\n }\n\n return client;\n }\n\n #region For Settings\n [JsonIgnore]\n public ObservableCollection AvailableModels { get; } = new();\n\n [JsonIgnore]\n public string Status\n {\n get;\n set\n {\n if (Set(ref field, value))\n {\n Raise(nameof(StatusAvailable));\n }\n }\n }\n\n [JsonIgnore]\n public bool StatusAvailable => !string.IsNullOrEmpty(Status);\n\n [JsonIgnore]\n public RelayCommand CmdSetDefaultEndpoint => field ??= new(_ =>\n {\n Endpoint = DefaultEndpoint;\n }, _ => Endpoint != DefaultEndpoint);\n\n [JsonIgnore]\n public RelayCommand CmdCheckEndpoint => new(async void (_) =>\n {\n try\n {\n Status = \"Checking...\";\n await LoadModels();\n Status = \"OK\";\n }\n catch (Exception ex)\n {\n Status = GetErrorDetails($\"NG: {ex.Message}\", ex);\n }\n });\n\n [JsonIgnore]\n public RelayCommand CmdGetModels => new(async void (_) =>\n {\n try\n {\n Status = \"Checking...\";\n await LoadModels();\n Status = \"\"; // clear\n }\n catch (Exception ex)\n {\n Status = GetErrorDetails($\"NG: {ex.Message}\", ex);\n }\n });\n\n [JsonIgnore]\n public RelayCommand CmdHelloModel => new(async void (_) =>\n {\n Stopwatch sw = new();\n sw.Start();\n try\n {\n Status = \"Waiting...\";\n\n await OpenAIBaseTranslateService.Hello(this);\n\n Status = $\"OK in {sw.Elapsed.TotalSeconds} secs\";\n }\n catch (Exception ex)\n {\n Status = GetErrorDetails($\"NG in {sw.Elapsed.TotalSeconds} secs: {ex.Message}\", ex);\n }\n });\n\n private async Task LoadModels()\n {\n string prevModel = Model;\n AvailableModels.Clear();\n\n var models = await OpenAIBaseTranslateService.GetLoadedModels(this);\n foreach (var model in models)\n {\n AvailableModels.Add(model);\n }\n\n if (!string.IsNullOrEmpty(prevModel))\n {\n Model = AvailableModels.FirstOrDefault(m => m == prevModel);\n }\n }\n\n internal static string GetErrorDetails(string header, Exception ex)\n {\n StringBuilder sb = new();\n sb.Append(header);\n\n if (ex.Data.Contains(\"status_code\") && (string)ex.Data[\"status_code\"] != \"-1\")\n {\n sb.AppendLine();\n sb.AppendLine();\n sb.Append($\"status_code: {ex.Data[\"status_code\"]}\");\n }\n\n if (ex.Data.Contains(\"response\") && (string)ex.Data[\"response\"] != \"\")\n {\n sb.AppendLine();\n sb.Append($\"response: {ex.Data[\"response\"]}\");\n }\n\n return sb.ToString();\n }\n #endregion\n}\n\npublic class OllamaTranslateSettings : OpenAIBaseTranslateSettings\n{\n public OllamaTranslateSettings()\n {\n TimeoutMs = 20000;\n }\n\n [JsonIgnore]\n public override TranslateServiceType ServiceType => TranslateServiceType.Ollama;\n [JsonIgnore]\n public override string DefaultEndpoint => \"http://127.0.0.1:11434\";\n}\n\npublic class LMStudioTranslateSettings : OpenAIBaseTranslateSettings\n{\n public LMStudioTranslateSettings()\n {\n TimeoutMs = 20000;\n }\n\n [JsonIgnore]\n public override TranslateServiceType ServiceType => TranslateServiceType.LMStudio;\n [JsonIgnore]\n public override string DefaultEndpoint => \"http://127.0.0.1:1234\";\n [JsonIgnore]\n public override bool ModelRequired => false;\n}\n\npublic class KoboldCppTranslateSettings : OpenAIBaseTranslateSettings\n{\n public KoboldCppTranslateSettings()\n {\n TimeoutMs = 20000;\n }\n\n [JsonIgnore]\n public override TranslateServiceType ServiceType => TranslateServiceType.KoboldCpp;\n [JsonIgnore]\n public override string DefaultEndpoint => \"http://127.0.0.1:5001\";\n\n // Disabled due to error when reusing connections\n [JsonIgnore]\n protected override bool ReuseConnection => false;\n\n [JsonIgnore]\n public override bool ModelRequired => false;\n}\n\npublic class OpenAITranslateSettings : OpenAIBaseTranslateSettings\n{\n [JsonIgnore]\n public override TranslateServiceType ServiceType => TranslateServiceType.OpenAI;\n [JsonIgnore]\n public override string DefaultEndpoint => \"https://api.openai.com\";\n public string ApiKey { get; set => Set(ref field, value); }\n\n [JsonIgnore]\n public override bool ReasonStripRequired => false;\n\n /// \n /// GetHttpClient\n /// \n /// \n /// \n /// \n internal override HttpClient GetHttpClient(bool healthCheck = false)\n {\n if (string.IsNullOrWhiteSpace(ApiKey))\n {\n throw new TranslationConfigException(\n $\"API Key for {ServiceType} is not configured.\");\n }\n\n HttpClient client = base.GetHttpClient(healthCheck);\n client.DefaultRequestHeaders.Add(\"Authorization\", $\"Bearer {ApiKey}\");\n\n return client;\n }\n}\n\npublic class OpenAILikeTranslateSettings : OpenAIBaseTranslateSettings\n{\n [JsonIgnore]\n public override TranslateServiceType ServiceType => TranslateServiceType.OpenAILike;\n [JsonIgnore]\n public override string DefaultEndpoint => \"https://api.openai.com\";\n\n private const string DefaultChatPath = \"/v1/chat/completions\";\n public override string ChatPath\n {\n get;\n set\n {\n if (Set(ref field, value))\n {\n CmdSetDefaultChatPath.OnCanExecuteChanged();\n }\n }\n } = DefaultChatPath;\n\n [JsonIgnore]\n public RelayCommand CmdSetDefaultChatPath => field ??= new(_ =>\n {\n ChatPath = DefaultChatPath;\n }, _ => ChatPath != DefaultChatPath);\n\n [JsonIgnore]\n public override bool ModelRequired => false;\n public string ApiKey { get; set => Set(ref field, value); }\n\n /// \n /// GetHttpClient\n /// \n /// \n /// \n /// \n internal override HttpClient GetHttpClient(bool healthCheck = false)\n {\n HttpClient client = base.GetHttpClient(healthCheck);\n\n // optional ApiKey\n if (!string.IsNullOrWhiteSpace(ApiKey))\n {\n client.DefaultRequestHeaders.Add(\"Authorization\", $\"Bearer {ApiKey}\");\n }\n\n return client;\n }\n}\n\npublic class ClaudeTranslateSettings : OpenAIBaseTranslateSettings\n{\n [JsonIgnore]\n public override TranslateServiceType ServiceType => TranslateServiceType.Claude;\n [JsonIgnore]\n public override string DefaultEndpoint => \"https://api.anthropic.com\";\n public string ApiKey { get; set => Set(ref field, value); }\n\n [JsonIgnore]\n public override bool ReasonStripRequired => false;\n\n internal override HttpClient GetHttpClient(bool healthCheck = false)\n {\n if (string.IsNullOrWhiteSpace(ApiKey))\n {\n throw new TranslationConfigException(\n $\"API Key for {ServiceType} is not configured.\");\n }\n\n HttpClient client = base.GetHttpClient(healthCheck);\n client.DefaultRequestHeaders.Add(\"x-api-key\", ApiKey);\n client.DefaultRequestHeaders.Add(\"anthropic-version\", \"2023-06-01\");\n\n return client;\n }\n}\n\npublic class LiteLLMTranslateSettings : OpenAIBaseTranslateSettings\n{\n [JsonIgnore]\n public override TranslateServiceType ServiceType => TranslateServiceType.LiteLLM;\n [JsonIgnore]\n public override string DefaultEndpoint => \"http://127.0.0.1:4000\";\n}\n\npublic class LanguageRegionMember : NotifyPropertyChanged, IEquatable\n{\n public string Name { get; set; }\n public string Code { get; set; }\n\n public bool Equals(LanguageRegionMember other)\n {\n if (other is null) return false;\n if (ReferenceEquals(this, other)) return true;\n return Code == other.Code;\n }\n\n public override bool Equals(object obj) => obj is LanguageRegionMember o && Equals(o);\n\n public override int GetHashCode()\n {\n return (Code != null ? Code.GetHashCode() : 0);\n }\n}\n\npublic class LanguageRegions : NotifyPropertyChanged\n{\n public string ISO6391 { get; set; }\n public string Name { get; set; }\n public List Regions { get; set; }\n\n public LanguageRegionMember SelectedRegionMember { get; set => Set(ref field, value); }\n}\n"], ["/LLPlayer/Plugins/YoutubeDL/YoutubeDL.cs", "using System;\nusing System.Collections.Generic;\nusing System.Diagnostics;\nusing System.IO;\nusing System.Linq;\nusing System.Text.Json;\nusing System.Text.Json.Serialization;\nusing System.Text.RegularExpressions;\nusing System.Threading;\nusing System.Threading.Tasks;\nusing FlyleafLib.MediaFramework.MediaDemuxer;\nusing FlyleafLib.MediaFramework.MediaPlaylist;\nusing FlyleafLib.MediaFramework.MediaStream;\n\nusing static FlyleafLib.Utils;\n\nnamespace FlyleafLib.Plugins\n{\n public class YoutubeDL : PluginBase, IOpen, ISuggestExternalAudio, ISuggestExternalVideo\n {\n /* TODO\n * 1) Check Audio streams if we need to add also video streams with audio\n * 2) Check Best Audio bitrates/quality (mainly for audio only player)\n * 3) Dispose ytdl and not tag it to every item (use only format if required)\n * 4) Use playlist_index to set the default playlist item\n */\n\n public new int Priority { get; set; } = 1999;\n static string plugin_path = \"yt-dlp.exe\";\n static JsonSerializerOptions\n jsonSettings = new() { DefaultIgnoreCondition = JsonIgnoreCondition.WhenWritingNull };\n\n FileSystemWatcher watcher;\n string workingDir;\n\n Process proc;\n int procId = -1;\n object procLocker = new();\n\n bool addingItem;\n string dynamicOptions = \"\";\n bool errGenericImpersonate;\n long sessionId = -1; // same for playlists\n int retries;\n\n static HashSet\n subsExt = new(StringComparer.OrdinalIgnoreCase) { \"vtt\", \"srt\", \"ass\", \"ssa\" };\n\n public override Dictionary GetDefaultOptions()\n => new()\n {\n { \"ExtraArguments\", \"\" }, // TBR: Restore default functionality with --cookies-from-browser {defaultBrowser} || https://github.com/yt-dlp/yt-dlp/issues/7271\n { \"MaxVideoHeight\", \"720\" },\n { \"PreferVideoWithAudio\", \"False\" },\n };\n\n public override void OnInitializing()\n => DisposeInternal();\n\n public override void Dispose()\n => DisposeInternal();\n\n private Format GetAudioOnly(YoutubeDLJson ytdl)\n {\n // Prefer best with no video and protocol\n // Prioritize m3u8 protocol because https is very slow on YouTube\n var m3u8Formats = ytdl.formats.Where(f => f.protocol == \"m3u8_native\").ToList();\n for (int i = m3u8Formats.Count - 1; i >= 0; i--)\n if (HasAudio(m3u8Formats[i]) && !HasVideo(m3u8Formats[i]))\n return m3u8Formats[i];\n\n // Prefer best with no video (dont waste bandwidth)\n for (int i = ytdl.formats.Count - 1; i >= 0; i--)\n if (HasAudio(ytdl.formats[i]) && !HasVideo(ytdl.formats[i]))\n return ytdl.formats[i];\n\n // Prefer audio from worst video?\n for (int i = 0; i < ytdl.formats.Count; i++)\n if (HasAudio(ytdl.formats[i]))\n return ytdl.formats[i];\n\n return null;\n }\n private Format GetBestMatch(YoutubeDLJson ytdl)\n {\n // TODO: Expose in settings (vCodecs Blacklist) || Create a HW decoding failed list dynamic (check also for whitelist)\n List vCodecsBlacklist = [];\n\n int maxHeight;\n\n if (int.TryParse(Options[\"MaxVideoHeight\"], out var height) && height > 0)\n maxHeight = Math.Min(Config.Video.MaxVerticalResolution, height);\n else\n maxHeight = Config.Video.MaxVerticalResolution;\n\n // Video Streams Order based on Screen Resolution\n var iresults =\n from format in ytdl.formats\n where HasVideo(format) && format.height <= maxHeight && (!Regex.IsMatch(format.protocol, \"dash\", RegexOptions.IgnoreCase) || format.vcodec.ToLower() == \"vp9\")\n orderby format.width descending,\n format.height descending,\n format.protocol descending, // prefer m3u8 over https (for performance)\n format.vcodec descending, // prefer vp09 over avc (for performance)\n format.tbr descending,\n format.fps descending\n select format;\n\n if (iresults == null || iresults.Count() == 0)\n {\n // Fall-back to any\n iresults =\n from format in ytdl.formats\n where HasVideo(format)\n orderby format.width descending,\n format.height descending,\n format.protocol descending,\n format.vcodec descending,\n format.tbr descending,\n format.fps descending\n select format;\n\n if (iresults == null || iresults.Count() == 0) return null;\n }\n\n List results = iresults.ToList();\n\n // Best Resolution\n double bestWidth = results[0].width;\n double bestHeight = results[0].height;\n\n // Choose from the best resolution (0. with acodec and not blacklisted 1. not blacklisted 2. any)\n int priority = 1;\n if (bool.TryParse(Options[\"PreferVideoWithAudio\"], out var v) && v)\n {\n priority = 0;\n }\n while (priority < 3)\n {\n for (int i = 0; i < results.Count; i++)\n {\n if (results[i].width != bestWidth || results[i].height != bestHeight)\n break;\n\n if (priority == 0 && !IsBlackListed(vCodecsBlacklist, results[i].vcodec) && results[i].acodec != \"none\")\n return results[i];\n else if (priority == 1 && !IsBlackListed(vCodecsBlacklist, results[i].vcodec))\n return results[i];\n else if (priority == 2)\n return results[i];\n }\n\n priority++;\n }\n\n return results[results.Count - 1]; // Fall-back to any\n }\n private static bool IsBlackListed(List blacklist, string codec)\n {\n foreach (string codec2 in blacklist)\n if (Regex.IsMatch(codec, codec2, RegexOptions.IgnoreCase))\n return true;\n\n return false;\n }\n private static bool HasVideo(Format fmt)\n {\n if (fmt.height > 0 || fmt.vbr > 0 || fmt.vcodec != \"none\")\n return true;\n\n return false;\n }\n private static bool HasAudio(Format fmt)\n {\n if (fmt.abr > 0 || fmt.acodec != \"none\")\n return true;\n\n return false;\n }\n\n private static bool IsAutomaticSubtitle(string url)\n {\n if (url.Contains(\"youtube\") && url.Contains(\"/api/timedtext\"))\n return true;\n\n return false;\n }\n\n private void DisposeInternal()\n {\n lock (procLocker)\n {\n if (Disposed)\n return;\n\n Log.Debug($\"Disposing ({procId})\");\n\n if (procId != -1)\n {\n Process.Start(new ProcessStartInfo\n {\n FileName = \"taskkill\",\n Arguments = $\"/pid {procId} /f /t\",\n CreateNoWindow = true,\n UseShellExecute = false,\n WindowStyle = ProcessWindowStyle.Hidden,\n }).WaitForExit();\n }\n\n retries = 0;\n sessionId = -1;\n dynamicOptions = \"\";\n errGenericImpersonate = false;\n\n if (watcher != null)\n {\n watcher.Dispose();\n watcher = null;\n }\n\n if (workingDir != null)\n {\n Log.Debug($\"Folder deleted ({workingDir})\");\n Directory.Delete(workingDir, true);\n workingDir = null;\n }\n\n Disposed = true;\n Log.Debug($\"Disposed ({procId})\");\n }\n }\n\n private void NewPlaylistItem(string path)\n {\n string json = null;\n\n // File Watcher informs us on rename but the process still accessing the file\n for (int i=0; i<3; i++)\n {\n Thread.Sleep(20);\n try { json = File.ReadAllText(path); } catch { if (sessionId != Handler.OpenCounter) return; continue; }\n break;\n }\n\n YoutubeDLJson ytdl = null;\n\n try\n {\n ytdl = JsonSerializer.Deserialize(json, jsonSettings);\n } catch (Exception e)\n {\n Log.Error($\"[JsonSerializer] {e.Message}\");\n }\n\n if (sessionId != Handler.OpenCounter) return;\n\n if (ytdl == null)\n return;\n\n if (ytdl._type == \"playlist\")\n return;\n\n PlaylistItem item = new();\n\n if (Playlist.ExpectingItems == 0)\n Playlist.ExpectingItems = (int)ytdl.playlist_count;\n\n if (Playlist.Title == null)\n {\n if (!string.IsNullOrEmpty(ytdl.playlist_title))\n {\n Playlist.Title = ytdl.playlist_title;\n Log.Debug($\"Playlist Title -> {Playlist.Title}\");\n }\n else if (!string.IsNullOrEmpty(ytdl.playlist))\n {\n Playlist.Title = ytdl.playlist;\n Log.Debug($\"Playlist Title -> {Playlist.Title}\");\n }\n }\n\n item.Title = ytdl.title;\n Log.Debug($\"Adding {item.Title}\");\n\n item.DirectUrl = ytdl.webpage_url;\n\n if (ytdl.chapters != null && ytdl.chapters.Count > 0)\n {\n item.Chapters.AddRange(ytdl.chapters.Select(c => new Demuxer.Chapter()\n {\n StartTime = TimeSpan.FromSeconds(c.start_time).Ticks,\n EndTime = TimeSpan.FromSeconds(c.end_time).Ticks,\n Title = c.title\n }));\n }\n\n // If no formats still could have a single format attched to the main root class\n if (ytdl.formats == null)\n ytdl.formats = [ytdl];\n\n // Audio / Video Streams\n for (int i=0; i addedUrl = new(); // for de-duplication\n\n if (ytdl.automatic_captions != null)\n {\n foreach (var subtitle1 in ytdl.automatic_captions)\n {\n if (sessionId != Handler.OpenCounter)\n return;\n\n // original (source) language has this suffix\n const string suffix = \"-orig\";\n\n string langCode = subtitle1.Key;\n bool isOriginal = langCode.EndsWith(suffix, StringComparison.OrdinalIgnoreCase);\n\n if (isOriginal)\n {\n // remove -orig suffix\n langCode = langCode[..^suffix.Length];\n }\n\n Language lang = Language.Get(langCode);\n\n foreach (var subtitle in subtitle1.Value)\n {\n if (!subsExt.Contains(subtitle.ext))\n continue;\n\n bool automatic = IsAutomaticSubtitle(subtitle.url);\n\n if (!isOriginal && automatic) // always load original subtitle\n {\n // Automatic subtitles are loaded under the following ORed conditions\n // 1. If the language matches the set language\n // 2. Subtitles in the same language as the video\n if (!(Config.Subtitles.Languages.Contains(lang) || videoLang != Language.Unknown && videoLang == lang))\n {\n continue;\n }\n }\n\n // because -orig may be duplicated\n if (!addedUrl.Add(subtitle.url))\n continue;\n\n AddExternalStream(new ExternalSubtitlesStream()\n {\n Downloaded = true,\n Protocol = subtitle.ext,\n Language = lang,\n Url = subtitle.url,\n Automatic = automatic\n }, null, item);\n }\n }\n }\n } catch (Exception e) { Log.Warn($\"Failed to add subtitles ({e.Message})\"); }\n\n AddPlaylistItem(item, ytdl);\n }\n public void AddHeaders(ExternalStream extStream, Format fmt)\n {\n if (fmt.http_headers != null)\n {\n if (fmt.http_headers.TryGetValue(\"User-Agent\", out string value))\n {\n extStream.UserAgent = value;\n fmt.http_headers.Remove(\"User-Agent\");\n }\n\n if (fmt.http_headers.TryGetValue(\"Referer\", out value))\n {\n extStream.Referrer = value;\n fmt.http_headers.Remove(\"Referer\");\n }\n\n extStream.HTTPHeaders = fmt.http_headers;\n\n if (!string.IsNullOrEmpty(fmt.cookies))\n extStream.HTTPHeaders.Add(\"Cookies\", fmt.cookies);\n\n }\n }\n\n public bool CanOpen()\n {\n try\n {\n if (Playlist.IOStream != null)\n return false;\n\n Uri uri = new(Playlist.Url);\n string scheme = uri.Scheme.ToLower();\n\n if (scheme != \"http\" && scheme != \"https\")\n return false;\n\n string ext = GetUrlExtention(uri.AbsolutePath);\n\n if (ext == \"m3u8\" || ext == \"mp3\" || ext == \"m3u\" || ext == \"pls\")\n return false;\n\n // TBR: try to avoid processing radio stations\n if (string.IsNullOrEmpty(uri.PathAndQuery) || uri.PathAndQuery.Length < 5)\n return false;\n\n } catch (Exception) { return false; }\n\n return true;\n }\n public OpenResults Open()\n {\n try\n {\n lock (procLocker)\n {\n Disposed = false;\n sessionId = Handler.OpenCounter;\n Playlist.InputType = InputType.Web;\n\n workingDir = Path.GetTempPath() + Guid.NewGuid().ToString();\n\n Log.Debug($\"Folder created ({workingDir})\");\n Directory.CreateDirectory(workingDir);\n proc = new Process\n {\n EnableRaisingEvents = true,\n\n StartInfo = new ProcessStartInfo\n {\n FileName = Path.Combine(Engine.Plugins.Folder, Name, plugin_path),\n Arguments = $\"{dynamicOptions}{Options[\"ExtraArguments\"]} --no-check-certificate --skip-download --youtube-skip-dash-manifest --write-info-json -P \\\"{workingDir}\\\" \\\"{Playlist.Url}\\\" -o \\\"%(title).220B\\\"\", // 418 max filename length\n CreateNoWindow = true,\n UseShellExecute = false,\n WindowStyle = ProcessWindowStyle.Hidden,\n RedirectStandardError = true,\n RedirectStandardOutput = Logger.CanDebug,\n }\n };\n\n proc.Exited += (o, e) =>\n {\n lock (procLocker)\n {\n if (Logger.CanDebug)\n Log.Debug($\"Process completed ({(procId == -1 ? \"Killed\" : $\"{procId}\")})\");\n\n proc.Close();\n proc = null;\n procId = -1;\n }\n };\n\n proc.ErrorDataReceived += (o, e) =>\n {\n if (sessionId != Handler.OpenCounter || e.Data == null)\n return;\n\n Log.Debug($\"[stderr] {e.Data}\");\n\n if (!errGenericImpersonate && e.Data.Contains(\"generic:impersonate\"))\n errGenericImpersonate = true;\n };\n\n if (Logger.CanDebug)\n proc.OutputDataReceived += (o, e) =>\n {\n if (sessionId == Handler.OpenCounter)\n Log.Debug($\"[stdout] {e.Data}\");\n };\n\n watcher = new()\n {\n Path = workingDir,\n EnableRaisingEvents = true,\n };\n watcher.Renamed += (o, e) =>\n {\n try\n {\n if (sessionId != Handler.OpenCounter)\n return;\n\n addingItem = true;\n\n NewPlaylistItem(e.FullPath);\n\n if (Playlist.Items.Count == 1)\n Handler.OnPlaylistCompleted();\n\n } catch (Exception e2) { Log.Warn($\"Renamed Event Error {e2.Message} | {sessionId != Handler.OpenCounter}\");\n } finally { addingItem = false; }\n };\n\n proc.Start();\n procId = proc.Id;\n Log.Debug($\"Process started ({procId})\");\n\n // Don't try to read them at once at the end as the buffers (hardcoded to 4096) can be full and proc will freeze\n proc.BeginErrorReadLine();\n if (Logger.CanDebug)\n proc.BeginOutputReadLine();\n }\n\n while (Playlist.Items.Count < 1 && (proc != null || addingItem) && sessionId == Handler.OpenCounter)\n Thread.Sleep(35);\n\n if (sessionId != Handler.OpenCounter)\n {\n Log.Info(\"Session cancelled\");\n DisposeInternal();\n return null;\n }\n\n if (Playlist.Items.Count == 0) // Allow fallback to default plugin in case of YT-DLP bug with windows filename (this affects proper direct URLs as well)\n {\n if (!errGenericImpersonate || retries > 0)\n return null;\n\n Log.Warn(\"Re-trying with --extractor-args \\\"generic:impersonate\\\"\");\n DisposeInternal();\n retries = 1;\n dynamicOptions = \"--extractor-args \\\"generic:impersonate\\\" \";\n return Open();\n }\n }\n catch (Exception e) { Log.Error($\"Open ({e.Message})\"); return new(e.Message); }\n\n return new();\n }\n\n public OpenResults OpenItem()\n => new();\n\n public ExternalAudioStream SuggestExternalAudio()\n {\n if (Handler.OpenedPlugin == null || Handler.OpenedPlugin.Name != Name)\n return null;\n\n var fmt = GetAudioOnly((YoutubeDLJson)GetTag(Selected));\n if (fmt == null)\n return null;\n\n foreach (var extStream in Selected.ExternalAudioStreams)\n if (fmt.url == extStream.Url)\n return extStream;\n\n return null;\n }\n public ExternalVideoStream SuggestExternalVideo()\n {\n if (Handler.OpenedPlugin == null || Handler.OpenedPlugin.Name != Name)\n return null;\n\n Format fmt = GetBestMatch((YoutubeDLJson)GetTag(Selected));\n if (fmt == null)\n return null;\n\n foreach (var extStream in Selected.ExternalVideoStreams)\n if (fmt.url == extStream.Url)\n return extStream;\n\n return null;\n }\n }\n}\n"], ["/LLPlayer/FlyleafLib/MediaFramework/MediaDecoder/AudioDecoder.Filters.cs", "using System.Runtime.InteropServices;\nusing System.Threading;\n\nusing FlyleafLib.MediaFramework.MediaStream;\nusing FlyleafLib.MediaFramework.MediaFrame;\n\nusing static FlyleafLib.Logger;\n\nnamespace FlyleafLib.MediaFramework.MediaDecoder;\n\npublic unsafe partial class AudioDecoder\n{\n AVFilterContext* abufferCtx;\n AVFilterContext* abufferSinkCtx;\n AVFilterGraph* filterGraph;\n bool abufferDrained;\n long curSamples;\n double missedSamples;\n long filterFirstPts;\n bool setFirstPts;\n object lockSpeed = new();\n AVRational sinkTimebase;\n AVFrame* filtframe;\n\n private AVFilterContext* CreateFilter(string name, string args, AVFilterContext* prevCtx = null, string id = null)\n {\n int ret;\n AVFilterContext* filterCtx;\n AVFilter* filter;\n\n id ??= name;\n\n filter = avfilter_get_by_name(name);\n if (filter == null)\n throw new Exception($\"[Filter {name}] not found\");\n\n ret = avfilter_graph_create_filter(&filterCtx, filter, id, args, null, filterGraph);\n if (ret < 0)\n throw new Exception($\"[Filter {name}] avfilter_graph_create_filter failed ({FFmpegEngine.ErrorCodeToMsg(ret)})\");\n\n if (prevCtx == null)\n return filterCtx;\n\n ret = avfilter_link(prevCtx, 0, filterCtx, 0);\n\n return ret != 0\n ? throw new Exception($\"[Filter {name}] avfilter_link failed ({FFmpegEngine.ErrorCodeToMsg(ret)})\")\n : filterCtx;\n }\n private int SetupFilters()\n {\n int ret = -1;\n\n try\n {\n DisposeFilters();\n\n AVFilterContext* linkCtx;\n\n sinkTimebase = new() { Num = 1, Den = codecCtx->sample_rate};\n filtframe = av_frame_alloc();\n filterGraph = avfilter_graph_alloc();\n setFirstPts = true;\n abufferDrained = false;\n\n // IN (abuffersrc)\n linkCtx = abufferCtx = CreateFilter(\"abuffer\",\n $\"channel_layout={AudioStream.ChannelLayoutStr}:sample_fmt={AudioStream.SampleFormatStr}:sample_rate={codecCtx->sample_rate}:time_base={sinkTimebase.Num}/{sinkTimebase.Den}\");\n\n // USER DEFINED\n if (Config.Audio.Filters != null)\n foreach (var filter in Config.Audio.Filters)\n try\n {\n linkCtx = CreateFilter(filter.Name, filter.Args, linkCtx, filter.Id);\n }\n catch (Exception e) { Log.Error($\"{e.Message}\"); }\n\n // SPEED (atempo up to 3) | [0.125 - 0.25](3), [0.25 - 0.5](2), [0.5 - 2.0](1), [2.0 - 4.0](2), [4.0 - X](3)\n if (speed != 1)\n {\n if (speed >= 0.5 && speed <= 2)\n linkCtx = CreateFilter(\"atempo\", $\"tempo={speed.ToString(\"0.0000000000\", System.Globalization.CultureInfo.InvariantCulture)}\", linkCtx);\n else if ((speed > 2 & speed <= 4) || (speed >= 0.25 && speed < 0.5))\n {\n var singleAtempoSpeed = Math.Sqrt(speed);\n linkCtx = CreateFilter(\"atempo\", $\"tempo={singleAtempoSpeed.ToString(\"0.0000000000\", System.Globalization.CultureInfo.InvariantCulture)}\", linkCtx);\n linkCtx = CreateFilter(\"atempo\", $\"tempo={singleAtempoSpeed.ToString(\"0.0000000000\", System.Globalization.CultureInfo.InvariantCulture)}\", linkCtx);\n }\n else if (speed > 4 || speed >= 0.125 && speed < 0.25)\n {\n var singleAtempoSpeed = Math.Pow(speed, 1.0 / 3);\n linkCtx = CreateFilter(\"atempo\", $\"tempo={singleAtempoSpeed.ToString(\"0.0000000000\", System.Globalization.CultureInfo.InvariantCulture)}\", linkCtx);\n linkCtx = CreateFilter(\"atempo\", $\"tempo={singleAtempoSpeed.ToString(\"0.0000000000\", System.Globalization.CultureInfo.InvariantCulture)}\", linkCtx);\n linkCtx = CreateFilter(\"atempo\", $\"tempo={singleAtempoSpeed.ToString(\"0.0000000000\", System.Globalization.CultureInfo.InvariantCulture)}\", linkCtx);\n }\n }\n\n // OUT (abuffersink)\n abufferSinkCtx = CreateFilter(\"abuffersink\", null, null);\n\n int tmpSampleRate = AudioStream.SampleRate;\n fixed (AVSampleFormat* ptr = &AOutSampleFormat)\n ret = av_opt_set_bin(abufferSinkCtx , \"sample_fmts\" , (byte*)ptr, sizeof(AVSampleFormat) , OptSearchFlags.Children);\n ret = av_opt_set_bin(abufferSinkCtx , \"sample_rates\" , (byte*)&tmpSampleRate, sizeof(int) , OptSearchFlags.Children);\n ret = av_opt_set_int(abufferSinkCtx , \"all_channel_counts\" , 0 , OptSearchFlags.Children);\n ret = av_opt_set(abufferSinkCtx , \"ch_layouts\" , \"stereo\" , OptSearchFlags.Children);\n avfilter_link(linkCtx, 0, abufferSinkCtx, 0);\n\n // GRAPH CONFIG\n ret = avfilter_graph_config(filterGraph, null);\n\n // CRIT TBR:!!!\n var tb = 1000 * 10000.0 / sinkTimebase.Den; // Ensures we have at least 20-70ms samples to avoid audio crackling and av sync issues\n ((FilterLink*)abufferSinkCtx->inputs[0])->min_samples = (int) (20 * 10000 / tb);\n ((FilterLink*)abufferSinkCtx->inputs[0])->max_samples = (int) (70 * 10000 / tb);\n\n return ret < 0\n ? throw new Exception($\"[FilterGraph] {FFmpegEngine.ErrorCodeToMsg(ret)} ({ret})\")\n : 0;\n }\n catch (Exception e)\n {\n fixed(AVFilterGraph** filterGraphPtr = &filterGraph)\n avfilter_graph_free(filterGraphPtr);\n\n Log.Error($\"{e.Message}\");\n\n return ret;\n }\n }\n\n private void DisposeFilters()\n {\n if (filterGraph == null)\n return;\n\n fixed(AVFilterGraph** filterGraphPtr = &filterGraph)\n avfilter_graph_free(filterGraphPtr);\n\n if (filtframe != null)\n fixed (AVFrame** ptr = &filtframe)\n av_frame_free(ptr);\n\n abufferCtx = null;\n abufferSinkCtx = null;\n filterGraph = null;\n filtframe = null;\n }\n protected override void OnSpeedChanged(double value)\n {\n // Possible Task to avoid locking UI thread as lockAtempo can wait for the Frames queue to be freed (will cause other issues and couldnt reproduce the possible dead lock)\n cBufTimesCur = cBufTimesSize;\n lock (lockSpeed)\n {\n if (filterGraph != null)\n DrainFilters();\n\n cBufTimesCur= 1;\n oldSpeed = speed;\n speed = value;\n\n var frames = Frames.ToArray();\n for (int i = 0; i < frames.Length; i++)\n FixSample(frames[i], oldSpeed, speed);\n\n if (filterGraph != null)\n SetupFilters();\n }\n }\n internal void FixSample(AudioFrame frame, double oldSpeed, double speed)\n {\n var oldDataLen = frame.dataLen;\n frame.dataLen = Utils.Align((int) (oldDataLen * oldSpeed / speed), ASampleBytes);\n fixed (byte* cBufStartPosPtr = &cBuf[0])\n {\n var curOffset = (long)frame.dataPtr - (long)cBufStartPosPtr;\n\n if (speed < oldSpeed)\n {\n if (curOffset + frame.dataLen >= cBuf.Length)\n {\n frame.dataPtr = (IntPtr)cBufStartPosPtr;\n curOffset = 0;\n oldDataLen = 0;\n }\n\n // fill silence\n for (int p = oldDataLen; p < frame.dataLen; p++)\n cBuf[curOffset + p] = 0;\n }\n }\n }\n private int UpdateFilterInternal(string filterId, string key, string value)\n {\n int ret = avfilter_graph_send_command(filterGraph, filterId, key, value, null, 0, 0);\n Log.Info($\"[{filterId}] {key}={value} {(ret >=0 ? \"success\" : \"failed\")}\");\n\n return ret;\n }\n internal int SetupFiltersOrSwr()\n {\n lock (lockSpeed)\n {\n int ret = -1;\n\n if (Disposed)\n return ret;\n\n if (Config.Audio.FiltersEnabled)\n {\n ret = SetupFilters();\n\n if (ret != 0)\n {\n Log.Error($\"Setup filters failed. Fallback to Swr.\");\n ret = SetupSwr();\n }\n else\n DisposeSwr();\n }\n else\n {\n DisposeFilters();\n ret = SetupSwr();\n }\n\n return ret;\n }\n }\n\n public int UpdateFilter(string filterId, string key, string value)\n {\n lock (lockCodecCtx)\n return filterGraph != null ? UpdateFilterInternal(filterId, key, value) : -1;\n }\n public int ReloadFilters()\n {\n if (!Config.Audio.FiltersEnabled)\n return -1;\n\n lock (lockActions)\n lock (lockCodecCtx)\n return SetupFilters();\n }\n\n private void ProcessFilters()\n {\n if (setFirstPts)\n {\n setFirstPts = false;\n filterFirstPts = frame->pts;\n curSamples = 0;\n missedSamples = 0;\n }\n else if (Math.Abs(frame->pts - nextPts) > 10 * 10000) // 10ms distance should resync filters (TBR: it should be 0ms however we might get 0 pkt_duration for unknown?)\n {\n DrainFilters();\n Log.Warn($\"Resync filters! ({Utils.TicksToTime((long)((frame->pts - nextPts) * AudioStream.Timebase))} distance)\");\n //resyncWithVideoRequired = !VideoDecoder.Disposed;\n DisposeFrames();\n avcodec_flush_buffers(codecCtx);\n if (filterGraph != null)\n SetupFilters();\n return;\n }\n\n nextPts = frame->pts + frame->duration;\n\n int ret;\n\n if ((ret = av_buffersrc_add_frame_flags(abufferCtx, frame, AVBuffersrcFlag.KeepRef | AVBuffersrcFlag.NoCheckFormat)) < 0) // AV_BUFFERSRC_FLAG_KEEP_REF = 8, AV_BUFFERSRC_FLAG_NO_CHECK_FORMAT = 1 (we check format change manually before here)\n {\n Log.Warn($\"[buffersrc] {FFmpegEngine.ErrorCodeToMsg(ret)} ({ret})\");\n Status = Status.Stopping;\n return;\n }\n\n while (true)\n {\n if ((ret = av_buffersink_get_frame_flags(abufferSinkCtx, filtframe, 0)) < 0) // Sometimes we get AccessViolationException while we UpdateFilter (possible related with .NET7 debug only bug)\n return; // EAGAIN (Some filters will send EAGAIN even if EOF currently we handled cause our Status will be Draining)\n\n if (filtframe->pts == AV_NOPTS_VALUE) // we might desync here (we dont count frames->nb_samples) ?\n {\n av_frame_unref(filtframe);\n continue;\n }\n\n ProcessFilter();\n\n // Wait until Queue not Full or Stopped\n if (Frames.Count >= Config.Decoder.MaxAudioFrames * cBufTimesCur)\n {\n Monitor.Exit(lockCodecCtx);\n lock (lockStatus)\n if (Status == Status.Running)\n Status = Status.QueueFull;\n\n while (Frames.Count >= Config.Decoder.MaxAudioFrames * cBufTimesCur && (Status == Status.QueueFull || Status == Status.Draining))\n Thread.Sleep(20);\n\n Monitor.Enter(lockCodecCtx);\n\n lock (lockStatus)\n {\n if (Status == Status.QueueFull)\n Status = Status.Running;\n else if (Status != Status.Draining)\n return;\n }\n }\n }\n }\n private void DrainFilters()\n {\n if (abufferDrained)\n return;\n\n abufferDrained = true;\n\n int ret;\n\n if ((ret = av_buffersrc_add_frame(abufferCtx, null)) < 0)\n {\n Log.Warn($\"[buffersrc] {FFmpegEngine.ErrorCodeToMsg(ret)} ({ret})\");\n return;\n }\n\n while (true)\n {\n if ((ret = av_buffersink_get_frame_flags(abufferSinkCtx, filtframe, 0)) < 0)\n return;\n\n if (filtframe->pts == AV_NOPTS_VALUE)\n {\n av_frame_unref(filtframe);\n return;\n }\n\n ProcessFilter();\n }\n }\n private void ProcessFilter()\n {\n var curLen = filtframe->nb_samples * ASampleBytes;\n\n if (filtframe->nb_samples > cBufSamples) // (min 10000)\n AllocateCircularBuffer(filtframe->nb_samples);\n else if (cBufPos + curLen >= cBuf.Length)\n cBufPos = 0;\n\n long newPts = filterFirstPts + av_rescale_q((long)(curSamples + missedSamples), sinkTimebase, AudioStream.AVStream->time_base);\n var samplesSpeed1 = filtframe->nb_samples * speed;\n missedSamples += samplesSpeed1 - (int)samplesSpeed1;\n curSamples += (int)samplesSpeed1;\n\n AudioFrame mFrame = new()\n {\n dataLen = curLen,\n timestamp = (long)((newPts * AudioStream.Timebase) - demuxer.StartTime + Config.Audio.Delay)\n };\n\n if (CanTrace) Log.Trace($\"Processes {Utils.TicksToTime(mFrame.timestamp)}\");\n\n fixed (byte* circularBufferPosPtr = &cBuf[cBufPos])\n mFrame.dataPtr = (IntPtr)circularBufferPosPtr;\n\n Marshal.Copy((IntPtr) filtframe->data[0], cBuf, cBufPos, mFrame.dataLen);\n cBufPos += curLen;\n\n Frames.Enqueue(mFrame);\n av_frame_unref(filtframe);\n }\n}\n\n/// \n/// FFmpeg Filter\n/// \npublic class Filter\n{\n /// \n /// \n /// FFmpeg valid filter id\n /// (Required only to send commands)\n /// \n /// \n public string Id { get; set; }\n\n /// \n /// FFmpeg valid filter name\n /// \n public string Name { get; set; }\n\n /// \n /// FFmpeg valid filter args\n /// \n public string Args { get; set; }\n}\n"], ["/LLPlayer/LLPlayer/App.xaml.cs", "using System.Diagnostics;\nusing System.Globalization;\nusing System.IO;\nusing System.Runtime.InteropServices;\nusing System.Windows;\nusing System.Windows.Threading;\nusing FlyleafLib;\nusing FlyleafLib.MediaPlayer;\nusing LLPlayer.Extensions;\nusing LLPlayer.Services;\nusing LLPlayer.Views;\n\nnamespace LLPlayer;\n\npublic partial class App : PrismApplication\n{\n public static string Name => \"LLPlayer\";\n public static string? CmdUrl { get; private set; } = null;\n public static string PlayerConfigPath { get; } = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, \"LLPlayer.PlayerConfig.json\");\n public static string EngineConfigPath { get; } = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, \"LLPlayer.Engine.json\");\n public static string AppConfigPath { get; } = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, \"LLPlayer.Config.json\");\n public static string CrashLogPath { get; } = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, \"crash.log\");\n\n private readonly LogHandler Log;\n\n public App()\n {\n Log = new LogHandler(\"[App] [MainApp ] \");\n }\n\n static App()\n {\n // Set thread culture to English and error messages to English\n Utils.SaveOriginalCulture();\n\n CultureInfo.DefaultThreadCurrentCulture = new CultureInfo(\"en-US\");\n CultureInfo.DefaultThreadCurrentUICulture = new CultureInfo(\"en-US\");\n }\n\n protected override void RegisterTypes(IContainerRegistry containerRegistry)\n {\n containerRegistry\n .Register(FlyleafLoader.CreateFlyleafPlayer)\n .RegisterSingleton()\n .RegisterSingleton();\n\n containerRegistry.RegisterDialogWindow();\n\n containerRegistry.RegisterDialog();\n containerRegistry.RegisterDialog();\n containerRegistry.RegisterDialog();\n containerRegistry.RegisterDialog();\n containerRegistry.RegisterDialog();\n containerRegistry.RegisterDialog();\n containerRegistry.RegisterDialog();\n containerRegistry.RegisterDialog();\n containerRegistry.RegisterDialog();\n }\n\n protected override Window CreateShell()\n {\n return Container.Resolve();\n }\n\n protected override void OnStartup(StartupEventArgs e)\n {\n if (e.Args.Length == 1)\n {\n CmdUrl = e.Args[0];\n }\n\n // TODO: L: customizable?\n // Ensures that we have enough worker threads to avoid the UI from freezing or not updating on time\n ThreadPool.GetMinThreads(out int workers, out int ports);\n ThreadPool.SetMinThreads(workers + 6, ports + 6);\n\n // Start flyleaf engine\n FlyleafLoader.StartEngine();\n\n base.OnStartup(e);\n }\n\n private void App_OnDispatcherUnhandledException(object sender, DispatcherUnhandledExceptionEventArgs e)\n {\n // Ignore WPF Clipboard exception\n if (e.Exception is COMException { ErrorCode: -2147221040 })\n {\n e.Handled = true;\n }\n\n if (!e.Handled)\n {\n Log.Error($\"Unknown error occurred in App: {e.Exception}\");\n Logger.ForceFlush();\n\n ErrorDialogHelper.ShowUnknownErrorPopup($\"Unhandled Exception: {e.Exception.Message}\", \"Global\", e.Exception);\n e.Handled = true;\n }\n }\n\n #region App Version\n public static string OSArchitecture => RuntimeInformation.OSArchitecture.ToString().ToLowerFirstChar();\n public static string ProcessArchitecture => RuntimeInformation.ProcessArchitecture.ToString().ToLowerFirstChar();\n\n private static string? _version;\n public static string Version\n {\n get\n {\n if (_version == null)\n {\n (_version, _commitHash) = GetVersion();\n }\n\n return _version;\n }\n }\n\n private static string? _commitHash;\n public static string CommitHash\n {\n get\n {\n if (_commitHash == null)\n {\n (_version, _commitHash) = GetVersion();\n }\n\n return _commitHash;\n }\n }\n\n private static (string version, string commitHash) GetVersion()\n {\n string exeLocation = Process.GetCurrentProcess().MainModule!.FileName;\n FileVersionInfo fvi = FileVersionInfo.GetVersionInfo(exeLocation);\n\n Guards.ThrowIfNull(fvi.ProductVersion);\n\n var version = fvi.ProductVersion.Split(\"+\");\n if (version.Length != 2)\n {\n throw new InvalidOperationException($\"ProductVersion is invalid: {fvi.ProductVersion}\");\n }\n\n return (version[0], version[1]);\n }\n #endregion\n}\n"], ["/LLPlayer/FlyleafLib/Engine/Config.cs", "using System.Collections.Generic;\nusing System.IO;\nusing System.Linq;\nusing System.Text.Json;\nusing System.Text.Json.Serialization;\nusing System.Threading;\nusing System.Threading.Tasks;\n\nusing FlyleafLib.Controls.WPF;\nusing FlyleafLib.MediaFramework.MediaDecoder;\nusing FlyleafLib.MediaFramework.MediaFrame;\nusing FlyleafLib.MediaFramework.MediaRenderer;\nusing FlyleafLib.MediaPlayer;\nusing FlyleafLib.MediaPlayer.Translation;\nusing FlyleafLib.MediaPlayer.Translation.Services;\nusing FlyleafLib.Plugins;\nusing static FlyleafLib.Utils;\n\nnamespace FlyleafLib;\n\n/// \n/// Player's configuration\n/// \npublic class Config : NotifyPropertyChanged\n{\n static JsonSerializerOptions jsonOpts = new() { WriteIndented = true };\n\n public Config()\n {\n // Parse default plugin options to Config.Plugins (Creates instances until fix with statics in interfaces)\n foreach (var plugin in Engine.Plugins.Types.Values)\n {\n var tmpPlugin = PluginHandler.CreatePluginInstance(plugin);\n var defaultOptions = tmpPlugin.GetDefaultOptions();\n tmpPlugin.Dispose();\n\n if (defaultOptions == null || defaultOptions.Count == 0) continue;\n\n Plugins.Add(plugin.Name, new ObservableDictionary());\n foreach (var opt in defaultOptions)\n Plugins[plugin.Name].Add(opt.Key, opt.Value);\n }\n // save default plugin options for later\n _PluginsDefault = Plugins;\n\n Player.config = this;\n Demuxer.config = this;\n }\n\n public Config(bool test) { }\n\n public Config Clone()\n {\n Config config = new()\n {\n Audio = Audio.Clone(),\n Video = Video.Clone(),\n Subtitles = Subtitles.Clone(),\n Demuxer = Demuxer.Clone(),\n Decoder = Decoder.Clone(),\n Player = Player.Clone()\n };\n\n config.Player.config = config;\n config.Demuxer.config = config;\n\n return config;\n }\n public static Config Load(string path, JsonSerializerOptions jsonOptions = null)\n {\n Config config = JsonSerializer.Deserialize(File.ReadAllText(path), jsonOptions);\n config.Loaded = true;\n config.LoadedPath = path;\n\n if (config.Audio.FiltersEnabled && Engine.Config.FFmpegLoadProfile == LoadProfile.Main)\n config.Audio.FiltersEnabled = false;\n\n // TODO: L: refactor\n config.Player.config = config;\n config.Demuxer.config = config;\n\n config.Subtitles.SetChildren();\n\n // Restore the plugin options initialized by the constructor, as they are overwritten during deserialization.\n\n // Remove removed plugin options\n foreach (var plugin in config.Plugins)\n {\n // plugin deleted\n if (!config._PluginsDefault.ContainsKey(plugin.Key))\n {\n config.Plugins.Remove(plugin.Key);\n continue;\n }\n\n // plugin option deleted\n foreach (var opt in plugin.Value)\n {\n if (!config._PluginsDefault[plugin.Key].ContainsKey(opt.Key))\n {\n config.Plugins[plugin.Key].Remove(opt.Key);\n }\n }\n }\n\n // Restore added plugin options\n foreach (var plugin in config._PluginsDefault)\n {\n // plugin added\n if (!config.Plugins.ContainsKey(plugin.Key))\n {\n config.Plugins[plugin.Key] = plugin.Value;\n continue;\n }\n\n // plugin option added\n foreach (var opt in plugin.Value)\n {\n if (!config.Plugins[plugin.Key].ContainsKey(opt.Key))\n {\n config.Plugins[plugin.Key][opt.Key] = opt.Value;\n }\n }\n }\n\n config.UpdateDefault();\n\n return config;\n }\n public void Save(string path = null, JsonSerializerOptions jsonOptions = null)\n {\n if (path == null)\n {\n if (string.IsNullOrEmpty(LoadedPath))\n return;\n\n path = LoadedPath;\n }\n\n jsonOptions ??= jsonOpts;\n\n File.WriteAllText(path, JsonSerializer.Serialize(this, jsonOptions));\n }\n\n private void UpdateDefault()\n {\n bool parsed = System.Version.TryParse(Version, out var loadedVer);\n\n if (!parsed || loadedVer <= System.Version.Parse(\"0.2.1\"))\n {\n // for FlyleafLib v3.8.3, Ensure extension_picky is set\n Demuxer.FormatOpt = DemuxerConfig.DefaultVideoFormatOpt();\n Demuxer.AudioFormatOpt = DemuxerConfig.DefaultVideoFormatOpt();\n Demuxer.SubtitlesFormatOpt = DemuxerConfig.DefaultVideoFormatOpt();\n\n\n // for subtitles search #91\n int ctrlFBindingIdx = Player.KeyBindings.Keys\n .FindIndex(k => k.Key == System.Windows.Input.Key.F &&\n k.Ctrl && !k.Alt && !k.Shift);\n if (ctrlFBindingIdx != -1)\n {\n // remove existing binding\n Player.KeyBindings.Keys.RemoveAt(ctrlFBindingIdx);\n }\n // set CTRL+F to subtitles search\n Player.KeyBindings.Keys.Add(new KeyBinding { Ctrl = true, Key = System.Windows.Input.Key.F, IsKeyUp = true, Action = KeyBindingAction.Custom, ActionName = \"ActivateSubsSearch\" });\n\n // Toggle always on top\n int ctrlTBindingIdx = Player.KeyBindings.Keys\n .FindIndex(k => k.Key == System.Windows.Input.Key.T &&\n k.Ctrl && !k.Alt && !k.Shift);\n if (ctrlTBindingIdx == -1)\n {\n Player.KeyBindings.Keys.Add(new KeyBinding { Ctrl = true, Key = System.Windows.Input.Key.T, IsKeyUp = true, Action = KeyBindingAction.Custom, ActionName = \"ToggleAlwaysOnTop\" });\n }\n\n // Set Ctrl+A for ToggleSubsAutoTextCopy (previous Alt+A)\n int ctrlABindingIdx = Player.KeyBindings.Keys\n .FindIndex(k => k.Key == System.Windows.Input.Key.A &&\n k.Ctrl && !k.Alt && !k.Shift);\n if (ctrlABindingIdx == -1)\n {\n Player.KeyBindings.Keys.Add(new KeyBinding { Ctrl = true, Key = System.Windows.Input.Key.A, IsKeyUp = true, Action = KeyBindingAction.Custom, ActionName = \"ToggleSubsAutoTextCopy\" });\n }\n }\n }\n\n internal void SetPlayer(Player player)\n {\n Player.player = player;\n Player.KeyBindings.SetPlayer(player);\n Demuxer.player = player;\n Decoder.player = player;\n Audio.player = player;\n Video.player = player;\n Subtitles.SetPlayer(player);\n }\n\n public string Version { get; set; }\n\n /// \n /// Whether configuration has been loaded from file\n /// \n [JsonIgnore]\n public bool Loaded { get; private set; }\n\n /// \n /// The path that this configuration has been loaded from\n /// \n [JsonIgnore]\n public string LoadedPath { get; private set; }\n\n public PlayerConfig Player { get; set; } = new PlayerConfig();\n public DemuxerConfig Demuxer { get; set; } = new DemuxerConfig();\n public DecoderConfig Decoder { get; set; } = new DecoderConfig();\n public VideoConfig Video { get; set; } = new VideoConfig();\n public AudioConfig Audio { get; set; } = new AudioConfig();\n public SubtitlesConfig Subtitles { get; set; } = new SubtitlesConfig();\n public DataConfig Data { get; set; } = new DataConfig();\n\n public Dictionary>\n Plugins { get; set; } = new();\n private\n Dictionary>\n _PluginsDefault;\n public class PlayerConfig : NotifyPropertyChanged\n {\n public PlayerConfig Clone()\n {\n PlayerConfig player = (PlayerConfig) MemberwiseClone();\n player.player = null;\n player.config = null;\n player.KeyBindings = KeyBindings.Clone();\n return player;\n }\n\n internal Player player;\n internal Config config;\n\n /// \n /// It will automatically start playing after open or seek after ended\n /// \n public bool AutoPlay { get; set; } = true;\n\n /// \n /// Required buffered duration ticks before playing\n /// \n public long MinBufferDuration {\n get => _MinBufferDuration;\n set\n {\n if (!Set(ref _MinBufferDuration, value)) return;\n if (config != null && value > config.Demuxer.BufferDuration)\n config.Demuxer.BufferDuration = value;\n }\n }\n long _MinBufferDuration = 500 * 10000;\n\n /// \n /// Key bindings configuration\n /// \n public KeysConfig\n KeyBindings { get; set; } = new KeysConfig();\n\n /// \n /// Fps while the player is not playing\n /// \n public double IdleFps { get; set; } = 60.0;\n\n /// \n /// Max Latency (ticks) forces playback (with speed x1+) to stay at the end of the live network stream (default: 0 - disabled)\n /// \n public long MaxLatency {\n get => _MaxLatency;\n set\n {\n if (value < 0)\n value = 0;\n\n if (!Set(ref _MaxLatency, value)) return;\n\n if (value == 0)\n {\n if (player != null)\n player.Speed = 1;\n\n if (config != null)\n config.Decoder.LowDelay = false;\n\n return;\n }\n\n // Large max buffer so we ensure the actual latency distance\n if (config != null)\n {\n if (config.Demuxer.BufferDuration < value * 2)\n config.Demuxer.BufferDuration = value * 2;\n\n config.Decoder.LowDelay = true;\n }\n\n // Small min buffer to avoid enabling latency speed directly\n if (_MinBufferDuration > value / 10)\n MinBufferDuration = value / 10;\n }\n }\n long _MaxLatency = 0;\n\n /// \n /// Min Latency (ticks) prevents MaxLatency to go (with speed x1) less than this limit (default: 0 - as low as possible)\n /// \n public long MinLatency { get => _MinLatency; set => Set(ref _MinLatency, value); }\n long _MinLatency = 0;\n\n /// \n /// Prevents frequent speed changes when MaxLatency is enabled (to avoid audio/video gaps and desyncs)\n /// \n public long LatencySpeedChangeInterval { get; set; } = TimeSpan.FromMilliseconds(700).Ticks;\n\n /// \n /// Folder to save recordings (when filename is not specified)\n /// \n public string FolderRecordings { get; set; } = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, \"Recordings\");\n\n /// \n /// Folder to save snapshots (when filename is not specified)\n /// \n\n public string FolderSnapshots { get; set; } = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, \"Snapshots\");\n\n /// \n /// Forces CurTime/SeekBackward/SeekForward to seek accurate on video\n /// \n public bool SeekAccurate { get => _SeekAccurate; set => Set(ref _SeekAccurate, value); }\n bool _SeekAccurate;\n\n /// \n /// Margin time to move back forward when doing an exact seek (ticks)\n /// \n public long SeekAccurateFixMargin { get; set => Set(ref field, value); } = TimeSpan.FromMilliseconds(0).Ticks;\n\n /// \n /// Margin time to move back forward when getting frame (ticks)\n /// \n public long SeekGetFrameFixMargin { get; set => Set(ref field, value); } = TimeSpan.FromMilliseconds(3000).Ticks;\n\n /// \n /// Snapshot encoding will be used (valid formats bmp, png, jpg/jpeg)\n /// \n public string SnapshotFormat { get ;set; } = \"bmp\";\n\n /// \n /// Whether to refresh statistics about bitrates/fps/drops etc.\n /// \n public bool Stats { get => _Stats; set => Set(ref _Stats, value); }\n bool _Stats = false;\n\n /// \n /// Sets playback's thread priority\n /// \n public ThreadPriority\n ThreadPriority { get; set; } = ThreadPriority.AboveNormal;\n\n /// \n /// Refreshes CurTime in UI on every frame (can cause performance issues)\n /// \n public bool UICurTimePerFrame { get; set; } = false;\n\n /// \n /// The upper limit of the volume amplifier\n /// \n public int VolumeMax { get => _VolumeMax; set { Set(ref _VolumeMax, value); if (player != null && player.Audio.masteringVoice != null) player.Audio.masteringVoice.Volume = value / 100f; } }\n int _VolumeMax = 150;\n\n /// \n /// The default volume\n /// \n public int VolumeDefault { get; set => Set(ref field, value); } = 75;\n\n /// \n /// The purpose of the player\n /// \n public Usage Usage { get; set; } = Usage.AVS;\n\n // Offsets\n public long AudioDelayOffset { get; set; } = 100 * 10000;\n public long AudioDelayOffset2 { get; set; } = 1000 * 10000;\n public long SubtitlesDelayOffset { get; set; } = 100 * 10000;\n public long SubtitlesDelayOffset2 { get; set; } = 1000 * 10000;\n public long SeekOffset { get; set; } = 1 * (long)1000 * 10000;\n public long SeekOffset2 { get; set; } = 5 * (long)1000 * 10000;\n public long SeekOffset3 { get; set; } = 15 * (long)1000 * 10000;\n public long SeekOffset4 { get; set; } = 30 * (long)1000 * 10000;\n public bool SeekOffsetAccurate { get; set; } = true;\n public bool SeekOffsetAccurate2 { get; set; } = false;\n public bool SeekOffsetAccurate3 { get; set; } = false;\n public bool SeekOffsetAccurate4 { get; set; } = false;\n public double SpeedOffset { get; set; } = 0.10;\n public double SpeedOffset2 { get; set; } = 0.25;\n public int ZoomOffset { get => _ZoomOffset; set { if (Set(ref _ZoomOffset, value)) player?.ResetAll(); } }\n int _ZoomOffset = 10;\n\n public int VolumeOffset { get; set; } = 5;\n }\n public class DemuxerConfig : NotifyPropertyChanged\n {\n public DemuxerConfig Clone()\n {\n DemuxerConfig demuxer = (DemuxerConfig) MemberwiseClone();\n\n demuxer.FormatOpt = new Dictionary();\n demuxer.AudioFormatOpt = new Dictionary();\n demuxer.SubtitlesFormatOpt = new Dictionary();\n\n foreach (var kv in FormatOpt) demuxer.FormatOpt.Add(kv.Key, kv.Value);\n foreach (var kv in AudioFormatOpt) demuxer.AudioFormatOpt.Add(kv.Key, kv.Value);\n foreach (var kv in SubtitlesFormatOpt) demuxer.SubtitlesFormatOpt.Add(kv.Key, kv.Value);\n\n demuxer.player = null;\n demuxer.config = null;\n\n return demuxer;\n }\n\n internal Player player;\n internal Config config;\n\n /// \n /// Whethere to allow avformat_find_stream_info during open (avoiding this can open the input faster but it could cause other issues)\n /// \n public bool AllowFindStreamInfo { get; set; } = true;\n\n /// \n /// Whether to enable demuxer's custom interrupt callback (for timeouts and interrupts)\n /// \n public bool AllowInterrupts { get; set; } = true;\n\n /// \n /// Whether to allow interrupts during av_read_frame\n /// \n public bool AllowReadInterrupts { get; set; } = true;\n\n /// \n /// Whether to allow timeouts checks within the interrupts callback\n /// \n public bool AllowTimeouts { get; set; } = true;\n\n /// \n /// List of FFmpeg formats to be excluded from interrupts\n /// \n public List ExcludeInterruptFmts{ get; set; } = new List() { \"rtsp\" };\n\n /// \n /// Maximum allowed duration ticks for buffering\n /// \n public long BufferDuration {\n get => _BufferDuration;\n set\n {\n if (!Set(ref _BufferDuration, value)) return;\n if (config != null && value < config.Player.MinBufferDuration)\n config.Player.MinBufferDuration = value;\n }\n }\n long _BufferDuration = 30 * (long)1000 * 10000;\n\n /// \n /// Maximuim allowed packets for buffering (as an extra check along with BufferDuration)\n /// \n public long BufferPackets { get; set; }\n\n /// \n /// Maximuim allowed audio packets (when reached it will drop the extra packets and will fire the AudioLimit event)\n /// \n public long MaxAudioPackets { get; set; }\n\n /// \n /// Maximum allowed errors before stopping\n /// \n public int MaxErrors { get; set; } = 30;\n\n /// \n /// Custom IO Stream buffer size (in bytes) for the AVIO Context\n /// \n public int IOStreamBufferSize\n { get; set; } = 0x200000;\n\n /// \n /// avformat_close_input timeout (ticks) for protocols that support interrupts\n /// \n public long CloseTimeout { get => closeTimeout; set { closeTimeout = value; closeTimeoutMs = value / 10000; } }\n private long closeTimeout = 1 * 1000 * 10000;\n internal long closeTimeoutMs = 1 * 1000;\n\n /// \n /// avformat_open_input + avformat_find_stream_info timeout (ticks) for protocols that support interrupts (should be related to probesize/analyzeduration)\n /// \n public long OpenTimeout { get => openTimeout; set { openTimeout = value; openTimeoutMs = value / 10000; } }\n private long openTimeout = 5 * 60 * (long)1000 * 10000;\n internal long openTimeoutMs = 5 * 60 * 1000;\n\n /// \n /// av_read_frame timeout (ticks) for protocols that support interrupts\n /// \n public long ReadTimeout { get => readTimeout; set { readTimeout = value; readTimeoutMs = value / 10000; } }\n private long readTimeout = 10 * 1000 * 10000;\n internal long readTimeoutMs = 10 * 1000;\n\n /// \n /// av_read_frame timeout (ticks) for protocols that support interrupts (for Live streams)\n /// \n public long ReadLiveTimeout { get => readLiveTimeout; set { readLiveTimeout = value; readLiveTimeoutMs = value / 10000; } }\n private long readLiveTimeout = 20 * 1000 * 10000;\n internal long readLiveTimeoutMs = 20 * 1000;\n\n /// \n /// av_seek_frame timeout (ticks) for protocols that support interrupts\n /// \n public long SeekTimeout { get => seekTimeout; set { seekTimeout = value; seekTimeoutMs = value / 10000; } }\n private long seekTimeout = 8 * 1000 * 10000;\n internal long seekTimeoutMs = 8 * 1000;\n\n /// \n /// Forces Input Format\n /// \n public string ForceFormat { get; set; }\n\n /// \n /// Forces FPS for NoTimestamp formats (such as h264/hevc)\n /// \n public double ForceFPS { get; set; }\n\n /// \n /// FFmpeg's format flags for demuxer (see https://ffmpeg.org/doxygen/trunk/avformat_8h.html)\n /// eg. FormatFlags |= 0x40; // For AVFMT_FLAG_NOBUFFER\n /// \n public DemuxerFlags FormatFlags { get; set; } = DemuxerFlags.DiscardCorrupt;// FFmpeg.AutoGen.ffmpeg.AVFMT_FLAG_DISCARD_CORRUPT;\n\n /// \n /// Certain muxers and demuxers do nesting (they open one or more additional internal format contexts). This will pass the FormatOpt and HTTPQuery params to the underlying contexts)\n /// \n public bool FormatOptToUnderlying\n { get; set; }\n\n /// \n /// Passes original's Url HTTP Query String parameters to underlying\n /// \n public bool DefaultHTTPQueryToUnderlying\n { get; set; } = true;\n\n /// \n /// HTTP Query String parameters to pass to underlying\n /// \n public Dictionary\n ExtraHTTPQueryParamsToUnderlying\n { get; set; } = new();\n\n /// \n /// FFmpeg's format options for demuxer\n /// \n public Dictionary\n FormatOpt { get; set; } = DefaultVideoFormatOpt();\n public Dictionary\n AudioFormatOpt { get; set; } = DefaultVideoFormatOpt();\n\n public Dictionary\n SubtitlesFormatOpt { get; set; } = DefaultVideoFormatOpt();\n\n public static Dictionary DefaultVideoFormatOpt()\n {\n // TODO: Those should be set based on the demuxer format/protocol (to avoid false warnings about invalid options and best fit for the input, eg. live stream)\n\n Dictionary defaults = new()\n {\n // General\n { \"probesize\", (50 * (long)1024 * 1024).ToString() }, // (Bytes) Default 5MB | Higher for weird formats (such as .ts?) and 4K/Hevc\n { \"analyzeduration\", (10 * (long)1000 * 1000).ToString() }, // (Microseconds) Default 5 seconds | Higher for network streams\n\n // HTTP\n { \"reconnect\", \"1\" }, // auto reconnect after disconnect before EOF\n { \"reconnect_streamed\", \"1\" }, // auto reconnect streamed / non seekable streams (this can cause issues with HLS ts segments - disable this or http_persistent)\n { \"reconnect_delay_max\",\"7\" }, // max reconnect delay in seconds after which to give up\n { \"user_agent\", \"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/92.0.4515.159 Safari/537.36\" },\n\n { \"extension_picky\", \"0\" }, // Added in ffmpeg v7.1.1 and causes issues when enabled with allowed extentions #577\n\n // HLS\n { \"http_persistent\", \"0\" }, // Disables keep alive for HLS - mainly when use reconnect_streamed and non-live HLS streams\n\n // RTSP\n { \"rtsp_transport\", \"tcp\" }, // Seems UDP causing issues\n };\n\n //defaults.Add(\"live_start_index\", \"-1\");\n //defaults.Add(\"timeout\", (2 * (long)1000 * 1000).ToString()); // (Bytes) Default 5MB | Higher for weird formats (such as .ts?)\n //defaults.Add(\"rw_timeout\", (2 * (long)1000 * 1000).ToString()); // (Microseconds) Default 5 seconds | Higher for network streams\n\n return defaults;\n }\n\n public Dictionary GetFormatOptPtr(MediaType type)\n => type == MediaType.Video ? FormatOpt : type == MediaType.Audio ? AudioFormatOpt : SubtitlesFormatOpt;\n }\n public class DecoderConfig : NotifyPropertyChanged\n {\n internal Player player;\n\n public DecoderConfig Clone()\n {\n DecoderConfig decoder = (DecoderConfig) MemberwiseClone();\n decoder.player = null;\n\n return decoder;\n }\n\n /// \n /// Threads that will be used from the decoder\n /// \n public int VideoThreads { get; set; } = Environment.ProcessorCount;\n\n /// \n /// Maximum video frames to be decoded and processed for rendering\n /// \n public int MaxVideoFrames { get => _MaxVideoFrames; set { if (Set(ref _MaxVideoFrames, value)) { player?.RefreshMaxVideoFrames(); } } }\n int _MaxVideoFrames = 4;\n\n /// \n /// Maximum audio frames to be decoded and processed for playback\n /// \n public int MaxAudioFrames { get; set; } = 10;\n\n /// \n /// Maximum subtitle frames to be decoded\n /// \n public int MaxSubsFrames { get; set; } = 1;\n\n /// \n /// Maximum data frames to be decoded\n /// \n public int MaxDataFrames { get; set; } = 100;\n\n /// \n /// Maximum allowed errors before stopping\n /// \n public int MaxErrors { get; set; } = 200;\n\n /// \n /// Whether or not to use decoder's textures directly as shader resources\n /// (TBR: Better performance but might need to be disabled while video input has padding or not supported by older Direct3D versions)\n /// \n public ZeroCopy ZeroCopy { get => _ZeroCopy; set { if (SetUI(ref _ZeroCopy, value) && player != null && player.Video.isOpened) player.VideoDecoder?.RecalculateZeroCopy(); } }\n ZeroCopy _ZeroCopy = ZeroCopy.Auto;\n\n /// \n /// Allows video accceleration even in codec's profile mismatch\n /// \n public bool AllowProfileMismatch\n { get => _AllowProfileMismatch; set => SetUI(ref _AllowProfileMismatch, value); }\n bool _AllowProfileMismatch;\n\n /// \n /// Allows corrupted frames (Parses AV_CODEC_FLAG_OUTPUT_CORRUPT to AVCodecContext)\n /// \n public bool ShowCorrupted { get => _ShowCorrupted; set => SetUI(ref _ShowCorrupted, value); }\n bool _ShowCorrupted;\n\n /// \n /// Forces low delay (Parses AV_CODEC_FLAG_LOW_DELAY to AVCodecContext) (auto-enabled with MaxLatency)\n /// \n public bool LowDelay { get => _LowDelay; set => SetUI(ref _LowDelay, value); }\n bool _LowDelay;\n\n public Dictionary\n AudioCodecOpt { get; set; } = new();\n public Dictionary\n VideoCodecOpt { get; set; } = new();\n public Dictionary\n SubtitlesCodecOpt { get; set; } = new();\n\n public Dictionary GetCodecOptPtr(MediaType type)\n => type == MediaType.Video ? VideoCodecOpt : type == MediaType.Audio ? AudioCodecOpt : SubtitlesCodecOpt;\n }\n public class VideoConfig : NotifyPropertyChanged\n {\n public VideoConfig Clone()\n {\n VideoConfig video = (VideoConfig) MemberwiseClone();\n video.player = null;\n\n return video;\n }\n\n internal Player player;\n\n /// \n /// Forces a specific GPU Adapter to be used by the renderer\n /// GPUAdapter must match with the description of the adapter eg. rx 580 (available adapters can be found in Engine.Video.GPUAdapters)\n /// \n public string GPUAdapter { get; set; }\n\n /// \n /// Video aspect ratio\n /// \n public AspectRatio AspectRatio { get => _AspectRatio; set { if (Set(ref _AspectRatio, value) && player != null && player.renderer != null && !player.renderer.SCDisposed) lock(player.renderer.lockDevice) { player.renderer.SetViewport(); if (player.renderer.child != null) player.renderer.child.SetViewport(); } } }\n AspectRatio _AspectRatio = AspectRatio.Keep;\n\n /// \n /// Custom aspect ratio (AspectRatio must be set to Custom to have an effect)\n /// \n public AspectRatio CustomAspectRatio { get => _CustomAspectRatio; set { if (Set(ref _CustomAspectRatio, value) && AspectRatio == AspectRatio.Custom) { _AspectRatio = AspectRatio.Fill; AspectRatio = AspectRatio.Custom; } } }\n AspectRatio _CustomAspectRatio = new(16, 9);\n\n /// \n /// Background color of the player's control\n /// \n public System.Windows.Media.Color\n BackgroundColor { get => VorticeToWPFColor(_BackgroundColor); set { Set(ref _BackgroundColor, WPFToVorticeColor(value)); player?.renderer?.UpdateBackgroundColor(); } }\n internal Vortice.Mathematics.Color _BackgroundColor = (Vortice.Mathematics.Color)Vortice.Mathematics.Colors.Black;\n\n /// \n /// Clears the screen on stop/close/open\n /// \n public bool ClearScreen { get; set; } = true;\n\n /// \n /// Whether video should be allowed\n /// \n public bool Enabled { get => _Enabled; set { if (Set(ref _Enabled, value)) if (value) player?.Video.Enable(); else player?.Video.Disable(); } }\n bool _Enabled = true;\n internal void SetEnabled(bool enabled) => Set(ref _Enabled, enabled, true, nameof(Enabled));\n\n /// \n /// Used to limit the number of frames rendered, particularly at increased speed\n /// \n public double MaxOutputFps { get; set; } = 60;\n\n /// \n /// DXGI Maximum Frame Latency (1 - 16)\n /// \n public uint MaxFrameLatency { get; set; } = 1;\n\n /// \n /// The max resolution that the current system can achieve and will be used from the input/stream suggester plugins\n /// \n [JsonIgnore]\n public int MaxVerticalResolutionAuto { get; internal set; }\n\n /// \n /// Custom max vertical resolution that will be used from the input/stream suggester plugins\n /// \n public int MaxVerticalResolutionCustom { get => _MaxVerticalResolutionCustom; set => Set(ref _MaxVerticalResolutionCustom, value); }\n int _MaxVerticalResolutionCustom;\n\n /// \n /// The max resolution that is currently used (based on Auto/Custom)\n /// \n [JsonIgnore]\n public int MaxVerticalResolution => MaxVerticalResolutionCustom == 0 ? (MaxVerticalResolutionAuto != 0 ? MaxVerticalResolutionAuto : 1080) : MaxVerticalResolutionCustom;\n\n /// \n /// In case of no hardware accelerated or post process accelerated pixel formats will use FFmpeg's SwsScale\n /// \n public bool SwsHighQuality { get; set; } = false;\n\n /// \n /// Forces SwsScale instead of FlyleafVP for non HW decoded frames\n /// \n public bool SwsForce { get; set; } = false;\n\n /// \n /// Activates Direct3D video acceleration (decoding)\n /// \n public bool VideoAcceleration { get; set => Set(ref field, value); } = true;\n\n /// \n /// Whether to use embedded video processor with custom pixel shaders or D3D11
\n /// (Currently D3D11 works only on video accelerated / hardware surfaces)
\n /// * FLVP supports HDR to SDR, D3D11 does not
\n /// * FLVP supports Pan Move/Zoom, D3D11 does not
\n /// * D3D11 possible performs better with color conversion and filters, FLVP supports only brightness/contrast filters
\n /// * D3D11 supports deinterlace (bob)\n ///
\n public VideoProcessors VideoProcessor { get => _VideoProcessor; set { if (Set(ref _VideoProcessor, value)) player?.renderer?.UpdateVideoProcessor(); } }\n VideoProcessors _VideoProcessor = VideoProcessors.Auto;\n\n /// \n /// Whether Vsync should be enabled (0: Disabled, 1: Enabled)\n /// \n public uint VSync { get; set; }\n\n /// \n /// Swap chain's present flags (mainly for waitable -None- or non-waitable -DoNotWait) (default: non-waitable)
\n /// Non-waitable swap chain will reduce re-buffering and audio/video desyncs\n ///
\n public Vortice.DXGI.PresentFlags\n PresentFlags { get; set; } = Vortice.DXGI.PresentFlags.DoNotWait;\n\n /// \n /// Enables the video processor to perform post process deinterlacing\n /// (D3D11 video processor should be enabled and support bob deinterlace method)\n /// \n public bool Deinterlace { get=> _Deinterlace; set { if (Set(ref _Deinterlace, value)) player?.renderer?.UpdateDeinterlace(); } }\n bool _Deinterlace;\n\n public bool DeinterlaceBottomFirst { get=> _DeinterlaceBottomFirst; set { if (Set(ref _DeinterlaceBottomFirst, value)) player?.renderer?.UpdateDeinterlace(); } }\n bool _DeinterlaceBottomFirst;\n\n /// \n /// The HDR to SDR method that will be used by the pixel shader\n /// \n public unsafe HDRtoSDRMethod\n HDRtoSDRMethod { get => _HDRtoSDRMethod; set { if (Set(ref _HDRtoSDRMethod, value) && player != null && player.VideoDecoder.VideoStream != null && player.VideoDecoder.VideoStream.ColorSpace == ColorSpace.BT2020) player.renderer.UpdateHDRtoSDR(); }}\n HDRtoSDRMethod _HDRtoSDRMethod = HDRtoSDRMethod.Hable;\n\n /// \n /// The HDR to SDR Tone float correnction (not used by Reinhard)\n /// \n public unsafe float HDRtoSDRTone { get => _HDRtoSDRTone; set { if (Set(ref _HDRtoSDRTone, value) && player != null && player.VideoDecoder.VideoStream != null && player.VideoDecoder.VideoStream.ColorSpace == ColorSpace.BT2020) player.renderer.UpdateHDRtoSDR(); } }\n float _HDRtoSDRTone = 1.4f;\n\n /// \n /// Whether the renderer will use 10-bit swap chaing or 8-bit output\n /// \n public bool Swap10Bit { get; set; }\n\n /// \n /// The number of buffers to use for the renderer's swap chain\n /// \n public uint SwapBuffers { get; set; } = 2;\n\n /// \n /// \n /// Whether the renderer will use R8G8B8A8_UNorm instead of B8G8R8A8_UNorm format for the swap chain (experimental)
\n /// (TBR: causes slightly different colors with D3D11VP)\n ///
\n ///
\n public bool SwapForceR8G8B8A8 { get; set; }\n\n public Dictionary Filters {get ; set; } = DefaultFilters();\n\n public static Dictionary DefaultFilters()\n {\n Dictionary filters = new();\n\n var available = Enum.GetValues(typeof(VideoFilters));\n\n foreach(object filter in available)\n filters.Add((VideoFilters)filter, new VideoFilter((VideoFilters)filter));\n\n return filters;\n }\n }\n public class AudioConfig : NotifyPropertyChanged\n {\n public AudioConfig Clone()\n {\n AudioConfig audio = (AudioConfig) MemberwiseClone();\n audio.player = null;\n\n return audio;\n }\n\n internal Player player;\n\n /// \n /// Audio delay ticks (will be reseted to 0 for every new audio stream)\n /// \n public long Delay { get => _Delay; set { if (player != null && !player.Audio.IsOpened) return; if (Set(ref _Delay, value)) player?.ReSync(player.decoder.AudioStream); } }\n long _Delay;\n internal void SetDelay(long delay) => Set(ref _Delay, delay, true, nameof(Delay));\n\n /// \n /// Whether audio should allowed\n /// \n public bool Enabled { get => _Enabled; set { if (Set(ref _Enabled, value)) if (value) player?.Audio.Enable(); else player?.Audio.Disable(); } }\n bool _Enabled = true;\n internal void SetEnabled(bool enabled) => Set(ref _Enabled, enabled, true, nameof(Enabled));\n\n /// \n /// Whether to process samples with Filters or SWR (experimental)
\n /// 1. Requires FFmpeg avfilter lib
\n /// 2. Currently SWR performs better if you dont need filters
\n ///
\n public bool FiltersEnabled { get => _FiltersEnabled; set { if (Set(ref _FiltersEnabled, value && Engine.Config.FFmpegLoadProfile != LoadProfile.Main)) player?.AudioDecoder.SetupFiltersOrSwr(); } }\n bool _FiltersEnabled = false;\n\n /// \n /// List of filters for post processing the audio samples (experimental)
\n /// (Requires FiltersEnabled)\n ///
\n public List Filters { get; set; }\n\n /// \n /// Audio languages preference by priority\n /// \n public List Languages\n {\n get\n {\n field ??= GetSystemLanguages();\n return field;\n }\n set => Set(ref field, value);\n }\n\n }\n\n public class SubConfig : NotifyPropertyChanged\n {\n internal Player player;\n\n public SubConfig()\n {\n }\n\n public SubConfig(int subIndex)\n {\n SubIndex = subIndex;\n }\n\n [JsonIgnore]\n public int SubIndex { get; set => Set(ref field, value); }\n\n [JsonIgnore]\n public bool EnabledTranslated\n {\n get;\n set\n {\n if (Set(ref field, value))\n {\n if (player == null)\n {\n return;\n }\n\n // Clear once to update the subtitle being displayed.\n player.sFramesPrev[SubIndex] = null;\n player.SubtitleClear(SubIndex);\n\n // Switching the display while leaving the translated text itself\n foreach (SubtitleData sub in player.SubtitlesManager[SubIndex].Subs)\n {\n sub.EnabledTranslated = field;\n }\n\n // Update text in sidebar\n player.SubtitlesManager[SubIndex].Refresh();\n }\n }\n } = false;\n\n /// \n /// Subtitle delay ticks (will be reset to 0 for every new subtitle stream)\n /// \n public long Delay\n {\n get => _delay;\n set\n {\n if (player == null || !player.Subtitles[SubIndex].Enabled)\n {\n return;\n }\n if (Set(ref _delay, value))\n {\n player.SubtitlesManager[SubIndex].SetCurrentTime(new TimeSpan(player.CurTime));\n player.ReSync(player.decoder.SubtitlesStreams[SubIndex]);\n }\n }\n }\n private long _delay;\n\n internal void SetDelay(long delay) => Set(ref _delay, delay, true, nameof(Delay));\n\n /// \n /// Whether subtitle should be visible\n /// TODO: L: should move to AppConfig?\n /// \n [JsonIgnore]\n public bool Visible { get; set => Set(ref field, value); } = true;\n\n /// \n /// OCR Engine Type\n /// \n public SubOCREngineType OCREngine { get; set => Set(ref field, value); } = SubOCREngineType.Tesseract;\n }\n\n public class SubtitlesConfig : NotifyPropertyChanged\n {\n public SubConfig[] SubConfigs { get; set; }\n\n public SubConfig this[int subIndex] => SubConfigs[subIndex];\n\n public SubtitlesConfig()\n {\n int subNum = 2;\n SubConfigs = new SubConfig[subNum];\n for (int i = 0; i < subNum; i++)\n {\n SubConfigs[i] = new SubConfig(i);\n }\n }\n\n internal void SetChildren()\n {\n for (int i = 0; i < SubConfigs.Length; i++)\n {\n SubConfigs[i].SubIndex = i;\n }\n }\n\n public SubtitlesConfig Clone()\n {\n SubtitlesConfig subs = new();\n subs = (SubtitlesConfig) MemberwiseClone();\n\n subs.Languages = new List();\n if (Languages != null) foreach(var lang in Languages) subs.Languages.Add(lang);\n\n subs.player = null;\n\n return subs;\n }\n\n internal Player player;\n internal void SetPlayer(Player player)\n {\n this.player = player;\n\n foreach (SubConfig conf in SubConfigs)\n {\n conf.player = player;\n }\n }\n\n /// \n /// Whether subtitles should be allowed\n /// \n public bool Enabled { get => _Enabled; set { if(Set(ref _Enabled, value)) if (value) player?.Subtitles.Enable(); else player?.Subtitles.Disable(); } }\n bool _Enabled = true;\n internal void SetEnabled(bool enabled) => Set(ref _Enabled, enabled, true, nameof(Enabled));\n\n /// \n /// Max number of subtitles (currently not configurable)\n /// \n public int Max { get; set => Set(ref field, value); } = 2;\n\n /// \n /// Whether to cache internal bitmap subtitles on memory\n /// Memory usage is larger since all bitmap are read on memory, but has the following advantages\n /// 1. Internal bitmap subtitles can be displayed in the sidebar\n /// 2. Can display bitmap subtitles during playback when seeking (mpv: can, VLC: cannot)\n /// \n public bool EnabledCached { get; set => Set(ref field, value); } = true;\n\n public bool OpenAutomaticSubs { get; set => Set(ref field, value); }\n\n /// \n /// Subtitle languages preference by priority\n /// \n public List Languages\n {\n get\n {\n field ??= GetSystemLanguages();\n return field;\n }\n set => Set(ref field, value);\n }\n\n /// \n /// Whether to use automatic language detection\n /// \n public bool LanguageAutoDetect { get; set => Set(ref field, value); } = true;\n\n /// \n /// Language to be used when source language was unknown (primary)\n /// \n public Language LanguageFallbackPrimary\n {\n get\n {\n field ??= Languages.FirstOrDefault();\n return field;\n }\n set => Set(ref field, value);\n }\n\n /// \n /// Language to be used when source language was unknown (secondary)\n /// \n public Language LanguageFallbackSecondary\n {\n get\n {\n if (LanguageFallbackSecondarySame)\n {\n return LanguageFallbackPrimary;\n }\n\n field ??= LanguageFallbackPrimary;\n\n return field;\n }\n set => Set(ref field, value);\n }\n\n /// \n /// Whether to use LanguageFallbackPrimary for secondary subtitles\n /// \n public bool LanguageFallbackSecondarySame\n {\n get;\n set\n {\n if (Set(ref field, value))\n {\n Raise(nameof(LanguageFallbackSecondary));\n }\n }\n } = true;\n\n /// \n /// Whether to use local search plugins (see also )\n /// \n public bool SearchLocal { get => _SearchLocal; set => Set(ref _SearchLocal, value); }\n bool _SearchLocal = false;\n\n public const string DefaultSearchLocalPaths = \"subs; subtitles\";\n\n public string SearchLocalPaths\n {\n get;\n set\n {\n if (Set(ref field, value))\n {\n CmdResetSearchLocalPaths.OnCanExecuteChanged();\n }\n }\n } = DefaultSearchLocalPaths;\n\n [JsonIgnore]\n public RelayCommand CmdResetSearchLocalPaths => field ??= new((_) =>\n {\n SearchLocalPaths = DefaultSearchLocalPaths;\n }, (_) => SearchLocalPaths != DefaultSearchLocalPaths);\n\n /// \n /// Allowed input types to be searched locally for subtitles (empty list allows all types)\n /// \n public List SearchLocalOnInputType\n { get; set; } = new List() { InputType.File, InputType.UNC, InputType.Torrent };\n\n /// \n /// Whether to use online search plugins (see also )\n /// \n public bool SearchOnline { get => _SearchOnline; set { Set(ref _SearchOnline, value); if (player != null && player.Video.isOpened) Task.Run(() => { if (player != null && player.Video.isOpened) player.decoder.SearchOnlineSubtitles(); }); } }\n bool _SearchOnline = false;\n\n /// \n /// Allowed input types to be searched online for subtitles (empty list allows all types)\n /// \n public List SearchOnlineOnInputType\n { get; set; } = new List() { InputType.File, InputType.Torrent };\n\n /// \n /// Subtitles parser (can be used for custom parsing)\n /// \n [JsonIgnore]\n public Action\n Parser { get; set; } = ParseSubtitles.Parse;\n\n #region ASR\n /// \n /// ASR Engine Type (Currently only supports OpenAI Whisper)\n /// \n public SubASREngineType ASREngine { get; set => Set(ref field, value); } = SubASREngineType.WhisperCpp;\n\n /// \n /// ASR OpenAI Whisper common config\n /// \n public WhisperConfig WhisperConfig { get; set => Set(ref field, value); } = new();\n\n /// \n /// ASR whisper.cpp config\n /// \n public WhisperCppConfig WhisperCppConfig { get; set => Set(ref field, value); } = new();\n\n /// \n /// ASR Faster-Whisper config\n /// \n public FasterWhisperConfig FasterWhisperConfig { get; set => Set(ref field, value); } = new();\n\n /// \n /// Chunk size (MB) when processing ASR with audio stream\n /// Increasing size will increase memory usage but may result in more natural subtitle breaks\n /// \n public int ASRChunkSizeMB\n {\n get;\n set\n {\n if (Set(ref field, value))\n {\n Raise(nameof(ASRChunkSize));\n }\n }\n } = 20;\n\n [JsonIgnore]\n public long ASRChunkSize => ASRChunkSizeMB * 1024 * 1024;\n\n /// \n /// Chunk seconds when processing ASR with audio stream\n /// In the case of network streams, etc., the size is small and can be divided by specifying the number of seconds.\n /// \n public int ASRChunkSeconds { get; set => Set(ref field, value); } = 20;\n #endregion\n\n #region OCR\n /// \n /// OCR Tesseract Region Settings (key: iso6391, value: LangCode)\n /// \n public Dictionary TesseractOcrRegions { get; set => Set(ref field, value); } = new();\n\n /// \n /// OCR Microsoft Region Settings (key: iso6391, value: LanguageTag (BCP-47)\n /// \n public Dictionary MsOcrRegions { get; set => Set(ref field, value); } = new();\n #endregion\n\n #region Translation\n /// \n /// Language to be translated to\n /// \n public TargetLanguage TranslateTargetLanguage\n {\n get;\n set\n {\n if (Set(ref field, value))\n {\n TranslateLanguage = Language.Get(value.ToISO6391());\n }\n }\n } = TargetLanguage.EnglishAmerican;\n\n [JsonIgnore]\n public Language TranslateLanguage { get; private set; }\n\n /// \n /// Translation Service Type\n /// \n public TranslateServiceType TranslateServiceType { get; set => Set(ref field, value); } = TranslateServiceType.GoogleV1;\n\n /// \n /// Translation Word Service Type\n /// \n public TranslateServiceType TranslateWordServiceType { get; set => Set(ref field, value); } = TranslateServiceType.GoogleV1;\n\n /// \n /// Translation Service Type Settings\n /// \n public Dictionary TranslateServiceSettings { get; set => Set(ref field, value); } = new();\n\n /// \n /// Maximum count backward\n /// \n public int TranslateCountBackward { get; set => Set(ref field, value); } = 1;\n\n /// \n /// Maximum count forward\n /// \n public int TranslateCountForward { get; set => Set(ref field, value); } = 12;\n\n /// \n /// Number of concurrent requests to translation services\n /// \n public int TranslateMaxConcurrency {\n get;\n set\n {\n if (value <= 0)\n return;\n\n Set(ref field, value);\n }\n } = 2;\n\n /// \n /// Chat-style LLM API config\n /// \n public TranslateChatConfig TranslateChatConfig { get; set => Set(ref field, value); } = new();\n #endregion\n }\n public class DataConfig : NotifyPropertyChanged\n {\n public DataConfig Clone()\n {\n DataConfig data = new();\n data = (DataConfig)MemberwiseClone();\n\n data.player = null;\n\n return data;\n }\n\n internal Player player;\n\n /// \n /// Whether data should be processed\n /// \n public bool Enabled { get => _Enabled; set { if (Set(ref _Enabled, value)) if (value) player?.Data.Enable(); else player?.Data.Disable(); } }\n bool _Enabled = false;\n internal void SetEnabled(bool enabled) => Set(ref _Enabled, enabled, true, nameof(Enabled));\n }\n}\n\n/// \n/// Engine's configuration\n/// \npublic class EngineConfig\n{\n public string Version { get; set; }\n\n /// \n /// It will not initiallize audio and will be disabled globally\n /// \n public bool DisableAudio { get; set; }\n\n /// \n /// Required to register ffmpeg libraries. Make sure you provide x86 or x64 based on your project.\n /// :<path> for relative path from current folder or any below\n /// <path> for absolute or relative path\n /// \n public string FFmpegPath { get; set; } = \"FFmpeg\";\n\n /// \n /// Can be used to choose which FFmpeg libs to load\n /// All (Devices & Filters)
\n /// Filters
\n /// Main
\n ///
\n public LoadProfile\n FFmpegLoadProfile { get; set; } = LoadProfile.Filters; // change default to disable devices\n\n /// \n /// Whether to allow HLS live seeking (this can cause segmentation faults in case of incompatible ffmpeg version with library's custom structures)\n /// \n public bool FFmpegHLSLiveSeek { get; set; }\n\n /// \n /// Sets FFmpeg logger's level\n /// \n public Flyleaf.FFmpeg.LogLevel\n FFmpegLogLevel { get => _FFmpegLogLevel; set { _FFmpegLogLevel = value; if (Engine.IsLoaded) FFmpegEngine.SetLogLevel(); } }\n Flyleaf.FFmpeg.LogLevel _FFmpegLogLevel = Flyleaf.FFmpeg.LogLevel.Quiet;\n\n /// \n /// Whether configuration has been loaded from file\n /// \n [JsonIgnore]\n public bool Loaded { get; private set; }\n\n /// \n /// The path that this configuration has been loaded from\n /// \n [JsonIgnore]\n public string LoadedPath { get; private set; }\n\n /// \n /// Sets loggers output\n /// :debug -> System.Diagnostics.Debug\n /// :console -> System.Console\n /// <path> -> Absolute or relative file path\n /// \n public string LogOutput { get => _LogOutput; set { _LogOutput = value; if (Engine.IsLoaded) Logger.SetOutput(); } }\n string _LogOutput = \"\";\n\n /// \n /// Sets logger's level\n /// \n public LogLevel LogLevel { get; set; } = LogLevel.Quiet;\n\n /// \n /// When the output is file it will append instead of overwriting\n /// \n public bool LogAppend { get; set; }\n\n /// \n /// Lines to cache before writing them to file\n /// \n public int LogCachedLines { get; set; } = 20;\n\n /// \n /// Sets the logger's datetime string format\n /// \n public string LogDateTimeFormat { get; set; } = \"HH.mm.ss.fff\";\n\n /// \n /// Required to register plugins. Make sure you provide x86 or x64 based on your project and same .NET framework.\n /// :<path> for relative path from current folder or any below\n /// <path> for absolute or relative path\n /// \n public string PluginsPath { get; set; } = \"Plugins\";\n\n /// \n /// Updates Player.CurTime when the second changes otherwise on every UIRefreshInterval\n /// \n public bool UICurTimePerSecond { get; set; } = true;\n\n /// \n /// Activates Master Thread to monitor all the players and perform the required updates\n /// Required for Activity Mode, Stats & Buffered Duration on Pause\n /// \n public bool UIRefresh { get => _UIRefresh; set { _UIRefresh = value; if (value && Engine.IsLoaded) Engine.StartThread(); } }\n static bool _UIRefresh;\n\n /// \n /// How often should update the UI in ms (low values can cause performance issues)\n /// Should UIRefreshInterval < 1000ms and 1000 % UIRefreshInterval == 0 for accurate per second stats\n /// \n public int UIRefreshInterval { get; set; } = 250;\n\n /// \n /// Loads engine's configuration\n /// \n /// Absolute or relative path to load the configuraiton\n /// JSON serializer options\n // \n public static EngineConfig Load(string path, JsonSerializerOptions jsonOptions = null)\n {\n EngineConfig config = JsonSerializer.Deserialize(File.ReadAllText(path), jsonOptions);\n config.Loaded = true;\n config.LoadedPath = path;\n\n return config;\n }\n\n /// \n /// Saves engine's current configuration\n /// \n /// Absolute or relative path to save the configuration\n /// JSON serializer options\n public void Save(string path = null, JsonSerializerOptions jsonOptions = null)\n {\n if (path == null)\n {\n if (string.IsNullOrEmpty(LoadedPath))\n return;\n\n path = LoadedPath;\n }\n\n jsonOptions ??= new JsonSerializerOptions { WriteIndented = true };\n\n File.WriteAllText(path, JsonSerializer.Serialize(this, jsonOptions));\n }\n}\n"], ["/LLPlayer/FlyleafLib/MediaFramework/MediaStream/VideoStream.cs", "using System.Runtime.InteropServices;\n\nusing FlyleafLib.MediaFramework.MediaDemuxer;\n\nnamespace FlyleafLib.MediaFramework.MediaStream;\n\npublic unsafe class VideoStream : StreamBase\n{\n public AspectRatio AspectRatio { get; set; }\n public ColorRange ColorRange { get; set; }\n public ColorSpace ColorSpace { get; set; }\n public AVColorTransferCharacteristic\n ColorTransfer { get; set; }\n public double Rotation { get; set; }\n public double FPS { get; set; }\n public long FrameDuration { get ;set; }\n public uint Height { get; set; }\n public bool IsRGB { get; set; }\n public AVComponentDescriptor[] PixelComps { get; set; }\n public int PixelComp0Depth { get; set; }\n public AVPixelFormat PixelFormat { get; set; }\n public AVPixFmtDescriptor* PixelFormatDesc { get; set; }\n public string PixelFormatStr { get; set; }\n public int PixelPlanes { get; set; }\n public bool PixelSameDepth { get; set; }\n public bool PixelInterleaved { get; set; }\n public int TotalFrames { get; set; }\n public uint Width { get; set; }\n public bool FixTimestamps { get; set; } // TBR: For formats such as h264/hevc that have no or invalid pts values\n\n public override string GetDump()\n => $\"[{Type} #{StreamIndex}] {Codec} {PixelFormatStr} {Width}x{Height} @ {FPS:#.###} | [Color: {ColorSpace}] [BR: {BitRate}] | {Utils.TicksToTime((long)(AVStream->start_time * Timebase))}/{Utils.TicksToTime((long)(AVStream->duration * Timebase))} | {Utils.TicksToTime(StartTime)}/{Utils.TicksToTime(Duration)}\";\n\n public VideoStream() { }\n public VideoStream(Demuxer demuxer, AVStream* st) : base(demuxer, st)\n {\n Demuxer = demuxer;\n AVStream = st;\n Refresh();\n }\n\n public void Refresh(AVPixelFormat format = AVPixelFormat.None, AVFrame* frame = null)\n {\n base.Refresh();\n\n PixelFormat = format == AVPixelFormat.None ? (AVPixelFormat)AVStream->codecpar->format : format;\n PixelFormatStr = PixelFormat.ToString().Replace(\"AV_PIX_FMT_\",\"\").ToLower();\n Width = (uint)AVStream->codecpar->width;\n Height = (uint)AVStream->codecpar->height;\n\n // TBR: Maybe required also for input formats with AVFMT_NOTIMESTAMPS (and audio/subs)\n // Possible FFmpeg.Autogen bug with Demuxer.FormatContext->iformat->flags (should be uint?) does not contain AVFMT_NOTIMESTAMPS (256 instead of 384)\n if (Demuxer.Name == \"h264\" || Demuxer.Name == \"hevc\")\n {\n FixTimestamps = true;\n\n if (Demuxer.Config.ForceFPS > 0)\n FPS = Demuxer.Config.ForceFPS;\n else\n FPS = av_q2d(av_guess_frame_rate(Demuxer.FormatContext, AVStream, frame));\n\n if (FPS == 0)\n FPS = 25;\n }\n else\n {\n FixTimestamps = false;\n FPS = av_q2d(av_guess_frame_rate(Demuxer.FormatContext, AVStream, frame));\n }\n\n FrameDuration = FPS > 0 ? (long) (10000000 / FPS) : 0;\n TotalFrames = AVStream->duration > 0 && FrameDuration > 0 ? (int) (AVStream->duration * Timebase / FrameDuration) : (FrameDuration > 0 ? (int) (Demuxer.Duration / FrameDuration) : 0);\n\n int x, y;\n AVRational sar = av_guess_sample_aspect_ratio(null, AVStream, null);\n if (av_cmp_q(sar, av_make_q(0, 1)) <= 0)\n sar = av_make_q(1, 1);\n\n av_reduce(&x, &y, Width * sar.Num, Height * sar.Den, 1024 * 1024);\n AspectRatio = new AspectRatio(x, y);\n\n if (PixelFormat != AVPixelFormat.None)\n {\n ColorRange = AVStream->codecpar->color_range == AVColorRange.Jpeg ? ColorRange.Full : ColorRange.Limited;\n\n if (AVStream->codecpar->color_space == AVColorSpace.Bt470bg)\n ColorSpace = ColorSpace.BT601;\n else if (AVStream->codecpar->color_space == AVColorSpace.Bt709)\n ColorSpace = ColorSpace.BT709;\n else ColorSpace = AVStream->codecpar->color_space == AVColorSpace.Bt2020Cl || AVStream->codecpar->color_space == AVColorSpace.Bt2020Ncl\n ? ColorSpace.BT2020\n : Height > 576 ? ColorSpace.BT709 : ColorSpace.BT601;\n\n // This causes issues\n //if (AVStream->codecpar->color_space == AVColorSpace.AVCOL_SPC_UNSPECIFIED && AVStream->codecpar->color_trc == AVColorTransferCharacteristic.AVCOL_TRC_UNSPECIFIED && Height > 1080)\n //{ // TBR: Handle Dolphy Vision?\n // ColorSpace = ColorSpace.BT2020;\n // ColorTransfer = AVColorTransferCharacteristic.AVCOL_TRC_SMPTE2084;\n //}\n //else\n ColorTransfer = AVStream->codecpar->color_trc;\n\n // We get rotation from frame side data only from 1st frame in case of exif orientation (mainly for jpeg) - TBR if required to check for each frame\n AVFrameSideData* frameSideData;\n AVPacketSideData* pktSideData;\n double rotation = 0;\n if (frame != null && (frameSideData = av_frame_get_side_data(frame, AVFrameSideDataType.Displaymatrix)) != null && frameSideData->data != null)\n rotation = -Math.Round(av_display_rotation_get((int*)frameSideData->data)); //int_array9 displayMatrix = Marshal.PtrToStructure((nint)frameSideData->data); TBR: NaN why?\n else if ((pktSideData = av_packet_side_data_get(AVStream->codecpar->coded_side_data, AVStream->codecpar->nb_coded_side_data, AVPacketSideDataType.Displaymatrix)) != null && pktSideData->data != null)\n rotation = -Math.Round(av_display_rotation_get((int*)pktSideData->data));\n\n Rotation = rotation - (360*Math.Floor(rotation/360 + 0.9/360));\n\n PixelFormatDesc = av_pix_fmt_desc_get(PixelFormat);\n var comps = PixelFormatDesc->comp.ToArray();\n PixelComps = new AVComponentDescriptor[PixelFormatDesc->nb_components];\n for (int i=0; ilog2_chroma_w != PixelFormatDesc->log2_chroma_h;\n IsRGB = (PixelFormatDesc->flags & PixFmtFlags.Rgb) != 0;\n\n PixelSameDepth = true;\n PixelPlanes = 0;\n if (PixelComps.Length > 0)\n {\n PixelComp0Depth = PixelComps[0].depth;\n int prevBit = PixelComp0Depth;\n for (int i=0; i PixelPlanes)\n PixelPlanes = PixelComps[i].plane;\n\n if (prevBit != PixelComps[i].depth)\n PixelSameDepth = false;\n }\n\n PixelPlanes++;\n }\n }\n }\n}\n"], ["/LLPlayer/FlyleafLib/MediaPlayer/Translation/Services/ITranslateService.cs", "using System.ComponentModel;\nusing System.Threading;\nusing System.Threading.Tasks;\n\nnamespace FlyleafLib.MediaPlayer.Translation.Services;\n\npublic interface ITranslateService : IDisposable\n{\n TranslateServiceType ServiceType { get; }\n\n /// \n /// Initialize\n /// \n /// \n /// \n /// when language is not supported or configured properly\n void Initialize(Language src, TargetLanguage target);\n\n /// \n /// TranslateAsync\n /// \n /// \n /// \n /// \n /// \n /// when translation is failed\n /// \n Task TranslateAsync(string text, CancellationToken token);\n}\n\n[Flags]\npublic enum TranslateServiceType\n{\n /// \n /// Google V1.\n /// \n [Description(\"Google V1\")]\n GoogleV1 = 1 << 0,\n\n /// \n /// DeepL\n /// \n [Description(nameof(DeepL))]\n DeepL = 1 << 1,\n\n /// \n /// DeepLX\n /// https://github.com/OwO-Network/DeepLX\n /// \n [Description(nameof(DeepLX))]\n DeepLX = 1 << 2,\n\n /// \n /// Ollama\n /// \n [Description(nameof(Ollama))]\n Ollama = 1 << 3,\n\n /// \n /// LM Studio\n /// \n [Description(\"LM Studio\")]\n LMStudio = 1 << 4,\n\n /// \n /// KoboldCpp\n /// \n [Description(nameof(KoboldCpp))]\n KoboldCpp = 1 << 5,\n\n /// \n /// OpenAI (ChatGPT)\n /// \n [Description(nameof(OpenAI))]\n OpenAI = 1 << 6,\n\n /// \n /// OpenAI compatible\n /// \n [Description(\"OpenAI Like\")]\n OpenAILike = 1 << 7,\n\n /// \n /// Anthropic Claude\n /// \n [Description(nameof(Claude))]\n Claude = 1 << 8,\n\n /// \n /// LiteLLM\n /// \n [Description(nameof(LiteLLM))]\n LiteLLM = 1 << 9,\n}\n\npublic static class TranslateServiceTypeExtensions\n{\n public static TranslateServiceType LLMServices =>\n TranslateServiceType.Ollama |\n TranslateServiceType.LMStudio |\n TranslateServiceType.KoboldCpp |\n TranslateServiceType.OpenAI |\n TranslateServiceType.OpenAILike |\n TranslateServiceType.Claude |\n TranslateServiceType.LiteLLM;\n\n public static bool IsLLM(this TranslateServiceType serviceType)\n {\n return LLMServices.HasFlag(serviceType);\n }\n\n public static ITranslateSettings DefaultSettings(this TranslateServiceType serviceType)\n {\n switch (serviceType)\n {\n case TranslateServiceType.GoogleV1:\n return new GoogleV1TranslateSettings();\n case TranslateServiceType.DeepL:\n return new DeepLTranslateSettings();\n case TranslateServiceType.DeepLX:\n return new DeepLXTranslateSettings();\n case TranslateServiceType.Ollama:\n return new OllamaTranslateSettings();\n case TranslateServiceType.LMStudio:\n return new LMStudioTranslateSettings();\n case TranslateServiceType.KoboldCpp:\n return new KoboldCppTranslateSettings();\n case TranslateServiceType.OpenAI:\n return new OpenAITranslateSettings();\n case TranslateServiceType.OpenAILike:\n return new OpenAILikeTranslateSettings();\n case TranslateServiceType.Claude:\n return new ClaudeTranslateSettings();\n case TranslateServiceType.LiteLLM:\n return new LiteLLMTranslateSettings();\n }\n\n throw new InvalidOperationException();\n }\n}\n\npublic static class TranslateServiceHelper\n{\n /// \n /// TryGetLanguage\n /// \n /// \n /// \n /// \n /// \n /// \n public static (TranslateLanguage srcLang, TranslateLanguage targetLang) TryGetLanguage(this ITranslateService service, Language src, TargetLanguage target)\n {\n string iso6391 = src.ISO6391;\n\n // TODO: L: Allow the user to choose auto-detection by translation provider?\n if (src == Language.Unknown)\n {\n throw new TranslationConfigException(\"source language are unknown\");\n }\n\n if (src.ISO6391 == target.ToISO6391())\n {\n // Only chinese allow translation between regions (Simplified <-> Traditional)\n // Portuguese, French, and English are not permitted.\n // TODO: L: review this validation?\n if (target is not (TargetLanguage.ChineseSimplified or TargetLanguage.ChineseTraditional))\n {\n throw new TranslationConfigException(\"source and target language are same\");\n }\n }\n\n if (!TranslateLanguage.Langs.TryGetValue(iso6391, out TranslateLanguage srcLang))\n {\n throw new TranslationConfigException($\"source language is not supported: {src.TopEnglishName}\");\n }\n\n if (!srcLang.SupportedServices.HasFlag(service.ServiceType))\n {\n throw new TranslationConfigException($\"source language is not supported by {service.ServiceType}: {src.TopEnglishName}\");\n }\n\n if (!TranslateLanguage.Langs.TryGetValue(target.ToISO6391(), out TranslateLanguage targetLang))\n {\n throw new TranslationConfigException($\"target language is not supported: {target.ToString()}\");\n }\n\n if (!targetLang.SupportedServices.HasFlag(service.ServiceType))\n {\n throw new TranslationConfigException($\"target language is not supported by {service.ServiceType}: {src.TopEnglishName}\");\n }\n\n return (srcLang, targetLang);\n }\n}\n\npublic class TranslationException : Exception\n{\n public TranslationException()\n {\n }\n\n public TranslationException(string message)\n : base(message)\n {\n }\n\n public TranslationException(string message, Exception inner)\n : base(message, inner)\n {\n }\n}\n\npublic class TranslationConfigException : Exception\n{\n public TranslationConfigException()\n {\n }\n\n public TranslationConfigException(string message)\n : base(message)\n {\n }\n\n public TranslationConfigException(string message, Exception inner)\n : base(message, inner)\n {\n }\n}\n"], ["/LLPlayer/FlyleafLib/Controls/WPF/FlyleafHost.cs", "using System;\nusing System.ComponentModel;\nusing System.Windows.Controls;\nusing System.Windows;\nusing System.Windows.Media;\nusing System.Windows.Input;\nusing System.Windows.Interop;\n\nusing FlyleafLib.MediaPlayer;\n\nusing static FlyleafLib.Utils;\nusing static FlyleafLib.Utils.NativeMethods;\n\nusing Brushes = System.Windows.Media.Brushes;\n\nnamespace FlyleafLib.Controls.WPF;\n\npublic class FlyleafHost : ContentControl, IHostPlayer, IDisposable\n{\n /* -= FlyleafHost Properties Notes =-\n\n Player\t\t\t\t\t\t\t[Can be changed, can be null]\n ReplicaPlayer | Replicates frames of the assigned Player (useful for interactive zoom) without the pan/zoom config\n\n Surface\t\t\t\t\t\t\t[ReadOnly / Required]\n Overlay\t\t\t\t\t\t\t[AutoCreated OnContentChanged | Provided directly | Provided in Stand Alone Constructor]\n\n Content\t\t\t\t\t\t\t[Overlay's Content]\n DetachedContent\t\t\t\t\t[Host's actual content]\n\n DataContext\t\t\t\t\t\t[Set by the user or default inheritance]\n HostDataContext\t\t\t\t\t[Will be set Sync with DataContext as helper to Overlay when we pass this as Overlay's DataContext]\n\n OpenOnDrop\t\t\t\t\t\t[None, Surface, Overlay, Both]\t\t| Requires Player and AllowDrop\n SwapOnDrop\t\t\t\t\t\t[None, Surface, Overlay, Both]\t\t| Requires Player and AllowDrop\n\n SwapDragEnterOnShift\t\t\t[None, Surface, Overlay, Both]\t\t| Requires Player and SwapOnDrop\n ToggleFullScreenOnDoubleClick\t[None, Surface, Overlay, Both]\n\n PanMoveOnCtrl\t\t\t\t\t[None, Surface, Overlay, Both]\t\t| Requires Player and VideoStream Opened\n PanZoomOnCtrlWheel\t\t\t [None, Surface, Overlay, Both]\t\t| Requires Player and VideoStream Opened\n PanRotateOnShiftWheel [None, Surface, Overlay, Both] | Requires Player and VideoStream Opened\n\n AttachedDragMove\t\t\t\t[None, Surface, Overlay, Both, SurfaceOwner, OverlayOwner, BothOwner]\n DetachedDragMove\t\t\t\t[None, Surface, Overlay, Both]\n\n AttachedResize\t\t\t\t\t[None, Surface, Overlay, Both]\n DetachedResize\t\t\t\t\t[None, Surface, Overlay, Both]\n KeepRatioOnResize\t\t\t\t[False, True]\n PreferredLandscapeWidth [X] | When KeepRatioOnResize will use it as helper and try to stay close to this value (CurResizeRatio >= 1) - Will be updated when user resizes a landscape\n PreferredPortraitHeight [Y] | When KeepRatioOnResize will use it as helper and try to stay close to this value (CurResizeRatio < 1) - Will be updated when user resizes a portrait\n CurResizeRatio [0 if not Keep Ratio or Player's aspect ratio]\n ResizeSensitivity Pixels sensitivity from the window's edges\n\n BringToFrontOnClick [False, True]\n\n DetachedPosition\t\t\t\t[Custom, TopLeft, TopCenter, TopRight, CenterLeft, CenterCenter, CenterRight, BottomLeft, BottomCenter, BottomRight]\n DetachedPositionMargin\t\t\t[X, Y, CX, CY]\t\t\t\t\t\t| Does not affect the Size / Eg. No point to provide both X/CX\n DetachedFixedPosition\t\t\t[X, Y]\t\t\t\t\t\t\t\t| if remember only first time\n DetachedFixedSize\t\t\t\t[CX, CY]\t\t\t\t\t\t\t| if remember only first time\n DetachedRememberPosition\t\t[False, True]\n DetachedRememberSize\t\t\t[False, True]\n DetachedTopMost\t\t\t\t\t[False, True] (Surfaces Only Required?)\n DetachedShowInTaskbar [False, True] | When Detached or Fullscreen will be in Switch Apps\n DetachedNoOwner [False, True] | When Detached will not follow the owner's window state (Minimize/Maximize)\n\n KeyBindings\t\t\t\t\t\t[None, Surface, Overlay, Both]\n MouseBindings [None, Surface, Overlay, Both] | Required for all other mouse events\n\n ActivityTimeout\t\t\t\t\t[0: Disabled]\t\t\t\t\t\t| Requires Player?\n ActivityRefresh?\t\t\t\t[None, Surface, Overlay, Both]\t\t| MouseMove / MouseDown / KeyUp\n\n PassWheelToOwner?\t\t\t\t[None, Surface, Overlay, Both]\t\t| When host belongs to ScrollViewer\n\n IsAttached [False, True]\n IsFullScreen [False, True] | Should be used instead of WindowStates\n IsMinimized [False, True] | Should be used instead of WindowStates\n IsResizing\t\t\t\t\t\t[ReadOnly]\n IsSwapping\t\t\t\t\t\t[ReadOnly]\n IsStandAlone\t\t\t\t\t[ReadOnly]\n */\n\n /* TODO\n * 1) The surface / overlay events code is repeated\n * 2) PassWheelToOwner (Related with LayoutUpdate performance / ScrollViewer) / ActivityRefresh\n * 3) Attach to different Owner (Load/Unload) and change Overlay?\n * 4) WindowStates should not be used by user directly. Use IsMinimized and IsFullScreen instead.\n * 5) WS_EX_NOACTIVATE should be set but for some reason is not required (for none-styled windows)? Currently BringToFront does the job but (only for left clicks?)\n */\n\n #region Properties / Variables\n public Window Owner { get; private set; }\n public Window Surface { get; private set; }\n public IntPtr SurfaceHandle { get; private set; }\n public IntPtr OverlayHandle { get; private set; }\n public IntPtr OwnerHandle { get; private set; }\n public int ResizingSide { get; private set; }\n\n public int UniqueId { get; private set; }\n public bool Disposed { get; private set; }\n\n\n public event EventHandler SurfaceCreated;\n public event EventHandler OverlayCreated;\n public event DragEventHandler OnSurfaceDrop;\n public event DragEventHandler OnOverlayDrop;\n\n static bool isDesignMode;\n static int idGenerator = 1;\n static nint NONE_STYLE = (nint) (WindowStyles.WS_MINIMIZEBOX | WindowStyles.WS_CLIPSIBLINGS | WindowStyles.WS_CLIPCHILDREN | WindowStyles.WS_VISIBLE); // WS_MINIMIZEBOX required for swapchain\n static Rect rectRandom = new(1, 2, 3, 4);\n\n float curResizeRatio;\n float curResizeRatioIfEnabled;\n bool surfaceClosed, surfaceClosing, overlayClosed;\n int panPrevX, panPrevY;\n bool isMouseBindingsSubscribedSurface;\n bool isMouseBindingsSubscribedOverlay;\n Window standAloneOverlay;\n\n CornerRadius zeroCornerRadius = new(0);\n Point zeroPoint = new(0, 0);\n Point mouseLeftDownPoint = new(0, 0);\n Point mouseMoveLastPoint = new(0, 0);\n Point ownerZeroPointPos = new();\n\n Rect zeroRect = new(0, 0, 0, 0);\n Rect rectDetachedLast = Rect.Empty;\n Rect rectInit;\n Rect rectInitLast = rectRandom;\n Rect rectIntersect;\n Rect rectIntersectLast = rectRandom;\n RECT beforeResizeRect = new();\n RECT curRect = new();\n\n private class FlyleafHostDropWrap { public FlyleafHost FlyleafHost; } // To allow non FlyleafHosts to drag & drop\n protected readonly LogHandler Log;\n #endregion\n\n #region Dependency Properties\n public void BringToFront() => SetWindowPos(SurfaceHandle, IntPtr.Zero, 0, 0, 0, 0, (UInt32)(SetWindowPosFlags.SWP_SHOWWINDOW | SetWindowPosFlags.SWP_NOSIZE | SetWindowPosFlags.SWP_NOMOVE));\n public bool BringToFrontOnClick\n {\n get { return (bool)GetValue(BringToFrontOnClickProperty); }\n set { SetValue(BringToFrontOnClickProperty, value); }\n }\n public static readonly DependencyProperty BringToFrontOnClickProperty =\n DependencyProperty.Register(nameof(BringToFrontOnClick), typeof(bool), typeof(FlyleafHost), new PropertyMetadata(true));\n\n public AvailableWindows OpenOnDrop\n {\n get => (AvailableWindows)GetValue(OpenOnDropProperty);\n set => SetValue(OpenOnDropProperty, value);\n }\n public static readonly DependencyProperty OpenOnDropProperty =\n DependencyProperty.Register(nameof(OpenOnDrop), typeof(AvailableWindows), typeof(FlyleafHost), new PropertyMetadata(AvailableWindows.Surface, new PropertyChangedCallback(DropChanged)));\n\n public AvailableWindows SwapOnDrop\n {\n get => (AvailableWindows)GetValue(SwapOnDropProperty);\n set => SetValue(SwapOnDropProperty, value);\n }\n public static readonly DependencyProperty SwapOnDropProperty =\n DependencyProperty.Register(nameof(SwapOnDrop), typeof(AvailableWindows), typeof(FlyleafHost), new PropertyMetadata(AvailableWindows.Surface, new PropertyChangedCallback(DropChanged)));\n\n public AvailableWindows SwapDragEnterOnShift\n {\n get => (AvailableWindows)GetValue(SwapDragEnterOnShiftProperty);\n set => SetValue(SwapDragEnterOnShiftProperty, value);\n }\n public static readonly DependencyProperty SwapDragEnterOnShiftProperty =\n DependencyProperty.Register(nameof(SwapDragEnterOnShift), typeof(AvailableWindows), typeof(FlyleafHost), new PropertyMetadata(AvailableWindows.Surface));\n\n public AvailableWindows ToggleFullScreenOnDoubleClick\n {\n get => (AvailableWindows)GetValue(ToggleFullScreenOnDoubleClickProperty);\n set => SetValue(ToggleFullScreenOnDoubleClickProperty, value);\n }\n public static readonly DependencyProperty ToggleFullScreenOnDoubleClickProperty =\n DependencyProperty.Register(nameof(ToggleFullScreenOnDoubleClick), typeof(AvailableWindows), typeof(FlyleafHost), new PropertyMetadata(AvailableWindows.Surface));\n\n public AvailableWindows PanMoveOnCtrl\n {\n get => (AvailableWindows)GetValue(PanMoveOnCtrlProperty);\n set => SetValue(PanMoveOnCtrlProperty, value);\n }\n public static readonly DependencyProperty PanMoveOnCtrlProperty =\n DependencyProperty.Register(nameof(PanMoveOnCtrl), typeof(AvailableWindows), typeof(FlyleafHost), new PropertyMetadata(AvailableWindows.Surface));\n\n public AvailableWindows PanRotateOnShiftWheel\n {\n get => (AvailableWindows)GetValue(PanRotateOnShiftWheelProperty);\n set => SetValue(PanRotateOnShiftWheelProperty, value);\n }\n public static readonly DependencyProperty PanRotateOnShiftWheelProperty =\n DependencyProperty.Register(nameof(PanRotateOnShiftWheel), typeof(AvailableWindows), typeof(FlyleafHost), new PropertyMetadata(AvailableWindows.Surface));\n\n public AvailableWindows PanZoomOnCtrlWheel\n {\n get => (AvailableWindows)GetValue(PanZoomOnCtrlWheelProperty);\n set => SetValue(PanZoomOnCtrlWheelProperty, value);\n }\n public static readonly DependencyProperty PanZoomOnCtrlWheelProperty =\n DependencyProperty.Register(nameof(PanZoomOnCtrlWheel), typeof(AvailableWindows), typeof(FlyleafHost), new PropertyMetadata(AvailableWindows.Surface));\n\n public AttachedDragMoveOptions AttachedDragMove\n {\n get => (AttachedDragMoveOptions)GetValue(AttachedDragMoveProperty);\n set => SetValue(AttachedDragMoveProperty, value);\n }\n public static readonly DependencyProperty AttachedDragMoveProperty =\n DependencyProperty.Register(nameof(AttachedDragMove), typeof(AttachedDragMoveOptions), typeof(FlyleafHost), new PropertyMetadata(AttachedDragMoveOptions.Surface));\n\n public AvailableWindows DetachedDragMove\n {\n get => (AvailableWindows)GetValue(DetachedDragMoveProperty);\n set => SetValue(DetachedDragMoveProperty, value);\n }\n public static readonly DependencyProperty DetachedDragMoveProperty =\n DependencyProperty.Register(nameof(DetachedDragMove), typeof(AvailableWindows), typeof(FlyleafHost), new PropertyMetadata(AvailableWindows.Surface));\n\n public AvailableWindows AttachedResize\n {\n get => (AvailableWindows)GetValue(AttachedResizeProperty);\n set => SetValue(AttachedResizeProperty, value);\n }\n public static readonly DependencyProperty AttachedResizeProperty =\n DependencyProperty.Register(nameof(AttachedResize), typeof(AvailableWindows), typeof(FlyleafHost), new PropertyMetadata(AvailableWindows.Surface));\n\n public AvailableWindows DetachedResize\n {\n get => (AvailableWindows)GetValue(DetachedResizeProperty);\n set => SetValue(DetachedResizeProperty, value);\n }\n public static readonly DependencyProperty DetachedResizeProperty =\n DependencyProperty.Register(nameof(DetachedResize), typeof(AvailableWindows), typeof(FlyleafHost), new PropertyMetadata(AvailableWindows.Surface));\n\n public bool KeepRatioOnResize\n {\n get => (bool)GetValue(KeepRatioOnResizeProperty);\n set => SetValue(KeepRatioOnResizeProperty, value);\n }\n public static readonly DependencyProperty KeepRatioOnResizeProperty =\n DependencyProperty.Register(nameof(KeepRatioOnResize), typeof(bool), typeof(FlyleafHost), new PropertyMetadata(false, new PropertyChangedCallback(OnKeepRatioOnResizeChanged)));\n\n public int PreferredLandscapeWidth\n {\n get { return (int)GetValue(PreferredLandscapeWidthProperty); }\n set { SetValue(PreferredLandscapeWidthProperty, value); }\n }\n public static readonly DependencyProperty PreferredLandscapeWidthProperty =\n DependencyProperty.Register(nameof(PreferredLandscapeWidth), typeof(int), typeof(FlyleafHost), new PropertyMetadata(0));\n\n public int PreferredPortraitHeight\n {\n get { return (int)GetValue(PreferredPortraitHeightProperty); }\n set { SetValue(PreferredPortraitHeightProperty, value); }\n }\n public static readonly DependencyProperty PreferredPortraitHeightProperty =\n DependencyProperty.Register(nameof(PreferredPortraitHeight), typeof(int), typeof(FlyleafHost), new PropertyMetadata(0));\n\n public int ResizeSensitivity\n {\n get => (int)GetValue(ResizeSensitivityProperty);\n set => SetValue(ResizeSensitivityProperty, value);\n }\n public static readonly DependencyProperty ResizeSensitivityProperty =\n DependencyProperty.Register(nameof(ResizeSensitivity), typeof(int), typeof(FlyleafHost), new PropertyMetadata(6));\n\n public DetachedPositionOptions DetachedPosition\n {\n get => (DetachedPositionOptions)GetValue(DetachedPositionProperty);\n set => SetValue(DetachedPositionProperty, value);\n }\n public static readonly DependencyProperty DetachedPositionProperty =\n DependencyProperty.Register(nameof(DetachedPosition), typeof(DetachedPositionOptions), typeof(FlyleafHost), new PropertyMetadata(DetachedPositionOptions.CenterCenter));\n\n public Thickness DetachedPositionMargin\n {\n get => (Thickness)GetValue(DetachedPositionMarginProperty);\n set => SetValue(DetachedPositionMarginProperty, value);\n }\n public static readonly DependencyProperty DetachedPositionMarginProperty =\n DependencyProperty.Register(nameof(DetachedPositionMargin), typeof(Thickness), typeof(FlyleafHost), new PropertyMetadata(new Thickness(0, 0, 0, 0)));\n\n public Point DetachedFixedPosition\n {\n get => (Point)GetValue(DetachedFixedPositionProperty);\n set => SetValue(DetachedFixedPositionProperty, value);\n }\n public static readonly DependencyProperty DetachedFixedPositionProperty =\n DependencyProperty.Register(nameof(DetachedFixedPosition), typeof(Point), typeof(FlyleafHost), new PropertyMetadata(new Point()));\n\n public Size DetachedFixedSize\n {\n get => (Size)GetValue(DetachedFixedSizeProperty);\n set => SetValue(DetachedFixedSizeProperty, value);\n }\n public static readonly DependencyProperty DetachedFixedSizeProperty =\n DependencyProperty.Register(nameof(DetachedFixedSize), typeof(Size), typeof(FlyleafHost), new PropertyMetadata(new Size(300, 200)));\n\n public bool DetachedRememberPosition\n {\n get => (bool)GetValue(DetachedRememberPositionProperty);\n set => SetValue(DetachedRememberPositionProperty, value);\n }\n public static readonly DependencyProperty DetachedRememberPositionProperty =\n DependencyProperty.Register(nameof(DetachedRememberPosition), typeof(bool), typeof(FlyleafHost), new PropertyMetadata(true));\n\n public bool DetachedRememberSize\n {\n get => (bool)GetValue(DetachedRememberSizeProperty);\n set => SetValue(DetachedRememberSizeProperty, value);\n }\n public static readonly DependencyProperty DetachedRememberSizeProperty =\n DependencyProperty.Register(nameof(DetachedRememberSize), typeof(bool), typeof(FlyleafHost), new PropertyMetadata(true));\n\n public bool DetachedTopMost\n {\n get => (bool)GetValue(DetachedTopMostProperty);\n set => SetValue(DetachedTopMostProperty, value);\n }\n public static readonly DependencyProperty DetachedTopMostProperty =\n DependencyProperty.Register(nameof(DetachedTopMost), typeof(bool), typeof(FlyleafHost), new PropertyMetadata(false, new PropertyChangedCallback(OnDetachedTopMostChanged)));\n\n public bool DetachedShowInTaskbar\n {\n get { return (bool)GetValue(DetachedShowInTaskbarProperty); }\n set { SetValue(DetachedShowInTaskbarProperty, value); }\n }\n public static readonly DependencyProperty DetachedShowInTaskbarProperty =\n DependencyProperty.Register(nameof(DetachedShowInTaskbar), typeof(bool), typeof(FlyleafHost), new PropertyMetadata(false, new PropertyChangedCallback(OnShowInTaskBarChanged)));\n\n public bool DetachedNoOwner\n {\n get { return (bool)GetValue(DetachedNoOwnerProperty); }\n set { SetValue(DetachedNoOwnerProperty, value); }\n }\n public static readonly DependencyProperty DetachedNoOwnerProperty =\n DependencyProperty.Register(nameof(DetachedNoOwner), typeof(bool), typeof(FlyleafHost), new PropertyMetadata(false, new PropertyChangedCallback(OnNoOwnerChanged)));\n\n public int DetachedMinHeight\n {\n get { return (int)GetValue(DetachedMinHeightProperty); }\n set { SetValue(DetachedMinHeightProperty, value); }\n }\n public static readonly DependencyProperty DetachedMinHeightProperty =\n DependencyProperty.Register(nameof(DetachedMinHeight), typeof(int), typeof(FlyleafHost), new PropertyMetadata(0));\n\n public int DetachedMinWidth\n {\n get { return (int)GetValue(DetachedMinWidthProperty); }\n set { SetValue(DetachedMinWidthProperty, value); }\n }\n public static readonly DependencyProperty DetachedMinWidthProperty =\n DependencyProperty.Register(nameof(DetachedMinWidth), typeof(int), typeof(FlyleafHost), new PropertyMetadata(0));\n\n public double DetachedMaxHeight\n {\n get { return (double)GetValue(DetachedMaxHeightProperty); }\n set { SetValue(DetachedMaxHeightProperty, value); }\n }\n public static readonly DependencyProperty DetachedMaxHeightProperty =\n DependencyProperty.Register(nameof(DetachedMaxHeight), typeof(double), typeof(FlyleafHost), new PropertyMetadata(double.PositiveInfinity));\n\n public double DetachedMaxWidth\n {\n get { return (double)GetValue(DetachedMaxWidthProperty); }\n set { SetValue(DetachedMaxWidthProperty, value); }\n }\n public static readonly DependencyProperty DetachedMaxWidthProperty =\n DependencyProperty.Register(nameof(DetachedMaxWidth), typeof(double), typeof(FlyleafHost), new PropertyMetadata(double.PositiveInfinity));\n\n public AvailableWindows KeyBindings\n {\n get => (AvailableWindows)GetValue(KeyBindingsProperty);\n set => SetValue(KeyBindingsProperty, value);\n }\n public static readonly DependencyProperty KeyBindingsProperty =\n DependencyProperty.Register(nameof(KeyBindings), typeof(AvailableWindows), typeof(FlyleafHost), new PropertyMetadata(AvailableWindows.Surface));\n\n public AvailableWindows MouseBindings\n {\n get => (AvailableWindows)GetValue(MouseBindingsProperty);\n set => SetValue(MouseBindingsProperty, value);\n }\n public static readonly DependencyProperty MouseBindingsProperty =\n DependencyProperty.Register(nameof(MouseBindings), typeof(AvailableWindows), typeof(FlyleafHost), new PropertyMetadata(AvailableWindows.Both, new PropertyChangedCallback(OnMouseBindings)));\n\n public int ActivityTimeout\n {\n get => (int)GetValue(ActivityTimeoutProperty);\n set => SetValue(ActivityTimeoutProperty, value);\n }\n public static readonly DependencyProperty ActivityTimeoutProperty =\n DependencyProperty.Register(nameof(ActivityTimeout), typeof(int), typeof(FlyleafHost), new PropertyMetadata(0, new PropertyChangedCallback(OnActivityTimeoutChanged)));\n\n public bool IsAttached\n {\n get => (bool)GetValue(IsAttachedProperty);\n set => SetValue(IsAttachedProperty, value);\n }\n public static readonly DependencyProperty IsAttachedProperty =\n DependencyProperty.Register(nameof(IsAttached), typeof(bool), typeof(FlyleafHost), new PropertyMetadata(true, new PropertyChangedCallback(OnIsAttachedChanged)));\n\n public bool IsMinimized\n {\n get => (bool)GetValue(IsMinimizedProperty);\n set => SetValue(IsMinimizedProperty, value);\n }\n public static readonly DependencyProperty IsMinimizedProperty =\n DependencyProperty.Register(nameof(IsMinimized), typeof(bool), typeof(FlyleafHost), new PropertyMetadata(false, new PropertyChangedCallback(OnIsMinimizedChanged)));\n\n public bool IsFullScreen\n {\n get => (bool)GetValue(IsFullScreenProperty);\n set => SetValue(IsFullScreenProperty, value);\n }\n public static readonly DependencyProperty IsFullScreenProperty =\n DependencyProperty.Register(nameof(IsFullScreen), typeof(bool), typeof(FlyleafHost), new PropertyMetadata(false, new PropertyChangedCallback(OnIsFullScreenChanged)));\n\n public bool IsResizing\n {\n get => (bool)GetValue(IsResizingProperty);\n private set => SetValue(IsResizingProperty, value);\n }\n public static readonly DependencyProperty IsResizingProperty =\n DependencyProperty.Register(nameof(IsResizing), typeof(bool), typeof(FlyleafHost), new PropertyMetadata(false));\n\n public bool IsStandAlone\n {\n get => (bool)GetValue(IsStandAloneProperty);\n private set => SetValue(IsStandAloneProperty, value);\n }\n public static readonly DependencyProperty IsStandAloneProperty =\n DependencyProperty.Register(nameof(IsStandAlone), typeof(bool), typeof(FlyleafHost), new PropertyMetadata(false));\n\n public bool IsSwappingStarted\n {\n get => (bool)GetValue(IsSwappingStartedProperty);\n private set => SetValue(IsSwappingStartedProperty, value);\n }\n public static readonly DependencyProperty IsSwappingStartedProperty =\n DependencyProperty.Register(nameof(IsSwappingStarted), typeof(bool), typeof(FlyleafHost), new PropertyMetadata(false));\n\n public bool IsPanMoving\n {\n get { return (bool)GetValue(IsPanMovingProperty); }\n private set { SetValue(IsPanMovingProperty, value); }\n }\n public static readonly DependencyProperty IsPanMovingProperty =\n DependencyProperty.Register(nameof(IsPanMoving), typeof(bool), typeof(FlyleafHost), new PropertyMetadata(false));\n\n public bool IsDragMoving\n {\n get { return (bool)GetValue(IsDragMovingProperty); }\n set { SetValue(IsDragMovingProperty, value); }\n }\n public static readonly DependencyProperty IsDragMovingProperty =\n DependencyProperty.Register(nameof(IsDragMoving), typeof(bool), typeof(FlyleafHost), new PropertyMetadata(false));\n\n public bool IsDragMovingOwner\n {\n get { return (bool)GetValue(IsDragMovingOwnerProperty); }\n set { SetValue(IsDragMovingOwnerProperty, value); }\n }\n public static readonly DependencyProperty IsDragMovingOwnerProperty =\n DependencyProperty.Register(nameof(IsDragMovingOwner), typeof(bool), typeof(FlyleafHost), new PropertyMetadata(false));\n\n public FrameworkElement MarginTarget\n {\n get => (FrameworkElement)GetValue(MarginTargetProperty);\n set => SetValue(MarginTargetProperty, value);\n }\n public static readonly DependencyProperty MarginTargetProperty =\n DependencyProperty.Register(nameof(MarginTarget), typeof(FrameworkElement), typeof(FlyleafHost), new PropertyMetadata(null));\n\n public object HostDataContext\n {\n get => GetValue(HostDataContextProperty);\n set => SetValue(HostDataContextProperty, value);\n }\n public static readonly DependencyProperty HostDataContextProperty =\n DependencyProperty.Register(nameof(HostDataContext), typeof(object), typeof(FlyleafHost), new PropertyMetadata(null));\n\n public object DetachedContent\n {\n get => GetValue(DetachedContentProperty);\n set => SetValue(DetachedContentProperty, value);\n }\n public static readonly DependencyProperty DetachedContentProperty =\n DependencyProperty.Register(nameof(DetachedContent), typeof(object), typeof(FlyleafHost), new PropertyMetadata(null));\n\n public Player Player\n {\n get => (Player)GetValue(PlayerProperty);\n set => SetValue(PlayerProperty, value);\n }\n public static readonly DependencyProperty PlayerProperty =\n DependencyProperty.Register(nameof(Player), typeof(Player), typeof(FlyleafHost), new PropertyMetadata(null, OnPlayerChanged));\n\n public Player ReplicaPlayer\n {\n get => (Player)GetValue(ReplicaPlayerProperty);\n set => SetValue(ReplicaPlayerProperty, value);\n }\n public static readonly DependencyProperty ReplicaPlayerProperty =\n DependencyProperty.Register(nameof(ReplicaPlayer), typeof(Player), typeof(FlyleafHost), new PropertyMetadata(null, OnReplicaPlayerChanged));\n\n public ControlTemplate OverlayTemplate\n {\n get => (ControlTemplate)GetValue(OverlayTemplateProperty);\n set => SetValue(OverlayTemplateProperty, value);\n }\n public static readonly DependencyProperty OverlayTemplateProperty =\n DependencyProperty.Register(nameof(OverlayTemplate), typeof(ControlTemplate), typeof(FlyleafHost), new PropertyMetadata(null, new PropertyChangedCallback(OnOverlayTemplateChanged)));\n\n public Window Overlay\n {\n get => (Window)GetValue(OverlayProperty);\n set => SetValue(OverlayProperty, value);\n }\n public static readonly DependencyProperty OverlayProperty =\n DependencyProperty.Register(nameof(Overlay), typeof(Window), typeof(FlyleafHost), new PropertyMetadata(null, new PropertyChangedCallback(OnOverlayChanged)));\n\n public CornerRadius CornerRadius\n {\n get => (CornerRadius)GetValue(CornerRadiusProperty);\n set => SetValue(CornerRadiusProperty, value);\n }\n public static readonly DependencyProperty CornerRadiusProperty =\n DependencyProperty.Register(nameof(CornerRadius), typeof(CornerRadius), typeof(FlyleafHost), new PropertyMetadata(new CornerRadius(0), new PropertyChangedCallback(OnCornerRadiusChanged)));\n #endregion\n\n #region Events\n private static void OnMouseBindings(DependencyObject d, DependencyPropertyChangedEventArgs e)\n {\n if (isDesignMode)\n return;\n\n FlyleafHost host = d as FlyleafHost;\n if (host.Disposed)\n return;\n\n host.SetMouseSurface();\n host.SetMouseOverlay();\n }\n private static void OnDetachedTopMostChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)\n {\n if (isDesignMode)\n return;\n\n FlyleafHost host = d as FlyleafHost;\n if (host.Disposed)\n return;\n\n if (host.Surface != null)\n host.Surface.Topmost = !host.IsAttached && host.DetachedTopMost;\n }\n private static void DropChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)\n {\n FlyleafHost host = d as FlyleafHost;\n if (host.Disposed)\n return;\n\n if (host.Surface == null)\n return;\n\n host.Surface.AllowDrop =\n host.OpenOnDrop == AvailableWindows.Surface || host.OpenOnDrop == AvailableWindows.Both ||\n host.SwapOnDrop == AvailableWindows.Surface || host.SwapOnDrop == AvailableWindows.Both;\n\n if (host.Overlay == null)\n return;\n\n host.Overlay.AllowDrop =\n host.OpenOnDrop == AvailableWindows.Overlay || host.OpenOnDrop == AvailableWindows.Both ||\n host.SwapOnDrop == AvailableWindows.Overlay || host.SwapOnDrop == AvailableWindows.Both;\n }\n private void UpdateCurRatio()\n {\n if (!KeepRatioOnResize || IsFullScreen)\n return;\n\n if (Player != null && Player.Video.AspectRatio.Value > 0)\n curResizeRatio = Player.Video.AspectRatio.Value;\n else if (ReplicaPlayer != null && ReplicaPlayer.Video.AspectRatio.Value > 0)\n curResizeRatio = ReplicaPlayer.Video.AspectRatio.Value;\n else\n curResizeRatio = (float)(16.0/9.0);\n\n curResizeRatioIfEnabled = curResizeRatio;\n\n Rect screen;\n\n if (IsAttached)\n {\n if (Owner == null)\n {\n Height = ActualWidth / curResizeRatio;\n return;\n }\n\n screen = new(zeroPoint, Owner.RenderSize);\n }\n else\n {\n if (Surface == null)\n return;\n\n var bounds = System.Windows.Forms.Screen.FromPoint(new System.Drawing.Point((int)Surface.Top, (int)Surface.Left)).Bounds;\n screen = new(bounds.Left / DpiX, bounds.Top / DpiY, bounds.Width / DpiX, bounds.Height / DpiY);\n }\n\n double WindowWidth;\n double WindowHeight;\n\n if (curResizeRatio >= 1)\n {\n WindowHeight = PreferredLandscapeWidth / curResizeRatio;\n\n if (WindowHeight < Surface.MinHeight)\n {\n WindowHeight = Surface.MinHeight;\n WindowWidth = WindowHeight * curResizeRatio;\n }\n else if (WindowHeight > Surface.MaxHeight)\n {\n WindowHeight = Surface.MaxHeight;\n WindowWidth = Surface.Height * curResizeRatio;\n }\n else if (WindowHeight > screen.Height)\n {\n WindowHeight = screen.Height;\n WindowWidth = WindowHeight * curResizeRatio;\n }\n else\n WindowWidth = PreferredLandscapeWidth;\n }\n else\n {\n WindowWidth = PreferredPortraitHeight * curResizeRatio;\n\n if (WindowWidth < Surface.MinWidth)\n {\n WindowWidth = Surface.MinWidth;\n WindowHeight = WindowWidth / curResizeRatio;\n }\n else if (WindowWidth > Surface.MaxWidth)\n {\n WindowWidth = Surface.MaxWidth;\n WindowHeight = WindowWidth / curResizeRatio;\n }\n else if (WindowWidth > screen.Width)\n {\n WindowWidth = screen.Width;\n WindowHeight = WindowWidth / curResizeRatio;\n }\n else\n WindowHeight = PreferredPortraitHeight;\n }\n\n if (IsAttached)\n {\n\n Height = WindowHeight;\n Width = WindowWidth;\n }\n\n else if (Surface != null)\n {\n double WindowLeft;\n double WindowTop;\n\n if (Surface.Left + Surface.Width / 2 > screen.Width / 2)\n WindowLeft = Math.Min(Math.Max(Surface.Left + Surface.Width - WindowWidth, 0), screen.Width - WindowWidth);\n else\n WindowLeft = Surface.Left;\n\n if (Surface.Top + Surface.Height / 2 > screen.Height / 2)\n WindowTop = Math.Min(Math.Max(Surface.Top + Surface.Height - WindowHeight, 0), screen.Height - WindowHeight);\n else\n WindowTop = Surface.Top;\n\n WindowLeft *= DpiX;\n WindowTop *= DpiY;\n WindowWidth *= DpiX;\n WindowHeight*= DpiY;\n\n SetWindowPos(SurfaceHandle, IntPtr.Zero,\n (int)WindowLeft,\n (int)WindowTop,\n (int)Math.Ceiling(WindowWidth),\n (int)Math.Ceiling(WindowHeight),\n (uint)(SetWindowPosFlags.SWP_NOZORDER | SetWindowPosFlags.SWP_NOACTIVATE));\n }\n }\n private static void OnShowInTaskBarChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)\n {\n FlyleafHost host = d as FlyleafHost;\n if (host.Disposed)\n return;\n\n if (host.Surface == null)\n return;\n\n if (host.DetachedShowInTaskbar)\n SetWindowLong(host.SurfaceHandle, (int)WindowLongFlags.GWL_EXSTYLE, GetWindowLong(host.SurfaceHandle, (int)WindowLongFlags.GWL_EXSTYLE) | (nint)WindowStylesEx.WS_EX_APPWINDOW);\n else\n SetWindowLong(host.SurfaceHandle, (int)WindowLongFlags.GWL_EXSTYLE, GetWindowLong(host.SurfaceHandle, (int)WindowLongFlags.GWL_EXSTYLE) & ~(nint)WindowStylesEx.WS_EX_APPWINDOW);\n }\n private static void OnNoOwnerChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)\n {\n FlyleafHost host = d as FlyleafHost;\n if (host.Disposed)\n return;\n\n if (host.Surface == null)\n return;\n\n if (!host.IsAttached)\n host.Surface.Owner = host.DetachedNoOwner ? null : host.Owner;\n }\n private static void OnKeepRatioOnResizeChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)\n {\n if (isDesignMode)\n return;\n\n FlyleafHost host = d as FlyleafHost;\n if (host.Disposed)\n return;\n\n if (!host.KeepRatioOnResize)\n host.curResizeRatioIfEnabled = 0;\n else\n host.UpdateCurRatio();\n }\n private static void OnPlayerChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)\n {\n if (isDesignMode)\n return;\n\n FlyleafHost host = d as FlyleafHost;\n if (host.Disposed)\n return;\n\n host.SetPlayer((Player)e.OldValue);\n }\n private static void OnReplicaPlayerChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)\n {\n if (isDesignMode)\n return;\n\n FlyleafHost host = d as FlyleafHost;\n if (host.Disposed)\n return;\n\n host.SetReplicaPlayer((Player)e.OldValue);\n }\n private static void OnIsFullScreenChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)\n {\n if (isDesignMode)\n return;\n\n FlyleafHost host = d as FlyleafHost;\n if (host.Disposed)\n return;\n\n host.RefreshNormalFullScreen();\n }\n private static void OnIsMinimizedChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)\n {\n if (isDesignMode)\n return;\n\n FlyleafHost host = d as FlyleafHost;\n if (host.Disposed)\n return;\n\n host.Surface.WindowState = host.IsMinimized ? WindowState.Minimized : (host.IsFullScreen ? WindowState.Maximized : WindowState.Normal);\n }\n private static void OnIsAttachedChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)\n {\n if (isDesignMode)\n return;\n\n FlyleafHost host = d as FlyleafHost;\n if (host.Disposed)\n return;\n\n if (host.IsStandAlone)\n {\n host.IsAttached = false;\n return;\n }\n\n if (!host.IsLoaded)\n return;\n\n if (host.IsAttached)\n host.Attach();\n else\n host.Detach();\n }\n private static void OnActivityTimeoutChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)\n {\n FlyleafHost host = d as FlyleafHost;\n if (host.Disposed)\n return;\n\n if (host.Player == null)\n return;\n\n host.Player.Activity.Timeout = host.ActivityTimeout;\n }\n bool setTemplate; // Issue #481 - FlyleafME override SetOverlay will not have a template to initialize properly *bool required if SetOverlay can be called multiple times and with different configs\n private static void OnOverlayTemplateChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)\n {\n if (isDesignMode)\n return;\n\n FlyleafHost host = d as FlyleafHost;\n if (host.Disposed)\n return;\n\n if (host.Overlay == null)\n {\n host.setTemplate= true;\n host.Overlay = new Window() { WindowStyle = WindowStyle.None, ResizeMode = ResizeMode.NoResize, AllowsTransparency = true };\n host.setTemplate= false;\n }\n else\n host.Overlay.Template = host.OverlayTemplate;\n }\n private static void OnOverlayChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)\n {\n FlyleafHost host = d as FlyleafHost;\n if (host.Disposed)\n return;\n\n if (!isDesignMode)\n host.SetOverlay();\n else\n {\n // XSurface.Wpf.Window (can this work on designer?\n }\n }\n private static void OnCornerRadiusChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)\n {\n if (isDesignMode)\n return;\n\n FlyleafHost host = d as FlyleafHost;\n if (host.Disposed)\n return;\n\n if (host.Surface == null)\n return;\n\n if (host.CornerRadius == host.zeroCornerRadius)\n host.Surface.Background = Brushes.Black;\n else\n {\n host.Surface.Background = Brushes.Transparent;\n host.SetCornerRadiusBorder();\n }\n\n if (host?.Player == null)\n return;\n\n host.Player.renderer.CornerRadius = (CornerRadius)e.NewValue;\n\n }\n private void SetCornerRadiusBorder()\n {\n // Required to handle mouse events as the window's background will be transparent\n // This does not set the background color we do that with the renderer (which causes some issues eg. when returning from fullscreen to normalscreen)\n Surface.Content = new Border()\n {\n Background = Brushes.Black, // TBR: for alpha channel -> Background == Brushes.Transparent || Background ==null ? new SolidColorBrush(Color.FromArgb(1,0,0,0)) : Background\n HorizontalAlignment = HorizontalAlignment.Stretch,\n VerticalAlignment = VerticalAlignment.Stretch,\n CornerRadius = CornerRadius,\n };\n }\n private static object OnContentChanging(DependencyObject d, object baseValue)\n {\n if (isDesignMode)\n return baseValue;\n\n FlyleafHost host = d as FlyleafHost;\n if (host.Disposed)\n return host.DetachedContent;\n\n if (baseValue != null && host.Overlay == null)\n host.Overlay = new Window() { WindowStyle = WindowStyle.None, ResizeMode = ResizeMode.NoResize, AllowsTransparency = true };\n\n if (host.Overlay != null)\n host.Overlay.Content = baseValue;\n\n return host.DetachedContent;\n }\n\n private void Host_Loaded(object sender, RoutedEventArgs e)\n {\n Window owner = Window.GetWindow(this);\n if (owner == null)\n return;\n\n var ownerHandle = new WindowInteropHelper(owner).EnsureHandle();\n\n // Owner Changed\n if (Owner != null)\n {\n if (!IsAttached || OwnerHandle == ownerHandle)\n return; // Check OwnerHandle changed (NOTE: Owner can be the same class/window but the handle can be different)\n\n Owner.SizeChanged -= Owner_SizeChanged;\n\n Surface.Hide();\n Overlay?.Hide();\n Detach();\n\n Owner = owner;\n OwnerHandle = ownerHandle;\n Surface.Title = Owner.Title;\n Surface.Icon = Owner.Icon;\n\n Owner.SizeChanged += Owner_SizeChanged;\n Attach();\n rectDetachedLast = Rect.Empty; // Attach will set it wrong first time\n Host_IsVisibleChanged(null, new());\n\n return;\n }\n\n Owner = owner;\n OwnerHandle = ownerHandle;\n HostDataContext = DataContext;\n\n SetSurface();\n\n Surface.Title = Owner.Title;\n Surface.Icon = Owner.Icon;\n\n Owner.SizeChanged += Owner_SizeChanged;\n DataContextChanged += Host_DataContextChanged;\n LayoutUpdated += Host_LayoutUpdated;\n IsVisibleChanged += Host_IsVisibleChanged;\n\n // TBR: We need to ensure that Surface/Overlay will be initial Show once to work properly (issue #415)\n if (IsAttached)\n {\n Attach();\n rectDetachedLast = Rect.Empty; // Attach will set it wrong first time\n Surface.Show();\n Overlay?.Show();\n Host_IsVisibleChanged(null, new());\n }\n else\n {\n Detach();\n\n if (PreferredLandscapeWidth == 0)\n PreferredLandscapeWidth = (int)Surface.Width;\n\n if (PreferredPortraitHeight == 0)\n PreferredPortraitHeight = (int)Surface.Height;\n\n UpdateCurRatio();\n Surface.Show();\n Overlay?.Show();\n }\n }\n\n // WindowChrome Issue #410: It will not properly move child windows when resized from top or left\n private void Owner_SizeChanged(object sender, SizeChangedEventArgs e)\n => rectInitLast = Rect.Empty;\n\n private void Host_DataContextChanged(object sender, DependencyPropertyChangedEventArgs e) =>\n // TBR\n // 1. this.DataContext: FlyleafHost's DataContext will not be affected (Inheritance)\n // 2. Overlay.DataContext: Overlay's DataContext will be FlyleafHost itself\n // 3. Overlay.DataContext.HostDataContext: FlyleafHost's DataContext includes HostDataContext to access FlyleafHost's DataContext\n // 4. In case of Stand Alone will let the user to decide\n\n HostDataContext = DataContext;\n private void Host_IsVisibleChanged(object sender, DependencyPropertyChangedEventArgs e)\n {\n if (!IsAttached)\n return;\n\n if (IsVisible)\n {\n Host_Loaded(null, null);\n Surface.Show();\n\n if (Overlay != null)\n {\n Overlay.Show();\n\n // It happens (eg. with MetroWindow) that overlay left will not be equal to surface left so we reset it by detach/attach the overlay to surface (https://github.com/SuRGeoNix/Flyleaf/issues/370)\n RECT surfRect = new();\n RECT overRect = new();\n GetWindowRect(SurfaceHandle, ref surfRect);\n GetWindowRect(OverlayHandle, ref overRect);\n\n if (surfRect.Left != overRect.Left)\n {\n // Detach Overlay\n SetParent(OverlayHandle, IntPtr.Zero);\n SetWindowLong(OverlayHandle, (int)WindowLongFlags.GWL_STYLE, NONE_STYLE);\n Overlay.Owner = null;\n\n SetWindowPos(OverlayHandle, IntPtr.Zero, 0, 0, (int)Surface.ActualWidth, (int)Surface.ActualHeight,\n (uint)(SetWindowPosFlags.SWP_NOZORDER | SetWindowPosFlags.SWP_NOACTIVATE));\n\n // Attache Overlay\n SetWindowLong(OverlayHandle, (int)WindowLongFlags.GWL_STYLE, NONE_STYLE | (nint)(WindowStyles.WS_CHILD | WindowStyles.WS_MAXIMIZE));\n Overlay.Owner = Surface;\n SetParent(OverlayHandle, SurfaceHandle);\n\n // Required to restore overlay\n Rect tt1 = new(0, 0, 0, 0);\n SetRect(ref tt1);\n }\n }\n\n // TBR: First time loaded in a tab control could cause UCEERR_RENDERTHREADFAILURE (can be avoided by hide/show again here)\n }\n else\n {\n Surface.Hide();\n Overlay?.Hide();\n }\n }\n private void Host_LayoutUpdated(object sender, EventArgs e)\n {\n // Finds Rect Intersect with FlyleafHost's parents and Clips Surface/Overlay (eg. within ScrollViewer)\n // TBR: Option not to clip rect or stop at first/second parent?\n // For performance should focus only on ScrollViewer if any and Owner Window (other sources that clip our host?)\n\n if (!IsVisible || !IsAttached || IsFullScreen || IsResizing)\n return;\n\n try\n {\n rectInit = rectIntersect = new(TransformToAncestor(Owner).Transform(zeroPoint), RenderSize);\n\n FrameworkElement parent = this;\n while ((parent = VisualTreeHelper.GetParent(parent) as FrameworkElement) != null)\n {\n if (parent.FlowDirection == FlowDirection.RightToLeft)\n {\n var location = parent.TransformToAncestor(Owner).Transform(zeroPoint);\n location.X -= parent.RenderSize.Width;\n rectIntersect.Intersect(new Rect(location, parent.RenderSize));\n }\n else\n rectIntersect.Intersect(new Rect(parent.TransformToAncestor(Owner).Transform(zeroPoint), parent.RenderSize));\n }\n\n if (rectInit != rectInitLast)\n {\n SetRect(ref rectInit);\n rectInitLast = rectInit;\n }\n\n if (rectIntersect == Rect.Empty)\n {\n if (rectIntersect == rectIntersectLast)\n return;\n\n rectIntersectLast = rectIntersect;\n SetVisibleRect(ref zeroRect);\n }\n else\n {\n rectIntersect.X -= rectInit.X;\n rectIntersect.Y -= rectInit.Y;\n\n if (rectIntersect == rectIntersectLast)\n return;\n\n rectIntersectLast = rectIntersect;\n\n SetVisibleRect(ref rectIntersect);\n }\n }\n catch (Exception ex)\n {\n // It has been noticed with NavigationService (The visual tree changes, visual root IsVisible is false but FlyleafHost is still visible)\n if (Logger.CanDebug) Log.Debug($\"Host_LayoutUpdated: {ex.Message}\");\n\n // TBR: (Currently handle on each time Visible=true) It's possible that the owner/parent has been changed (for some reason Host_Loaded will not be called) *probably when the Owner stays the same but the actual Handle changes\n //if (ex.Message == \"The specified Visual is not an ancestor of this Visual.\")\n //Host_Loaded(null, null);\n }\n }\n private void Player_Video_PropertyChanged(object sender, PropertyChangedEventArgs e)\n {\n if (KeepRatioOnResize && e.PropertyName == nameof(Player.Video.AspectRatio) && Player.Video.AspectRatio.Value > 0)\n UpdateCurRatio();\n }\n private void ReplicaPlayer_Video_PropertyChanged(object sender, PropertyChangedEventArgs e)\n {\n if (KeepRatioOnResize && e.PropertyName == nameof(ReplicaPlayer.Video.AspectRatio) && ReplicaPlayer.Video.AspectRatio.Value > 0)\n UpdateCurRatio();\n }\n #endregion\n\n #region Events Surface / Overlay\n private void Surface_KeyDown(object sender, KeyEventArgs e) { if (KeyBindings == AvailableWindows.Surface || KeyBindings == AvailableWindows.Both) e.Handled = Player.KeyDown(Player, e); }\n private void Overlay_KeyDown(object sender, KeyEventArgs e) { if (KeyBindings == AvailableWindows.Overlay || KeyBindings == AvailableWindows.Both) e.Handled = Player.KeyDown(Player, e); }\n\n private void Surface_KeyUp(object sender, KeyEventArgs e) { if (KeyBindings == AvailableWindows.Surface || KeyBindings == AvailableWindows.Both) e.Handled = Player.KeyUp(Player, e); }\n private void Overlay_KeyUp(object sender, KeyEventArgs e) { if (KeyBindings == AvailableWindows.Overlay || KeyBindings == AvailableWindows.Both) e.Handled = Player.KeyUp(Player, e); }\n\n private void Surface_Drop(object sender, DragEventArgs e)\n {\n IsSwappingStarted = false;\n Surface.ReleaseMouseCapture();\n FlyleafHostDropWrap hostWrap = (FlyleafHostDropWrap) e.Data.GetData(typeof(FlyleafHostDropWrap));\n\n // Swap FlyleafHosts\n if (hostWrap != null)\n {\n (hostWrap.FlyleafHost.Player, Player) = (Player, hostWrap.FlyleafHost.Player);\n Surface.Activate();\n return;\n }\n\n if (Player == null)\n return;\n\n // Invoke event first and see if it gets handled\n OnSurfaceDrop?.Invoke(this, e);\n\n if (!e.Handled)\n {\n // Player Open Text (TBR: Priority matters, eg. firefox will set both - cached file thumbnail of a video & the link of the video)\n if (e.Data.GetDataPresent(DataFormats.Text))\n {\n string text = e.Data.GetData(DataFormats.Text, false).ToString();\n if (text.Length > 0)\n Player.OpenAsync(text);\n }\n\n // Player Open File\n else if (e.Data.GetDataPresent(DataFormats.FileDrop))\n {\n string filename = ((string[])e.Data.GetData(DataFormats.FileDrop, false))[0];\n Player.OpenAsync(filename);\n }\n }\n\n Surface.Activate();\n }\n private void Overlay_Drop(object sender, DragEventArgs e)\n {\n IsSwappingStarted = false;\n Overlay.ReleaseMouseCapture();\n FlyleafHostDropWrap hostWrap = (FlyleafHostDropWrap) e.Data.GetData(typeof(FlyleafHostDropWrap));\n\n // Swap FlyleafHosts\n if (hostWrap != null)\n {\n (hostWrap.FlyleafHost.Player, Player) = (Player, hostWrap.FlyleafHost.Player);\n Overlay.Activate();\n return;\n }\n\n if (Player == null)\n return;\n\n // Invoke event first and see if it gets handled\n OnOverlayDrop?.Invoke(this, e);\n\n if (!e.Handled)\n {\n // Player Open Text\n if (e.Data.GetDataPresent(DataFormats.Text))\n {\n string text = e.Data.GetData(DataFormats.Text, false).ToString();\n if (text.Length > 0)\n Player.OpenAsync(text);\n }\n\n // Player Open File\n else if (e.Data.GetDataPresent(DataFormats.FileDrop))\n {\n string filename = ((string[])e.Data.GetData(DataFormats.FileDrop, false))[0];\n Player.OpenAsync(filename);\n }\n }\n\n Overlay.Activate();\n }\n private void Surface_DragEnter(object sender, DragEventArgs e) { if (Player != null) e.Effects = DragDropEffects.All; }\n private void Overlay_DragEnter(object sender, DragEventArgs e) { if (Player != null) e.Effects = DragDropEffects.All; }\n private void Surface_StateChanged(object sender, EventArgs e)\n {\n switch (Surface.WindowState)\n {\n case WindowState.Maximized:\n IsFullScreen = true;\n IsMinimized = false;\n Player?.Activity.RefreshFullActive();\n\n break;\n\n case WindowState.Normal:\n\n IsFullScreen = false;\n IsMinimized = false;\n Player?.Activity.RefreshFullActive();\n\n break;\n\n case WindowState.Minimized:\n\n IsMinimized = true;\n break;\n }\n }\n\n private void Surface_MouseLeftButtonDown(object sender, MouseButtonEventArgs e) => SO_MouseLeftButtonDown(e, Surface);\n private void Overlay_MouseLeftButtonDown(object sender, MouseButtonEventArgs e) => SO_MouseLeftButtonDown(e, Overlay);\n private void SO_MouseLeftButtonDown(MouseButtonEventArgs e, Window window)\n {\n AvailableWindows availWindow;\n AttachedDragMoveOptions availDragMove;\n AttachedDragMoveOptions availDragMoveOwner;\n\n if (window == Surface)\n {\n availWindow = AvailableWindows.Surface;\n availDragMove = AttachedDragMoveOptions.Surface;\n availDragMoveOwner = AttachedDragMoveOptions.SurfaceOwner;\n }\n else\n {\n availWindow = AvailableWindows.Overlay;\n availDragMove = AttachedDragMoveOptions.Overlay;\n availDragMoveOwner = AttachedDragMoveOptions.OverlayOwner;\n }\n\n if (BringToFrontOnClick) // Activate and Z-order top\n BringToFront();\n\n window.Focus();\n Player?.Activity.RefreshFullActive();\n\n mouseLeftDownPoint = e.GetPosition(window);\n IsSwappingStarted = false; // currently we don't care if it was cancelled (it can be stay true if we miss the mouse up) - QueryContinueDrag\n\n // Resize\n if (ResizingSide != 0)\n {\n IsResizing = true;\n\n if (IsAttached)\n {\n ownerZeroPointPos = Owner.PointToScreen(zeroPoint);\n GetWindowRect(SurfaceHandle, ref beforeResizeRect);\n LayoutUpdated -= Host_LayoutUpdated;\n ResetVisibleRect();\n }\n }\n\n // Swap\n else if ((SwapOnDrop == availWindow || SwapOnDrop == AvailableWindows.Both) &&\n (Keyboard.IsKeyDown(Key.LeftShift) || Keyboard.IsKeyDown(Key.RightShift)))\n {\n IsSwappingStarted = true;\n DragDrop.DoDragDrop(this, new FlyleafHostDropWrap() { FlyleafHost = this }, DragDropEffects.Move);\n\n return; // No Capture\n }\n\n // PanMove\n else if (Player != null &&\n (PanMoveOnCtrl == availWindow || PanMoveOnCtrl == AvailableWindows.Both) &&\n (Keyboard.IsKeyDown(Key.LeftCtrl) || Keyboard.IsKeyDown(Key.RightCtrl)))\n {\n panPrevX = Player.PanXOffset;\n panPrevY = Player.PanYOffset;\n IsPanMoving = true;\n }\n\n // DragMoveOwner\n else if (IsAttached && Owner != null &&\n (AttachedDragMove == availDragMoveOwner || AttachedDragMove == AttachedDragMoveOptions.BothOwner))\n IsDragMovingOwner = true;\n\n\n // DragMove (Attach|Detach)\n else if ((IsAttached && (AttachedDragMove == availDragMove || AttachedDragMove == AttachedDragMoveOptions.Both))\n || (!IsAttached && (DetachedDragMove == availWindow || DetachedDragMove == AvailableWindows.Both)))\n IsDragMoving = true;\n\n else\n return; // No Capture\n\n window.CaptureMouse();\n }\n\n private void Surface_MouseLeftButtonUp(object sender, MouseButtonEventArgs e) => Surface_ReleaseCapture();\n private void Overlay_MouseLeftButtonUp(object sender, MouseButtonEventArgs e) => Overlay_ReleaseCapture();\n private void Surface_LostMouseCapture(object sender, MouseEventArgs e) => Surface_ReleaseCapture();\n private void Overlay_LostMouseCapture(object sender, MouseEventArgs e) => Overlay_ReleaseCapture();\n private void Surface_ReleaseCapture()\n {\n if (!IsResizing && !IsPanMoving && !IsDragMoving && !IsDragMovingOwner)\n return;\n\n Surface.ReleaseMouseCapture();\n\n if (IsResizing)\n {\n ResizingSide = 0;\n Surface.Cursor = Cursors.Arrow;\n IsResizing = false;\n\n if (IsAttached)\n {\n GetWindowRect(SurfaceHandle, ref curRect);\n MarginTarget.Margin = new(MarginTarget.Margin.Left + (curRect.Left - beforeResizeRect.Left) / DpiX, MarginTarget.Margin.Top + (curRect.Top - beforeResizeRect.Top) / DpiY, MarginTarget.Margin.Right, MarginTarget.Margin.Bottom);\n Width = Surface.Width;\n Height = Surface.Height;\n Host_LayoutUpdated(null, null); // When attached to restore the clipped rect\n LayoutUpdated += Host_LayoutUpdated;\n }\n }\n else if (IsPanMoving)\n IsPanMoving = false;\n else if (IsDragMoving)\n IsDragMoving = false;\n else if (IsDragMovingOwner)\n IsDragMovingOwner = false;\n else\n return;\n }\n private void Overlay_ReleaseCapture()\n {\n if (!IsResizing && !IsPanMoving && !IsDragMoving && !IsDragMovingOwner)\n return;\n\n Overlay.ReleaseMouseCapture();\n\n if (IsResizing)\n {\n ResizingSide = 0;\n Overlay.Cursor = Cursors.Arrow;\n IsResizing = false;\n\n if (IsAttached)\n {\n GetWindowRect(SurfaceHandle, ref curRect);\n MarginTarget.Margin = new(MarginTarget.Margin.Left + (curRect.Left - beforeResizeRect.Left) / DpiX, MarginTarget.Margin.Top + (curRect.Top - beforeResizeRect.Top) / DpiY, MarginTarget.Margin.Right, MarginTarget.Margin.Bottom);\n Width = Surface.Width;\n Height = Surface.Height;\n Host_LayoutUpdated(null, null); // When attached to restore the clipped rect\n LayoutUpdated += Host_LayoutUpdated;\n }\n }\n else if (IsPanMoving)\n IsPanMoving = false;\n else if (IsDragMoving)\n IsDragMoving = false;\n else if (IsDragMovingOwner)\n IsDragMovingOwner = false;\n }\n\n private void Surface_MouseMove(object sender, MouseEventArgs e)\n {\n var cur = e.GetPosition(Surface);\n\n if (Player != null && cur != mouseMoveLastPoint)\n {\n Player.Activity.RefreshFullActive();\n mouseMoveLastPoint = cur;\n }\n\n // Resize Sides (CanResize + !MouseDown + !FullScreen)\n if (e.MouseDevice.LeftButton != MouseButtonState.Pressed)\n {\n if ( !IsFullScreen &&\n ((IsAttached && (AttachedResize == AvailableWindows.Surface || AttachedResize == AvailableWindows.Both)) ||\n (!IsAttached && (DetachedResize == AvailableWindows.Surface || DetachedResize == AvailableWindows.Both))))\n {\n ResizingSide = ResizeSides(Surface, cur, ResizeSensitivity, CornerRadius);\n }\n\n return;\n }\n\n SO_MouseLeftDownAndMove(cur);\n }\n private void Overlay_MouseMove(object sender, MouseEventArgs e)\n {\n var cur = e.GetPosition(Overlay);\n\n if (Player != null && cur != mouseMoveLastPoint)\n {\n Player.Activity.RefreshFullActive();\n mouseMoveLastPoint = cur;\n }\n\n // Resize Sides (CanResize + !MouseDown + !FullScreen)\n if (e.MouseDevice.LeftButton != MouseButtonState.Pressed)\n {\n if (!IsFullScreen && cur != zeroPoint &&\n ((IsAttached && (AttachedResize == AvailableWindows.Overlay || AttachedResize == AvailableWindows.Both)) ||\n (!IsAttached && (DetachedResize == AvailableWindows.Overlay || DetachedResize == AvailableWindows.Both))))\n {\n ResizingSide = ResizeSides(Overlay, cur, ResizeSensitivity, CornerRadius);\n }\n\n return;\n }\n\n SO_MouseLeftDownAndMove(cur);\n }\n private void SO_MouseLeftDownAndMove(Point cur)\n {\n if (IsSwappingStarted)\n return;\n\n // Player's Pan Move (Ctrl + Drag Move)\n if (IsPanMoving)\n {\n Player.PanXOffset = panPrevX + (int) (cur.X - mouseLeftDownPoint.X);\n Player.PanYOffset = panPrevY + (int) (cur.Y - mouseLeftDownPoint.Y);\n\n return;\n }\n\n if (IsFullScreen)\n return;\n\n // Resize (MouseDown + ResizeSide != 0)\n if (IsResizing)\n Resize(cur, ResizingSide, curResizeRatioIfEnabled);\n\n // Drag Move Self (Attached|Detached)\n else if (IsDragMoving)\n {\n if (IsAttached)\n {\n MarginTarget.Margin = new(\n MarginTarget.Margin.Left + cur.X - mouseLeftDownPoint.X,\n MarginTarget.Margin.Top + cur.Y - mouseLeftDownPoint.Y,\n MarginTarget.Margin.Right,\n MarginTarget.Margin.Bottom);\n }\n else\n {\n Surface.Left += cur.X - mouseLeftDownPoint.X;\n Surface.Top += cur.Y - mouseLeftDownPoint.Y;\n }\n }\n\n // Drag Move Owner (Attached)\n else if (IsDragMovingOwner)\n {\n if (Owner.Owner != null)\n {\n Owner.Owner.Left += cur.X - mouseLeftDownPoint.X;\n Owner.Owner.Top += cur.Y - mouseLeftDownPoint.Y;\n }\n else\n {\n Owner.Left += cur.X - mouseLeftDownPoint.X;\n Owner.Top += cur.Y - mouseLeftDownPoint.Y;\n }\n }\n }\n\n private void Surface_MouseLeave(object sender, MouseEventArgs e) { ResizingSide = 0; Surface.Cursor = Cursors.Arrow; }\n private void Overlay_MouseLeave(object sender, MouseEventArgs e) { ResizingSide = 0; Overlay.Cursor = Cursors.Arrow; }\n\n private void Surface_MouseDoubleClick(object sender, MouseButtonEventArgs e) { if (ToggleFullScreenOnDoubleClick == AvailableWindows.Surface || ToggleFullScreenOnDoubleClick == AvailableWindows.Both) { IsFullScreen = !IsFullScreen; e.Handled = true; } }\n private void Overlay_MouseDoubleClick(object sender, MouseButtonEventArgs e) { if (ToggleFullScreenOnDoubleClick == AvailableWindows.Overlay || ToggleFullScreenOnDoubleClick == AvailableWindows.Both) { IsFullScreen = !IsFullScreen; e.Handled = true; } }\n\n private void Surface_MouseWheel(object sender, MouseWheelEventArgs e)\n {\n if (Player == null || e.Delta == 0)\n return;\n\n if ((Keyboard.IsKeyDown(Key.LeftCtrl) || Keyboard.IsKeyDown(Key.RightCtrl)) &&\n (PanZoomOnCtrlWheel == AvailableWindows.Surface || PanZoomOnCtrlWheel == AvailableWindows.Both))\n {\n var cur = e.GetPosition(Surface);\n Point curDpi = new(cur.X * DpiX, cur.Y * DpiY);\n if (e.Delta > 0)\n Player.ZoomIn(curDpi);\n else\n Player.ZoomOut(curDpi);\n }\n else if ((Keyboard.IsKeyDown(Key.LeftShift) || Keyboard.IsKeyDown(Key.RightShift)) &&\n (PanRotateOnShiftWheel == AvailableWindows.Surface || PanZoomOnCtrlWheel == AvailableWindows.Both))\n {\n if (e.Delta > 0)\n Player.RotateRight();\n else\n Player.RotateLeft();\n }\n\n //else if (IsAttached) // TBR ScrollViewer\n //{\n // RaiseEvent(e);\n //}\n }\n private void Overlay_MouseWheel(object sender, MouseWheelEventArgs e)\n {\n if (Player == null || e.Delta == 0)\n return;\n\n if ((Keyboard.IsKeyDown(Key.LeftCtrl) || Keyboard.IsKeyDown(Key.RightCtrl)) &&\n (PanZoomOnCtrlWheel == AvailableWindows.Overlay || PanZoomOnCtrlWheel == AvailableWindows.Both))\n {\n var cur = e.GetPosition(Overlay);\n Point curDpi = new(cur.X * DpiX, cur.Y * DpiY);\n if (e.Delta > 0)\n Player.ZoomIn(curDpi);\n else\n Player.ZoomOut(curDpi);\n }\n else if ((Keyboard.IsKeyDown(Key.LeftShift) || Keyboard.IsKeyDown(Key.RightShift)) &&\n (PanRotateOnShiftWheel == AvailableWindows.Overlay || PanZoomOnCtrlWheel == AvailableWindows.Both))\n {\n if (e.Delta > 0)\n Player.RotateRight();\n else\n Player.RotateLeft();\n }\n }\n\n private void Surface_Closed(object sender, EventArgs e)\n {\n surfaceClosed = true;\n Dispose();\n }\n private void Surface_Closing(object sender, CancelEventArgs e) => surfaceClosing = true;\n private void Overlay_Closed(object sender, EventArgs e)\n {\n overlayClosed = true;\n if (!surfaceClosing)\n Surface?.Close();\n }\n private void OverlayStandAlone_Loaded(object sender, RoutedEventArgs e)\n {\n if (Overlay != null)\n return;\n\n if (standAloneOverlay.WindowStyle != WindowStyle.None || standAloneOverlay.AllowsTransparency == false)\n throw new Exception(\"Stand-alone FlyleafHost requires WindowStyle = WindowStyle.None and AllowsTransparency = true\");\n\n SetSurface();\n Overlay = standAloneOverlay;\n Overlay.IsVisibleChanged += OverlayStandAlone_IsVisibleChanged;\n Surface.ShowInTaskbar = false; Surface.ShowInTaskbar = true; // It will not be visible in taskbar if user clicks in another window when loading\n OverlayStandAlone_IsVisibleChanged(null, new());\n }\n private void OverlayStandAlone_IsVisibleChanged(object sender, DependencyPropertyChangedEventArgs e)\n {\n // Surface should be visible first (this happens only on initialization of standalone)\n\n if (Surface.IsVisible)\n return;\n\n if (Overlay.IsVisible)\n {\n Surface.Show();\n ShowWindow(OverlayHandle, (int)ShowWindowCommands.SW_SHOWMINIMIZED);\n ShowWindow(OverlayHandle, (int)ShowWindowCommands.SW_SHOWMAXIMIZED);\n }\n }\n\n public void Resize(Point p, int resizingSide, double ratio = 0.0)\n {\n double WindowWidth = Surface.ActualWidth;\n double WindowHeight = Surface.ActualHeight;\n double WindowLeft;\n double WindowTop;\n\n if (IsAttached) // NOTE: Window.Left will not be updated when the Owner moves, don't use it when attached\n {\n GetWindowRect(SurfaceHandle, ref curRect);\n WindowLeft = (curRect.Left - ownerZeroPointPos.X) / DpiX;\n WindowTop = (curRect.Top - ownerZeroPointPos.Y) / DpiY;\n }\n else\n {\n WindowLeft = Surface.Left;\n WindowTop = Surface.Top;\n }\n\n if (resizingSide == 2 || resizingSide == 3 || resizingSide == 6)\n {\n p.X += 5;\n\n WindowWidth = p.X > Surface.MinWidth ?\n p.X < Surface.MaxWidth ? p.X : Surface.MaxWidth :\n Surface.MinWidth;\n }\n else if (resizingSide == 1 || resizingSide == 4 || resizingSide == 5)\n {\n p.X -= 5;\n double temp = Surface.ActualWidth - p.X;\n if (temp > Surface.MinWidth && temp < Surface.MaxWidth)\n {\n WindowWidth = temp;\n WindowLeft = WindowLeft + p.X;\n }\n }\n\n if (resizingSide == 2 || resizingSide == 4 || resizingSide == 8)\n {\n p.Y += 5;\n\n if (p.Y > Surface.MinHeight)\n {\n WindowHeight = p.Y < Surface.MaxHeight ? p.Y : Surface.MaxHeight;\n }\n else\n return;\n }\n else if (resizingSide == 1 || resizingSide == 3 || resizingSide == 7)\n {\n if (ratio != 0 && resizingSide != 7)\n {\n double temp = WindowWidth / ratio;\n if (temp > Surface.MinHeight && temp < Surface.MaxHeight)\n WindowTop += Surface.ActualHeight - temp;\n else\n return;\n }\n else\n {\n p.Y -= 5;\n double temp = Surface.ActualHeight - p.Y;\n if (temp > Surface.MinHeight && temp < Surface.MaxHeight)\n {\n WindowHeight= temp;\n WindowTop += p.Y;\n }\n else\n return;\n }\n }\n\n if (ratio != 0)\n {\n if (resizingSide == 7 || resizingSide == 8)\n WindowWidth = WindowHeight * ratio;\n else\n WindowHeight = WindowWidth / ratio;\n }\n\n if (WindowWidth >= WindowHeight)\n PreferredLandscapeWidth = (int)WindowWidth;\n else\n PreferredPortraitHeight = (int)WindowHeight;\n\n WindowLeft *= DpiX;\n WindowTop *= DpiY;\n WindowWidth *= DpiX;\n WindowHeight*= DpiY;\n\n SetWindowPos(SurfaceHandle, IntPtr.Zero,\n (int)WindowLeft,\n (int)WindowTop,\n (int)Math.Ceiling(WindowWidth),\n (int)Math.Ceiling(WindowHeight),\n (uint)(SetWindowPosFlags.SWP_NOZORDER | SetWindowPosFlags.SWP_NOACTIVATE));\n }\n public static int ResizeSides(Window Window, Point p, int ResizeSensitivity, CornerRadius cornerRadius)\n {\n if (p.X <= ResizeSensitivity + (cornerRadius.TopLeft / 2) && p.Y <= ResizeSensitivity + (cornerRadius.TopLeft / 2))\n {\n Window.Cursor = Cursors.SizeNWSE;\n return 1;\n }\n else if (p.X + ResizeSensitivity + (cornerRadius.BottomRight / 2) >= Window.ActualWidth && p.Y + ResizeSensitivity + (cornerRadius.BottomRight / 2) >= Window.ActualHeight)\n {\n Window.Cursor = Cursors.SizeNWSE;\n return 2;\n }\n else if (p.X + ResizeSensitivity + (cornerRadius.TopRight / 2) >= Window.ActualWidth && p.Y <= ResizeSensitivity + (cornerRadius.TopRight / 2))\n {\n Window.Cursor = Cursors.SizeNESW;\n return 3;\n }\n else if (p.X <= ResizeSensitivity + (cornerRadius.BottomLeft / 2) && p.Y + ResizeSensitivity + (cornerRadius.BottomLeft / 2) >= Window.ActualHeight)\n {\n Window.Cursor = Cursors.SizeNESW;\n return 4;\n }\n else if (p.X <= ResizeSensitivity)\n {\n Window.Cursor = Cursors.SizeWE;\n return 5;\n }\n else if (p.X + ResizeSensitivity >= Window.ActualWidth)\n {\n Window.Cursor = Cursors.SizeWE;\n return 6;\n }\n else if (p.Y <= ResizeSensitivity)\n {\n Window.Cursor = Cursors.SizeNS;\n return 7;\n }\n else if (p.Y + ResizeSensitivity >= Window.ActualHeight)\n {\n Window.Cursor = Cursors.SizeNS;\n return 8;\n }\n else\n {\n Window.Cursor = Cursors.Arrow;\n return 0;\n }\n }\n #endregion\n\n #region Constructors\n static FlyleafHost()\n {\n DefaultStyleKeyProperty.OverrideMetadata(typeof(FlyleafHost), new FrameworkPropertyMetadata(typeof(FlyleafHost)));\n ContentProperty.OverrideMetadata(typeof(FlyleafHost), new FrameworkPropertyMetadata(null, new CoerceValueCallback(OnContentChanging)));\n }\n public FlyleafHost()\n {\n UniqueId = idGenerator++;\n isDesignMode = DesignerProperties.GetIsInDesignMode(this);\n if (isDesignMode)\n return;\n\n MarginTarget= this;\n Log = new LogHandler((\"[#\" + UniqueId + \"]\").PadRight(8, ' ') + $\" [FlyleafHost NP] \");\n Loaded += Host_Loaded;\n }\n public FlyleafHost(Window standAloneOverlay)\n {\n UniqueId = idGenerator++;\n Log = new LogHandler((\"[#\" + UniqueId + \"]\").PadRight(8, ' ') + $\" [FlyleafHost NP] \");\n\n IsStandAlone = true;\n IsAttached = false;\n\n this.standAloneOverlay = standAloneOverlay;\n standAloneOverlay.Loaded += OverlayStandAlone_Loaded;\n if (standAloneOverlay.IsLoaded)\n OverlayStandAlone_Loaded(null, null);\n }\n #endregion\n\n #region Methods\n public virtual void SetReplicaPlayer(Player oldPlayer)\n {\n if (oldPlayer != null)\n {\n oldPlayer.renderer.SetChildHandle(IntPtr.Zero);\n oldPlayer.Video.PropertyChanged -= ReplicaPlayer_Video_PropertyChanged;\n }\n\n if (ReplicaPlayer == null)\n return;\n\n if (Surface != null)\n ReplicaPlayer.renderer.SetChildHandle(SurfaceHandle);\n\n ReplicaPlayer.Video.PropertyChanged += ReplicaPlayer_Video_PropertyChanged;\n }\n public virtual void SetPlayer(Player oldPlayer)\n {\n // De-assign old Player's Handle/FlyleafHost\n if (oldPlayer != null)\n {\n Log.Debug($\"De-assign Player #{oldPlayer.PlayerId}\");\n\n oldPlayer.Video.PropertyChanged -= Player_Video_PropertyChanged;\n oldPlayer.VideoDecoder.DestroySwapChain();\n oldPlayer.Host = null;\n }\n\n if (Player == null)\n return;\n\n Log.Prefix = (\"[#\" + UniqueId + \"]\").PadRight(8, ' ') + $\" [FlyleafHost #{Player.PlayerId}] \";\n\n // De-assign new Player's Handle/FlyleafHost\n Player.Host?.Player_Disposed();\n\n if (Player == null) // We might just de-assign our Player\n return;\n\n // Assign new Player's (Handle/FlyleafHost)\n Log.Debug($\"Assign Player #{Player.PlayerId}\");\n\n Player.Host = this;\n Player.Activity.Timeout = ActivityTimeout;\n if (Player.renderer != null) // TBR: using as AudioOnly with a Control*\n Player.renderer.CornerRadius = IsFullScreen ? zeroCornerRadius : CornerRadius;\n\n if (Surface != null)\n {\n if (CornerRadius == zeroCornerRadius)\n Surface.Background = new SolidColorBrush(Player.Config.Video.BackgroundColor);\n //else // TBR: this border probably not required? only when we don't have a renderer?\n //((Border)Surface.Content).Background = new SolidColorBrush(Player.Config.Video.BackgroundColor);\n\n Player.VideoDecoder.CreateSwapChain(SurfaceHandle);\n }\n\n Player.Video.PropertyChanged += Player_Video_PropertyChanged;\n UpdateCurRatio();\n }\n public virtual void SetSurface(bool fromSetOverlay = false)\n {\n if (Surface != null)\n return;\n\n // Required for some reason (WindowStyle.None will not be updated with our style)\n Surface = new();\n Surface.Name = $\"Surface_{UniqueId}\";\n Surface.Width = Surface.Height = 1; // Will be set on loaded\n Surface.WindowStyle = WindowStyle.None;\n Surface.ResizeMode = ResizeMode.NoResize;\n Surface.ShowInTaskbar = false;\n\n // CornerRadius must be set initially to AllowsTransparency!\n if (CornerRadius == zeroCornerRadius)\n Surface.Background = Player != null ? new SolidColorBrush(Player.Config.Video.BackgroundColor) : Brushes.Black;\n else\n {\n Surface.AllowsTransparency = true;\n Surface.Background = Brushes.Transparent;\n SetCornerRadiusBorder();\n }\n\n // When using ItemsControl with ObservableCollection to fill DataTemplates with FlyleafHost EnsureHandle will call Host_loaded\n if (IsAttached) Loaded -= Host_Loaded;\n SurfaceHandle = new WindowInteropHelper(Surface).EnsureHandle();\n if (IsAttached) Loaded += Host_Loaded;\n\n if (IsAttached)\n {\n SetWindowLong(SurfaceHandle, (int)WindowLongFlags.GWL_STYLE, NONE_STYLE | (nint)WindowStyles.WS_CHILD);\n SetWindowLong(SurfaceHandle, (int)WindowLongFlags.GWL_EXSTYLE, (nint)WindowStylesEx.WS_EX_LAYERED);\n }\n else // Detached || StandAlone\n {\n SetWindowLong(SurfaceHandle, (int)WindowLongFlags.GWL_STYLE, NONE_STYLE);\n if (DetachedShowInTaskbar || IsStandAlone)\n SetWindowLong(SurfaceHandle, (int)WindowLongFlags.GWL_EXSTYLE, (nint)(WindowStylesEx.WS_EX_APPWINDOW | WindowStylesEx.WS_EX_LAYERED));\n else\n SetWindowLong(SurfaceHandle, (int)WindowLongFlags.GWL_EXSTYLE, (nint)WindowStylesEx.WS_EX_LAYERED);\n }\n\n if (Player != null)\n Player.VideoDecoder.CreateSwapChain(SurfaceHandle);\n\n if (ReplicaPlayer != null)\n ReplicaPlayer.renderer.SetChildHandle(SurfaceHandle);\n\n Surface.Closed += Surface_Closed;\n Surface.Closing += Surface_Closing;\n Surface.KeyDown += Surface_KeyDown;\n Surface.KeyUp += Surface_KeyUp;\n Surface.Drop += Surface_Drop;\n Surface.DragEnter += Surface_DragEnter;\n Surface.StateChanged+= Surface_StateChanged;\n Surface.SizeChanged += SetRectOverlay;\n\n SetMouseSurface();\n\n Surface.AllowDrop =\n OpenOnDrop == AvailableWindows.Surface || OpenOnDrop == AvailableWindows.Both ||\n SwapOnDrop == AvailableWindows.Surface || SwapOnDrop == AvailableWindows.Both;\n\n if (IsAttached && IsLoaded && Owner == null && !fromSetOverlay)\n Host_Loaded(null, null);\n\n SurfaceCreated?.Invoke(this, new());\n }\n public virtual void SetOverlay()\n {\n if (Overlay == null)\n return;\n\n SetSurface(true);\n\n if (IsAttached) Loaded -= Host_Loaded;\n OverlayHandle = new WindowInteropHelper(Overlay).EnsureHandle();\n if (IsAttached) Loaded += Host_Loaded;\n\n if (IsStandAlone)\n {\n if (PreferredLandscapeWidth == 0)\n PreferredLandscapeWidth = (int)Overlay.Width;\n\n if (PreferredPortraitHeight == 0)\n PreferredPortraitHeight = (int)Overlay.Height;\n\n SetWindowPos(SurfaceHandle, IntPtr.Zero, (int)Math.Round(Overlay.Left * DpiX), (int)Math.Round(Overlay.Top * DpiY), (int)Math.Round(Overlay.ActualWidth * DpiX), (int)Math.Round(Overlay.ActualHeight * DpiY),\n (uint)(SetWindowPosFlags.SWP_NOZORDER | SetWindowPosFlags.SWP_NOACTIVATE));\n\n Surface.Title = Overlay.Title;\n Surface.Icon = Overlay.Icon;\n Surface.MinHeight = Overlay.MinHeight;\n Surface.MaxHeight = Overlay.MaxHeight;\n Surface.MinWidth = Overlay.MinWidth;\n Surface.MaxWidth = Overlay.MaxWidth;\n Surface.Topmost = DetachedTopMost;\n }\n else\n {\n Overlay.Resources = Resources;\n Overlay.DataContext = this; // TBR: or this.DataContext?\n }\n\n SetWindowPos(OverlayHandle, IntPtr.Zero, 0, 0, (int)Surface.ActualWidth, (int)Surface.ActualHeight,\n (uint)(SetWindowPosFlags.SWP_NOZORDER | SetWindowPosFlags.SWP_NOACTIVATE));\n\n Overlay.Name = $\"Overlay_{UniqueId}\";\n Overlay.Background = Brushes.Transparent;\n Overlay.ShowInTaskbar = false;\n Overlay.Owner = Surface;\n SetParent(OverlayHandle, SurfaceHandle);\n SetWindowLong(OverlayHandle, (int)WindowLongFlags.GWL_STYLE, NONE_STYLE | (nint)(WindowStyles.WS_CHILD | WindowStyles.WS_MAXIMIZE)); // TBR: WS_MAXIMIZE required? (possible better for DWM on fullscreen?)\n\n Overlay.KeyUp += Overlay_KeyUp;\n Overlay.KeyDown += Overlay_KeyDown;\n Overlay.Closed += Overlay_Closed;\n Overlay.Drop += Overlay_Drop;\n Overlay.DragEnter += Overlay_DragEnter;\n\n SetMouseOverlay();\n\n // Owner will close the overlay\n Overlay.KeyDown += (o, e) => { if (e.Key == Key.System && e.SystemKey == Key.F4) Surface?.Focus(); };\n\n Overlay.AllowDrop =\n OpenOnDrop == AvailableWindows.Overlay || OpenOnDrop == AvailableWindows.Both ||\n SwapOnDrop == AvailableWindows.Overlay || SwapOnDrop == AvailableWindows.Both;\n\n if (setTemplate)\n Overlay.Template = OverlayTemplate;\n\n if (Surface.IsVisible)\n Overlay.Show();\n else if (!IsStandAlone && !Overlay.IsVisible)\n {\n Overlay.Show();\n Overlay.Hide();\n }\n\n if (IsAttached && IsLoaded && Owner == null)\n Host_Loaded(null, null);\n\n OverlayCreated?.Invoke(this, new());\n }\n private void SetMouseSurface()\n {\n if (Surface == null)\n return;\n\n if ((MouseBindings == AvailableWindows.Surface || MouseBindings == AvailableWindows.Both) && !isMouseBindingsSubscribedSurface)\n {\n Surface.LostMouseCapture += Surface_LostMouseCapture;\n Surface.MouseLeftButtonDown += Surface_MouseLeftButtonDown;\n Surface.MouseLeftButtonUp += Surface_MouseLeftButtonUp;\n if (PanZoomOnCtrlWheel != AvailableWindows.None ||\n PanRotateOnShiftWheel != AvailableWindows.None)\n {\n Surface.MouseWheel += Surface_MouseWheel;\n }\n Surface.MouseMove += Surface_MouseMove;\n Surface.MouseLeave += Surface_MouseLeave;\n if (ToggleFullScreenOnDoubleClick != AvailableWindows.None)\n {\n Surface.MouseDoubleClick += Surface_MouseDoubleClick;\n }\n isMouseBindingsSubscribedSurface = true;\n }\n else if (isMouseBindingsSubscribedSurface)\n {\n Surface.LostMouseCapture -= Surface_LostMouseCapture;\n Surface.MouseLeftButtonDown -= Surface_MouseLeftButtonDown;\n Surface.MouseLeftButtonUp -= Surface_MouseLeftButtonUp;\n if (PanZoomOnCtrlWheel != AvailableWindows.None ||\n PanRotateOnShiftWheel != AvailableWindows.None)\n {\n Surface.MouseWheel -= Surface_MouseWheel;\n }\n Surface.MouseMove -= Surface_MouseMove;\n Surface.MouseLeave -= Surface_MouseLeave;\n if (ToggleFullScreenOnDoubleClick != AvailableWindows.None)\n {\n Surface.MouseDoubleClick -= Surface_MouseDoubleClick;\n }\n isMouseBindingsSubscribedSurface = false;\n }\n }\n private void SetMouseOverlay()\n {\n if (Overlay == null)\n return;\n\n if ((MouseBindings == AvailableWindows.Overlay || MouseBindings == AvailableWindows.Both) && !isMouseBindingsSubscribedOverlay)\n {\n Overlay.LostMouseCapture += Overlay_LostMouseCapture;\n Overlay.MouseLeftButtonDown += Overlay_MouseLeftButtonDown;\n Overlay.MouseLeftButtonUp += Overlay_MouseLeftButtonUp;\n if (PanZoomOnCtrlWheel != AvailableWindows.None ||\n PanRotateOnShiftWheel != AvailableWindows.None)\n {\n Overlay.MouseWheel += Overlay_MouseWheel;\n }\n Overlay.MouseMove += Overlay_MouseMove;\n Overlay.MouseLeave += Overlay_MouseLeave;\n if (ToggleFullScreenOnDoubleClick != AvailableWindows.None)\n {\n Overlay.MouseDoubleClick += Overlay_MouseDoubleClick;\n }\n isMouseBindingsSubscribedOverlay = true;\n }\n else if (isMouseBindingsSubscribedOverlay)\n {\n Overlay.LostMouseCapture -= Overlay_LostMouseCapture;\n Overlay.MouseLeftButtonDown -= Overlay_MouseLeftButtonDown;\n Overlay.MouseLeftButtonUp -= Overlay_MouseLeftButtonUp;\n if (PanZoomOnCtrlWheel != AvailableWindows.None ||\n PanRotateOnShiftWheel != AvailableWindows.None)\n {\n Overlay.MouseWheel -= Overlay_MouseWheel;\n }\n Overlay.MouseMove -= Overlay_MouseMove;\n Overlay.MouseLeave -= Overlay_MouseLeave;\n if (ToggleFullScreenOnDoubleClick != AvailableWindows.None)\n {\n Overlay.MouseDoubleClick -= Overlay_MouseDoubleClick;\n }\n\n isMouseBindingsSubscribedOverlay = false;\n }\n }\n\n public virtual void Attach(bool ignoreRestoreRect = false)\n {\n Window wasFocus = Overlay != null && Overlay.IsKeyboardFocusWithin ? Overlay : Surface;\n\n if (IsFullScreen)\n {\n IsFullScreen = false;\n return;\n }\n if (!ignoreRestoreRect)\n rectDetachedLast= new(Surface.Left, Surface.Top, Surface.Width, Surface.Height);\n\n Surface.Topmost = false;\n Surface.MinWidth = MinWidth;\n Surface.MinHeight = MinHeight;\n Surface.MaxWidth = MaxWidth;\n Surface.MaxHeight = MaxHeight;\n\n SetWindowLong(SurfaceHandle, (int)WindowLongFlags.GWL_STYLE, NONE_STYLE | (nint)WindowStyles.WS_CHILD);\n Surface.Owner = Owner;\n SetParent(SurfaceHandle, OwnerHandle);\n\n rectInitLast = rectIntersectLast = rectRandom;\n Host_LayoutUpdated(null, null);\n Owner.Activate();\n wasFocus.Focus();\n }\n public virtual void Detach()\n {\n if (IsFullScreen)\n IsFullScreen = false;\n\n Surface.MinWidth = DetachedMinWidth;\n Surface.MinHeight = DetachedMinHeight;\n Surface.MaxWidth = DetachedMaxWidth;\n Surface.MaxHeight = DetachedMaxHeight;\n\n // Calculate Size\n var newSize = DetachedRememberSize && rectDetachedLast != Rect.Empty\n ? new Size(rectDetachedLast.Width, rectDetachedLast.Height)\n : DetachedFixedSize;\n\n // Calculate Position\n Point newPos;\n if (DetachedRememberPosition && rectDetachedLast != Rect.Empty)\n newPos = new Point(rectDetachedLast.X, rectDetachedLast.Y);\n else\n {\n var screen = System.Windows.Forms.Screen.FromPoint(new System.Drawing.Point((int)Surface.Top, (int)Surface.Left)).Bounds;\n\n // Drop Dpi to work with screen (no Dpi)\n newSize.Width *= DpiX;\n newSize.Height *= DpiY;\n\n switch (DetachedPosition)\n {\n case DetachedPositionOptions.TopLeft:\n newPos = new Point(screen.Left, screen.Top);\n break;\n case DetachedPositionOptions.TopCenter:\n newPos = new Point(screen.Left + (screen.Width / 2) - (newSize.Width / 2), screen.Top);\n break;\n\n case DetachedPositionOptions.TopRight:\n newPos = new Point(screen.Left + screen.Width - newSize.Width, screen.Top);\n break;\n\n case DetachedPositionOptions.CenterLeft:\n newPos = new Point(screen.Left, screen.Top + (screen.Height / 2) - (newSize.Height / 2));\n break;\n\n case DetachedPositionOptions.CenterCenter:\n newPos = new Point(screen.Left + (screen.Width / 2) - (newSize.Width / 2), screen.Top + (screen.Height / 2) - (newSize.Height / 2));\n break;\n\n case DetachedPositionOptions.CenterRight:\n newPos = new Point(screen.Left + screen.Width - newSize.Width, screen.Top + (screen.Height / 2) - (newSize.Height / 2));\n break;\n\n case DetachedPositionOptions.BottomLeft:\n newPos = new Point(screen.Left, screen.Top + screen.Height - newSize.Height);\n break;\n\n case DetachedPositionOptions.BottomCenter:\n newPos = new Point(screen.Left + (screen.Width / 2) - (newSize.Width / 2), screen.Top + screen.Height - newSize.Height);\n break;\n\n case DetachedPositionOptions.BottomRight:\n newPos = new Point(screen.Left + screen.Width - newSize.Width, screen.Top + screen.Height - newSize.Height);\n break;\n\n case DetachedPositionOptions.Custom:\n newPos = DetachedFixedPosition;\n break;\n\n default:\n newPos = new(); //satisfy the compiler\n break;\n }\n\n // SetRect will drop DPI so we add it\n newPos.X /= DpiX;\n newPos.Y /= DpiY;\n\n newPos.X += DetachedPositionMargin.Left - DetachedPositionMargin.Right;\n newPos.Y += DetachedPositionMargin.Top - DetachedPositionMargin.Bottom;\n\n // Restore DPI\n newSize.Width /= DpiX;\n newSize.Height /= DpiY;\n }\n\n Rect final = new(newPos.X, newPos.Y, newSize.Width, newSize.Height);\n\n // Detach (Parent=Null, Owner=Null ?, ShowInTaskBar?, TopMost?)\n SetParent(SurfaceHandle, IntPtr.Zero);\n SetWindowLong(SurfaceHandle, (int)WindowLongFlags.GWL_STYLE, NONE_STYLE); // TBR (also in Attach/FullScren): Needs to be after SetParent. when detached and trying to close the owner will take two clicks (like mouse capture without release) //SetWindowLong(SurfaceHandle, (int)WindowLongFlags.GWL_STYLE, GetWindowLong(SurfaceHandle, (int)WindowLongFlags.GWL_STYLE) & ~(nint)WindowStyles.WS_CHILD);\n Surface.Owner = DetachedNoOwner ? null : Owner;\n Surface.Topmost = DetachedTopMost;\n\n SetRect(ref final);\n ResetVisibleRect();\n\n if (Surface.IsVisible) // Initially detached will not be visible yet and activate not required (in case of multiple)\n Surface.Activate();\n }\n\n public void RefreshNormalFullScreen()\n {\n if (IsFullScreen)\n {\n if (IsAttached)\n {\n // When we set the parent to null we don't really know in which left/top will be transfered and maximized into random screen\n GetWindowRect(SurfaceHandle, ref curRect);\n\n ResetVisibleRect();\n SetParent(SurfaceHandle, IntPtr.Zero);\n SetWindowLong(SurfaceHandle, (int)WindowLongFlags.GWL_STYLE, NONE_STYLE); // TBR (also in Attach/FullScren): Needs to be after SetParent. when detached and trying to close the owner will take two clicks (like mouse capture without release) //SetWindowLong(SurfaceHandle, (int)WindowLongFlags.GWL_STYLE, GetWindowLong(SurfaceHandle, (int)WindowLongFlags.GWL_STYLE) & ~(nint)WindowStyles.WS_CHILD);\n Surface.Owner = DetachedNoOwner ? null : Owner;\n Surface.Topmost = DetachedTopMost;\n\n SetWindowPos(SurfaceHandle, IntPtr.Zero, curRect.Left, curRect.Top, 0, 0, (uint)(SetWindowPosFlags.SWP_NOZORDER | SetWindowPosFlags.SWP_NOACTIVATE | SetWindowPosFlags.SWP_NOSIZE));\n }\n\n if (Player != null)\n Player.renderer.CornerRadius = zeroCornerRadius;\n\n if (CornerRadius != zeroCornerRadius)\n ((Border)Surface.Content).CornerRadius = zeroCornerRadius;\n\n Surface.WindowState = WindowState.Maximized;\n\n // If it was above the borders and double click (mouse didn't move to refresh)\n Surface.Cursor = Cursors.Arrow;\n if (Overlay != null)\n Overlay.Cursor = Cursors.Arrow;\n }\n else\n {\n if (IsStandAlone)\n Surface.WindowState = WindowState.Normal;\n\n if (IsAttached)\n {\n Attach(true);\n InvalidateVisual(); // To force the FlyleafSharedOverlay (if any) redraw on-top\n }\n else if (Surface.Topmost || DetachedTopMost) // Bring to front (in Desktop, above windows bar)\n {\n Surface.Topmost = false;\n Surface.Topmost = true;\n }\n\n UpdateCurRatio();\n\n // TBR: CornerRadius background has issue it's like a mask color?\n if (Player != null)\n Player.renderer.CornerRadius = CornerRadius;\n\n if (CornerRadius != zeroCornerRadius)\n ((Border)Surface.Content).CornerRadius = CornerRadius;\n\n if (!IsStandAlone) //when play with alpha video and not standalone, we need to set window state to normal last, otherwise it will be lost the background\n Surface.WindowState = WindowState.Normal;\n }\n }\n public void SetRect(ref Rect rect)\n => SetWindowPos(SurfaceHandle, IntPtr.Zero, (int)Math.Round(rect.X * DpiX), (int)Math.Round(rect.Y * DpiY), (int)Math.Round(rect.Width * DpiX), (int)Math.Round(rect.Height * DpiY),\n (uint)(SetWindowPosFlags.SWP_NOZORDER | SetWindowPosFlags.SWP_NOACTIVATE));\n\n private void SetRectOverlay(object sender, SizeChangedEventArgs e)\n {\n if (Overlay != null)\n SetWindowPos(OverlayHandle, IntPtr.Zero, 0, 0, (int)Math.Round(Surface.ActualWidth * DpiX), (int)Math.Round(Surface.ActualHeight * DpiY),\n (uint)(SetWindowPosFlags.SWP_NOZORDER | SetWindowPosFlags.SWP_NOMOVE | SetWindowPosFlags.SWP_NOACTIVATE));\n }\n\n public void ResetVisibleRect()\n {\n SetWindowRgn(SurfaceHandle, IntPtr.Zero, true);\n if (Overlay != null)\n SetWindowRgn(OverlayHandle, IntPtr.Zero, true);\n }\n public void SetVisibleRect(ref Rect rect)\n {\n SetWindowRgn(SurfaceHandle, CreateRectRgn((int)Math.Round(rect.X * DpiX), (int)Math.Round(rect.Y * DpiY), (int)Math.Round(rect.Right * DpiX), (int)Math.Round(rect.Bottom * DpiY)), true);\n if (Overlay != null)\n SetWindowRgn(OverlayHandle, CreateRectRgn((int)Math.Round(rect.X * DpiX), (int)Math.Round(rect.Y * DpiY), (int)Math.Round(rect.Right * DpiX), (int)Math.Round(rect.Bottom * DpiY)), true);\n }\n\n /// \n /// Disposes the Surface and Overlay Windows and de-assigns the Player\n /// \n public void Dispose()\n {\n lock (this)\n {\n if (Disposed)\n return;\n\n // Disposes SwapChain Only\n Player = null;\n ReplicaPlayer = null;\n Disposed = true;\n\n DataContextChanged -= Host_DataContextChanged;\n LayoutUpdated -= Host_LayoutUpdated;\n IsVisibleChanged -= Host_IsVisibleChanged;\n Loaded \t\t\t-= Host_Loaded;\n\n if (Overlay != null)\n {\n if (isMouseBindingsSubscribedOverlay)\n SetMouseOverlay();\n\n Overlay.IsVisibleChanged-= OverlayStandAlone_IsVisibleChanged;\n Overlay.KeyUp -= Overlay_KeyUp;\n Overlay.KeyDown -= Overlay_KeyDown;\n Overlay.Closed -= Overlay_Closed;\n Overlay.Drop -= Overlay_Drop;\n Overlay.DragEnter -= Overlay_DragEnter;\n }\n\n if (Surface != null)\n {\n if (isMouseBindingsSubscribedSurface)\n SetMouseSurface();\n\n Surface.Closed -= Surface_Closed;\n Surface.Closing -= Surface_Closing;\n Surface.KeyDown -= Surface_KeyDown;\n Surface.KeyUp -= Surface_KeyUp;\n Surface.Drop -= Surface_Drop;\n Surface.DragEnter -= Surface_DragEnter;\n Surface.StateChanged-= Surface_StateChanged;\n Surface.SizeChanged -= SetRectOverlay;\n\n // If not shown yet app will not close properly\n if (!surfaceClosed)\n {\n Surface.Owner = null;\n SetParent(SurfaceHandle, IntPtr.Zero);\n Surface.Width = Surface.Height = 1;\n Surface.Show();\n if (!overlayClosed)\n Overlay?.Show();\n Surface.Close();\n }\n }\n\n if (Owner != null)\n Owner.SizeChanged -= Owner_SizeChanged;\n\n Surface = null;\n Overlay = null;\n Owner = null;\n\n SurfaceHandle = IntPtr.Zero;\n OverlayHandle = IntPtr.Zero;\n OwnerHandle = IntPtr.Zero;\n\n Log.Debug(\"Disposed\");\n }\n }\n\n public bool Player_CanHideCursor() => (Surface != null && Surface.IsMouseOver) ||\n (Overlay != null && Overlay.IsActive);\n public bool Player_GetFullScreen() => IsFullScreen;\n public void Player_SetFullScreen(bool value) => IsFullScreen = value;\n public void Player_Disposed() => UIInvokeIfRequired(() => Player = null);\n #endregion\n}\n\npublic enum AvailableWindows\n{\n None, Surface, Overlay, Both\n}\n\npublic enum AttachedDragMoveOptions\n{\n None, Surface, Overlay, Both, SurfaceOwner, OverlayOwner, BothOwner\n}\n\npublic enum DetachedPositionOptions\n{\n Custom, TopLeft, TopCenter, TopRight, CenterLeft, CenterCenter, CenterRight, BottomLeft, BottomCenter, BottomRight\n}\n"], ["/LLPlayer/LLPlayer/Controls/SelectableSubtitleText.xaml.cs", "using System.Diagnostics;\nusing System.Text.RegularExpressions;\nusing System.Windows;\nusing System.Windows.Controls;\nusing System.Windows.Data;\nusing System.Windows.Input;\nusing System.Windows.Media;\nusing FlyleafLib;\nusing LLPlayer.Extensions;\nusing NMeCab.Specialized;\n\nnamespace LLPlayer.Controls;\n\npublic partial class SelectableSubtitleText : UserControl\n{\n private readonly Binding _bindFontSize;\n private readonly Binding _bindFontWeight;\n private readonly Binding _bindFontFamily;\n private readonly Binding _bindFontStyle;\n private readonly Binding _bindFill;\n private readonly Binding _bindStroke;\n private readonly Binding _bindStrokeThicknessInitial;\n\n private OutlinedTextBlock? _wordStart;\n\n public SelectableSubtitleText()\n {\n InitializeComponent();\n\n // DataContext is set in WrapPanel, so there is no need to use ElementName.\n //_bindFontSize = new Binding(nameof(FontSize))\n //{\n // //ElementName = nameof(Root),\n // Mode = BindingMode.OneWay\n //};\n _bindFontSize = new Binding(nameof(FontSize));\n _bindFontWeight = new Binding(nameof(FontWeight));\n _bindFontFamily = new Binding(nameof(FontFamily));\n _bindFontStyle = new Binding(nameof(FontStyle));\n _bindFill = new Binding(nameof(Fill));\n _bindStroke = new Binding(nameof(Stroke));\n _bindStrokeThicknessInitial = new Binding(nameof(StrokeThicknessInitial));\n }\n\n public static readonly RoutedEvent WordClickedEvent =\n EventManager.RegisterRoutedEvent(nameof(WordClicked), RoutingStrategy.Bubble, typeof(WordClickedEventHandler), typeof(SelectableSubtitleText));\n\n public event WordClickedEventHandler WordClicked\n {\n add => AddHandler(WordClickedEvent, value);\n remove => RemoveHandler(WordClickedEvent, value);\n }\n\n public event EventHandler? WordClickedDown;\n\n public static readonly DependencyProperty TextProperty =\n DependencyProperty.Register(nameof(Text), typeof(string), typeof(SelectableSubtitleText), new FrameworkPropertyMetadata(string.Empty, OnTextChanged));\n\n public string Text\n {\n get => (string)GetValue(TextProperty);\n set => SetValue(TextProperty, value);\n }\n\n private string _textFix = string.Empty;\n\n public static readonly DependencyProperty IsTranslatedProperty =\n DependencyProperty.Register(nameof(IsTranslated), typeof(bool), typeof(SelectableSubtitleText), new FrameworkPropertyMetadata(false));\n\n public bool IsTranslated\n {\n get => (bool)GetValue(IsTranslatedProperty);\n set => SetValue(IsTranslatedProperty, value);\n }\n\n public static readonly DependencyProperty TextLanguageProperty =\n DependencyProperty.Register(nameof(TextLanguage), typeof(Language), typeof(SelectableSubtitleText), new FrameworkPropertyMetadata(null, OnTextLanguageChanged));\n\n public Language? TextLanguage\n {\n get => (Language)GetValue(TextLanguageProperty);\n set => SetValue(TextLanguageProperty, value);\n }\n\n public static readonly DependencyProperty SubIndexProperty =\n DependencyProperty.Register(nameof(SubIndex), typeof(int), typeof(SelectableSubtitleText), new FrameworkPropertyMetadata(0));\n\n public int SubIndex\n {\n get => (int)GetValue(SubIndexProperty);\n set => SetValue(SubIndexProperty, value);\n }\n\n public static readonly DependencyProperty FillProperty =\n OutlinedTextBlock.FillProperty.AddOwner(typeof(SelectableSubtitleText));\n\n public Brush Fill\n {\n get => (Brush)GetValue(FillProperty);\n set => SetValue(FillProperty, value);\n }\n\n public static readonly DependencyProperty StrokeProperty =\n OutlinedTextBlock.StrokeProperty.AddOwner(typeof(SelectableSubtitleText));\n\n public Brush Stroke\n {\n get => (Brush)GetValue(StrokeProperty);\n set => SetValue(StrokeProperty, value);\n }\n\n public static readonly DependencyProperty WidthPercentageProperty =\n DependencyProperty.Register(nameof(WidthPercentage), typeof(double), typeof(SelectableSubtitleText), new FrameworkPropertyMetadata(60.0, OnWidthPercentageChanged));\n\n public double WidthPercentage\n {\n get => (double)GetValue(WidthPercentageProperty);\n set => SetValue(WidthPercentageProperty, value);\n }\n\n public static readonly DependencyProperty WidthPercentageFixProperty =\n DependencyProperty.Register(nameof(WidthPercentageFix), typeof(double), typeof(SelectableSubtitleText), new FrameworkPropertyMetadata(60.0));\n\n public double WidthPercentageFix\n {\n get => (double)GetValue(WidthPercentageFixProperty);\n set => SetValue(WidthPercentageFixProperty, value);\n }\n\n public static readonly DependencyProperty IgnoreLineBreakProperty =\n DependencyProperty.Register(nameof(IgnoreLineBreak), typeof(bool), typeof(SelectableSubtitleText), new FrameworkPropertyMetadata(false));\n\n public double MaxFixedWidth\n {\n get => (double)GetValue(MaxFixedWidthProperty);\n set => SetValue(MaxFixedWidthProperty, value);\n }\n\n public static readonly DependencyProperty MaxFixedWidthProperty =\n DependencyProperty.Register(nameof(MaxFixedWidth), typeof(double), typeof(SelectableSubtitleText), new FrameworkPropertyMetadata(0.0));\n\n public bool IgnoreLineBreak\n {\n get => (bool)GetValue(IgnoreLineBreakProperty);\n set => SetValue(IgnoreLineBreakProperty, value);\n }\n\n public static readonly DependencyProperty StrokeThicknessInitialProperty =\n DependencyProperty.Register(nameof(StrokeThicknessInitial), typeof(double), typeof(SelectableSubtitleText), new FrameworkPropertyMetadata(3.0));\n\n public double StrokeThicknessInitial\n {\n get => (double)GetValue(StrokeThicknessInitialProperty);\n set => SetValue(StrokeThicknessInitialProperty, value);\n }\n\n public static readonly DependencyProperty WordHoverBorderBrushProperty =\n DependencyProperty.Register(nameof(WordHoverBorderBrush), typeof(Brush), typeof(SelectableSubtitleText), new FrameworkPropertyMetadata(Brushes.Cyan));\n\n public Brush WordHoverBorderBrush\n {\n get => (Brush)GetValue(WordHoverBorderBrushProperty);\n set => SetValue(WordHoverBorderBrushProperty, value);\n }\n\n private static void OnWidthPercentageChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)\n {\n var ctl = (SelectableSubtitleText)d;\n ctl.WidthPercentageFix = (double)e.NewValue;\n }\n\n private static void OnTextChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)\n {\n var ctl = (SelectableSubtitleText)d;\n ctl.SetText((string)e.NewValue);\n }\n\n private static void OnTextLanguageChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)\n {\n var ctl = (SelectableSubtitleText)d;\n if (ctl.TextLanguage != null && ctl.TextLanguage.IsRTL)\n {\n ctl.wrapPanel.FlowDirection = FlowDirection.RightToLeft;\n }\n else\n {\n ctl.wrapPanel.FlowDirection = FlowDirection.LeftToRight;\n }\n }\n\n // SelectableTextBox uses char.IsPunctuation(), so use a regular expression for it.\n // TODO: L: Sharing the code with TextBox\n [GeneratedRegex(@\"((?:[^\\P{P}'-]+|\\s))\")]\n private static partial Regex WordSplitReg { get; }\n\n [GeneratedRegex(@\"^(?:[^\\P{P}'-]+|\\s)$\")]\n private static partial Regex WordSplitFullReg { get; }\n\n [GeneratedRegex(@\"((?:[^\\P{P}'-]+|\\s|[\\p{IsCJKUnifiedIdeographs}\\p{IsCJKUnifiedIdeographsExtensionA}]))\")]\n private static partial Regex ChineseWordSplitReg { get; }\n\n\n private static readonly Lazy MeCabTagger = new(() => MeCabIpaDicTagger.Create(), true);\n\n private void SetText(string text)\n {\n if (text == null)\n {\n return;\n }\n\n if (IgnoreLineBreak)\n {\n text = SubtitleTextUtil.FlattenText(text);\n }\n\n _textFix = text;\n\n bool containLineBreak = text.AsSpan().ContainsAny('\\r', '\\n');\n\n // If it contains line feeds, expand them to the full screen width (respecting the formatting in the SRT subtitle)\n WidthPercentageFix = containLineBreak ? 100.0 : WidthPercentage;\n\n wrapPanel.Children.Clear();\n _wordStart = null;\n\n string[] lines = text.SplitToLines().ToArray();\n\n var wordOffset = 0;\n\n // Use an OutlinedTextBlock for each word to display the border Text and enclose it in a WrapPanel\n for (int i = 0; i < lines.Length; i++)\n {\n IEnumerable words;\n\n if (TextLanguage != null && TextLanguage.ISO6391 == \"ja\")\n {\n // word segmentation for Japanese\n // TODO: L: Also do word segmentation in sidebar\n var nodes = MeCabTagger.Value.Parse(lines[i]);\n List wordsList = new(nodes.Length);\n foreach (var node in nodes)\n {\n // If there are space-separated characters, such as English, add them manually since they are not on the Surface\n if (char.IsWhiteSpace(lines[i][node.BPos]))\n {\n wordsList.Add(\" \");\n }\n wordsList.Add(node.Surface);\n }\n\n words = wordsList;\n }\n else if (TextLanguage != null && TextLanguage.ISO6391 == \"zh\")\n {\n words = ChineseWordSplitReg.Split(lines[i]);\n }\n else\n {\n words = WordSplitReg.Split(lines[i]);\n }\n\n foreach (string word in words)\n {\n // skip empty string because Split includes\n if (word.Length == 0)\n {\n continue;\n }\n\n if (string.IsNullOrWhiteSpace(word))\n {\n // Blanks are inserted with TextBlock.\n TextBlock space = new()\n {\n Text = word,\n // Created a click judgment to prevent playback toggling when clicking between words.\n Background = new SolidColorBrush(Color.FromArgb(1, 0, 0, 0)),\n };\n space.SetBinding(TextBlock.FontSizeProperty, _bindFontSize);\n space.SetBinding(TextBlock.FontWeightProperty, _bindFontWeight);\n space.SetBinding(TextBlock.FontStyleProperty, _bindFontStyle);\n space.SetBinding(TextBlock.FontFamilyProperty, _bindFontFamily);\n wrapPanel.Children.Add(space);\n wordOffset += word.Length;\n continue;\n }\n\n bool isSplitChar = WordSplitFullReg.IsMatch(word);\n\n OutlinedTextBlock textBlock = new()\n {\n Text = word,\n ClipToBounds = false,\n TextWrapping = TextWrapping.Wrap,\n StrokePosition = StrokePosition.Outside,\n IsHitTestVisible = false,\n WordOffset = wordOffset,\n // Fixed because the word itself is inverted\n FlowDirection = FlowDirection.LeftToRight\n };\n\n wordOffset += word.Length;\n\n textBlock.SetBinding(OutlinedTextBlock.FontSizeProperty, _bindFontSize);\n textBlock.SetBinding(OutlinedTextBlock.FontWeightProperty, _bindFontWeight);\n textBlock.SetBinding(OutlinedTextBlock.FontStyleProperty, _bindFontStyle);\n textBlock.SetBinding(OutlinedTextBlock.FontFamilyProperty, _bindFontFamily);\n textBlock.SetBinding(OutlinedTextBlock.FillProperty, _bindFill);\n textBlock.SetBinding(OutlinedTextBlock.StrokeProperty, _bindStroke);\n textBlock.SetBinding(OutlinedTextBlock.StrokeThicknessInitialProperty, _bindStrokeThicknessInitial);\n\n if (isSplitChar)\n {\n wrapPanel.Children.Add(textBlock);\n }\n else\n {\n Border border = new()\n {\n // Set brush to Border because OutlinedTextBlock's character click judgment is only on the character.\n //ref: https://stackoverflow.com/questions/50653308/hit-testing-a-transparent-element-in-a-transparent-window\n Background = new SolidColorBrush(Color.FromArgb(1, 0, 0, 0)),\n BorderThickness = new Thickness(1),\n IsHitTestVisible = true,\n Child = textBlock,\n Cursor = Cursors.Hand,\n };\n\n border.MouseLeftButtonDown += WordMouseLeftButtonDown;\n border.MouseLeftButtonUp += WordMouseLeftButtonUp;\n border.MouseRightButtonUp += WordMouseRightButtonUp;\n border.MouseUp += WordMouseMiddleButtonUp;\n\n // Change background color on mouse over\n border.MouseEnter += (_, _) =>\n {\n border.BorderBrush = WordHoverBorderBrush;\n border.Background = new SolidColorBrush(Color.FromArgb(80, 127, 127, 127));\n };\n border.MouseLeave += (_, _) =>\n {\n border.BorderBrush = null;\n border.Background = new SolidColorBrush(Color.FromArgb(1, 0, 0, 0));\n };\n\n wrapPanel.Children.Add(border);\n }\n }\n\n if (containLineBreak && i != lines.Length - 1)\n {\n // Add line breaks except at the end when there are two or more lines\n wrapPanel.Children.Add(new NewLine());\n }\n }\n }\n\n private void WordMouseLeftButtonDown(object sender, MouseButtonEventArgs e)\n {\n if (sender is Border { Child: OutlinedTextBlock word })\n {\n _wordStart = word;\n WordClickedDown?.Invoke(this, EventArgs.Empty);\n\n e.Handled = true;\n }\n }\n\n private void WordMouseLeftButtonUp(object sender, MouseButtonEventArgs e)\n {\n if (sender is Border { Child: OutlinedTextBlock word })\n {\n if (_wordStart == word)\n {\n // word clicked\n Point wordPoint = word.TranslatePoint(default, Root);\n\n WordClickedEventArgs args = new(WordClickedEvent)\n {\n Mouse = MouseClick.Left,\n Words = word.Text,\n IsWord = true,\n Text = _textFix,\n IsTranslated = IsTranslated,\n SubIndex = SubIndex,\n WordOffset = word.WordOffset,\n WordsX = wordPoint.X,\n WordsWidth = word.ActualWidth\n };\n RaiseEvent(args);\n }\n else if (_wordStart != null)\n {\n // phrase selected\n var wordStart = _wordStart!;\n var wordEnd = word;\n\n // support right to left drag\n if (wordStart.WordOffset > wordEnd.WordOffset)\n {\n (wordStart, wordEnd) = (wordEnd, wordStart);\n }\n\n List elements = wrapPanel.Children.OfType().ToList();\n\n int startIndex = elements.IndexOf((FrameworkElement)wordStart.Parent);\n int endIndex = elements.IndexOf((FrameworkElement)wordEnd.Parent);\n\n if (startIndex == -1 || endIndex == -1)\n {\n Debug.Assert(startIndex >= 0);\n Debug.Assert(endIndex >= 0);\n return;\n }\n\n var selectedElements = elements[startIndex..(endIndex + 1)];\n var selectedWords = selectedElements.Select(fe =>\n {\n switch (fe)\n {\n case Border { Child: OutlinedTextBlock word }:\n return word.Text;\n case OutlinedTextBlock splitter:\n return splitter.Text;\n case TextBlock space:\n return space.Text;\n case NewLine:\n // convert to space\n return \" \";\n default:\n throw new InvalidOperationException();\n }\n }).ToList();\n string selectedText = string.Join(string.Empty, selectedWords);\n\n Point startPoint = wordStart.TranslatePoint(default, Root);\n Point endPoint = wordEnd.TranslatePoint(default, Root);\n\n // if different Y axis, then line break or text wrapping\n double wordsX = 0;\n double wordsWidth = wrapPanel.ActualWidth;\n\n if (startPoint.Y == endPoint.Y)\n {\n // selection in one line\n\n if (wrapPanel.FlowDirection == FlowDirection.LeftToRight)\n {\n wordsX = startPoint.X;\n wordsWidth = endPoint.X + wordEnd.ActualWidth - startPoint.X;\n }\n else\n {\n wordsX = endPoint.X;\n wordsWidth = startPoint.X + wordStart.ActualWidth - endPoint.X;\n }\n }\n\n WordClickedEventArgs args = new(WordClickedEvent)\n {\n Mouse = MouseClick.Left,\n Words = selectedText,\n IsWord = false,\n Text = _textFix,\n IsTranslated = IsTranslated,\n SubIndex = SubIndex,\n WordOffset = wordStart.WordOffset,\n WordsX = wordsX,\n WordsWidth = wordsWidth\n };\n RaiseEvent(args);\n }\n\n _wordStart = null;\n e.Handled = true;\n }\n }\n\n private void WordMouseRightButtonUp(object sender, MouseButtonEventArgs e)\n {\n if (sender is Border { Child: OutlinedTextBlock word })\n {\n Point wordPoint = word.TranslatePoint(default, Root);\n\n WordClickedEventArgs args = new(WordClickedEvent)\n {\n Mouse = MouseClick.Right,\n Words = word.Text,\n IsWord = true,\n Text = _textFix,\n IsTranslated = IsTranslated,\n SubIndex = SubIndex,\n WordOffset = word.WordOffset,\n WordsX = wordPoint.X,\n WordsWidth = word.ActualWidth\n };\n RaiseEvent(args);\n e.Handled = true;\n }\n }\n\n private void WordMouseMiddleButtonUp(object sender, MouseButtonEventArgs e)\n {\n if (e.ChangedButton == MouseButton.Middle)\n {\n WordClickedEventArgs args = new(WordClickedEvent)\n {\n Mouse = MouseClick.Middle,\n Words = _textFix,\n IsWord = false,\n Text = _textFix,\n IsTranslated = IsTranslated,\n SubIndex = SubIndex,\n WordOffset = 0,\n WordsX = 0,\n WordsWidth = wrapPanel.ActualWidth\n };\n RaiseEvent(args);\n e.Handled = true;\n }\n }\n}\n\npublic class NewLine : FrameworkElement\n{\n}\n"], ["/LLPlayer/FlyleafLib/MediaPlayer/Player.Screamers.cs", "using System.Diagnostics;\nusing System.Threading;\n\nusing FlyleafLib.MediaFramework.MediaDecoder;\nusing FlyleafLib.MediaFramework.MediaFrame;\nusing FlyleafLib.MediaFramework.MediaStream;\nusing static FlyleafLib.Utils;\nusing static FlyleafLib.Logger;\n\nnamespace FlyleafLib.MediaPlayer;\n\nunsafe partial class Player\n{\n /// \n /// Fires on Data frame when it's supposed to be shown according to the stream\n /// Warning: Uses Invoke and it comes from playback thread so you can't pause/stop etc. You need to use another thread if you have to.\n /// \n public event EventHandler OnDataFrame;\n\n /// \n /// Fires on buffering started\n /// Warning: Uses Invoke and it comes from playback thread so you can't pause/stop etc. You need to use another thread if you have to.\n /// \n public event EventHandler BufferingStarted;\n protected virtual void OnBufferingStarted()\n {\n if (onBufferingStarted != onBufferingCompleted) return;\n BufferingStarted?.Invoke(this, new EventArgs());\n onBufferingStarted++;\n\n if (CanDebug) Log.Debug($\"OnBufferingStarted\");\n }\n\n /// \n /// Fires on buffering completed (will fire also on failed buffering completed)\n /// (BufferDration > Config.Player.MinBufferDuration)\n /// Warning: Uses Invoke and it comes from playback thread so you can't pause/stop etc. You need to use another thread if you have to.\n /// \n public event EventHandler BufferingCompleted;\n protected virtual void OnBufferingCompleted(string error = null)\n {\n if (onBufferingStarted - 1 != onBufferingCompleted) return;\n\n if (error != null && LastError == null)\n {\n lastError = error;\n UI(() => LastError = LastError);\n }\n\n BufferingCompleted?.Invoke(this, new BufferingCompletedArgs(error));\n onBufferingCompleted++;\n if (CanDebug) Log.Debug($\"OnBufferingCompleted{(error != null ? $\" (Error: {error})\" : \"\")}\");\n }\n\n long onBufferingStarted;\n long onBufferingCompleted;\n\n int vDistanceMs;\n int aDistanceMs;\n int[] sDistanceMss;\n int dDistanceMs;\n int sleepMs;\n\n long elapsedTicks;\n long elapsedSec;\n long startTicks;\n long showOneFrameTicks;\n\n int allowedLateAudioDrops;\n long lastSpeedChangeTicks;\n long curLatency;\n internal long curAudioDeviceDelay;\n\n public int subNum => Config.Subtitles.Max;\n\n Stopwatch sw = new();\n\n private void ShowOneFrame()\n {\n for (int i = 0; i < subNum; i++)\n {\n sFrames[i] = null;\n }\n if (VideoDecoder.Frames.IsEmpty || !VideoDecoder.Frames.TryDequeue(out vFrame))\n return;\n\n renderer.Present(vFrame);\n\n if (!seeks.IsEmpty)\n return;\n\n if (!VideoDemuxer.IsHLSLive)\n curTime = vFrame.timestamp;\n\n UI(() => UpdateCurTime());\n\n for (int i = 0; i < subNum; i++)\n {\n // Prevents blinking after seek\n if (sFramesPrev[i] != null)\n {\n var cur = SubtitlesManager[i].GetCurrent();\n if (cur != null)\n {\n if (!string.IsNullOrEmpty(cur.DisplayText) || (cur.IsBitmap && cur.Bitmap != null))\n {\n continue;\n }\n }\n }\n\n // Clear last subtitles text if video timestamp is not within subs timestamp + duration (to prevent clearing current subs on pause/play)\n if (sFramesPrev[i] == null || sFramesPrev[i].timestamp > vFrame.timestamp || (sFramesPrev[i].timestamp + (sFramesPrev[i].duration * (long)10000)) < vFrame.timestamp)\n {\n sFramesPrev[i] = null;\n SubtitleClear(i);\n }\n }\n\n // Required for buffering on paused\n if (decoder.RequiresResync && !IsPlaying && seeks.IsEmpty)\n decoder.Resync(vFrame.timestamp);\n\n vFrame = null;\n }\n\n // !!! NEEDS RECODING (We show one frame, we dispose it, we get another one and we show it also after buffering which can be in 'no time' which can leave us without any more decoded frames so we rebuffer)\n private bool MediaBuffer()\n {\n if (CanTrace) Log.Trace(\"Buffering\");\n\n while (isVideoSwitch && IsPlaying) Thread.Sleep(10);\n\n Audio.ClearBuffer();\n\n VideoDemuxer.Start();\n VideoDecoder.Start();\n\n if (Audio.isOpened && Config.Audio.Enabled)\n {\n curAudioDeviceDelay = Audio.GetDeviceDelay();\n\n if (AudioDecoder.OnVideoDemuxer)\n AudioDecoder.Start();\n else if (!decoder.RequiresResync)\n {\n AudioDemuxer.Start();\n AudioDecoder.Start();\n }\n }\n\n if (Config.Subtitles.Enabled)\n {\n for (int i = 0; i < subNum; i++)\n {\n if (!Subtitles[i].IsOpened)\n {\n continue;\n }\n\n lock (lockSubtitles)\n {\n if (SubtitlesDecoders[i].OnVideoDemuxer)\n {\n SubtitlesDecoders[i].Start();\n }\n //else if (!decoder.RequiresResync)\n //{\n // SubtitlesDemuxers[i].Start();\n // SubtitlesDecoders[i].Start();\n //}\n }\n }\n }\n\n if (Data.isOpened && Config.Data.Enabled)\n {\n if (DataDecoder.OnVideoDemuxer)\n DataDecoder.Start();\n else if (!decoder.RequiresResync)\n {\n DataDemuxer.Start();\n DataDecoder.Start();\n }\n }\n\n VideoDecoder.DisposeFrame(vFrame);\n vFrame = null;\n aFrame = null;\n for (int i = 0; i < subNum; i++)\n {\n sFrames[i] = null;\n }\n dFrame = null;\n\n bool gotAudio = !Audio.IsOpened || Config.Player.MaxLatency != 0;\n bool gotVideo = false;\n bool shouldStop = false;\n bool showOneFrame = true;\n int audioRetries = 4;\n int loops = 0;\n\n if (Config.Player.MaxLatency != 0)\n {\n lastSpeedChangeTicks = DateTime.UtcNow.Ticks;\n showOneFrame = false;\n Speed = 1;\n }\n\n do\n {\n loops++;\n\n if (showOneFrame && !VideoDecoder.Frames.IsEmpty)\n {\n ShowOneFrame();\n showOneFrameTicks = DateTime.UtcNow.Ticks;\n showOneFrame = false;\n }\n\n // We allo few ms to show a frame before cancelling\n if ((!showOneFrame || loops > 8) && !seeks.IsEmpty)\n return false;\n\n if (!gotVideo && !showOneFrame && !VideoDecoder.Frames.IsEmpty)\n {\n VideoDecoder.Frames.TryDequeue(out vFrame);\n if (vFrame != null) gotVideo = true;\n }\n\n if (!gotAudio && aFrame == null && !AudioDecoder.Frames.IsEmpty)\n AudioDecoder.Frames.TryDequeue(out aFrame);\n\n if (gotVideo)\n {\n if (decoder.RequiresResync)\n decoder.Resync(vFrame.timestamp);\n\n if (!gotAudio && aFrame != null)\n {\n for (int i=0; i vFrame.timestamp\n || vFrame.timestamp > Duration)\n {\n gotAudio = true;\n break;\n }\n\n if (CanTrace) Log.Trace($\"Drop aFrame {TicksToTime(aFrame.timestamp)}\");\n AudioDecoder.Frames.TryDequeue(out aFrame);\n }\n\n // Avoid infinite loop in case of all audio timestamps wrong\n if (!gotAudio)\n {\n audioRetries--;\n\n if (audioRetries < 1)\n {\n gotAudio = true;\n aFrame = null;\n Log.Warn($\"Audio Exhausted 1\");\n }\n }\n }\n }\n\n if (!IsPlaying || decoderHasEnded)\n shouldStop = true;\n else\n {\n if (!VideoDecoder.IsRunning && !isVideoSwitch)\n {\n Log.Warn(\"Video Exhausted\");\n shouldStop= true;\n }\n\n if (gotVideo && !gotAudio && audioRetries > 0 && (!AudioDecoder.IsRunning || AudioDecoder.Demuxer.Status == MediaFramework.Status.QueueFull))\n {\n if (CanWarn) Log.Warn($\"Audio Exhausted 2 | {audioRetries}\");\n\n audioRetries--;\n\n if (audioRetries < 1)\n gotAudio = true;\n }\n }\n\n Thread.Sleep(10);\n\n } while (!shouldStop && (!gotVideo || !gotAudio));\n\n if (shouldStop && !(decoderHasEnded && IsPlaying && vFrame != null))\n {\n Log.Info(\"Stopped\");\n return false;\n }\n\n if (vFrame == null)\n {\n Log.Error(\"No Frames!\");\n return false;\n }\n\n // Negative Buffer Duration during codec change (we don't dipose the cached frames or we receive them later) *skip waiting for now\n var bufDuration = GetBufferedDuration();\n if (bufDuration >= 0)\n while(seeks.IsEmpty && bufDuration < Config.Player.MinBufferDuration && IsPlaying && VideoDemuxer.IsRunning && VideoDemuxer.Status != MediaFramework.Status.QueueFull)\n {\n Thread.Sleep(20);\n bufDuration = GetBufferedDuration();\n if (bufDuration < 0)\n break;\n }\n\n if (!seeks.IsEmpty)\n return false;\n\n if (CanInfo) Log.Info($\"Started [V: {TicksToTime(vFrame.timestamp)}]\" + (aFrame == null ? \"\" : $\" [A: {TicksToTime(aFrame.timestamp)}]\"));\n\n decoder.OpenedPlugin.OnBufferingCompleted();\n\n return true;\n }\n private void Screamer()\n {\n long audioBufferedDuration = 0; // We force audio resync with = 0\n\n while (Status == Status.Playing)\n {\n if (seeks.TryPop(out var seekData))\n {\n seeks.Clear();\n requiresBuffering = true;\n\n for (int i = 0; i < subNum; i++)\n {\n // Display subtitles from cache when seeking while playing\n bool display = false;\n var cur = SubtitlesManager[i].GetCurrent();\n if (cur != null)\n {\n if (!string.IsNullOrEmpty(cur.DisplayText))\n {\n SubtitleDisplay(cur.DisplayText, i, cur.UseTranslated);\n display = true;\n }\n else if (cur.IsBitmap && cur.Bitmap != null)\n {\n SubtitleDisplay(cur.Bitmap, i);\n display = true;\n }\n\n if (display)\n {\n sFramesPrev[i] = new SubtitlesFrame\n {\n timestamp = cur.StartTime.Ticks + Config.Subtitles[i].Delay,\n duration = (uint)cur.Duration.TotalMilliseconds,\n isTranslated = cur.UseTranslated\n };\n }\n }\n\n // clear subtitles\n // but do not clear when cache hit\n if (!display && sFramesPrev[i] != null)\n {\n sFramesPrev[i] = null;\n SubtitleClear(i);\n }\n }\n\n decoder.PauseDecoders(); // TBR: Required to avoid gettings packets between Seek and ShowFrame which causes resync issues\n\n if (decoder.Seek(seekData.accurate ? Math.Max(0, seekData.ms - (int)new TimeSpan(Config.Player.SeekAccurateFixMargin).TotalMilliseconds) : seekData.ms, seekData.forward, !seekData.accurate) < 0) // Consider using GetVideoFrame with no timestamp (any) to ensure keyframe packet for faster seek in HEVC\n Log.Warn(\"Seek failed\");\n else if (seekData.accurate)\n decoder.GetVideoFrame(seekData.ms * (long)10000);\n }\n\n if (requiresBuffering)\n {\n if (VideoDemuxer.Interrupter.Timedout)\n break;\n\n OnBufferingStarted();\n MediaBuffer();\n requiresBuffering = false;\n if (!seeks.IsEmpty)\n continue;\n\n if (vFrame == null)\n {\n if (decoderHasEnded)\n OnBufferingCompleted();\n\n Log.Warn(\"[MediaBuffer] No video frame\");\n break;\n }\n\n // Temp fix to ensure we had enough time to decode one more frame\n int retries = 5;\n while (IsPlaying && VideoDecoder.Frames.Count == 0 && retries-- > 0)\n Thread.Sleep(10);\n\n // Give enough time for the 1st frame to be presented\n while (IsPlaying && DateTime.UtcNow.Ticks - showOneFrameTicks < VideoDecoder.VideoStream.FrameDuration)\n Thread.Sleep(4);\n\n OnBufferingCompleted();\n\n audioBufferedDuration = 0;\n allowedLateAudioDrops = 7;\n elapsedSec = 0;\n startTicks = vFrame.timestamp;\n sw.Restart();\n }\n\n if (Status != Status.Playing)\n break;\n\n if (vFrame == null)\n {\n if (VideoDecoder.Status == MediaFramework.Status.Ended)\n {\n if (!MainDemuxer.IsHLSLive)\n {\n if (Math.Abs(MainDemuxer.Duration - curTime) < 2 * VideoDemuxer.VideoStream.FrameDuration)\n curTime = MainDemuxer.Duration;\n else\n curTime += VideoDemuxer.VideoStream.FrameDuration;\n\n UI(() => Set(ref _CurTime, curTime, true, nameof(CurTime)));\n }\n\n break;\n }\n\n Log.Warn(\"No video frames\");\n requiresBuffering = true;\n continue;\n }\n\n if (aFrame == null && !isAudioSwitch)\n AudioDecoder.Frames.TryDequeue(out aFrame);\n\n for (int i = 0; i < subNum; i++)\n {\n if (sFrames[i] == null && !isSubsSwitches[i])\n SubtitlesDecoders[i].Frames.TryPeek(out sFrames[i]);\n }\n\n if (dFrame == null && !isDataSwitch)\n DataDecoder.Frames.TryPeek(out dFrame);\n\n elapsedTicks = (long) (sw.ElapsedTicks * SWFREQ_TO_TICKS); // Do we really need ticks precision?\n\n vDistanceMs =\n (int) ((((vFrame.timestamp - startTicks) / speed) - elapsedTicks) / 10000);\n\n if (aFrame != null)\n {\n curAudioDeviceDelay = Audio.GetDeviceDelay();\n audioBufferedDuration = Audio.GetBufferedDuration();\n aDistanceMs = (int) ((((aFrame.timestamp - startTicks) / speed) - (elapsedTicks - curAudioDeviceDelay)) / 10000);\n\n // Try to keep the audio buffer full enough to avoid audio crackling (up to 50ms)\n while (audioBufferedDuration > 0 && audioBufferedDuration < 50 * 10000 && aDistanceMs > -5 && aDistanceMs < 50)\n {\n Audio.AddSamples(aFrame);\n\n if (isAudioSwitch)\n {\n audioBufferedDuration = 0;\n aDistanceMs = int.MaxValue;\n aFrame = null;\n }\n else\n {\n audioBufferedDuration = Audio.GetBufferedDuration();\n AudioDecoder.Frames.TryDequeue(out aFrame);\n if (aFrame != null)\n aDistanceMs = (int) ((((aFrame.timestamp - startTicks) / speed) - (elapsedTicks - curAudioDeviceDelay)) / 10000);\n else\n aDistanceMs = int.MaxValue;\n }\n }\n }\n else\n aDistanceMs = int.MaxValue;\n\n for (int i = 0; i < subNum; i++)\n {\n sDistanceMss[i] = sFrames[i] != null\n ? (int)((((sFrames[i].timestamp - startTicks) / speed) - elapsedTicks) / 10000)\n : int.MaxValue;\n }\n\n dDistanceMs = dFrame != null\n ? (int)((((dFrame.timestamp - startTicks) / speed) - elapsedTicks) / 10000)\n : int.MaxValue;\n\n sleepMs = Math.Min(vDistanceMs, aDistanceMs) - 1;\n if (sleepMs < 0 || sleepMs == int.MaxValue)\n sleepMs = 0;\n\n if (sleepMs > 2)\n {\n if (vDistanceMs > 2000)\n {\n Log.Warn($\"vDistanceMs = {vDistanceMs} (restarting)\");\n requiresBuffering = true;\n continue;\n }\n\n if (Engine.Config.UICurTimePerSecond && (\n (!MainDemuxer.IsHLSLive && curTime / 10000000 != _CurTime / 10000000) ||\n (MainDemuxer.IsHLSLive && Math.Abs(elapsedTicks - elapsedSec) > 10000000)))\n {\n elapsedSec = elapsedTicks;\n UI(() => UpdateCurTime());\n }\n\n Thread.Sleep(sleepMs);\n }\n\n if (aFrame != null) // Should use different thread for better accurancy (renderer might delay it on high fps) | also on high offset we will have silence between samples\n {\n if (Math.Abs(aDistanceMs - sleepMs) <= 5)\n {\n Audio.AddSamples(aFrame);\n\n // Audio Desync - Large Buffer | ASampleBytes (S16 * 2 Channels = 4) * TimeBase * 2 -frames duration-\n if (Audio.GetBufferedDuration() > Math.Max(50 * 10000, (aFrame.dataLen / 4) * Audio.Timebase * 2))\n {\n if (CanDebug)\n Log.Debug($\"Audio desynced by {(int)(audioBufferedDuration / 10000)}ms, clearing buffers\");\n\n Audio.ClearBuffer();\n audioBufferedDuration = 0;\n }\n\n aFrame = null;\n }\n else if (aDistanceMs > 4000) // Drops few audio frames in case of wrong timestamps (Note this should be lower, until swr has min/max samples for about 20-70ms)\n {\n if (allowedLateAudioDrops > 0)\n {\n Audio.framesDropped++;\n allowedLateAudioDrops--;\n if (CanDebug) Log.Debug($\"aDistanceMs 3 = {aDistanceMs}\");\n aFrame = null;\n audioBufferedDuration = 0;\n }\n }\n else if (aDistanceMs < -5) // Will be transfered back to decoder to drop invalid timestamps\n {\n if (CanTrace) Log.Trace($\"aDistanceMs = {aDistanceMs} | AudioFrames: {AudioDecoder.Frames.Count} AudioPackets: {AudioDecoder.Demuxer.AudioPackets.Count}\");\n\n if (GetBufferedDuration() < Config.Player.MinBufferDuration / 2)\n {\n if (CanInfo)\n Log.Warn($\"Not enough buffer (restarting)\");\n\n requiresBuffering = true;\n continue;\n }\n\n audioBufferedDuration = 0;\n\n if (aDistanceMs < -600)\n {\n if (CanTrace) Log.Trace($\"All audio frames disposed\");\n Audio.framesDropped += AudioDecoder.Frames.Count;\n AudioDecoder.DisposeFrames();\n aFrame = null;\n }\n else\n {\n int maxdrop = Math.Max(Math.Min(vDistanceMs - sleepMs - 1, 20), 3);\n for (int i=0; i 0)\n break;\n\n aFrame = null;\n }\n }\n }\n }\n\n if (Math.Abs(vDistanceMs - sleepMs) <= 2)\n {\n if (CanTrace) Log.Trace($\"[V] Presenting {TicksToTime(vFrame.timestamp)}\");\n\n if (decoder.VideoDecoder.Renderer.Present(vFrame, false))\n Video.framesDisplayed++;\n else\n Video.framesDropped++;\n\n lock (seeks)\n if (seeks.IsEmpty)\n {\n curTime = !MainDemuxer.IsHLSLive ? vFrame.timestamp : VideoDemuxer.CurTime;\n\n if (Config.Player.UICurTimePerFrame)\n UI(() => UpdateCurTime());\n }\n\n VideoDecoder.Frames.TryDequeue(out vFrame);\n if (vFrame != null && Config.Player.MaxLatency != 0)\n CheckLatency();\n }\n else if (vDistanceMs < -2)\n {\n if (vDistanceMs < -10 || GetBufferedDuration() < Config.Player.MinBufferDuration / 2)\n {\n if (CanDebug)\n Log.Debug($\"vDistanceMs = {vDistanceMs} (restarting)\");\n\n requiresBuffering = true;\n continue;\n }\n\n if (CanDebug)\n Log.Debug($\"vDistanceMs = {vDistanceMs}\");\n\n Video.framesDropped++;\n VideoDecoder.DisposeFrame(vFrame);\n VideoDecoder.Frames.TryDequeue(out vFrame);\n }\n\n // Set the current time to SubtitleManager in a loop\n if (Config.Subtitles.Enabled)\n {\n for (int i = 0; i < subNum; i++)\n {\n if (Subtitles[i].Enabled)\n {\n SubtitlesManager[i].SetCurrentTime(new TimeSpan(curTime));\n }\n }\n }\n // Internal subtitles (Text or Bitmap or OCR)\n for (int i = 0; i < subNum; i++)\n {\n if (sFramesPrev[i] != null && ((sFramesPrev[i].timestamp - startTicks + (sFramesPrev[i].duration * (long)10000)) / speed) - (long) (sw.ElapsedTicks * SWFREQ_TO_TICKS) < 0)\n {\n SubtitleClear(i);\n\n sFramesPrev[i] = null;\n }\n\n if (sFrames[i] != null)\n {\n if (Math.Abs(sDistanceMss[i] - sleepMs) < 30 || (sDistanceMss[i] < -30 && sFrames[i].duration + sDistanceMss[i] > 0))\n {\n if (sFrames[i].isBitmap && sFrames[i].sub.num_rects > 0)\n {\n if (SubtitlesSelectedHelper.GetMethod(i) == SelectSubMethod.OCR)\n {\n // Prevent the problem of OCR subtitles not being used in priority by setting\n // the timestamp of the subtitles as they are displayed a little earlier\n SubtitlesManager[i].SetCurrentTime(new TimeSpan(sFrames[i].timestamp));\n }\n\n var cur = SubtitlesManager[i].GetCurrent();\n\n if (cur != null && !string.IsNullOrEmpty(cur.Text))\n {\n // Use OCR text subtitles if available\n SubtitleDisplay(cur.DisplayText, i, cur.UseTranslated);\n }\n else\n {\n // renderer.CreateOverlayTexture(sFrame, SubtitlesDecoder.CodecCtx->width, SubtitlesDecoder.CodecCtx->height);\n SubtitleDisplay(sFrames[i].bitmap, i);\n }\n\n SubtitlesDecoder.DisposeFrame(sFrames[i]); // only rects\n }\n else if (sFrames[i].isBitmap && sFrames[i].sub.num_rects == 0)\n {\n // For Blu-ray subtitles (PGS), clear the previous subtitle\n SubtitleClear(i);\n sFramesPrev[i] = sFrames[i] = null;\n }\n else\n {\n // internal text sub (does not support translate)\n SubtitleDisplay(sFrames[i].text, i, false);\n }\n sFramesPrev[i] = sFrames[i];\n sFrames[i] = null;\n SubtitlesDecoders[i].Frames.TryDequeue(out _);\n }\n else if (sDistanceMss[i] < -30)\n {\n if (CanDebug)\n Log.Debug($\"sDistanceMss[i] = {sDistanceMss[i]}\");\n\n //SubtitleClear(i);\n\n // TODO: L: Here sFrames can be null, occurs when switching subtitles?\n SubtitlesDecoder.DisposeFrame(sFrames[i]);\n sFrames[i] = null;\n SubtitlesDecoders[i].Frames.TryDequeue(out _);\n }\n }\n }\n\n // External or ASR subtitles\n for (int i = 0; i < subNum; i++)\n {\n if (!Config.Subtitles.Enabled || !Subtitles[i].Enabled)\n {\n continue;\n }\n\n SubtitleData cur = SubtitlesManager[i].GetCurrent();\n\n if (cur == null)\n {\n continue;\n }\n\n if (sFramesPrev[i] == null ||\n sFramesPrev[i].timestamp != cur.StartTime.Ticks + Config.Subtitles[i].Delay)\n {\n bool display = false;\n if (!string.IsNullOrEmpty(cur.DisplayText))\n {\n SubtitleDisplay(cur.DisplayText, i, cur.UseTranslated);\n display = true;\n }\n else if (cur.IsBitmap && cur.Bitmap != null)\n {\n SubtitleDisplay(cur.Bitmap, i);\n display = true;\n }\n\n if (display)\n {\n sFramesPrev[i] = new SubtitlesFrame\n {\n timestamp = cur.StartTime.Ticks + Config.Subtitles[i].Delay,\n duration = (uint)cur.Duration.TotalMilliseconds,\n isTranslated = cur.UseTranslated\n };\n }\n }\n else\n {\n // Apply translation to current sub\n if (Config.Subtitles[i].EnabledTranslated) {\n\n // If the subtitle currently playing is not translated, change to the translated for display\n if (sFramesPrev[i] != null &&\n sFramesPrev[i].timestamp == cur.StartTime.Ticks + Config.Subtitles[i].Delay &&\n sFramesPrev[i].isTranslated != cur.UseTranslated)\n {\n SubtitleDisplay(cur.DisplayText, i, cur.UseTranslated);\n sFramesPrev[i].isTranslated = cur.UseTranslated;\n }\n }\n }\n }\n\n if (dFrame != null)\n {\n if (Math.Abs(dDistanceMs - sleepMs) < 30 || (dDistanceMs < -30))\n {\n OnDataFrame?.Invoke(this, dFrame);\n\n dFrame = null;\n DataDecoder.Frames.TryDequeue(out var devnull);\n }\n else if (dDistanceMs < -30)\n {\n if (CanDebug)\n Log.Debug($\"dDistanceMs = {dDistanceMs}\");\n\n dFrame = null;\n DataDecoder.Frames.TryDequeue(out var devnull);\n }\n }\n }\n\n if (CanInfo) Log.Info($\"Finished -> {TicksToTime(CurTime)}\");\n }\n\n private void CheckLatency()\n {\n curLatency = GetBufferedDuration();\n\n if (CanDebug)\n Log.Debug($\"[Latency {curLatency/10000}ms] Frames: {VideoDecoder.Frames.Count} Packets: {VideoDemuxer.VideoPackets.Count} Speed: {speed}\");\n\n if (curLatency <= Config.Player.MinLatency) // We've reached the down limit (back to speed x1)\n {\n ChangeSpeedWithoutBuffering(1);\n return;\n }\n else if (curLatency < Config.Player.MaxLatency)\n return;\n\n var newSpeed = Math.Max(Math.Round((double)curLatency / Config.Player.MaxLatency, 1, MidpointRounding.ToPositiveInfinity), 1.1);\n\n if (newSpeed > 4) // TBR: dispose only as much as required to avoid rebuffering\n {\n decoder.Flush();\n requiresBuffering = true;\n Log.Debug($\"[Latency {curLatency/10000}ms] Clearing queue\");\n return;\n }\n\n ChangeSpeedWithoutBuffering(newSpeed);\n }\n private void ChangeSpeedWithoutBuffering(double newSpeed)\n {\n if (speed == newSpeed)\n return;\n\n long curTicks = DateTime.UtcNow.Ticks;\n\n if (newSpeed != 1 && curTicks - lastSpeedChangeTicks < Config.Player.LatencySpeedChangeInterval)\n return;\n\n lastSpeedChangeTicks = curTicks;\n\n if (CanDebug)\n Log.Debug($\"[Latency {curLatency/10000}ms] Speed changed x{speed} -> x{newSpeed}\");\n\n if (aFrame != null)\n AudioDecoder.FixSample(aFrame, speed, newSpeed);\n\n Speed = newSpeed;\n requiresBuffering\n = false;\n startTicks = curTime;\n elapsedSec = 0;\n sw.Restart();\n }\n private long GetBufferedDuration()\n {\n var decoder = VideoDecoder.Frames.IsEmpty ? 0 : VideoDecoder.Frames.ToArray()[^1].timestamp - vFrame.timestamp;\n var demuxer = VideoDemuxer.VideoPackets.IsEmpty || VideoDemuxer.VideoPackets.LastTimestamp == NoTs\n ? 0 :\n (VideoDemuxer.VideoPackets.LastTimestamp - VideoDemuxer.StartTime) - vFrame.timestamp;\n\n return Math.Max(decoder, demuxer);\n }\n\n private void AudioBuffer()\n {\n if (CanTrace) Log.Trace(\"Buffering\");\n\n while ((isVideoSwitch || isAudioSwitch) && IsPlaying)\n Thread.Sleep(10);\n\n if (!IsPlaying)\n return;\n\n aFrame = null;\n Audio.ClearBuffer();\n decoder.AudioStream.Demuxer.Start();\n AudioDecoder.Start();\n\n while(AudioDecoder.Frames.IsEmpty && IsPlaying && AudioDecoder.IsRunning)\n Thread.Sleep(10);\n\n AudioDecoder.Frames.TryPeek(out aFrame);\n\n if (aFrame == null)\n return;\n\n lock (seeks)\n if (seeks.IsEmpty)\n {\n curTime = !MainDemuxer.IsHLSLive ? aFrame.timestamp : MainDemuxer.CurTime;\n UI(() =>\n {\n Set(ref _CurTime, curTime, true, nameof(CurTime));\n UpdateBufferedDuration();\n });\n }\n\n while(seeks.IsEmpty && decoder.AudioStream.Demuxer.BufferedDuration < Config.Player.MinBufferDuration && AudioDecoder.Frames.Count < Config.Decoder.MaxAudioFrames / 2 && IsPlaying && decoder.AudioStream.Demuxer.IsRunning && decoder.AudioStream.Demuxer.Status != MediaFramework.Status.QueueFull)\n Thread.Sleep(20);\n }\n private void ScreamerAudioOnly()\n {\n long bufferedDuration = 0;\n\n while (IsPlaying)\n {\n if (seeks.TryPop(out var seekData))\n {\n seeks.Clear();\n requiresBuffering = true;\n\n if (AudioDecoder.OnVideoDemuxer)\n {\n if (decoder.Seek(seekData.ms, seekData.forward) < 0)\n Log.Warn(\"Seek failed 1\");\n }\n else\n {\n if (decoder.SeekAudio(seekData.ms, seekData.forward) < 0)\n Log.Warn(\"Seek failed 2\");\n }\n }\n\n if (requiresBuffering)\n {\n OnBufferingStarted();\n AudioBuffer();\n requiresBuffering = false;\n\n if (!seeks.IsEmpty)\n continue;\n\n if (!IsPlaying || AudioDecoder.Frames.IsEmpty)\n break;\n\n OnBufferingCompleted();\n }\n\n if (AudioDecoder.Frames.IsEmpty)\n {\n if (bufferedDuration == 0)\n {\n if (!IsPlaying || AudioDecoder.Status == MediaFramework.Status.Ended)\n break;\n\n Log.Warn(\"No audio frames\");\n requiresBuffering = true;\n }\n else\n {\n Thread.Sleep(50); // waiting for audio buffer to be played before end\n bufferedDuration = Audio.GetBufferedDuration();\n }\n\n continue;\n }\n\n // Support only ASR subtitle for audio\n foreach (int i in SubtitlesASR.SubIndexSet)\n {\n SubtitlesManager[i].SetCurrentTime(new TimeSpan(curTime));\n\n var cur = SubtitlesManager[i].GetCurrent();\n if (cur != null && !string.IsNullOrEmpty(cur.DisplayText))\n {\n SubtitleDisplay(cur.DisplayText, i, cur.UseTranslated);\n }\n else\n {\n SubtitleClear(i);\n }\n }\n\n bufferedDuration = Audio.GetBufferedDuration();\n\n if (bufferedDuration < 300 * 10000)\n {\n do\n {\n AudioDecoder.Frames.TryDequeue(out aFrame);\n if (aFrame == null || !IsPlaying)\n break;\n\n Audio.AddSamples(aFrame);\n bufferedDuration += (long) ((aFrame.dataLen / 4) * Audio.Timebase);\n curTime = !MainDemuxer.IsHLSLive ? aFrame.timestamp : MainDemuxer.CurTime;\n } while (bufferedDuration < 100 * 10000);\n\n lock (seeks)\n if (seeks.IsEmpty)\n {\n if (!Engine.Config.UICurTimePerSecond || curTime / 10000000 != _CurTime / 10000000)\n {\n UI(() =>\n {\n Set(ref _CurTime, curTime, true, nameof(CurTime));\n UpdateBufferedDuration();\n });\n }\n }\n\n Thread.Sleep(20);\n }\n else\n Thread.Sleep(50);\n }\n }\n\n private void ScreamerReverse()\n {\n while (Status == Status.Playing)\n {\n if (seeks.TryPop(out var seekData))\n {\n seeks.Clear();\n if (decoder.Seek(seekData.ms, seekData.forward) < 0)\n Log.Warn(\"Seek failed\");\n }\n\n if (vFrame == null)\n {\n if (VideoDecoder.Status == MediaFramework.Status.Ended)\n break;\n\n OnBufferingStarted();\n if (reversePlaybackResync)\n {\n decoder.Flush();\n VideoDemuxer.EnableReversePlayback(CurTime);\n reversePlaybackResync = false;\n }\n VideoDemuxer.Start();\n VideoDecoder.Start();\n\n while (VideoDecoder.Frames.IsEmpty && Status == Status.Playing && VideoDecoder.IsRunning) Thread.Sleep(15);\n OnBufferingCompleted();\n VideoDecoder.Frames.TryDequeue(out vFrame);\n if (vFrame == null) { Log.Warn(\"No video frame\"); break; }\n vFrame.timestamp = (long) (vFrame.timestamp / Speed);\n\n startTicks = vFrame.timestamp;\n sw.Restart();\n elapsedSec = 0;\n\n if (!MainDemuxer.IsHLSLive && seeks.IsEmpty)\n curTime = (long) (vFrame.timestamp * Speed);\n UI(() => UpdateCurTime());\n }\n\n elapsedTicks = startTicks - (long) (sw.ElapsedTicks * SWFREQ_TO_TICKS);\n vDistanceMs = (int) ((elapsedTicks - vFrame.timestamp) / 10000);\n sleepMs = vDistanceMs - 1;\n\n if (sleepMs < 0) sleepMs = 0;\n\n if (Math.Abs(vDistanceMs - sleepMs) > 5)\n {\n //Log($\"vDistanceMs |-> {vDistanceMs}\");\n VideoDecoder.DisposeFrame(vFrame);\n vFrame = null;\n Thread.Sleep(5);\n continue; // rebuffer\n }\n\n if (sleepMs > 2)\n {\n if (sleepMs > 1000)\n {\n //Log($\"sleepMs -> {sleepMs} , vDistanceMs |-> {vDistanceMs}\");\n VideoDecoder.DisposeFrame(vFrame);\n vFrame = null;\n Thread.Sleep(5);\n continue; // rebuffer\n }\n\n // Every seconds informs the application with CurTime / Bitrates (invokes UI thread to ensure the updates will actually happen)\n if (Engine.Config.UICurTimePerSecond && (\n (!MainDemuxer.IsHLSLive && curTime / 10000000 != _CurTime / 10000000) ||\n (MainDemuxer.IsHLSLive && Math.Abs(elapsedTicks - elapsedSec) > 10000000)))\n {\n elapsedSec = elapsedTicks;\n UI(() => UpdateCurTime());\n }\n\n Thread.Sleep(sleepMs);\n }\n\n decoder.VideoDecoder.Renderer.Present(vFrame, false);\n if (!MainDemuxer.IsHLSLive && seeks.IsEmpty)\n {\n curTime = (long) (vFrame.timestamp * Speed);\n\n if (Config.Player.UICurTimePerFrame)\n UI(() => UpdateCurTime());\n }\n\n VideoDecoder.Frames.TryDequeue(out vFrame);\n if (vFrame != null)\n vFrame.timestamp = (long) (vFrame.timestamp / Speed);\n }\n }\n}\n\npublic class BufferingCompletedArgs : EventArgs\n{\n public string Error { get; }\n public bool Success { get; }\n\n public BufferingCompletedArgs(string error)\n {\n Error = error;\n Success = Error == null;\n }\n}\n"], ["/LLPlayer/LLPlayer/ViewModels/WhisperEngineDownloadDialogVM.cs", "using System.Diagnostics;\nusing System.IO;\nusing System.Net.Http;\nusing FlyleafLib;\nusing LLPlayer.Extensions;\nusing LLPlayer.Services;\nusing SevenZip;\nusing File = System.IO.File;\n\nnamespace LLPlayer.ViewModels;\n\npublic class WhisperEngineDownloadDialogVM : Bindable, IDialogAware\n{\n // currently not reusable at all\n public static string EngineURL => \"https://github.com/Purfview/whisper-standalone-win/releases/tag/Faster-Whisper-XXL\";\n public static string EngineFile => \"Faster-Whisper-XXL_r245.4_windows.7z\";\n private static string EngineDownloadURL =\n \"https://github.com/umlx5h/LLPlayer/releases/download/v0.0.1/Faster-Whisper-XXL_r245.4_windows.7z\";\n private static string EngineName = \"Faster-Whisper-XXL\";\n private static string EnginePath = Path.Combine(WhisperConfig.EnginesDirectory, EngineName);\n\n public FlyleafManager FL { get; }\n\n public WhisperEngineDownloadDialogVM(FlyleafManager fl)\n {\n FL = fl;\n\n CmdDownloadEngine!.PropertyChanged += (sender, args) =>\n {\n if (args.PropertyName == nameof(CmdDownloadEngine.IsExecuting))\n {\n OnPropertyChanged(nameof(CanDownload));\n OnPropertyChanged(nameof(CanDelete));\n }\n };\n }\n\n public string StatusText { get; set => Set(ref field, value); } = \"\";\n\n public long DownloadedSize { get; set => Set(ref field, value); }\n\n public bool Downloaded => Directory.Exists(EnginePath);\n\n public bool CanDownload => !Downloaded && !CmdDownloadEngine!.IsExecuting;\n\n public bool CanDelete => Downloaded && !CmdDownloadEngine!.IsExecuting;\n\n private CancellationTokenSource? _cts;\n\n public AsyncDelegateCommand? CmdDownloadEngine => field ??= new AsyncDelegateCommand(async () =>\n {\n _cts = new CancellationTokenSource();\n CancellationToken token = _cts.Token;\n\n string tempPath = Path.GetTempPath();\n string tempDownloadFile = Path.Combine(tempPath, EngineFile);\n\n try\n {\n StatusText = $\"Engine '{EngineName}' downloading..\";\n\n await DownloadEngineWithProgressAsync(EngineDownloadURL, tempDownloadFile, token);\n\n StatusText = $\"Engine '{EngineName}' unzipping..\";\n await UnzipEngine(tempDownloadFile);\n\n StatusText = $\"Engine '{EngineName}' is downloaded successfully\";\n OnDownloadStatusChanged();\n }\n catch (OperationCanceledException)\n {\n StatusText = \"Download canceled\";\n }\n catch (Exception ex)\n {\n StatusText = $\"Failed to download: {ex.Message}\";\n }\n finally\n {\n _cts = null;\n DeleteTempEngine();\n }\n\n return;\n\n bool DeleteTempEngine()\n {\n // Delete temporary files if they exist\n if (File.Exists(tempDownloadFile))\n {\n try\n {\n File.Delete(tempDownloadFile);\n }\n catch (Exception)\n {\n // ignore\n\n return false;\n }\n }\n\n return true;\n }\n }).ObservesCanExecute(() => CanDownload);\n\n public DelegateCommand? CmdCancelDownloadEngine => field ??= new(() =>\n {\n _cts?.Cancel();\n });\n\n public AsyncDelegateCommand? CmdDeleteEngine => field ??= new AsyncDelegateCommand(async () =>\n {\n try\n {\n StatusText = $\"Engine '{EngineName}' deleting...\";\n\n // Delete engine if exists\n if (Directory.Exists(EnginePath))\n {\n await Task.Run(() =>\n {\n Directory.Delete(EnginePath, true);\n });\n }\n\n OnDownloadStatusChanged();\n\n StatusText = $\"Engine '{EngineName}' is deleted successfully\";\n }\n catch (Exception ex)\n {\n StatusText = $\"Failed to delete engine: {ex.Message}\";\n }\n }).ObservesCanExecute(() => CanDelete);\n\n public DelegateCommand? CmdOpenFolder => field ??= new(() =>\n {\n if (!Directory.Exists(WhisperConfig.EnginesDirectory))\n return;\n\n Process.Start(new ProcessStartInfo\n {\n FileName = WhisperConfig.EnginesDirectory,\n UseShellExecute = true,\n CreateNoWindow = true\n });\n });\n\n private void OnDownloadStatusChanged()\n {\n OnPropertyChanged(nameof(CanDownload));\n OnPropertyChanged(nameof(CanDelete));\n }\n\n private async Task UnzipEngine(string zipPath)\n {\n WhisperConfig.EnsureEnginesDirectory();\n\n SevenZipBase.SetLibraryPath(\"lib/7z.dll\");\n\n using (SevenZipExtractor extractor = new(zipPath))\n {\n await extractor.ExtractArchiveAsync(WhisperConfig.EnginesDirectory);\n }\n\n string licencePath = Path.Combine(WhisperConfig.EnginesDirectory, \"license.txt\");\n\n if (File.Exists(licencePath) && Directory.Exists(WhisperConfig.EnginesDirectory))\n {\n // move license.txt to engine directory\n File.Move(licencePath, Path.Combine(EnginePath, \"license.txt\"));\n }\n }\n\n private async Task DownloadEngineWithProgressAsync(string url, string destinationPath, CancellationToken token)\n {\n DownloadedSize = 0;\n\n using HttpClient httpClient = new();\n httpClient.Timeout = TimeSpan.FromSeconds(10);\n\n using var response = await httpClient.GetAsync(url, HttpCompletionOption.ResponseHeadersRead, token);\n\n response.EnsureSuccessStatusCode();\n\n await using Stream engineStream = await response.Content.ReadAsStreamAsync(token);\n await using FileStream fileWriter = File.Open(destinationPath, FileMode.Create);\n\n byte[] buffer = new byte[1024 * 128];\n int bytesRead;\n long totalBytesRead = 0;\n\n Stopwatch sw = new();\n sw.Start();\n\n while ((bytesRead = await engineStream.ReadAsync(buffer, 0, buffer.Length, token)) > 0)\n {\n await fileWriter.WriteAsync(buffer, 0, bytesRead, token);\n totalBytesRead += bytesRead;\n\n if (sw.Elapsed > TimeSpan.FromMilliseconds(50))\n {\n DownloadedSize = totalBytesRead;\n sw.Restart();\n }\n\n token.ThrowIfCancellationRequested();\n }\n\n return totalBytesRead;\n }\n\n #region IDialogAware\n public string Title { get; set => Set(ref field, value); } = $\"Whisper Engine Downloader - {App.Name}\";\n public double WindowWidth { get; set => Set(ref field, value); } = 400;\n public double WindowHeight { get; set => Set(ref field, value); } = 210;\n\n public bool CanCloseDialog() => !CmdDownloadEngine!.IsExecuting;\n public void OnDialogClosed() { }\n public void OnDialogOpened(IDialogParameters parameters) { }\n public DialogCloseListener RequestClose { get; }\n #endregion IDialogAware\n}\n"], ["/LLPlayer/FlyleafLib/MediaFramework/MediaRenderer/Renderer.PresentOffline.cs", "using System.Drawing.Imaging;\nusing System.Drawing;\nusing System.Threading;\nusing System.Windows.Media.Imaging;\n\nusing SharpGen.Runtime;\n\nusing Vortice;\nusing Vortice.Direct3D11;\nusing Vortice.DXGI;\nusing Vortice.Mathematics;\n\nusing FlyleafLib.MediaFramework.MediaDecoder;\nusing FlyleafLib.MediaFramework.MediaFrame;\n\nusing ID3D11Texture2D = Vortice.Direct3D11.ID3D11Texture2D;\n\nnamespace FlyleafLib.MediaFramework.MediaRenderer;\n\npublic partial class Renderer\n{\n // subs\n Texture2DDescription overlayTextureDesc;\n ID3D11Texture2D overlayTexture;\n ID3D11ShaderResourceView overlayTextureSrv;\n int overlayTextureOriginalWidth;\n int overlayTextureOriginalHeight;\n int overlayTextureOriginalPosX;\n int overlayTextureOriginalPosY;\n\n ID3D11ShaderResourceView[] overlayTextureSRVs = new ID3D11ShaderResourceView[1];\n\n // Used for off screen rendering\n Texture2DDescription singleStageDesc, singleGpuDesc;\n ID3D11Texture2D singleStage;\n ID3D11Texture2D singleGpu;\n ID3D11RenderTargetView singleGpuRtv;\n Viewport singleViewport;\n\n // Used for parallel off screen rendering\n ID3D11RenderTargetView[] rtv2;\n ID3D11Texture2D[] backBuffer2;\n bool[] backBuffer2busy;\n\n unsafe internal void PresentOffline(VideoFrame frame, ID3D11RenderTargetView rtv, Viewport viewport)\n {\n if (videoProcessor == VideoProcessors.D3D11)\n {\n var tmpResource = rtv.Resource;\n vd1.CreateVideoProcessorOutputView(tmpResource, vpe, vpovd, out var vpov);\n\n RawRect rect = new((int)viewport.X, (int)viewport.Y, (int)(viewport.Width + viewport.X), (int)(viewport.Height + viewport.Y));\n vc.VideoProcessorSetStreamSourceRect(vp, 0, true, VideoRect);\n vc.VideoProcessorSetStreamDestRect(vp, 0, true, rect);\n vc.VideoProcessorSetOutputTargetRect(vp, true, rect);\n\n if (frame.avFrame != null)\n {\n vpivd.Texture2D.ArraySlice = (uint) frame.avFrame->data[1];\n vd1.CreateVideoProcessorInputView(VideoDecoder.textureFFmpeg, vpe, vpivd, out vpiv);\n }\n else\n {\n vpivd.Texture2D.ArraySlice = 0;\n vd1.CreateVideoProcessorInputView(frame.textures[0], vpe, vpivd, out vpiv);\n }\n\n vpsa[0].InputSurface = vpiv;\n vc.VideoProcessorBlt(vp, vpov, 0, 1, vpsa);\n vpiv.Dispose();\n vpov.Dispose();\n tmpResource.Dispose();\n }\n else\n {\n context.OMSetRenderTargets(rtv);\n context.ClearRenderTargetView(rtv, Config.Video._BackgroundColor);\n context.RSSetViewport(viewport);\n context.PSSetShaderResources(0, frame.srvs);\n context.Draw(6, 0);\n }\n }\n\n /// \n /// Gets bitmap from a video frame\n /// \n /// Specify the width (-1: will keep the ratio based on height)\n /// Specify the height (-1: will keep the ratio based on width)\n /// Video frame to process (null: will use the current/last frame)\n /// \n unsafe public Bitmap GetBitmap(int width = -1, int height = -1, VideoFrame frame = null)\n {\n try\n {\n lock (lockDevice)\n {\n frame ??= LastFrame;\n\n if (Disposed || frame == null || (frame.textures == null && frame.avFrame == null))\n return null;\n\n if (width == -1 && height == -1)\n {\n width = VideoRect.Right;\n height = VideoRect.Bottom;\n }\n else if (width != -1 && height == -1)\n height = (int)(width / curRatio);\n else if (height != -1 && width == -1)\n width = (int)(height * curRatio);\n\n if (singleStageDesc.Width != width || singleStageDesc.Height != height)\n {\n singleGpu?.Dispose();\n singleStage?.Dispose();\n singleGpuRtv?.Dispose();\n\n singleStageDesc.Width = (uint)width;\n singleStageDesc.Height = (uint)height;\n singleGpuDesc.Width = (uint)width;\n singleGpuDesc.Height = (uint)height;\n\n singleStage = Device.CreateTexture2D(singleStageDesc);\n singleGpu = Device.CreateTexture2D(singleGpuDesc);\n singleGpuRtv= Device.CreateRenderTargetView(singleGpu);\n\n singleViewport = new Viewport(width, height);\n }\n\n PresentOffline(frame, singleGpuRtv, singleViewport);\n\n if (videoProcessor == VideoProcessors.D3D11)\n SetViewport();\n }\n\n context.CopyResource(singleStage, singleGpu);\n return GetBitmap(singleStage);\n\n } catch (Exception e)\n {\n Log.Warn($\"GetBitmap failed with: {e.Message}\");\n return null;\n }\n }\n public Bitmap GetBitmap(ID3D11Texture2D stageTexture)\n {\n Bitmap bitmap = new((int)stageTexture.Description.Width, (int)stageTexture.Description.Height);\n var db = context.Map(stageTexture, 0, MapMode.Read, Vortice.Direct3D11.MapFlags.None);\n var bitmapData = bitmap.LockBits(new Rectangle(0, 0, bitmap.Width, bitmap.Height), ImageLockMode.WriteOnly, PixelFormat.Format32bppArgb);\n\n if (db.RowPitch == bitmapData.Stride)\n MemoryHelpers.CopyMemory(bitmapData.Scan0, db.DataPointer, bitmap.Width * bitmap.Height * 4);\n else\n {\n var sourcePtr = db.DataPointer;\n var destPtr = bitmapData.Scan0;\n\n for (int y = 0; y < bitmap.Height; y++)\n {\n MemoryHelpers.CopyMemory(destPtr, sourcePtr, bitmap.Width * 4);\n\n sourcePtr = IntPtr.Add(sourcePtr, (int)db.RowPitch);\n destPtr = IntPtr.Add(destPtr, bitmapData.Stride);\n }\n }\n\n bitmap.UnlockBits(bitmapData);\n context.Unmap(stageTexture, 0);\n\n return bitmap;\n }\n /// \n /// Gets BitmapSource from a video frame\n /// \n /// Specify the width (-1: will keep the ratio based on height)\n /// Specify the height (-1: will keep the ratio based on width)\n /// Video frame to process (null: will use the current/last frame)\n /// \n unsafe public BitmapSource GetBitmapSource(int width = -1, int height = -1, VideoFrame frame = null)\n {\n try\n {\n lock (lockDevice)\n {\n frame ??= LastFrame;\n\n if (Disposed || frame == null || (frame.textures == null && frame.avFrame == null))\n return null;\n\n if (width == -1 && height == -1)\n {\n width = VideoRect.Right;\n height = VideoRect.Bottom;\n }\n else if (width != -1 && height == -1)\n height = (int)(width / curRatio);\n else if (height != -1 && width == -1)\n width = (int)(height * curRatio);\n\n if (singleStageDesc.Width != width || singleStageDesc.Height != height)\n {\n singleGpu?.Dispose();\n singleStage?.Dispose();\n singleGpuRtv?.Dispose();\n\n singleStageDesc.Width = (uint)width;\n singleStageDesc.Height = (uint)height;\n singleGpuDesc.Width = (uint)width;\n singleGpuDesc.Height = (uint)height;\n\n singleStage = Device.CreateTexture2D(singleStageDesc);\n singleGpu = Device.CreateTexture2D(singleGpuDesc);\n singleGpuRtv = Device.CreateRenderTargetView(singleGpu);\n\n singleViewport = new Viewport(width, height);\n }\n\n PresentOffline(frame, singleGpuRtv, singleViewport);\n\n if (videoProcessor == VideoProcessors.D3D11)\n SetViewport();\n }\n\n context.CopyResource(singleStage, singleGpu);\n return GetBitmapSource(singleStage);\n\n }\n catch (Exception e)\n {\n Log.Warn($\"GetBitmapSource failed with: {e.Message}\");\n return null;\n }\n }\n public BitmapSource GetBitmapSource(ID3D11Texture2D stageTexture)\n {\n WriteableBitmap bitmap = new((int)stageTexture.Description.Width, (int)stageTexture.Description.Height, 96, 96, System.Windows.Media.PixelFormats.Bgra32, null);\n var db = context.Map(stageTexture, 0, MapMode.Read, Vortice.Direct3D11.MapFlags.None);\n bitmap.Lock();\n\n if (db.RowPitch == bitmap.BackBufferStride)\n MemoryHelpers.CopyMemory(bitmap.BackBuffer, db.DataPointer, bitmap.PixelWidth * bitmap.PixelHeight * 4);\n else\n {\n var sourcePtr = db.DataPointer;\n var destPtr = bitmap.BackBuffer;\n\n for (int y = 0; y < bitmap.Height; y++)\n {\n MemoryHelpers.CopyMemory(destPtr, sourcePtr, bitmap.PixelWidth * 4);\n\n sourcePtr = IntPtr.Add(sourcePtr, (int)db.RowPitch);\n destPtr = IntPtr.Add(destPtr, bitmap.BackBufferStride);\n }\n }\n\n bitmap.Unlock();\n context.Unmap(stageTexture, 0);\n\n // Freezing animated wpf assets improves performance\n bitmap.Freeze();\n\n return bitmap;\n }\n\n /// \n /// Extracts a bitmap from a video frame\n /// (Currently cannot be used in parallel with the rendering)\n /// \n /// \n /// \n public Bitmap ExtractFrame(VideoFrame frame)\n {\n if (Device == null || frame == null) return null;\n\n int subresource = -1;\n\n Texture2DDescription stageDesc = new()\n {\n Usage = ResourceUsage.Staging,\n Width = VideoDecoder.VideoStream.Width,\n Height = VideoDecoder.VideoStream.Height,\n Format = Format.B8G8R8A8_UNorm,\n ArraySize = 1,\n MipLevels = 1,\n BindFlags = BindFlags.None,\n CPUAccessFlags = CpuAccessFlags.Read,\n SampleDescription = new SampleDescription(1, 0)\n };\n var stage = Device.CreateTexture2D(stageDesc);\n\n lock (lockDevice)\n {\n while (true)\n {\n for (int i=0; i 10)) // With slow FPS we need to refresh as fast as possible\n return;\n\n if (isPresenting)\n {\n lastPresentRequestAt = DateTime.UtcNow.Ticks;\n return;\n }\n\n isPresenting = true;\n }\n\n Task.Run(() =>\n {\n long presentingAt;\n do\n {\n long sleepMs = DateTime.UtcNow.Ticks - lastPresentAt;\n sleepMs = sleepMs < (long)(1.0 / Config.Player.IdleFps * 1000 * 10000) ? (long) (1.0 / Config.Player.IdleFps * 1000) : 0;\n if (sleepMs > 2)\n Thread.Sleep((int)sleepMs);\n\n presentingAt = DateTime.UtcNow.Ticks;\n RefreshLayout();\n lastPresentAt = DateTime.UtcNow.Ticks;\n\n } while (lastPresentRequestAt > presentingAt);\n\n isPresenting = false;\n });\n }\n internal void PresentInternal(VideoFrame frame, bool forceWait = true)\n {\n if (SCDisposed)\n return;\n\n // TBR: Replica performance issue with D3D11 (more zoom more gpu overload)\n if (frame.srvs == null) // videoProcessor can be FlyleafVP but the player can send us a cached frame from prev videoProcessor D3D11VP (check frame.srv instead of videoProcessor)\n {\n if (frame.avFrame != null)\n {\n vpivd.Texture2D.ArraySlice = (uint) frame.avFrame->data[1];\n vd1.CreateVideoProcessorInputView(VideoDecoder.textureFFmpeg, vpe, vpivd, out vpiv);\n }\n else\n {\n vpivd.Texture2D.ArraySlice = 0;\n vd1.CreateVideoProcessorInputView(frame.textures[0], vpe, vpivd, out vpiv);\n }\n\n vpsa[0].InputSurface = vpiv;\n vc.VideoProcessorBlt(vp, vpov, 0, 1, vpsa);\n swapChain.Present(Config.Video.VSync, forceWait ? PresentFlags.None : Config.Video.PresentFlags);\n\n vpiv.Dispose();\n }\n else\n {\n context.OMSetRenderTargets(backBufferRtv);\n context.ClearRenderTargetView(backBufferRtv, Config.Video._BackgroundColor);\n context.RSSetViewport(GetViewport);\n context.PSSetShaderResources(0, frame.srvs);\n context.Draw(6, 0);\n\n if (overlayTexture != null)\n {\n // Don't stretch the overlay (reduce height based on ratiox) | Sub's stream size might be different from video size (fix y based on percentage)\n var ratiox = (double)GetViewport.Width / overlayTextureOriginalWidth;\n var ratioy = (double)overlayTextureOriginalPosY / overlayTextureOriginalHeight;\n\n context.OMSetBlendState(blendStateAlpha);\n context.PSSetShaderResources(0, overlayTextureSRVs);\n context.RSSetViewport((float) (GetViewport.X + (overlayTextureOriginalPosX * ratiox)), (float) (GetViewport.Y + (GetViewport.Height * ratioy)), (float) (overlayTexture.Description.Width * ratiox), (float) (overlayTexture.Description.Height * ratiox));\n context.PSSetShader(ShaderBGRA);\n context.Draw(6, 0);\n\n // restore context\n context.PSSetShader(ShaderPS);\n context.OMSetBlendState(curPSCase == PSCase.RGBPacked ? blendStateAlpha : null);\n }\n\n swapChain.Present(Config.Video.VSync, forceWait ? PresentFlags.None : Config.Video.PresentFlags);\n }\n\n child?.PresentInternal(frame);\n }\n\n public void ClearOverlayTexture()\n {\n if (overlayTexture == null)\n return;\n\n overlayTexture?.Dispose();\n overlayTextureSrv?.Dispose();\n overlayTexture = null;\n overlayTextureSrv = null;\n }\n\n internal void CreateOverlayTexture(SubtitlesFrame frame, int streamWidth, int streamHeight)\n {\n var rect = frame.sub.rects[0];\n var stride = rect->linesize[0] * 4;\n\n overlayTextureOriginalWidth = streamWidth;\n overlayTextureOriginalHeight= streamHeight;\n overlayTextureOriginalPosX = rect->x;\n overlayTextureOriginalPosY = rect->y;\n overlayTextureDesc.Width = (uint)rect->w;\n overlayTextureDesc.Height = (uint)rect->h;\n\n byte[] data = ConvertBitmapSub(frame.sub, false);\n\n fixed(byte* ptr = data)\n {\n SubresourceData subData = new()\n {\n DataPointer = (nint)ptr,\n RowPitch = (uint)stride\n };\n\n overlayTexture?.Dispose();\n overlayTextureSrv?.Dispose();\n overlayTexture = Device.CreateTexture2D(overlayTextureDesc, new SubresourceData[] { subData });\n overlayTextureSrv = Device.CreateShaderResourceView(overlayTexture);\n overlayTextureSRVs[0] = overlayTextureSrv;\n }\n }\n\n public static byte[] ConvertBitmapSub(AVSubtitle sub, bool grey)\n {\n var rect = sub.rects[0];\n var stride = rect->linesize[0] * 4;\n\n byte[] data = new byte[rect->w * rect->h * 4];\n Span colors = stackalloc uint[256];\n\n fixed(byte* ptr = data)\n {\n var colorsData = new Span((byte*)rect->data[1], rect->nb_colors);\n\n for (int i = 0; i < colorsData.Length; i++)\n colors[i] = colorsData[i];\n\n ConvertPal(colors, 256, grey);\n\n for (int y = 0; y < rect->h; y++)\n {\n uint* xout =(uint*) (ptr + y * stride);\n byte* xin = ((byte*)rect->data[0]) + y * rect->linesize[0];\n\n for (int x = 0; x < rect->w; x++)\n *xout++ = colors[*xin++];\n }\n }\n\n return data;\n }\n\n static void ConvertPal(Span colors, int count, bool gray) // subs bitmap (source: mpv)\n {\n for (int n = 0; n < count; n++)\n {\n uint c = colors[n];\n uint b = c & 0xFF;\n uint g = (c >> 8) & 0xFF;\n uint r = (c >> 16) & 0xFF;\n uint a = (c >> 24) & 0xFF;\n\n if (gray)\n r = g = b = (r + g + b) / 3;\n\n // from straight to pre-multiplied alpha\n b = b * a / 255;\n g = g * a / 255;\n r = r * a / 255;\n colors[n] = b | (g << 8) | (r << 16) | (a << 24);\n }\n }\n\n public void RefreshLayout()\n {\n if (Monitor.TryEnter(lockDevice, 5))\n {\n try\n {\n if (SCDisposed)\n return;\n\n if (LastFrame != null && (LastFrame.textures != null || LastFrame.avFrame != null))\n PresentInternal(LastFrame);\n else if (Config.Video.ClearScreen)\n {\n context.ClearRenderTargetView(backBufferRtv, Config.Video._BackgroundColor);\n swapChain.Present(Config.Video.VSync, PresentFlags.None);\n }\n }\n catch (Exception e)\n {\n if (CanWarn) Log.Warn($\"Present idle failed {e.Message} | {Device.DeviceRemovedReason}\");\n }\n finally\n {\n Monitor.Exit(lockDevice);\n }\n }\n }\n public void ClearScreen()\n {\n ClearOverlayTexture();\n VideoDecoder.DisposeFrame(LastFrame);\n Present();\n }\n}\n"], ["/LLPlayer/FlyleafLib/Utils/TextEncodings.cs", "using System.IO;\nusing System.Text;\nusing UtfUnknown;\n\nnamespace FlyleafLib;\n\n#nullable enable\n\npublic static class TextEncodings\n{\n private static Encoding? DetectEncodingInternal(byte[] data)\n {\n // 1. Check Unicode BOM\n Encoding? encoding = DetectEncodingWithBOM(data);\n if (encoding != null)\n {\n return encoding;\n }\n\n // 2. If no BOM, then check text is UTF-8 without BOM\n // Perform UTF-8 check first because automatic detection often results in false positives such as WINDOWS-1252.\n if (IsUtf8(data))\n {\n return Encoding.UTF8;\n }\n\n // 3. Auto detect encoding using library\n try\n {\n var result = CharsetDetector.DetectFromBytes(data);\n return result.Detected.Encoding;\n }\n catch\n {\n return null;\n }\n }\n\n /// \n /// Detect character encoding of text binary files\n /// \n /// text binary\n /// Bytes to read\n /// Detected Encoding or null\n public static Encoding? DetectEncoding(byte[] original, int maxBytes = 1 * 1024 * 1024)\n {\n if (maxBytes > original.Length)\n {\n maxBytes = original.Length;\n }\n\n byte[] data = new byte[maxBytes];\n Array.Copy(original, data, maxBytes);\n\n return DetectEncodingInternal(data);\n }\n\n /// \n /// Detect character encoding of text files\n /// \n /// file path\n /// Bytes to read\n /// Detected Encoding or null\n public static Encoding? DetectEncoding(string path, int maxBytes = 1 * 1024 * 1024)\n {\n byte[] data = new byte[maxBytes];\n\n try\n {\n using FileStream fs = new(path, FileMode.Open, FileAccess.Read);\n int bytesRead = fs.Read(data, 0, data.Length);\n Array.Resize(ref data, bytesRead);\n }\n catch\n {\n return null;\n }\n\n return DetectEncodingInternal(data);\n }\n\n /// \n /// Detect character encoding using BOM\n /// \n /// string raw data\n /// Detected Encoding or null\n private static Encoding? DetectEncodingWithBOM(byte[] bytes)\n {\n // UTF-8 BOM: EF BB BF\n if (bytes.Length >= 3 && bytes[0] == 0xEF && bytes[1] == 0xBB && bytes[2] == 0xBF)\n {\n return Encoding.UTF8;\n }\n\n // UTF-16 LE BOM: FF FE\n if (bytes.Length >= 2 && bytes[0] == 0xFF && bytes[1] == 0xFE)\n {\n return Encoding.Unicode; // UTF-16 LE\n }\n\n // UTF-16 BE BOM: FE FF\n if (bytes.Length >= 2 && bytes[0] == 0xFE && bytes[1] == 0xFF)\n {\n return Encoding.BigEndianUnicode; // UTF-16 BE\n }\n\n // UTF-32 LE BOM: FF FE 00 00\n if (bytes.Length >= 4 && bytes[0] == 0xFF && bytes[1] == 0xFE && bytes[2] == 0x00 && bytes[3] == 0x00)\n {\n return Encoding.UTF32;\n }\n\n // UTF-32 BE BOM: 00 00 FE FF\n if (bytes.Length >= 4 && bytes[0] == 0x00 && bytes[1] == 0x00 && bytes[2] == 0xFE && bytes[3] == 0xFF)\n {\n return new UTF32Encoding(bigEndian: true, byteOrderMark: true);\n }\n\n // No BOM\n return null;\n }\n\n private static bool IsUtf8(byte[] bytes)\n {\n // enable validation\n UTF8Encoding encoding = new(encoderShouldEmitUTF8Identifier: false, throwOnInvalidBytes: true);\n\n try\n {\n encoding.GetString(bytes);\n\n return true;\n }\n catch (DecoderFallbackException ex)\n {\n // Ignore when a trailing cut character causes a validation error.\n if (bytes.Length - ex.Index < 4)\n {\n return true;\n }\n\n return false;\n }\n }\n}\n"], ["/LLPlayer/FlyleafLib/MediaPlayer/Player.cs", "using System;\nusing System.Collections.Concurrent;\nusing System.Collections.Generic;\nusing System.Collections.ObjectModel;\nusing System.Threading;\n\nusing FlyleafLib.Controls;\nusing FlyleafLib.MediaFramework.MediaContext;\nusing FlyleafLib.MediaFramework.MediaDecoder;\nusing FlyleafLib.MediaFramework.MediaFrame;\nusing FlyleafLib.MediaFramework.MediaRenderer;\nusing FlyleafLib.MediaFramework.MediaPlaylist;\nusing FlyleafLib.MediaFramework.MediaDemuxer;\n\nusing static FlyleafLib.Utils;\nusing static FlyleafLib.Logger;\n\nnamespace FlyleafLib.MediaPlayer;\n\npublic unsafe partial class Player : NotifyPropertyChanged, IDisposable\n{\n #region Properties\n public bool IsDisposed { get; private set; }\n\n /// \n /// FlyleafHost (WinForms, WPF or WinUI)\n /// \n public IHostPlayer Host { get => _Host; set => Set(ref _Host, value); }\n IHostPlayer _Host;\n\n /// \n /// Player's Activity (Idle/Active/FullActive)\n /// \n public Activity Activity { get; private set; }\n\n /// \n /// Helper ICommands for WPF MVVM\n /// \n public Commands Commands { get; private set; }\n\n public Playlist Playlist => decoder.Playlist;\n\n /// \n /// Player's Audio (In/Out)\n /// \n public Audio Audio { get; private set; }\n\n /// \n /// Player's Video\n /// \n public Video Video { get; private set; }\n\n /// \n /// Player's Subtitles\n /// \n public Subtitles Subtitles { get; private set; }\n\n /// \n /// Player's Data\n /// \n public Data Data { get; private set; }\n\n /// \n /// Player's Renderer\n /// (Normally you should not access this directly)\n /// \n public Renderer renderer => decoder.VideoDecoder.Renderer;\n\n /// \n /// Player's Decoder Context\n /// (Normally you should not access this directly)\n /// \n public DecoderContext decoder { get; private set; }\n\n /// \n /// Audio Decoder\n /// (Normally you should not access this directly)\n /// \n public AudioDecoder AudioDecoder => decoder.AudioDecoder;\n\n /// \n /// Video Decoder\n /// (Normally you should not access this directly)\n /// \n public VideoDecoder VideoDecoder => decoder.VideoDecoder;\n\n /// \n /// Subtitles Decoder\n /// (Normally you should not access this directly)\n /// \n public SubtitlesDecoder[] SubtitlesDecoders => decoder.SubtitlesDecoders;\n\n /// \n /// Data Decoder\n /// (Normally you should not access this directly)\n /// \n public DataDecoder DataDecoder => decoder.DataDecoder;\n\n /// \n /// Main Demuxer (if video disabled or audio only can be AudioDemuxer instead of VideoDemuxer)\n /// (Normally you should not access this directly)\n /// \n public Demuxer MainDemuxer => decoder.MainDemuxer;\n\n /// \n /// Audio Demuxer\n /// (Normally you should not access this directly)\n /// \n public Demuxer AudioDemuxer => decoder.AudioDemuxer;\n\n /// \n /// Video Demuxer\n /// (Normally you should not access this directly)\n /// \n public Demuxer VideoDemuxer => decoder.VideoDemuxer;\n\n /// \n /// Subtitles Demuxer\n /// (Normally you should not access this directly)\n /// \n public Demuxer[] SubtitlesDemuxers => decoder.SubtitlesDemuxers;\n\n /// \n /// Subtitles Manager\n /// \n public SubtitlesManager SubtitlesManager => decoder.SubtitlesManager;\n\n /// \n /// Subtitles OCR\n /// \n public SubtitlesOCR SubtitlesOCR => decoder.SubtitlesOCR;\n\n /// \n /// Subtitles ASR\n /// \n public SubtitlesASR SubtitlesASR => decoder.SubtitlesASR;\n\n /// \n /// Data Demuxer\n /// (Normally you should not access this directly)\n /// \n public Demuxer DataDemuxer => decoder.DataDemuxer;\n\n\n /// \n /// Player's incremental unique id\n /// \n public int PlayerId { get; private set; }\n\n /// \n /// Player's configuration (set once in the constructor)\n /// \n public Config Config { get; protected set; }\n\n /// \n /// Player's Status\n /// \n public Status Status\n {\n get => status;\n private set\n {\n var prev = _Status;\n\n if (Set(ref _Status, value))\n {\n // Loop Playback\n if (value == Status.Ended)\n {\n if (LoopPlayback && !ReversePlayback)\n {\n int seekMs = (int)(MainDemuxer.StartTime == 0 ? 0 : MainDemuxer.StartTime / 10000);\n Seek(seekMs);\n }\n }\n\n if (prev == Status.Opening || value == Status.Opening)\n {\n Raise(nameof(IsOpening));\n }\n }\n }\n }\n\n Status _Status = Status.Stopped, status = Status.Stopped;\n public bool IsPlaying => status == Status.Playing;\n public bool IsOpening => status == Status.Opening;\n\n /// \n /// Whether the player's status is capable of accepting playback commands\n /// \n public bool CanPlay { get => canPlay; internal set => Set(ref _CanPlay, value); }\n internal bool _CanPlay, canPlay;\n\n /// \n /// The list of chapters\n /// \n public ObservableCollection\n Chapters => VideoDemuxer?.Chapters;\n\n /// \n /// Player's current time or user's current seek time (uses backward direction or accurate seek based on Config.Player.SeekAccurate)\n /// \n public long CurTime { get => curTime; set { if (Config.Player.SeekAccurate) SeekAccurate((int) (value/10000)); else Seek((int) (value/10000), false); } } // Note: forward seeking casues issues to some formats and can have serious delays (eg. dash with h264, dash with vp9 works fine)\n long _CurTime, curTime;\n internal void UpdateCurTime()\n {\n lock (seeks)\n {\n if (MainDemuxer == null || !seeks.IsEmpty)\n return;\n\n if (MainDemuxer.IsHLSLive)\n {\n curTime = MainDemuxer.CurTime; // *speed ?\n duration = MainDemuxer.Duration;\n Duration = Duration;\n }\n }\n\n if (Set(ref _CurTime, curTime, true, nameof(CurTime)))\n {\n Raise(nameof(RemainingDuration));\n }\n\n UpdateBufferedDuration();\n }\n internal void UpdateBufferedDuration()\n {\n if (_BufferedDuration != MainDemuxer.BufferedDuration)\n {\n _BufferedDuration = MainDemuxer.BufferedDuration;\n Raise(nameof(BufferedDuration));\n }\n }\n\n public long RemainingDuration => Duration - CurTime;\n\n /// \n /// Input's duration\n /// \n public long Duration\n {\n get => duration;\n private set\n {\n if (Set(ref _Duration, value))\n {\n Raise(nameof(RemainingDuration));\n }\n }\n }\n long _Duration, duration;\n\n /// \n /// Forces Player's and Demuxer's Duration to allow Seek\n /// \n /// Duration (Ticks)\n /// Demuxer must be opened before forcing the duration\n public void ForceDuration(long duration)\n {\n if (MainDemuxer == null)\n throw new ArgumentNullException(nameof(MainDemuxer));\n\n this.duration = duration;\n MainDemuxer.ForceDuration(duration);\n isLive = MainDemuxer.IsLive;\n UI(() =>\n {\n Duration= Duration;\n IsLive = IsLive;\n });\n }\n\n /// \n /// The current buffered duration in the demuxer\n /// \n public long BufferedDuration { get => MainDemuxer == null ? 0 : MainDemuxer.BufferedDuration;\n internal set => Set(ref _BufferedDuration, value); }\n long _BufferedDuration;\n\n /// \n /// Whether the input is live (duration might not be 0 on live sessions to allow live seek, eg. hls)\n /// \n public bool IsLive { get => isLive; private set => Set(ref _IsLive, value); }\n bool _IsLive, isLive;\n\n ///// \n ///// Total bitrate (Kbps)\n ///// \n public double BitRate { get => bitRate; internal set => Set(ref _BitRate, value); }\n internal double _BitRate, bitRate;\n\n /// \n /// Whether the player is recording\n /// \n public bool IsRecording\n {\n get => decoder != null && decoder.IsRecording;\n private set { if (_IsRecording == value) return; _IsRecording = value; UI(() => Set(ref _IsRecording, value, false)); }\n }\n bool _IsRecording;\n\n /// \n /// Pan X Offset to change the X location\n /// \n public int PanXOffset { get => renderer.PanXOffset; set { renderer.PanXOffset = value; Raise(nameof(PanXOffset)); } }\n\n /// \n /// Pan Y Offset to change the Y location\n /// \n public int PanYOffset { get => renderer.PanYOffset; set { renderer.PanYOffset = value; Raise(nameof(PanYOffset)); } }\n\n /// \n /// Playback's speed (x1 - x4)\n /// \n public double Speed {\n get => speed;\n set\n {\n double newValue = Math.Round(value, 3);\n if (value < 0.125)\n newValue = 0.125;\n else if (value > 16)\n newValue = 16;\n\n if (newValue == speed)\n return;\n\n AudioDecoder.Speed = newValue;\n VideoDecoder.Speed = newValue;\n speed = newValue;\n decoder.RequiresResync = true;\n requiresBuffering = true;\n for (int i = 0; i < subNum; i++)\n {\n sFramesPrev[i] = null;\n }\n SubtitleClear();\n UI(() =>\n {\n Raise(nameof(Speed));\n });\n }\n }\n double speed = 1;\n\n /// \n /// Pan zoom percentage (100 for 100%)\n /// \n public int Zoom\n {\n get => (int)(renderer.Zoom * 100);\n set { renderer.SetZoom(renderer.Zoom = value / 100.0); RaiseUI(nameof(Zoom)); }\n //set { renderer.SetZoomAndCenter(renderer.Zoom = value / 100.0, Renderer.ZoomCenterPoint); RaiseUI(nameof(Zoom)); } // should reset the zoom center point?\n }\n\n /// \n /// Pan rotation angle (for D3D11 VP allowed values are 0, 90, 180, 270 only)\n /// \n public uint Rotation { get => renderer.Rotation;\n set\n {\n renderer.Rotation = value;\n RaiseUI(nameof(Rotation));\n }\n }\n\n /// \n /// Pan Horizontal Flip (FlyleafVP only)\n /// \n public bool HFlip { get => renderer.HFlip; set => renderer.HFlip = value; }\n\n /// \n /// Pan Vertical Flip (FlyleafVP only)\n /// \n public bool VFlip { get => renderer.VFlip; set => renderer.VFlip = value; }\n\n /// \n /// Whether to use reverse playback mode\n /// \n public bool ReversePlayback\n {\n get => _ReversePlayback;\n\n set\n {\n if (_ReversePlayback == value)\n return;\n\n _ReversePlayback = value;\n UI(() => Set(ref _ReversePlayback, value, false));\n\n if (!Video.IsOpened || !CanPlay | IsLive)\n return;\n\n lock (lockActions)\n {\n bool shouldPlay = IsPlaying || (Status == Status.Ended && Config.Player.AutoPlay);\n Pause();\n dFrame = null;\n\n for (int i = 0; i < subNum; i++)\n {\n sFrames[i] = null;\n SubtitleClear(i);\n }\n\n decoder.StopThreads();\n decoder.Flush();\n\n if (Status == Status.Ended)\n {\n status = Status.Paused;\n UI(() => Status = Status);\n }\n\n if (value)\n {\n Speed = 1;\n VideoDemuxer.EnableReversePlayback(CurTime);\n }\n else\n {\n VideoDemuxer.DisableReversePlayback();\n\n var vFrame = VideoDecoder.GetFrame(VideoDecoder.GetFrameNumber(CurTime));\n VideoDecoder.DisposeFrame(vFrame);\n vFrame = null;\n decoder.RequiresResync = true;\n }\n\n reversePlaybackResync = false;\n if (shouldPlay) Play();\n }\n }\n }\n bool _ReversePlayback;\n\n public bool LoopPlayback { get; set => Set(ref field, value); }\n\n public object Tag { get => tag; set => Set(ref tag, value); }\n object tag;\n\n public string LastError { get => lastError; set => Set(ref _LastError, value); }\n string _LastError, lastError;\n\n public string OSDMessage { get; set => Set(ref field, value, false); }\n\n public event EventHandler KnownErrorOccurred;\n public event EventHandler UnknownErrorOccurred;\n\n bool decoderHasEnded => decoder != null && (VideoDecoder.Status == MediaFramework.Status.Ended || (VideoDecoder.Disposed && AudioDecoder.Status == MediaFramework.Status.Ended));\n #endregion\n\n #region Properties Internal\n readonly object lockActions = new();\n readonly object lockSubtitles= new();\n\n bool taskSeekRuns;\n bool taskPlayRuns;\n bool taskOpenAsyncRuns;\n\n readonly ConcurrentStack seeks = new();\n readonly ConcurrentQueue UIActions = new();\n\n internal AudioFrame aFrame;\n internal VideoFrame vFrame;\n internal SubtitlesFrame[] sFrames, sFramesPrev;\n internal DataFrame dFrame;\n internal PlayerStats stats = new();\n internal LogHandler Log;\n\n internal bool requiresBuffering;\n bool reversePlaybackResync;\n\n bool isVideoSwitch;\n bool isAudioSwitch;\n bool[] isSubsSwitches;\n bool isDataSwitch;\n #endregion\n\n public Player(Config config = null)\n {\n if (config != null)\n {\n if (config.Player.player != null)\n throw new Exception(\"Player's configuration is already assigned to another player\");\n\n Config = config;\n }\n else\n Config = new Config();\n\n PlayerId = GetUniqueId();\n Log = new LogHandler((\"[#\" + PlayerId + \"]\").PadRight(8, ' ') + \" [Player ] \");\n Log.Debug($\"Creating Player (Usage = {Config.Player.Usage})\");\n\n Activity = new Activity(this);\n Audio = new Audio(this);\n Video = new Video(this);\n Subtitles = new Subtitles(this);\n Data = new Data(this);\n Commands = new Commands(this);\n\n Config.SetPlayer(this);\n\n if (Config.Player.Usage == Usage.Audio)\n {\n Config.Video.Enabled = false;\n Config.Subtitles.Enabled = false;\n }\n\n decoder = new DecoderContext(Config, PlayerId) { Tag = this };\n Engine.AddPlayer(this);\n\n if (decoder.VideoDecoder.Renderer != null)\n decoder.VideoDecoder.Renderer.forceNotExtractor = true;\n\n //decoder.OpenPlaylistItemCompleted += Decoder_OnOpenExternalSubtitlesStreamCompleted;\n\n decoder.OpenAudioStreamCompleted += Decoder_OpenAudioStreamCompleted;\n decoder.OpenVideoStreamCompleted += Decoder_OpenVideoStreamCompleted;\n decoder.OpenSubtitlesStreamCompleted += Decoder_OpenSubtitlesStreamCompleted;\n decoder.OpenDataStreamCompleted += Decoder_OpenDataStreamCompleted;\n\n decoder.OpenExternalAudioStreamCompleted += Decoder_OpenExternalAudioStreamCompleted;\n decoder.OpenExternalVideoStreamCompleted += Decoder_OpenExternalVideoStreamCompleted;\n decoder.OpenExternalSubtitlesStreamCompleted += Decoder_OpenExternalSubtitlesStreamCompleted;\n\n AudioDecoder.CBufAlloc = () => { if (aFrame != null) aFrame.dataPtr = IntPtr.Zero; aFrame = null; Audio.ClearBuffer(); aFrame = null; };\n AudioDecoder.CodecChanged = Decoder_AudioCodecChanged;\n VideoDecoder.CodecChanged = Decoder_VideoCodecChanged;\n decoder.RecordingCompleted += (o, e) => { IsRecording = false; };\n Chapters.CollectionChanged += (o, e) => { RaiseUI(nameof(Chapters)); };\n\n // second subtitles\n sFrames = new SubtitlesFrame[subNum];\n sFramesPrev = new SubtitlesFrame[subNum];\n sDistanceMss = new int[subNum];\n isSubsSwitches = new bool[subNum];\n\n status = Status.Stopped;\n Reset();\n Log.Debug(\"Created\");\n }\n\n /// \n /// Disposes the Player and de-assigns it from FlyleafHost\n /// \n public void Dispose() => Engine.DisposePlayer(this);\n internal void DisposeInternal()\n {\n lock (lockActions)\n {\n if (IsDisposed)\n return;\n\n try\n {\n Initialize();\n Audio.Dispose();\n decoder.Dispose();\n Host?.Player_Disposed();\n Log.Info(\"Disposed\");\n } catch (Exception e) { Log.Warn($\"Disposed ({e.Message})\"); }\n\n IsDisposed = true;\n }\n }\n internal void RefreshMaxVideoFrames()\n {\n lock (lockActions)\n {\n if (!Video.isOpened)\n return;\n\n bool wasPlaying = IsPlaying;\n Pause();\n VideoDecoder.RefreshMaxVideoFrames();\n ReSync(decoder.VideoStream, (int) (CurTime / 10000), true);\n\n if (wasPlaying)\n Play();\n }\n }\n\n private void ResetMe()\n {\n canPlay = false;\n bitRate = 0;\n curTime = 0;\n duration = 0;\n isLive = false;\n lastError = null;\n\n UIAdd(() =>\n {\n BitRate = BitRate;\n Duration = Duration;\n IsLive = IsLive;\n Status = Status;\n CanPlay = CanPlay;\n LastError = LastError;\n BufferedDuration = 0;\n Set(ref _CurTime, curTime, true, nameof(CurTime));\n });\n }\n private void Reset()\n {\n ResetMe();\n Video.Reset();\n Audio.Reset();\n Subtitles.Reset();\n UIAll();\n }\n private void Initialize(Status status = Status.Stopped, bool andDecoder = true, bool isSwitch = false)\n {\n if (CanDebug) Log.Debug($\"Initializing\");\n\n lock (lockActions) // Required in case of OpenAsync and Stop requests\n {\n try\n {\n Engine.TimeBeginPeriod1();\n\n this.status = status;\n canPlay = false;\n isVideoSwitch = false;\n seeks.Clear();\n\n while (taskPlayRuns || taskSeekRuns) Thread.Sleep(5);\n\n if (andDecoder)\n {\n if (isSwitch)\n decoder.InitializeSwitch();\n else\n decoder.Initialize();\n }\n\n Reset();\n VideoDemuxer.DisableReversePlayback();\n ReversePlayback = false;\n\n if (CanDebug) Log.Debug($\"Initialized\");\n\n } catch (Exception e)\n {\n Log.Error($\"Initialize() Error: {e.Message}\");\n\n } finally\n {\n Engine.TimeEndPeriod1();\n }\n }\n }\n\n internal void UIAdd(Action action) => UIActions.Enqueue(action);\n internal void UIAll()\n {\n while (!UIActions.IsEmpty)\n if (UIActions.TryDequeue(out var action))\n UI(action);\n }\n\n public override bool Equals(object obj)\n => obj == null || !(obj is Player) ? false : ((Player)obj).PlayerId == PlayerId;\n public override int GetHashCode() => PlayerId.GetHashCode();\n\n // Avoid having this code in OnPaintBackground as it can cause designer issues (renderer will try to load FFmpeg.Autogen assembly because of HDR Data)\n internal bool WFPresent() { if (renderer == null || renderer.SCDisposed) return false; renderer?.Present(); return true; }\n\n internal void RaiseKnownErrorOccurred(string message, KnownErrorType errorType)\n {\n KnownErrorOccurred?.Invoke(this, new KnownErrorOccurredEventArgs\n {\n Message = message,\n ErrorType = errorType\n });\n }\n\n internal void RaiseUnknownErrorOccurred(string message, UnknownErrorType errorType, Exception exception = null)\n {\n UnknownErrorOccurred?.Invoke(this, new UnknownErrorOccurredEventArgs\n {\n Message = message,\n ErrorType = errorType,\n Exception = exception\n });\n }\n}\n\npublic enum KnownErrorType\n{\n Configuration,\n ASR\n}\n\npublic class KnownErrorOccurredEventArgs : EventArgs\n{\n public required string Message { get; init; }\n public required KnownErrorType ErrorType { get; init; }\n}\n\npublic enum UnknownErrorType\n{\n Translation,\n Subtitles,\n ASR,\n Playback,\n Network\n}\n\npublic class UnknownErrorOccurredEventArgs : EventArgs\n{\n public required string Message { get; init; }\n public required UnknownErrorType ErrorType { get; init; }\n public Exception Exception { get; init; }\n}\n\npublic enum Status\n{\n Opening,\n Failed,\n Stopped,\n Paused,\n Playing,\n Ended\n}\npublic enum Usage\n{\n AVS,\n Audio\n}\n"], ["/LLPlayer/FlyleafLib/Engine/Globals.cs", "global using System;\nglobal using Flyleaf.FFmpeg;\nglobal using static Flyleaf.FFmpeg.Raw;\n\nusing System.Collections.Generic;\nusing System.ComponentModel;\nusing System.Globalization;\nusing System.Runtime.CompilerServices;\nusing System.Text.RegularExpressions;\n\nnamespace FlyleafLib;\n\npublic enum PixelFormatType\n{\n Hardware,\n Software_Handled,\n Software_Sws\n}\npublic enum MediaType\n{\n Audio,\n Video,\n Subs,\n Data\n}\npublic enum InputType\n{\n File = 0,\n UNC = 1,\n Torrent = 2,\n Web = 3,\n Unknown = 4\n}\npublic enum HDRtoSDRMethod : int\n{\n None = 0,\n Aces = 1,\n Hable = 2,\n Reinhard = 3\n}\npublic enum VideoProcessors\n{\n Auto,\n D3D11,\n Flyleaf,\n}\npublic enum ZeroCopy : int\n{\n Auto = 0,\n Enabled = 1,\n Disabled = 2\n}\npublic enum ColorSpace : int\n{\n None = 0,\n BT601 = 1,\n BT709 = 2,\n BT2020 = 3\n}\npublic enum ColorRange : int\n{\n None = 0,\n Full = 1,\n Limited = 2\n}\n\npublic enum SubOCREngineType\n{\n Tesseract,\n MicrosoftOCR\n}\n\npublic enum SubASREngineType\n{\n [Description(\"whisper.cpp\")]\n WhisperCpp,\n [Description(\"faster-whisper (Recommended)\")]\n FasterWhisper\n}\n\npublic class GPUOutput\n{\n public static int GPUOutputIdGenerator;\n\n public int Id { get; set; }\n public string DeviceName { get; internal set; }\n public int Left { get; internal set; }\n public int Top { get; internal set; }\n public int Right { get; internal set; }\n public int Bottom { get; internal set; }\n public int Width => Right- Left;\n public int Height => Bottom- Top;\n public bool IsAttached { get; internal set; }\n public int Rotation { get; internal set; }\n\n public override string ToString()\n {\n int gcd = Utils.GCD(Width, Height);\n return $\"{DeviceName,-20} [Id: {Id,-4}\\t, Top: {Top,-4}, Left: {Left,-4}, Width: {Width,-4}, Height: {Height,-4}, Ratio: [\" + (gcd > 0 ? $\"{Width/gcd}:{Height/gcd}]\" : \"]\");\n }\n}\n\npublic class GPUAdapter\n{\n public int MaxHeight { get; internal set; }\n public nuint SystemMemory { get; internal set; }\n public nuint VideoMemory { get; internal set; }\n public nuint SharedMemory { get; internal set; }\n\n\n public uint Id { get; internal set; }\n public string Vendor { get; internal set; }\n public string Description { get; internal set; }\n public long Luid { get; internal set; }\n public bool HasOutput { get; internal set; }\n public List\n Outputs { get; internal set; }\n\n public override string ToString()\n => (Vendor + \" \" + Description).PadRight(40) + $\"[ID: {Id,-6}, LUID: {Luid,-6}, DVM: {Utils.GetBytesReadable(VideoMemory),-8}, DSM: {Utils.GetBytesReadable(SystemMemory),-8}, SSM: {Utils.GetBytesReadable(SharedMemory)}]\";\n}\npublic enum VideoFilters\n{\n // Ensure we have the same values with Vortice.Direct3D11.VideoProcessorFilterCaps (d3d11.h) | we can extended if needed with other values\n\n Brightness = 0x01,\n Contrast = 0x02,\n Hue = 0x04,\n Saturation = 0x08,\n NoiseReduction = 0x10,\n EdgeEnhancement = 0x20,\n AnamorphicScaling = 0x40,\n StereoAdjustment = 0x80\n}\n\npublic struct AspectRatio : IEquatable\n{\n public static readonly AspectRatio Keep = new(-1, 1);\n public static readonly AspectRatio Fill = new(-2, 1);\n public static readonly AspectRatio Custom = new(-3, 1);\n public static readonly AspectRatio Invalid = new(-999, 1);\n\n public static readonly List AspectRatios = new()\n {\n Keep,\n Fill,\n Custom,\n new AspectRatio(1, 1),\n new AspectRatio(4, 3),\n new AspectRatio(16, 9),\n new AspectRatio(16, 10),\n new AspectRatio(2.35f, 1),\n };\n\n public static implicit operator AspectRatio(string value) => new AspectRatio(value);\n\n public float Num { get; set; }\n public float Den { get; set; }\n\n public float Value\n {\n get => Num / Den;\n set { Num = value; Den = 1; }\n }\n\n public string ValueStr\n {\n get => ToString();\n set => FromString(value);\n }\n\n public AspectRatio(float value) : this(value, 1) { }\n public AspectRatio(float num, float den) { Num = num; Den = den; }\n public AspectRatio(string value) { Num = Invalid.Num; Den = Invalid.Den; FromString(value); }\n\n public bool Equals(AspectRatio other) => Num == other.Num && Den == other.Den;\n public override bool Equals(object obj) => obj is AspectRatio o && Equals(o);\n public override int GetHashCode() => HashCode.Combine(Num, Den);\n public static bool operator ==(AspectRatio a, AspectRatio b) => a.Equals(b);\n public static bool operator !=(AspectRatio a, AspectRatio b) => !(a == b);\n\n public void FromString(string value)\n {\n if (value == \"Keep\")\n { Num = Keep.Num; Den = Keep.Den; return; }\n else if (value == \"Fill\")\n { Num = Fill.Num; Den = Fill.Den; return; }\n else if (value == \"Custom\")\n { Num = Custom.Num; Den = Custom.Den; return; }\n else if (value == \"Invalid\")\n { Num = Invalid.Num; Den = Invalid.Den; return; }\n\n string newvalue = value.ToString().Replace(',', '.');\n\n if (Regex.IsMatch(newvalue.ToString(), @\"^\\s*[0-9\\.]+\\s*[:/]\\s*[0-9\\.]+\\s*$\"))\n {\n string[] values = newvalue.ToString().Split(':');\n if (values.Length < 2)\n values = newvalue.ToString().Split('/');\n\n Num = float.Parse(values[0], NumberStyles.Any, CultureInfo.InvariantCulture);\n Den = float.Parse(values[1], NumberStyles.Any, CultureInfo.InvariantCulture);\n }\n\n else if (float.TryParse(newvalue.ToString(), NumberStyles.Any, CultureInfo.InvariantCulture, out float result))\n { Num = result; Den = 1; }\n\n else\n { Num = Invalid.Num; Den = Invalid.Den; }\n }\n public override string ToString() => this == Keep ? \"Keep\" : (this == Fill ? \"Fill\" : (this == Custom ? \"Custom\" : (this == Invalid ? \"Invalid\" : $\"{Num}:{Den}\")));\n}\n\nclass PlayerStats\n{\n public long TotalBytes { get; set; }\n public long VideoBytes { get; set; }\n public long AudioBytes { get; set; }\n public long FramesDisplayed { get; set; }\n}\npublic class NotifyPropertyChanged : INotifyPropertyChanged\n{\n public event PropertyChangedEventHandler PropertyChanged;\n\n //public bool DisableNotifications { get; set; }\n\n //private static bool IsUI() => System.Threading.Thread.CurrentThread.ManagedThreadId == System.Windows.Application.Current.Dispatcher.Thread.ManagedThreadId;\n\n protected bool Set(ref T field, T value, bool check = true, [CallerMemberName] string propertyName = \"\")\n {\n //Utils.Log($\"[===| {propertyName} |===] | Set | {IsUI()}\");\n\n if (!check || !EqualityComparer.Default.Equals(field, value))\n {\n field = value;\n\n //if (!DisableNotifications)\n PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));\n\n return true;\n }\n\n return false;\n }\n\n protected bool SetUI(ref T field, T value, bool check = true, [CallerMemberName] string propertyName = \"\")\n {\n //Utils.Log($\"[===| {propertyName} |===] | SetUI | {IsUI()}\");\n\n if (!check || !EqualityComparer.Default.Equals(field, value))\n {\n field = value;\n\n //if (!DisableNotifications)\n Utils.UI(() => PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName)));\n\n return true;\n }\n\n return false;\n }\n protected void Raise([CallerMemberName] string propertyName = \"\")\n {\n //Utils.Log($\"[===| {propertyName} |===] | Raise | {IsUI()}\");\n\n //if (!DisableNotifications)\n PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));\n }\n\n\n protected void RaiseUI([CallerMemberName] string propertyName = \"\")\n {\n //Utils.Log($\"[===| {propertyName} |===] | RaiseUI | {IsUI()}\");\n\n //if (!DisableNotifications)\n Utils.UI(() => PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName)));\n }\n}\n"], ["/LLPlayer/LLPlayer/Services/OpenSubtitlesProvider.cs", "using System.IO;\nusing System.IO.Compression;\nusing System.Net.Http;\nusing System.Text;\nusing System.Xml.Serialization;\nusing FlyleafLib;\nusing LLPlayer.Extensions;\n\nnamespace LLPlayer.Services;\n\npublic class OpenSubtitlesProvider\n{\n private readonly FlyleafManager FL;\n private readonly HttpClient _client;\n private string? _token;\n private bool _initialized = false;\n\n public OpenSubtitlesProvider(FlyleafManager fl)\n {\n FL = fl;\n HttpClient client = new();\n client.BaseAddress = new Uri(\"http://api.opensubtitles.org/xml-rpc\");\n client.Timeout = TimeSpan.FromSeconds(15);\n\n _client = client;\n }\n\n private readonly SemaphoreSlim _loginSemaphore = new(1);\n\n private async Task Initialize()\n {\n if (!_initialized)\n {\n try\n {\n await _loginSemaphore.WaitAsync();\n await Login();\n _initialized = true;\n }\n finally\n {\n _loginSemaphore.Release();\n }\n }\n }\n\n /// \n /// Login\n /// \n /// \n /// \n /// \n private async Task Login()\n {\n string loginReqXml =\n\"\"\"\n\n\n LogIn\n \n \n \n \n \n \n \n \n \n \n \n \n en\n \n \n VLsub 0.10.2\n \n \n\n\"\"\";\n\n var result = await _client.PostAsync(string.Empty, new StringContent(loginReqXml));\n var content = await result.Content.ReadAsStringAsync();\n\n var serializer = new XmlSerializer(typeof(MethodResponse));\n LoginResponse loginResponse = new();\n using (var reader = new StringReader(content))\n {\n MethodResponse? response = null;\n try\n {\n result.EnsureSuccessStatusCode();\n response = serializer.Deserialize(reader) as MethodResponse;\n if (response == null)\n {\n throw new InvalidOperationException(\"response is not MethodResponse\");\n }\n }\n catch (Exception ex)\n {\n throw new InvalidOperationException($\"Can't parse the login content: {ex.Message}\", ex)\n {\n Data =\n {\n [\"status_code\"] = ((int)result.StatusCode).ToString(),\n [\"login_content\"] = content\n }\n };\n }\n\n foreach (var member in response.Params.Param.Value.Struct.Member)\n {\n var propertyName = member.Name.ToUpperFirstChar();\n switch (propertyName)\n {\n case nameof(loginResponse.Token):\n loginResponse.Token = member.Value.String;\n break;\n case nameof(loginResponse.Status):\n loginResponse.Status = member.Value.String;\n break;\n }\n }\n }\n\n if (loginResponse.StatusCode != \"200\")\n throw new InvalidOperationException($\"Can't login because status is '{loginResponse.StatusCode}'\");\n\n if (string.IsNullOrWhiteSpace(loginResponse.Token))\n throw new InvalidOperationException(\"Can't login because token is empty\");\n\n _token = loginResponse.Token;\n }\n\n\n /// \n /// Search\n /// \n /// \n /// \n /// \n /// \n public async Task> Search(string query)\n {\n await Initialize();\n\n if (_token == null)\n throw new InvalidOperationException(\"token is not initialized\");\n\n var subLanguageId = \"all\";\n var limit = 500;\n\n string searchReqXml =\n$\"\"\"\n\n\n SearchSubtitles\n \n \n {_token}\n \n \n \n \n \n \n \n \n query\n {query}\n \n \n sublanguageid\n {subLanguageId}\n \n \n \n \n \n \n \n \n \n \n \n limit\n \n {limit}\n \n \n \n \n \n \n\n\"\"\";\n\n var result = await _client.PostAsync(string.Empty, new StringContent(searchReqXml));\n var content = await result.Content.ReadAsStringAsync();\n\n var serializer = new XmlSerializer(typeof(MethodResponse));\n\n List searchResponses = new();\n\n using (StringReader reader = new(content))\n {\n MethodResponse? response = null;\n try\n {\n result.EnsureSuccessStatusCode();\n response = serializer.Deserialize(reader) as MethodResponse;\n if (response == null)\n {\n throw new InvalidOperationException(\"response is not MethodResponse\");\n }\n }\n catch (Exception ex)\n {\n throw new InvalidOperationException($\"Can't parse the search content: {ex.Message}\", ex)\n {\n Data =\n {\n [\"status_code\"] = ((int)result.StatusCode).ToString(),\n [\"search_content\"] = content\n }\n };\n }\n\n if (!response.Params.Param.Value.Struct.Member.Any(m => m.Name == \"status\" && m.Value.String == \"200 OK\"))\n throw new InvalidOperationException(\"Can't get the search result, status is not 200.\");\n\n var resultMembers = response.Params.Param.Value.Struct.Member.FirstOrDefault(m => m.Name == \"data\");\n if (resultMembers == null)\n throw new InvalidOperationException(\"Can't get the search result, data is not found.\");\n\n foreach (var record in resultMembers.Value.Array.Data.Value)\n {\n SearchResponse searchResponse = new();\n foreach (var member in record.Struct.Member)\n {\n var propertyName = member.Name.ToUpperFirstChar();\n\n var property = typeof(SearchResponse).GetProperty(propertyName);\n if (property != null && property.CanWrite)\n {\n switch (Type.GetTypeCode(property.PropertyType))\n {\n case TypeCode.Int32:\n if (member.Value.String != null &&\n int.TryParse(member.Value.String, out var n))\n {\n property.SetValue(searchResponse, n);\n }\n else\n {\n property.SetValue(searchResponse, member.Value.Int);\n }\n break;\n\n case TypeCode.Double:\n if (member.Value.String != null &&\n double.TryParse(member.Value.String, out var d))\n {\n property.SetValue(searchResponse, d);\n }\n else\n {\n property.SetValue(searchResponse, member.Value.Double);\n }\n break;\n\n case TypeCode.String:\n property.SetValue(searchResponse, member.Value.String);\n break;\n }\n }\n }\n\n searchResponses.Add(searchResponse);\n }\n }\n\n return searchResponses;\n }\n\n /// \n /// Download\n /// \n /// \n /// \n /// \n /// \n public async Task<(byte[] data, bool isBitmap)> Download(SearchResponse sub)\n {\n await Initialize();\n\n if (_token == null)\n throw new InvalidOperationException(\"token is not initialized\");\n\n var idSubtitleFile = sub.IDSubtitleFile;\n var isBitmap = sub.SubFormat.ToLower() == \"sub\";\n\n string downloadReqXml =\n$\"\"\"\n \n \n DownloadSubtitles\n \n \n {_token}\n \n \n \n \n \n {idSubtitleFile}\n \n \n \n \n \n \n \"\"\";\n\n var result = await _client.PostAsync(string.Empty, new StringContent(downloadReqXml));\n var content = await result.Content.ReadAsStringAsync();\n\n XmlSerializer serializer = new(typeof(MethodResponse));\n\n DownloadResponse downloadResponse = new();\n\n using (StringReader reader = new(content))\n {\n MethodResponse? response = null;\n try\n {\n result.EnsureSuccessStatusCode();\n response = serializer.Deserialize(reader) as MethodResponse;\n if (response == null)\n {\n throw new InvalidOperationException(\"response is not MethodResponse\");\n }\n }\n catch (Exception ex)\n {\n throw new InvalidOperationException($\"Can't parse the download content: {ex.Message}\", ex)\n {\n Data =\n {\n [\"status_code\"] = ((int)result.StatusCode).ToString(),\n [\"download_content\"] = content\n }\n };\n }\n\n if (!response.Params.Param.Value.Struct.Member.Any(m => m.Name == \"status\" && m.Value.String == \"200 OK\"))\n throw new InvalidOperationException(\"Can't get the download result, status is not 200.\");\n\n var resultMembers = response.Params.Param.Value.Struct.Member.FirstOrDefault(m => m.Name == \"data\");\n if (resultMembers == null)\n throw new InvalidOperationException(\"Can't get the download result, data is not found.\");\n\n var data = resultMembers.Value.Array.Data.Value.First();\n\n foreach (var member in data.Struct.Member)\n {\n var propertyName = member.Name.ToUpperFirstChar();\n switch (propertyName)\n {\n case nameof(downloadResponse.Data):\n downloadResponse.Data = member.Value.String;\n break;\n case nameof(downloadResponse.Idsubtitlefile):\n downloadResponse.Idsubtitlefile = member.Value.String;\n break;\n }\n }\n }\n\n if (string.IsNullOrEmpty(downloadResponse.Data))\n throw new InvalidOperationException(\"Can't get the download result, base64 data is not found.\");\n\n var gzipSub = Convert.FromBase64String(downloadResponse.Data);\n byte[]? subData;\n\n using MemoryStream compressedStream = new(gzipSub);\n using (GZipStream gzipStream = new(compressedStream, CompressionMode.Decompress))\n using (MemoryStream resultStream = new())\n {\n gzipStream.CopyTo(resultStream);\n subData = resultStream.ToArray();\n }\n\n if (subData == null)\n throw new InvalidOperationException(\"Can't get the download result, decompressed data is not found.\");\n\n if (isBitmap)\n {\n return (subData, true);\n }\n\n Encoding? encoding = TextEncodings.DetectEncoding(subData);\n encoding ??= Encoding.UTF8;\n\n // If there is originally a BOM, it will remain even if it is converted to a string, so delete it.\n string subString = encoding.GetString(subData).TrimStart('\\uFEFF');\n\n // Convert to UTF-8 and return\n byte[] subText = Encoding.UTF8.GetBytes(subString);\n\n if (FL.Config.Subs.SubsExportUTF8WithBom)\n {\n // append BOM\n subText = Encoding.UTF8.GetPreamble().Concat(subText).ToArray();\n }\n\n return (subText, false);\n }\n}\n\n\npublic class LoginResponse\n{\n public string? Token { get; set; }\n public string? Status { get; set; }\n public string? StatusCode => Status?.Split(' ')[0];\n}\n\npublic class SearchResponse\n{\n public string IDSubtitleFile { get; set; } = \"\";\n public string SubFileName { get; set; } = \"\";\n public int SubSize { get; set; } // from string\n public string SubLastTS { get; set; } = \"\";\n public string IDSubtitle { get; set; } = \"\";\n public string SubLanguageID { get; set; } = \"\";\n public string SubFormat { get; set; } = \"\";\n public string SubAddDate { get; set; } = \"\";\n public double SubRating { get; set; } // from string\n public string SubSumVotes { get; set; } = \"\";\n public int SubDownloadsCnt { get; set; } // from string\n public string MovieName { get; set; } = \"\";\n public string MovieYear { get; set; } = \"\";\n public string MovieKind { get; set; } = \"\";\n public string ISO639 { get; set; } = \"\";\n public string LanguageName { get; set; } = \"\";\n public string SeriesSeason { get; set; } = \"\";\n public string SeriesEpisode { get; set; } = \"\";\n public string SubEncoding { get; set; } = \"\";\n public string SubDownloadLink { get; set; } = \"\";\n public string SubtitlesLink { get; set; } = \"\";\n public double Score { get; set; }\n}\n\npublic class DownloadResponse\n{\n public string? Data { get; set; }\n public string? Idsubtitlefile { get; set; }\n}\n\n[XmlRoot(\"value\")]\npublic class Value\n{\n [XmlElement(\"string\")]\n public string? String { get; set; }\n\n [XmlElement(\"struct\")]\n public Struct Struct { get; set; } = null!;\n\n [XmlElement(\"int\")]\n public int Int { get; set; }\n\n [XmlElement(\"double\")]\n public double Double { get; set; }\n\n [XmlElement(\"array\")]\n public Array Array { get; set; } = null!;\n}\n\n[XmlRoot(\"member\")]\npublic class Member\n{\n [XmlElement(\"name\")]\n public string Name { get; set; } = null!;\n\n [XmlElement(\"value\")]\n public Value Value { get; set; } = null!;\n}\n\n[XmlRoot(\"struct\")]\npublic class Struct\n{\n [XmlElement(\"member\")]\n public List Member { get; set; } = null!;\n}\n\n[XmlRoot(\"data\")]\npublic class Data\n{\n [XmlElement(\"value\")]\n public List Value { get; set; } = null!;\n}\n\n[XmlRoot(\"array\")]\npublic class Array\n{\n [XmlElement(\"data\")]\n public Data Data { get; set; } = null!;\n}\n\n[XmlRoot(\"param\")]\npublic class Param\n{\n [XmlElement(\"value\")]\n public Value Value { get; set; } = null!;\n}\n\n[XmlRoot(\"params\")]\npublic class Params\n{\n [XmlElement(\"param\")]\n public Param Param { get; set; } = null!;\n}\n\n[XmlRoot(\"methodResponse\")]\npublic class MethodResponse\n{\n [XmlElement(\"params\")]\n public Params Params { get; set; } = null!;\n}\n"], ["/LLPlayer/FlyleafLib/MediaFramework/MediaRenderer/Renderer.VideoProcessor.cs", "using System.Collections.Generic;\nusing System.Numerics;\nusing System.Text.Json.Serialization;\nusing Vortice.DXGI;\nusing Vortice.Direct3D11;\n\nusing ID3D11VideoContext = Vortice.Direct3D11.ID3D11VideoContext;\n\nusing FlyleafLib.Controls.WPF;\nusing FlyleafLib.MediaPlayer;\n\nusing static FlyleafLib.Logger;\nusing static FlyleafLib.Utils;\n\nnamespace FlyleafLib.MediaFramework.MediaRenderer;\n\nunsafe public partial class Renderer\n{\n /* TODO\n * 1) Try to sync filters between Flyleaf and D3D11 video processors so we will not have to reset on change\n * 2) Filter default values will change when the device/adapter is changed\n */\n\n public static Dictionary VideoProcessorsCapsCache = new();\n\n internal static VideoProcessorFilter ConvertFromVideoProcessorFilterCaps(VideoProcessorFilterCaps filter)\n {\n switch (filter)\n {\n case VideoProcessorFilterCaps.Brightness:\n return VideoProcessorFilter.Brightness;\n case VideoProcessorFilterCaps.Contrast:\n return VideoProcessorFilter.Contrast;\n case VideoProcessorFilterCaps.Hue:\n return VideoProcessorFilter.Hue;\n case VideoProcessorFilterCaps.Saturation:\n return VideoProcessorFilter.Saturation;\n case VideoProcessorFilterCaps.EdgeEnhancement:\n return VideoProcessorFilter.EdgeEnhancement;\n case VideoProcessorFilterCaps.NoiseReduction:\n return VideoProcessorFilter.NoiseReduction;\n case VideoProcessorFilterCaps.AnamorphicScaling:\n return VideoProcessorFilter.AnamorphicScaling;\n case VideoProcessorFilterCaps.StereoAdjustment:\n return VideoProcessorFilter.StereoAdjustment;\n\n default:\n return VideoProcessorFilter.StereoAdjustment;\n }\n }\n internal static VideoProcessorFilterCaps ConvertFromVideoProcessorFilter(VideoProcessorFilter filter)\n {\n switch (filter)\n {\n case VideoProcessorFilter.Brightness:\n return VideoProcessorFilterCaps.Brightness;\n case VideoProcessorFilter.Contrast:\n return VideoProcessorFilterCaps.Contrast;\n case VideoProcessorFilter.Hue:\n return VideoProcessorFilterCaps.Hue;\n case VideoProcessorFilter.Saturation:\n return VideoProcessorFilterCaps.Saturation;\n case VideoProcessorFilter.EdgeEnhancement:\n return VideoProcessorFilterCaps.EdgeEnhancement;\n case VideoProcessorFilter.NoiseReduction:\n return VideoProcessorFilterCaps.NoiseReduction;\n case VideoProcessorFilter.AnamorphicScaling:\n return VideoProcessorFilterCaps.AnamorphicScaling;\n case VideoProcessorFilter.StereoAdjustment:\n return VideoProcessorFilterCaps.StereoAdjustment;\n\n default:\n return VideoProcessorFilterCaps.StereoAdjustment;\n }\n }\n internal static VideoFilter ConvertFromVideoProcessorFilterRange(VideoProcessorFilterRange filter) => new()\n {\n Minimum = filter.Minimum,\n Maximum = filter.Maximum,\n Value = filter.Default,\n Step = filter.Multiplier\n };\n\n VideoColor D3D11VPBackgroundColor;\n ID3D11VideoDevice1 vd1;\n ID3D11VideoProcessor vp;\n ID3D11VideoContext vc;\n ID3D11VideoProcessorEnumerator vpe;\n ID3D11VideoProcessorInputView vpiv;\n ID3D11VideoProcessorOutputView vpov;\n\n VideoProcessorStream[] vpsa = new VideoProcessorStream[] { new VideoProcessorStream() { Enable = true } };\n VideoProcessorContentDescription vpcd = new()\n {\n Usage = VideoUsage.PlaybackNormal,\n InputFrameFormat = VideoFrameFormat.InterlacedTopFieldFirst,\n\n InputFrameRate = new Rational(1, 1),\n OutputFrameRate = new Rational(1, 1),\n };\n VideoProcessorOutputViewDescription vpovd = new() { ViewDimension = VideoProcessorOutputViewDimension.Texture2D };\n VideoProcessorInputViewDescription vpivd = new()\n {\n FourCC = 0,\n ViewDimension = VideoProcessorInputViewDimension.Texture2D,\n Texture2D = new Texture2DVideoProcessorInputView() { MipSlice = 0, ArraySlice = 0 }\n };\n VideoProcessorColorSpace inputColorSpace;\n VideoProcessorColorSpace outputColorSpace;\n\n AVDynamicHDRPlus* hdrPlusData = null;\n AVContentLightMetadata lightData = new();\n AVMasteringDisplayMetadata displayData = new();\n\n uint actualRotation;\n bool actualHFlip, actualVFlip;\n bool configLoadedChecked;\n\n void InitializeVideoProcessor()\n {\n lock (VideoProcessorsCapsCache)\n try\n {\n vpcd.InputWidth = 1;\n vpcd.InputHeight= 1;\n vpcd.OutputWidth = vpcd.InputWidth;\n vpcd.OutputHeight= vpcd.InputHeight;\n\n outputColorSpace = new VideoProcessorColorSpace()\n {\n Usage = 0,\n RGB_Range = 0,\n YCbCr_Matrix = 1,\n YCbCr_xvYCC = 0,\n Nominal_Range = 2\n };\n\n if (VideoProcessorsCapsCache.ContainsKey(Device.Tag.ToString()))\n {\n if (VideoProcessorsCapsCache[Device.Tag.ToString()].Failed)\n {\n InitializeFilters();\n return;\n }\n\n vd1 = Device.QueryInterface();\n vc = context.QueryInterface();\n\n vd1.CreateVideoProcessorEnumerator(ref vpcd, out vpe);\n\n if (vpe == null)\n {\n VPFailed();\n return;\n }\n\n // if (!VideoProcessorsCapsCache[Device.Tag.ToString()].TypeIndex != -1)\n vd1.CreateVideoProcessor(vpe, (uint)VideoProcessorsCapsCache[Device.Tag.ToString()].TypeIndex, out vp);\n InitializeFilters();\n\n return;\n }\n\n VideoProcessorCapsCache cache = new();\n VideoProcessorsCapsCache.Add(Device.Tag.ToString(), cache);\n\n vd1 = Device.QueryInterface();\n vc = context.QueryInterface();\n\n vd1.CreateVideoProcessorEnumerator(ref vpcd, out vpe);\n\n if (vpe == null || Device.FeatureLevel < Vortice.Direct3D.FeatureLevel.Level_10_0)\n {\n VPFailed();\n return;\n }\n\n var vpe1 = vpe.QueryInterface();\n bool supportHLG = vpe1.CheckVideoProcessorFormatConversion(Format.P010, ColorSpaceType.YcbcrStudioGhlgTopLeftP2020, Format.B8G8R8A8_UNorm, ColorSpaceType.RgbFullG22NoneP709);\n bool supportHDR10Limited = vpe1.CheckVideoProcessorFormatConversion(Format.P010, ColorSpaceType.YcbcrStudioG2084TopLeftP2020, Format.B8G8R8A8_UNorm, ColorSpaceType.RgbStudioG2084NoneP2020);\n\n var vpCaps = vpe.VideoProcessorCaps;\n string dump = \"\";\n\n if (CanDebug)\n {\n dump += $\"=====================================================\\r\\n\";\n dump += $\"MaxInputStreams {vpCaps.MaxInputStreams}\\r\\n\";\n dump += $\"MaxStreamStates {vpCaps.MaxStreamStates}\\r\\n\";\n dump += $\"HDR10 Limited {(supportHDR10Limited ? \"yes\" : \"no\")}\\r\\n\";\n dump += $\"HLG {(supportHLG ? \"yes\" : \"no\")}\\r\\n\";\n\n dump += $\"\\n[Video Processor Device Caps]\\r\\n\";\n foreach (VideoProcessorDeviceCaps cap in Enum.GetValues(typeof(VideoProcessorDeviceCaps)))\n dump += $\"{cap,-25} {((vpCaps.DeviceCaps & cap) != 0 ? \"yes\" : \"no\")}\\r\\n\";\n\n dump += $\"\\n[Video Processor Feature Caps]\\r\\n\";\n foreach (VideoProcessorFeatureCaps cap in Enum.GetValues(typeof(VideoProcessorFeatureCaps)))\n dump += $\"{cap,-25} {((vpCaps.FeatureCaps & cap) != 0 ? \"yes\" : \"no\")}\\r\\n\";\n\n dump += $\"\\n[Video Processor Stereo Caps]\\r\\n\";\n foreach (VideoProcessorStereoCaps cap in Enum.GetValues(typeof(VideoProcessorStereoCaps)))\n dump += $\"{cap,-25} {((vpCaps.StereoCaps & cap) != 0 ? \"yes\" : \"no\")}\\r\\n\";\n\n dump += $\"\\n[Video Processor Input Format Caps]\\r\\n\";\n foreach (VideoProcessorFormatCaps cap in Enum.GetValues(typeof(VideoProcessorFormatCaps)))\n dump += $\"{cap,-25} {((vpCaps.InputFormatCaps & cap) != 0 ? \"yes\" : \"no\")}\\r\\n\";\n\n dump += $\"\\n[Video Processor Filter Caps]\\r\\n\";\n }\n\n foreach (VideoProcessorFilterCaps filter in Enum.GetValues(typeof(VideoProcessorFilterCaps)))\n if ((vpCaps.FilterCaps & filter) != 0)\n {\n vpe1.GetVideoProcessorFilterRange(ConvertFromVideoProcessorFilterCaps(filter), out var range);\n if (CanDebug) dump += $\"{filter,-25} [{range.Minimum,6} - {range.Maximum,4}] | x{range.Multiplier,4} | *{range.Default}\\r\\n\";\n var vf = ConvertFromVideoProcessorFilterRange(range);\n vf.Filter = (VideoFilters)filter;\n cache.Filters.Add((VideoFilters)filter, vf);\n }\n else if (CanDebug)\n dump += $\"{filter,-25} no\\r\\n\";\n\n if (CanDebug)\n {\n dump += $\"\\n[Video Processor Input Format Caps]\\r\\n\";\n foreach (VideoProcessorAutoStreamCaps cap in Enum.GetValues(typeof(VideoProcessorAutoStreamCaps)))\n dump += $\"{cap,-25} {((vpCaps.AutoStreamCaps & cap) != 0 ? \"yes\" : \"no\")}\\r\\n\";\n }\n\n uint typeIndex = 0;\n VideoProcessorRateConversionCaps rcCap = new();\n for (uint i = 0; i < vpCaps.RateConversionCapsCount; i++)\n {\n vpe.GetVideoProcessorRateConversionCaps(i, out rcCap);\n VideoProcessorProcessorCaps pCaps = (VideoProcessorProcessorCaps) rcCap.ProcessorCaps;\n\n if (CanDebug)\n {\n dump += $\"\\n[Video Processor Rate Conversion Caps #{i}]\\r\\n\";\n\n dump += $\"\\n\\t[Video Processor Rate Conversion Caps]\\r\\n\";\n var fields = typeof(VideoProcessorRateConversionCaps).GetFields();\n foreach (var field in fields)\n dump += $\"\\t{field.Name,-35} {field.GetValue(rcCap)}\\r\\n\";\n\n dump += $\"\\n\\t[Video Processor Processor Caps]\\r\\n\";\n foreach (VideoProcessorProcessorCaps cap in Enum.GetValues(typeof(VideoProcessorProcessorCaps)))\n dump += $\"\\t{cap,-35} {(((VideoProcessorProcessorCaps)rcCap.ProcessorCaps & cap) != 0 ? \"yes\" : \"no\")}\\r\\n\";\n }\n\n typeIndex = i;\n\n if (((VideoProcessorProcessorCaps)rcCap.ProcessorCaps & VideoProcessorProcessorCaps.DeinterlaceBob) != 0)\n break; // TBR: When we add past/future frames support\n }\n vpe1.Dispose();\n\n if (CanDebug) Log.Debug($\"D3D11 Video Processor\\r\\n{dump}\");\n\n cache.TypeIndex = (int)typeIndex;\n cache.HLG = supportHLG;\n cache.HDR10Limited = supportHDR10Limited;\n cache.VideoProcessorCaps = vpCaps;\n cache.VideoProcessorRateConversionCaps = rcCap;\n\n //if (typeIndex != -1)\n vd1.CreateVideoProcessor(vpe, (uint)typeIndex, out vp);\n if (vp == null)\n {\n VPFailed();\n return;\n }\n\n cache.Failed = false;\n Log.Info($\"D3D11 Video Processor Initialized (Rate Caps #{typeIndex})\");\n\n } catch { DisposeVideoProcessor(); Log.Error($\"D3D11 Video Processor Initialization Failed\"); }\n\n InitializeFilters();\n }\n void VPFailed()\n {\n Log.Error($\"D3D11 Video Processor Initialization Failed\");\n\n if (!VideoProcessorsCapsCache.ContainsKey(Device.Tag.ToString()))\n VideoProcessorsCapsCache.Add(Device.Tag.ToString(), new VideoProcessorCapsCache());\n VideoProcessorsCapsCache[Device.Tag.ToString()].Failed = true;\n\n VideoProcessorsCapsCache[Device.Tag.ToString()].Filters.Add(VideoFilters.Brightness, new VideoFilter() { Filter = VideoFilters.Brightness });\n VideoProcessorsCapsCache[Device.Tag.ToString()].Filters.Add(VideoFilters.Contrast, new VideoFilter() { Filter = VideoFilters.Contrast });\n\n DisposeVideoProcessor();\n InitializeFilters();\n }\n void DisposeVideoProcessor()\n {\n vpiv?.Dispose();\n vpov?.Dispose();\n vp?. Dispose();\n vpe?. Dispose();\n vc?. Dispose();\n vd1?. Dispose();\n\n vc = null;\n }\n void InitializeFilters()\n {\n Filters = VideoProcessorsCapsCache[Device.Tag.ToString()].Filters;\n\n // Add FLVP filters if D3D11VP does not support them\n if (!Filters.ContainsKey(VideoFilters.Brightness))\n Filters.Add(VideoFilters.Brightness, new VideoFilter(VideoFilters.Brightness));\n\n if (!Filters.ContainsKey(VideoFilters.Contrast))\n Filters.Add(VideoFilters.Contrast, new VideoFilter(VideoFilters.Contrast));\n\n foreach(var filter in Filters.Values)\n {\n if (!Config.Video.Filters.ContainsKey(filter.Filter))\n continue;\n\n var cfgFilter = Config.Video.Filters[filter.Filter];\n cfgFilter.Available = true;\n cfgFilter.renderer = this;\n\n if (!configLoadedChecked && !Config.Loaded)\n {\n cfgFilter.Minimum = filter.Minimum;\n cfgFilter.Maximum = filter.Maximum;\n cfgFilter.DefaultValue = filter.Value;\n cfgFilter.Value = filter.Value;\n cfgFilter.Step = filter.Step;\n }\n\n UpdateFilterValue(cfgFilter);\n }\n\n configLoadedChecked = true;\n UpdateBackgroundColor();\n\n if (vc != null)\n {\n vc.VideoProcessorSetStreamAutoProcessingMode(vp, 0, false);\n vc.VideoProcessorSetStreamFrameFormat(vp, 0, !Config.Video.Deinterlace ? VideoFrameFormat.Progressive : (Config.Video.DeinterlaceBottomFirst ? VideoFrameFormat.InterlacedBottomFieldFirst : VideoFrameFormat.InterlacedTopFieldFirst));\n }\n\n // Reset FLVP filters to defaults (can be different from D3D11VP filters scaling)\n if (videoProcessor == VideoProcessors.Flyleaf)\n {\n Config.Video.Filters[VideoFilters.Brightness].Value = Config.Video.Filters[VideoFilters.Brightness].Minimum + ((Config.Video.Filters[VideoFilters.Brightness].Maximum - Config.Video.Filters[VideoFilters.Brightness].Minimum) / 2);\n Config.Video.Filters[VideoFilters.Contrast].Value = Config.Video.Filters[VideoFilters.Contrast].Minimum + ((Config.Video.Filters[VideoFilters.Contrast].Maximum - Config.Video.Filters[VideoFilters.Contrast].Minimum) / 2);\n }\n }\n\n internal void UpdateBackgroundColor()\n {\n D3D11VPBackgroundColor.Rgba.R = Scale(Config.Video.BackgroundColor.R, 0, 255, 0, 100) / 100.0f;\n D3D11VPBackgroundColor.Rgba.G = Scale(Config.Video.BackgroundColor.G, 0, 255, 0, 100) / 100.0f;\n D3D11VPBackgroundColor.Rgba.B = Scale(Config.Video.BackgroundColor.B, 0, 255, 0, 100) / 100.0f;\n\n vc?.VideoProcessorSetOutputBackgroundColor(vp, false, D3D11VPBackgroundColor);\n\n Present();\n }\n internal void UpdateDeinterlace()\n {\n lock (lockDevice)\n {\n if (Disposed)\n return;\n\n vc?.VideoProcessorSetStreamFrameFormat(vp, 0, !Config.Video.Deinterlace ? VideoFrameFormat.Progressive : (Config.Video.DeinterlaceBottomFirst ? VideoFrameFormat.InterlacedBottomFieldFirst : VideoFrameFormat.InterlacedTopFieldFirst));\n\n if (Config.Video.VideoProcessor != VideoProcessors.Auto)\n return;\n\n if (parent != null)\n return;\n\n ConfigPlanes();\n Present();\n }\n }\n internal void UpdateFilterValue(VideoFilter filter)\n {\n // D3D11VP\n if (Filters.ContainsKey(filter.Filter) && vc != null)\n {\n int scaledValue = (int) Scale(filter.Value, filter.Minimum, filter.Maximum, Filters[filter.Filter].Minimum, Filters[filter.Filter].Maximum);\n vc.VideoProcessorSetStreamFilter(vp, 0, ConvertFromVideoProcessorFilterCaps((VideoProcessorFilterCaps)filter.Filter), true, scaledValue);\n }\n\n if (parent != null)\n return;\n\n // FLVP\n switch (filter.Filter)\n {\n case VideoFilters.Brightness:\n int scaledValue = (int) Scale(filter.Value, filter.Minimum, filter.Maximum, 0, 100);\n psBufferData.brightness = scaledValue / 100.0f;\n context.UpdateSubresource(psBufferData, psBuffer);\n\n break;\n\n case VideoFilters.Contrast:\n scaledValue = (int) Scale(filter.Value, filter.Minimum, filter.Maximum, 0, 100);\n psBufferData.contrast = scaledValue / 100.0f;\n context.UpdateSubresource(psBufferData, psBuffer);\n\n break;\n\n default:\n break;\n }\n\n Present();\n }\n internal void UpdateHDRtoSDR(bool updateResource = true)\n {\n if(parent != null)\n return;\n\n float lum1 = 400;\n\n if (hdrPlusData != null)\n {\n lum1 = (float) (av_q2d(hdrPlusData->@params[0].average_maxrgb) * 100000.0);\n\n // this is not accurate more research required\n if (lum1 < 100)\n lum1 *= 10;\n lum1 = Math.Max(lum1, 400);\n }\n else if (Config.Video.HDRtoSDRMethod != HDRtoSDRMethod.Reinhard)\n {\n float lum2 = lum1;\n float lum3 = lum1;\n\n double lum = displayData.has_luminance != 0 ? av_q2d(displayData.max_luminance) : 400;\n\n if (lightData.MaxCLL > 0)\n {\n if (lightData.MaxCLL >= lum)\n {\n lum1 = (float)lum;\n lum2 = lightData.MaxCLL;\n }\n else\n {\n lum1 = lightData.MaxCLL;\n lum2 = (float)lum;\n }\n lum3 = lightData.MaxFALL;\n lum1 = (lum1 * 0.5f) + (lum2 * 0.2f) + (lum3 * 0.3f);\n }\n else\n {\n lum1 = (float)lum;\n }\n }\n else\n {\n if (lightData.MaxCLL > 0)\n lum1 = lightData.MaxCLL;\n else if (displayData.has_luminance != 0)\n lum1 = (float)av_q2d(displayData.max_luminance);\n }\n\n psBufferData.hdrmethod = Config.Video.HDRtoSDRMethod;\n\n if (psBufferData.hdrmethod == HDRtoSDRMethod.Hable)\n {\n psBufferData.g_luminance = lum1 > 1 ? lum1 : 400.0f;\n psBufferData.g_toneP1 = 10000.0f / psBufferData.g_luminance * (2.0f / Config.Video.HDRtoSDRTone);\n psBufferData.g_toneP2 = psBufferData.g_luminance / (100.0f * Config.Video.HDRtoSDRTone);\n }\n else if (psBufferData.hdrmethod == HDRtoSDRMethod.Reinhard)\n {\n psBufferData.g_toneP1 = lum1 > 0 ? (float)(Math.Log10(100) / Math.Log10(lum1)) : 0.72f;\n if (psBufferData.g_toneP1 < 0.1f || psBufferData.g_toneP1 > 5.0f)\n psBufferData.g_toneP1 = 0.72f;\n\n psBufferData.g_toneP1 *= Config.Video.HDRtoSDRTone;\n }\n else if (psBufferData.hdrmethod == HDRtoSDRMethod.Aces)\n {\n psBufferData.g_luminance = lum1 > 1 ? lum1 : 400.0f;\n psBufferData.g_toneP1 = Config.Video.HDRtoSDRTone;\n }\n\n if (updateResource)\n {\n context.UpdateSubresource(psBufferData, psBuffer);\n if (!VideoDecoder.IsRunning)\n Present();\n }\n }\n void UpdateRotation(uint angle, bool refresh = true)\n {\n _RotationAngle = angle;\n\n uint newRotation = _RotationAngle;\n\n if (VideoStream != null)\n newRotation += (uint)VideoStream.Rotation;\n\n if (rotationLinesize)\n newRotation += 180;\n\n newRotation %= 360;\n\n if (Disposed || (actualRotation == newRotation && actualHFlip == _HFlip && actualVFlip == _VFlip))\n return;\n\n bool hvFlipChanged = (actualHFlip || actualVFlip) != (_HFlip || _VFlip);\n\n actualRotation = newRotation;\n actualHFlip = _HFlip;\n actualVFlip = _VFlip;\n\n if (actualRotation < 45 || actualRotation == 360)\n _d3d11vpRotation = VideoProcessorRotation.Identity;\n else if (actualRotation < 135)\n _d3d11vpRotation = VideoProcessorRotation.Rotation90;\n else if (actualRotation < 225)\n _d3d11vpRotation = VideoProcessorRotation.Rotation180;\n else if (actualRotation < 360)\n _d3d11vpRotation = VideoProcessorRotation.Rotation270;\n\n vsBufferData.mat = Matrix4x4.CreateFromYawPitchRoll(0.0f, 0.0f, (float) (Math.PI / 180 * actualRotation));\n\n if (_HFlip || _VFlip)\n {\n vsBufferData.mat *= Matrix4x4.CreateScale(_HFlip ? -1 : 1, _VFlip ? -1 : 1, 1);\n if (hvFlipChanged)\n {\n // Renders both sides required for H-V Flip - TBR: consider for performance changing the vertex buffer / input layout instead?\n rasterizerState?.Dispose();\n rasterizerState = Device.CreateRasterizerState(new(CullMode.None, FillMode.Solid));\n context.RSSetState(rasterizerState);\n }\n }\n else if (hvFlipChanged)\n {\n // Removes back rendering for better performance\n rasterizerState?.Dispose();\n rasterizerState = Device.CreateRasterizerState(new(CullMode.Back, FillMode.Solid));\n context.RSSetState(rasterizerState);\n }\n\n if (parent == null)\n context.UpdateSubresource(vsBufferData, vsBuffer);\n\n if (child != null)\n {\n child.actualRotation = actualRotation;\n child._d3d11vpRotation = _d3d11vpRotation;\n child._RotationAngle = _RotationAngle;\n child.rotationLinesize = rotationLinesize;\n child.SetViewport();\n }\n\n vc?.VideoProcessorSetStreamRotation(vp, 0, true, _d3d11vpRotation);\n\n if (refresh)\n SetViewport();\n }\n internal void UpdateVideoProcessor()\n {\n if(parent != null)\n return;\n\n if (Config.Video.VideoProcessor == videoProcessor || (Config.Video.VideoProcessor == VideoProcessors.D3D11 && D3D11VPFailed))\n return;\n\n ConfigPlanes();\n Present();\n }\n}\n\npublic class VideoFilter : NotifyPropertyChanged\n{\n internal Renderer renderer;\n\n [JsonIgnore]\n public bool Available { get => _Available; set => SetUI(ref _Available, value); }\n bool _Available;\n\n public VideoFilters Filter { get => _Filter; set => SetUI(ref _Filter, value); }\n VideoFilters _Filter = VideoFilters.Brightness;\n\n public int Minimum { get => _Minimum; set => SetUI(ref _Minimum, value); }\n int _Minimum = 0;\n\n public int Maximum { get => _Maximum; set => SetUI(ref _Maximum, value); }\n int _Maximum = 100;\n\n public float Step { get => _Step; set => SetUI(ref _Step, value); }\n float _Step = 1;\n\n public int DefaultValue\n {\n get;\n set\n {\n if (SetUI(ref field, value))\n {\n SetDefaultValue.OnCanExecuteChanged();\n }\n }\n } = 50;\n\n public int Value\n {\n get;\n set\n {\n int v = value;\n v = Math.Min(v, Maximum);\n v = Math.Max(v, Minimum);\n\n if (Set(ref field, v))\n {\n renderer?.UpdateFilterValue(this);\n SetDefaultValue.OnCanExecuteChanged();\n }\n }\n } = 50;\n\n public RelayCommand SetDefaultValue => field ??= new(_ =>\n {\n Value = DefaultValue;\n }, _ => Value != DefaultValue);\n\n //internal void SetValue(int value) => SetUI(ref _Value, value, true, nameof(Value));\n\n public VideoFilter() { }\n public VideoFilter(VideoFilters filter, Player player = null)\n => Filter = filter;\n}\n\npublic class VideoProcessorCapsCache\n{\n public bool Failed = true;\n public int TypeIndex = -1;\n public bool HLG;\n public bool HDR10Limited;\n public VideoProcessorCaps VideoProcessorCaps;\n public VideoProcessorRateConversionCaps VideoProcessorRateConversionCaps;\n\n public Dictionary Filters { get; set; } = new();\n}\n"], ["/LLPlayer/FlyleafLib/MediaFramework/MediaDecoder/AudioDecoder.cs", "using System.Collections.Concurrent;\nusing System.Threading;\n\nusing FlyleafLib.MediaFramework.MediaStream;\nusing FlyleafLib.MediaFramework.MediaFrame;\nusing FlyleafLib.MediaFramework.MediaRemuxer;\n\nusing static FlyleafLib.Logger;\n\nnamespace FlyleafLib.MediaFramework.MediaDecoder;\n\n/* TODO\n *\n * Circular Buffer\n * - Safe re-allocation and check also actual frames in queue (as now during draining we can overwrite them)\n * - Locking with Audio.AddSamples during re-allocation and re-write old data to the new buffer and update the pointers in queue\n *\n * Filters\n * - Note: Performance issue (for seek/speed change). We can't drain the buffersrc and re-use the filtergraph without re-initializing it, is not supported\n * - Check if av_buffersrc_get_nb_failed_requests required\n * - Add Config for filter threads?\n * - Review Access Violation issue with dynaudnorm/loudnorm filters in combination with atempo (when changing speed to fast?)\n * - Use multiple atempo for better quality (for < 0.5 and > 2, use eg. 2 of sqrt(X) * sqrt(X) to achive this)\n * - Review locks / recode RunInternal to be able to continue from where it stopped (eg. ProcessFilter)\n *\n * Custom Frames Queue to notify when the queue is not full anymore (to avoid thread sleep which can cause delays)\n * Support more output formats/channels/sampleRates (and currently output to 32-bit, sample rate to 48Khz and not the same as input? - should calculate possible delays)\n */\n\npublic unsafe partial class AudioDecoder : DecoderBase\n{\n public AudioStream AudioStream => (AudioStream) Stream;\n public readonly\n VideoDecoder VideoDecoder;\n public ConcurrentQueue\n Frames { get; protected set; } = new();\n\n static AVSampleFormat AOutSampleFormat = AVSampleFormat.S16;\n static string AOutSampleFormatStr = av_get_sample_fmt_name(AOutSampleFormat);\n static AVChannelLayout AOutChannelLayout = AV_CHANNEL_LAYOUT_STEREO;// new() { order = AVChannelOrder.Native, nb_channels = 2, u = new AVChannelLayout_u() { mask = AVChannel.for AV_CH_FRONT_LEFT | AV_CH_FRONT_RIGHT} };\n static int AOutChannels = AOutChannelLayout.nb_channels;\n static int ASampleBytes = av_get_bytes_per_sample(AOutSampleFormat) * AOutChannels;\n\n public readonly object CircularBufferLocker= new();\n internal Action CBufAlloc; // Informs Audio player to clear buffer pointers to avoid access violation\n static int cBufTimesSize = 4;\n int cBufTimesCur = 1;\n byte[] cBuf;\n int cBufPos;\n int cBufSamples;\n internal bool resyncWithVideoRequired;\n SwrContext* swrCtx;\n\n internal long nextPts;\n double sampleRateTimebase;\n\n public AudioDecoder(Config config, int uniqueId = -1, VideoDecoder syncDecoder = null) : base(config, uniqueId)\n => VideoDecoder = syncDecoder;\n\n protected override int Setup(AVCodec* codec) => 0;\n private int SetupSwr()\n {\n int ret;\n\n DisposeSwr();\n swrCtx = swr_alloc();\n\n av_opt_set_chlayout(swrCtx, \"in_chlayout\", &codecCtx->ch_layout, 0);\n av_opt_set_int(swrCtx, \"in_sample_rate\", codecCtx->sample_rate, 0);\n av_opt_set_sample_fmt(swrCtx, \"in_sample_fmt\", codecCtx->sample_fmt, 0);\n\n fixed(AVChannelLayout* ptr = &AOutChannelLayout)\n av_opt_set_chlayout(swrCtx, \"out_chlayout\", ptr, 0);\n av_opt_set_int(swrCtx, \"out_sample_rate\", codecCtx->sample_rate, 0);\n av_opt_set_sample_fmt(swrCtx, \"out_sample_fmt\", AOutSampleFormat, 0);\n\n ret = swr_init(swrCtx);\n if (ret < 0)\n Log.Error($\"Swr setup failed {FFmpegEngine.ErrorCodeToMsg(ret)} ({ret})\");\n\n return ret;\n }\n private void DisposeSwr()\n {\n if (swrCtx == null)\n return;\n\n swr_close(swrCtx);\n\n fixed(SwrContext** ptr = &swrCtx)\n swr_free(ptr);\n\n swrCtx = null;\n }\n\n protected override void DisposeInternal()\n {\n DisposeFrames();\n DisposeSwr();\n DisposeFilters();\n\n lock (CircularBufferLocker)\n cBuf = null;\n cBufSamples = 0;\n filledFromCodec = false;\n nextPts = AV_NOPTS_VALUE;\n }\n public void DisposeFrames() => Frames = new();\n public void Flush()\n {\n lock (lockActions)\n lock (lockCodecCtx)\n {\n if (Disposed)\n return;\n\n if (Status == Status.Ended)\n Status = Status.Stopped;\n else if (Status == Status.Draining)\n Status = Status.Stopping;\n\n resyncWithVideoRequired = !VideoDecoder.Disposed;\n nextPts = AV_NOPTS_VALUE;\n DisposeFrames();\n avcodec_flush_buffers(codecCtx);\n if (filterGraph != null)\n SetupFilters();\n }\n }\n\n protected override void RunInternal()\n {\n int ret = 0;\n int allowedErrors = Config.Decoder.MaxErrors;\n int sleepMs = Config.Decoder.MaxAudioFrames > 5 && Config.Player.MaxLatency == 0 ? 10 : 4;\n AVPacket *packet;\n\n do\n {\n // Wait until Queue not Full or Stopped\n if (Frames.Count >= Config.Decoder.MaxAudioFrames)\n {\n lock (lockStatus)\n if (Status == Status.Running)\n Status = Status.QueueFull;\n\n while (Frames.Count >= Config.Decoder.MaxAudioFrames && Status == Status.QueueFull)\n Thread.Sleep(sleepMs);\n\n lock (lockStatus)\n {\n if (Status != Status.QueueFull)\n break;\n\n Status = Status.Running;\n }\n }\n\n // While Packets Queue Empty (Ended | Quit if Demuxer stopped | Wait until we get packets)\n if (demuxer.AudioPackets.Count == 0)\n {\n CriticalArea = true;\n\n lock (lockStatus)\n if (Status == Status.Running) Status = Status.QueueEmpty;\n\n while (demuxer.AudioPackets.Count == 0 && Status == Status.QueueEmpty)\n {\n if (demuxer.Status == Status.Ended)\n {\n lock (lockStatus)\n {\n // TODO: let the demuxer push the draining packet\n Log.Debug(\"Draining\");\n Status = Status.Draining;\n var drainPacket = av_packet_alloc();\n drainPacket->data = null;\n drainPacket->size = 0;\n demuxer.AudioPackets.Enqueue(drainPacket);\n }\n\n break;\n }\n else if (!demuxer.IsRunning)\n {\n if (CanDebug) Log.Debug($\"Demuxer is not running [Demuxer Status: {demuxer.Status}]\");\n\n int retries = 5;\n\n while (retries > 0)\n {\n retries--;\n Thread.Sleep(10);\n if (demuxer.IsRunning) break;\n }\n\n lock (demuxer.lockStatus)\n lock (lockStatus)\n {\n if (demuxer.Status == Status.Pausing || demuxer.Status == Status.Paused)\n Status = Status.Pausing;\n else if (demuxer.Status != Status.Ended)\n Status = Status.Stopping;\n else\n continue;\n }\n\n break;\n }\n\n Thread.Sleep(sleepMs);\n }\n\n lock (lockStatus)\n {\n CriticalArea = false;\n if (Status != Status.QueueEmpty && Status != Status.Draining) break;\n if (Status != Status.Draining) Status = Status.Running;\n }\n }\n\n Monitor.Enter(lockCodecCtx); // restore the old lock / add interrupters similar to the demuxer\n try\n {\n if (Status == Status.Stopped)\n { Monitor.Exit(lockCodecCtx); continue; }\n\n packet = demuxer.AudioPackets.Dequeue();\n\n if (packet == null)\n { Monitor.Exit(lockCodecCtx); continue; }\n\n if (isRecording)\n {\n if (!recGotKeyframe && VideoDecoder.StartRecordTime != AV_NOPTS_VALUE && (long)(packet->pts * AudioStream.Timebase) - demuxer.StartTime > VideoDecoder.StartRecordTime)\n recGotKeyframe = true;\n\n if (recGotKeyframe)\n curRecorder.Write(av_packet_clone(packet), !OnVideoDemuxer);\n }\n\n ret = avcodec_send_packet(codecCtx, packet);\n av_packet_free(&packet);\n\n if (ret != 0 && ret != AVERROR(EAGAIN))\n {\n if (ret == AVERROR_EOF)\n {\n Status = Status.Ended;\n break;\n }\n else\n {\n allowedErrors--;\n if (CanWarn) Log.Warn($\"{FFmpegEngine.ErrorCodeToMsg(ret)} ({ret})\");\n\n if (allowedErrors == 0) { Log.Error(\"Too many errors!\"); Status = Status.Stopping; break; }\n\n Monitor.Exit(lockCodecCtx); continue;\n }\n }\n\n while (true)\n {\n ret = avcodec_receive_frame(codecCtx, frame);\n if (ret != 0)\n {\n av_frame_unref(frame);\n\n if (ret == AVERROR_EOF && filterGraph != null)\n {\n lock (lockSpeed)\n {\n DrainFilters();\n Status = Status.Ended;\n }\n }\n\n break;\n }\n\n if (frame->best_effort_timestamp != AV_NOPTS_VALUE)\n frame->pts = frame->best_effort_timestamp;\n else if (frame->pts == AV_NOPTS_VALUE)\n {\n if (nextPts == AV_NOPTS_VALUE && filledFromCodec) // Possible after seek (maybe set based on pkt_pos?)\n {\n av_frame_unref(frame);\n continue;\n }\n\n frame->pts = nextPts;\n }\n\n // We could fix it down to the demuxer based on size?\n if (frame->duration <= 0)\n frame->duration = av_rescale_q((long)(frame->nb_samples * sampleRateTimebase), Engine.FFmpeg.AV_TIMEBASE_Q, Stream.AVStream->time_base);\n\n bool codecChanged = AudioStream.SampleFormat != codecCtx->sample_fmt || AudioStream.SampleRate != codecCtx->sample_rate || AudioStream.ChannelLayout != codecCtx->ch_layout.u.mask;\n\n if (!filledFromCodec || codecChanged)\n {\n if (codecChanged && filledFromCodec)\n {\n byte[] buf = new byte[50];\n fixed (byte* bufPtr = buf)\n {\n av_channel_layout_describe(&codecCtx->ch_layout, bufPtr, (nuint)buf.Length);\n Log.Warn($\"Codec changed {AudioStream.CodecIDOrig} {AudioStream.SampleFormat} {AudioStream.SampleRate} {AudioStream.ChannelLayoutStr} => {codecCtx->codec_id} {codecCtx->sample_fmt} {codecCtx->sample_rate} {Utils.BytePtrToStringUTF8(bufPtr)}\");\n }\n }\n\n DisposeInternal();\n filledFromCodec = true;\n\n avcodec_parameters_from_context(Stream.AVStream->codecpar, codecCtx);\n AudioStream.AVStream->time_base = codecCtx->pkt_timebase;\n AudioStream.Refresh();\n resyncWithVideoRequired = !VideoDecoder.Disposed;\n sampleRateTimebase = 1000 * 1000.0 / codecCtx->sample_rate;\n nextPts = AudioStream.StartTimePts;\n\n if (frame->pts == AV_NOPTS_VALUE)\n frame->pts = nextPts;\n\n ret = SetupFiltersOrSwr();\n\n CodecChanged?.Invoke(this);\n\n if (ret != 0)\n {\n Status = Status.Stopping;\n av_frame_unref(frame);\n break;\n }\n\n if (nextPts == AV_NOPTS_VALUE)\n {\n av_frame_unref(frame);\n continue;\n }\n }\n\n if (resyncWithVideoRequired)\n {\n // TODO: in case of long distance will spin (CPU issue), possible reseek?\n while (VideoDecoder.StartTime == AV_NOPTS_VALUE && VideoDecoder.IsRunning && resyncWithVideoRequired)\n Thread.Sleep(10);\n\n long ts = (long)((frame->pts + frame->duration) * AudioStream.Timebase) - demuxer.StartTime + Config.Audio.Delay;\n\n if (ts < VideoDecoder.StartTime)\n {\n if (CanTrace) Log.Trace($\"Drops {Utils.TicksToTime(ts)} (< V: {Utils.TicksToTime(VideoDecoder.StartTime)})\");\n av_frame_unref(frame);\n continue;\n }\n else\n resyncWithVideoRequired = false;\n }\n\n lock (lockSpeed)\n {\n if (filterGraph != null)\n ProcessFilters();\n else\n Process();\n\n av_frame_unref(frame);\n }\n }\n } catch { }\n\n Monitor.Exit(lockCodecCtx);\n\n } while (Status == Status.Running);\n\n if (isRecording) { StopRecording(); recCompleted(MediaType.Audio); }\n\n if (Status == Status.Draining) Status = Status.Ended;\n }\n private void Process()\n {\n try\n {\n nextPts = frame->pts + frame->duration;\n\n var dataLen = frame->nb_samples * ASampleBytes;\n var speedDataLen= Utils.Align((int)(dataLen / speed), ASampleBytes);\n\n AudioFrame mFrame = new()\n {\n timestamp = (long)(frame->pts * AudioStream.Timebase) - demuxer.StartTime + Config.Audio.Delay,\n dataLen = speedDataLen\n };\n if (CanTrace) Log.Trace($\"Processes {Utils.TicksToTime(mFrame.timestamp)}\");\n\n if (frame->nb_samples > cBufSamples)\n AllocateCircularBuffer(frame->nb_samples);\n else if (cBufPos + Math.Max(dataLen, speedDataLen) >= cBuf.Length)\n cBufPos = 0;\n\n fixed (byte *circularBufferPosPtr = &cBuf[cBufPos])\n {\n int ret = swr_convert(swrCtx, &circularBufferPosPtr, frame->nb_samples, (byte**)&frame->data, frame->nb_samples);\n if (ret < 0)\n return;\n\n mFrame.dataPtr = (IntPtr)circularBufferPosPtr;\n }\n\n // Fill silence\n if (speed < 1)\n for (int p = dataLen; p < speedDataLen; p++)\n cBuf[cBufPos + p] = 0;\n\n cBufPos += Math.Max(dataLen, speedDataLen);\n Frames.Enqueue(mFrame);\n\n // Wait until Queue not Full or Stopped\n if (Frames.Count >= Config.Decoder.MaxAudioFrames * cBufTimesCur)\n {\n Monitor.Exit(lockCodecCtx);\n lock (lockStatus)\n if (Status == Status.Running) Status = Status.QueueFull;\n\n while (Frames.Count >= Config.Decoder.MaxAudioFrames * cBufTimesCur && Status == Status.QueueFull)\n Thread.Sleep(20);\n\n Monitor.Enter(lockCodecCtx);\n\n lock (lockStatus)\n {\n if (Status != Status.QueueFull)\n return;\n\n Status = Status.Running;\n }\n }\n }\n catch (Exception e)\n {\n Log.Error($\"Failed to process frame ({e.Message})\");\n }\n }\n\n private void AllocateCircularBuffer(int samples)\n {\n /* TBR\n * 1. If we change to different in/out sample rates we need to calculate delay\n * 2. By destorying the cBuf can create critical issues while the audio decoder reads the data? (add lock) | we need to copy the lost data and change the pointers\n * 3. Recalculate on Config.Decoder.MaxAudioFrames change (greater)\n * 4. cBufTimesSize cause filters can pass the limit when we need to use lockSpeed\n */\n\n samples = Math.Max(10000, samples); // 10K samples to ensure that currently we will not re-allocate?\n int size = Config.Decoder.MaxAudioFrames * samples * ASampleBytes * cBufTimesSize;\n Log.Debug($\"Re-allocating circular buffer ({samples} > {cBufSamples}) with {size}bytes\");\n\n lock (CircularBufferLocker)\n {\n DisposeFrames(); // TODO: copy data\n CBufAlloc?.Invoke();\n cBuf = new byte[size];\n cBufPos = 0;\n cBufSamples = samples;\n }\n\n }\n\n #region Recording\n internal Action\n recCompleted;\n Remuxer curRecorder;\n bool recGotKeyframe;\n internal bool isRecording;\n internal void StartRecording(Remuxer remuxer)\n {\n if (Disposed || isRecording) return;\n\n curRecorder = remuxer;\n isRecording = true;\n recGotKeyframe = VideoDecoder.Disposed || VideoDecoder.Stream == null;\n }\n internal void StopRecording() => isRecording = false;\n #endregion\n}\n"], ["/LLPlayer/FlyleafLib/MediaFramework/MediaPlaylist/M3UPlaylist.cs", "using System.Collections.Generic;\nusing System.IO;\nusing System.Text.RegularExpressions;\n\nnamespace FlyleafLib.MediaFramework.MediaPlaylist;\n\npublic class M3UPlaylistItem\n{\n public long Duration { get; set; }\n public string Title { get; set; }\n public string OriginalTitle\n { get; set; }\n public string Url { get; set; }\n public string UserAgent { get; set; }\n public string Referrer { get; set; }\n public bool GeoBlocked { get; set; }\n public bool Not_24_7 { get; set; }\n public int Height { get; set; }\n\n public Dictionary Tags { get; set; } = new Dictionary();\n}\n\npublic class M3UPlaylist\n{\n public static List ParseFromHttp(string url, int timeoutMs = 30000)\n {\n string downStr = Utils.DownloadToString(url, timeoutMs);\n if (downStr == null)\n return new();\n\n using StringReader reader = new(downStr);\n return Parse(reader);\n }\n\n public static List ParseFromString(string text)\n {\n using StringReader reader = new(text);\n return Parse(reader);\n }\n\n public static List Parse(string filename)\n {\n using StreamReader reader = new(filename);\n return Parse(reader);\n }\n private static List Parse(TextReader reader)\n {\n string line;\n List items = new();\n\n while ((line = reader.ReadLine()) != null)\n {\n if (line.StartsWith(\"#EXTINF\"))\n {\n M3UPlaylistItem item = new();\n var matches = Regex.Matches(line, \" ([^\\\\s=]+)=\\\"([^\\\\s\\\"]+)\\\"\");\n foreach (Match match in matches)\n {\n if (match.Groups.Count == 3 && !string.IsNullOrWhiteSpace(match.Groups[2].Value))\n item.Tags.Add(match.Groups[1].Value, match.Groups[2].Value);\n }\n\n item.Title = GetMatch(line, @\",\\s*(.*)$\");\n item.OriginalTitle = item.Title;\n\n if (item.Title.IndexOf(\" [Geo-blocked]\") >= 0)\n {\n item.GeoBlocked = true;\n item.Title = item.Title.Replace(\" [Geo-blocked]\", \"\");\n }\n\n if (item.Title.IndexOf(\" [Not 24/7]\") >= 0)\n {\n item.Not_24_7 = true;\n item.Title = item.Title.Replace(\" [Not 24/7]\", \"\");\n }\n\n var height = Regex.Match(item.Title, \" \\\\(([0-9]+)p\\\\)\");\n if (height.Groups.Count == 2)\n {\n item.Height = int.Parse(height.Groups[1].Value);\n item.Title = item.Title.Replace(height.Groups[0].Value, \"\");\n }\n\n while ((line = reader.ReadLine()) != null && line.StartsWith(\"#EXTVLCOPT\"))\n {\n if (item.UserAgent == null)\n {\n item.UserAgent = GetMatch(line, \"http-user-agent\\\\s*=\\\\s*\\\"*(.*)\\\"*\");\n if (item.UserAgent != null) continue;\n }\n\n if (item.Referrer == null)\n {\n item.Referrer = GetMatch(line, \"http-referrer\\\\s*=\\\\s*\\\"*(.*)\\\"*\");\n if (item.Referrer != null) continue;\n }\n }\n\n item.Url = line;\n items.Add(item);\n }\n\n // TODO: for m3u8 saved from windows media player\n //else if (!line.StartsWith(\"#\"))\n //{\n // M3UPlaylistItem item = new();\n // item.Url = line.Trim(); // this can be relative path (base path from the root m3u8) in case of http(s) this can be another m3u8*\n // if (item.Url.Length > 0)\n // {\n // item.Title = Path.GetFileName(item.Url);\n // items.Add(item);\n // }\n //}\n }\n\n return items;\n }\n\n private static string GetMatch(string text, string pattern)\n {\n var match = Regex.Match(text, pattern);\n return match.Success && match.Groups.Count > 1 ? match.Groups[1].Value : null;\n }\n}\n"], ["/LLPlayer/LLPlayer/Controls/OutlinedTextBlock.cs", "using System.ComponentModel;\nusing System.Globalization;\nusing System.Windows;\nusing System.Windows.Documents;\nusing System.Windows.Markup;\nusing System.Windows.Media;\n\nnamespace LLPlayer.Controls;\n\n[ContentProperty(\"Text\")]\npublic class OutlinedTextBlock : FrameworkElement\n{\n public OutlinedTextBlock()\n {\n UpdatePen();\n TextDecorations = new TextDecorationCollection();\n }\n\n #region dependency properties\n public static readonly DependencyProperty FillProperty = DependencyProperty.Register(\n nameof(Fill),\n typeof(Brush),\n typeof(OutlinedTextBlock),\n new FrameworkPropertyMetadata(Brushes.White, FrameworkPropertyMetadataOptions.AffectsRender));\n\n public static readonly DependencyProperty StrokeProperty = DependencyProperty.Register(\n nameof(Stroke),\n typeof(Brush),\n typeof(OutlinedTextBlock),\n new FrameworkPropertyMetadata(Brushes.Black, FrameworkPropertyMetadataOptions.AffectsRender));\n\n public static readonly DependencyProperty StrokeThicknessProperty = DependencyProperty.Register(\n nameof(StrokeThickness),\n typeof(double),\n typeof(OutlinedTextBlock),\n new FrameworkPropertyMetadata(1d, FrameworkPropertyMetadataOptions.AffectsRender));\n\n public static readonly DependencyProperty FontFamilyProperty = TextElement.FontFamilyProperty.AddOwner(\n typeof(OutlinedTextBlock),\n new FrameworkPropertyMetadata(OnFormattedTextUpdated));\n\n public static readonly DependencyProperty FontSizeProperty = TextElement.FontSizeProperty.AddOwner(\n typeof(OutlinedTextBlock),\n new FrameworkPropertyMetadata(OnFormattedTextUpdated));\n\n public static readonly DependencyProperty FontSizeInitialProperty = DependencyProperty.Register(\n nameof(FontSizeInitial),\n typeof(double),\n typeof(OutlinedTextBlock),\n new FrameworkPropertyMetadata(OnFormattedTextUpdated));\n\n public static readonly DependencyProperty FontSizeAutoProperty = DependencyProperty.Register(\n nameof(FontSizeAuto),\n typeof(bool),\n typeof(OutlinedTextBlock),\n new FrameworkPropertyMetadata(OnFormattedTextUpdated));\n\n public static readonly DependencyProperty FontStretchProperty = TextElement.FontStretchProperty.AddOwner(\n typeof(OutlinedTextBlock),\n new FrameworkPropertyMetadata(OnFormattedTextUpdated));\n\n public static readonly DependencyProperty FontStyleProperty = TextElement.FontStyleProperty.AddOwner(\n typeof(OutlinedTextBlock),\n new FrameworkPropertyMetadata(OnFormattedTextUpdated));\n\n public static readonly DependencyProperty FontWeightProperty = TextElement.FontWeightProperty.AddOwner(\n typeof(OutlinedTextBlock),\n new FrameworkPropertyMetadata(OnFormattedTextUpdated));\n\n public static readonly DependencyProperty StrokePositionProperty = DependencyProperty.Register(\n nameof(StrokePosition),\n typeof(StrokePosition),\n typeof(OutlinedTextBlock),\n new FrameworkPropertyMetadata(StrokePosition.Outside, FrameworkPropertyMetadataOptions.AffectsRender));\n\n public static readonly DependencyProperty StrokeThicknessInitialProperty = DependencyProperty.Register(\n nameof(StrokeThicknessInitial),\n typeof(double),\n typeof(OutlinedTextBlock),\n new FrameworkPropertyMetadata(OnFormattedTextUpdated));\n\n public static readonly DependencyProperty TextProperty = DependencyProperty.Register(\n nameof(Text),\n typeof(string),\n typeof(OutlinedTextBlock),\n new FrameworkPropertyMetadata(OnFormattedTextInvalidated));\n\n public static readonly DependencyProperty TextAlignmentProperty = DependencyProperty.Register(\n nameof(TextAlignment),\n typeof(TextAlignment),\n typeof(OutlinedTextBlock),\n new FrameworkPropertyMetadata(OnFormattedTextUpdated));\n\n public static readonly DependencyProperty TextDecorationsProperty = DependencyProperty.Register(\n nameof(TextDecorations),\n typeof(TextDecorationCollection),\n typeof(OutlinedTextBlock),\n new FrameworkPropertyMetadata(OnFormattedTextUpdated));\n\n public static readonly DependencyProperty TextTrimmingProperty = DependencyProperty.Register(\n nameof(TextTrimming),\n typeof(TextTrimming),\n typeof(OutlinedTextBlock),\n new FrameworkPropertyMetadata(OnFormattedTextUpdated));\n\n public static readonly DependencyProperty TextWrappingProperty = DependencyProperty.Register(\n nameof(TextWrapping),\n typeof(TextWrapping),\n typeof(OutlinedTextBlock),\n new FrameworkPropertyMetadata(TextWrapping.NoWrap, OnFormattedTextUpdated));\n\n private FormattedText? _FormattedText;\n private Geometry? _TextGeometry;\n private Pen? _Pen;\n private PathGeometry? _clipGeometry;\n\n public Brush Fill\n {\n get => (Brush)GetValue(FillProperty);\n set => SetValue(FillProperty, value);\n }\n\n public FontFamily FontFamily\n {\n get => (FontFamily)GetValue(FontFamilyProperty);\n set => SetValue(FontFamilyProperty, value);\n }\n\n [TypeConverter(typeof(FontSizeConverter))]\n public double FontSize\n {\n get => (double)GetValue(FontSizeProperty);\n set => SetValue(FontSizeProperty, value);\n }\n\n [TypeConverter(typeof(FontSizeConverter))]\n public double FontSizeInitial\n {\n get => (double)GetValue(FontSizeInitialProperty);\n set => SetValue(FontSizeInitialProperty, value);\n }\n\n public bool FontSizeAuto\n {\n get => (bool)GetValue(FontSizeAutoProperty);\n set => SetValue(FontSizeAutoProperty, value);\n }\n\n public FontStretch FontStretch\n {\n get => (FontStretch)GetValue(FontStretchProperty);\n set => SetValue(FontStretchProperty, value);\n }\n\n public FontStyle FontStyle\n {\n get => (FontStyle)GetValue(FontStyleProperty);\n set => SetValue(FontStyleProperty, value);\n }\n\n public FontWeight FontWeight\n {\n get => (FontWeight)GetValue(FontWeightProperty);\n set => SetValue(FontWeightProperty, value);\n }\n\n public Brush Stroke\n {\n get => (Brush)GetValue(StrokeProperty);\n set => SetValue(StrokeProperty, value);\n }\n\n public StrokePosition StrokePosition\n {\n get => (StrokePosition)GetValue(StrokePositionProperty);\n set => SetValue(StrokePositionProperty, value);\n }\n\n public double StrokeThickness\n {\n get => (double)GetValue(StrokeThicknessProperty);\n set => SetValue(StrokeThicknessProperty, value);\n }\n\n public double StrokeThicknessInitial\n {\n get => (double)GetValue(StrokeThicknessInitialProperty);\n set => SetValue(StrokeThicknessInitialProperty, value);\n }\n\n public string Text\n {\n get => (string)GetValue(TextProperty);\n set => SetValue(TextProperty, value);\n }\n\n public TextAlignment TextAlignment\n {\n get => (TextAlignment)GetValue(TextAlignmentProperty);\n set => SetValue(TextAlignmentProperty, value);\n }\n\n public TextDecorationCollection TextDecorations\n {\n get => (TextDecorationCollection)GetValue(TextDecorationsProperty);\n set => SetValue(TextDecorationsProperty, value);\n }\n\n public TextTrimming TextTrimming\n {\n get => (TextTrimming)GetValue(TextTrimmingProperty);\n set => SetValue(TextTrimmingProperty, value);\n }\n\n public TextWrapping TextWrapping\n {\n get => (TextWrapping)GetValue(TextWrappingProperty);\n set => SetValue(TextWrappingProperty, value);\n }\n\n #endregion\n\n #region PDIC\n\n public int WordOffset { get; set; }\n\n #endregion\n\n private void UpdatePen()\n {\n _Pen = new Pen(Stroke, StrokeThickness)\n {\n DashCap = PenLineCap.Round,\n EndLineCap = PenLineCap.Round,\n LineJoin = PenLineJoin.Round,\n StartLineCap = PenLineCap.Round\n };\n\n if (StrokePosition == StrokePosition.Outside || StrokePosition == StrokePosition.Inside)\n _Pen.Thickness = StrokeThickness * 2;\n\n InvalidateVisual();\n }\n\n protected override void OnRender(DrawingContext drawingContext)\n {\n EnsureGeometry();\n\n drawingContext.DrawGeometry(Fill, null, _TextGeometry);\n\n if (StrokePosition == StrokePosition.Outside)\n drawingContext.PushClip(_clipGeometry);\n else if (StrokePosition == StrokePosition.Inside)\n drawingContext.PushClip(_TextGeometry);\n\n drawingContext.DrawGeometry(null, _Pen, _TextGeometry);\n\n if (StrokePosition == StrokePosition.Outside || StrokePosition == StrokePosition.Inside)\n drawingContext.Pop();\n }\n\n protected override Size MeasureOverride(Size availableSize)\n {\n EnsureFormattedText();\n\n // constrain the formatted text according to the available size\n double w = availableSize.Width;\n double h = availableSize.Height;\n\n if (FontSizeAuto)\n {\n if (FontSizeInitial > 0)\n {\n double r = w / 1920; // FontSizeInitial should be based on fixed Screen Width (eg. Full HD 1920)\n FontSize = FontSizeInitial * (r + ((1 - r) * 0.20f)); // TBR: Weight/Percentage for how much it will be affected by the change (possible dependency property / config)\n _FormattedText!.SetFontSize(FontSize);\n }\n }\n\n if (StrokeThicknessInitial > 0)\n {\n double r = FontSize / 48; // StrokeThicknessInitial should be based on fixed FontSize (eg. 48)\n StrokeThickness = Math.Max(1, StrokeThicknessInitial * r);\n UpdatePen();\n }\n\n // the Math.Min call is important - without this constraint (which seems arbitrary, but is the maximum allowable text width), things blow up when availableSize is infinite in both directions\n // the Math.Max call is to ensure we don't hit zero, which will cause MaxTextHeight to throw\n _FormattedText!.MaxTextWidth = Math.Min(3579139, w);\n _FormattedText!.MaxTextHeight = Math.Max(0.0001d, h);\n\n // return the desired size\n return new Size(Math.Ceiling(_FormattedText.Width), Math.Ceiling(_FormattedText.Height));\n }\n\n protected override Size ArrangeOverride(Size finalSize)\n {\n EnsureFormattedText();\n\n // update the formatted text with the final size\n _FormattedText!.MaxTextWidth = finalSize.Width;\n _FormattedText!.MaxTextHeight = Math.Max(0.0001d, finalSize.Height);\n\n // need to re-generate the geometry now that the dimensions have changed\n _TextGeometry = null;\n UpdatePen();\n\n return finalSize;\n }\n\n private static void OnFormattedTextInvalidated(DependencyObject dependencyObject,\n DependencyPropertyChangedEventArgs e)\n {\n var outlinedTextBlock = (OutlinedTextBlock)dependencyObject;\n outlinedTextBlock._FormattedText = null;\n outlinedTextBlock._TextGeometry = null;\n\n outlinedTextBlock.InvalidateMeasure();\n outlinedTextBlock.InvalidateVisual();\n }\n\n private static void OnFormattedTextUpdated(DependencyObject dependencyObject, DependencyPropertyChangedEventArgs e)\n {\n var outlinedTextBlock = (OutlinedTextBlock)dependencyObject;\n if (outlinedTextBlock._FormattedText != null)\n outlinedTextBlock.UpdateFormattedText();\n outlinedTextBlock._TextGeometry = null;\n\n outlinedTextBlock.InvalidateMeasure();\n outlinedTextBlock.InvalidateVisual();\n }\n\n private void EnsureFormattedText()\n {\n if (_FormattedText != null)\n return;\n\n _FormattedText = new FormattedText(\n Text ?? \"\",\n CultureInfo.CurrentUICulture,\n FlowDirection,\n new Typeface(FontFamily, FontStyle, FontWeight, FontStretch),\n FontSize,\n Brushes.Black,\n VisualTreeHelper.GetDpi(this).PixelsPerDip);\n\n UpdateFormattedText();\n }\n\n private void UpdateFormattedText()\n {\n _FormattedText!.MaxLineCount = TextWrapping == TextWrapping.NoWrap ? 1 : int.MaxValue;\n _FormattedText.TextAlignment = TextAlignment;\n _FormattedText.Trimming = TextTrimming;\n _FormattedText.SetFontSize(FontSize);\n _FormattedText.SetFontStyle(FontStyle);\n _FormattedText.SetFontWeight(FontWeight);\n _FormattedText.SetFontFamily(FontFamily);\n _FormattedText.SetFontStretch(FontStretch);\n _FormattedText.SetTextDecorations(TextDecorations);\n }\n\n private void EnsureGeometry()\n {\n if (_TextGeometry != null)\n return;\n\n EnsureFormattedText();\n _TextGeometry = _FormattedText!.BuildGeometry(new Point(0, 0));\n\n if (StrokePosition == StrokePosition.Outside)\n {\n var boundsGeo = new RectangleGeometry(new Rect(-(2 * StrokeThickness),\n -(2 * StrokeThickness), ActualWidth + (4 * StrokeThickness), ActualHeight + (4 * StrokeThickness)));\n _clipGeometry = Geometry.Combine(boundsGeo, _TextGeometry, GeometryCombineMode.Exclude, null);\n }\n }\n}\n\npublic enum StrokePosition\n{\n Center,\n Outside,\n Inside\n}\n"], ["/LLPlayer/FlyleafLib/MediaFramework/MediaContext/DecoderContext.Open.cs", "using System;\nusing System.Collections.Generic;\nusing System.IO;\nusing System.Linq;\nusing System.Threading.Tasks;\n\nusing FlyleafLib.MediaFramework.MediaDemuxer;\nusing FlyleafLib.MediaFramework.MediaPlaylist;\nusing FlyleafLib.MediaFramework.MediaStream;\nusing FlyleafLib.MediaPlayer;\nusing static FlyleafLib.Logger;\nusing static FlyleafLib.Utils;\n\nnamespace FlyleafLib.MediaFramework.MediaContext;\n\npublic partial class DecoderContext\n{\n #region Events\n public event EventHandler OpenCompleted;\n public event EventHandler OpenSessionCompleted;\n public event EventHandler OpenSubtitlesCompleted;\n public event EventHandler OpenPlaylistItemCompleted;\n\n public event EventHandler OpenAudioStreamCompleted;\n public event EventHandler OpenVideoStreamCompleted;\n public event EventHandler OpenSubtitlesStreamCompleted;\n public event EventHandler OpenDataStreamCompleted;\n\n public event EventHandler OpenExternalAudioStreamCompleted;\n public event EventHandler OpenExternalVideoStreamCompleted;\n public event EventHandler OpenExternalSubtitlesStreamCompleted;\n\n public class OpenCompletedArgs\n {\n public string Url;\n public Stream IOStream;\n public string Error;\n public bool Success => Error == null;\n public OpenCompletedArgs(string url = null, Stream iostream = null, string error = null) { Url = url; IOStream = iostream; Error = error; }\n }\n public class OpenSubtitlesCompletedArgs\n {\n public string Url;\n public string Error;\n public bool Success => Error == null;\n public OpenSubtitlesCompletedArgs(string url = null, string error = null) { Url = url; Error = error; }\n }\n public class OpenSessionCompletedArgs\n {\n public Session Session;\n public string Error;\n public bool Success => Error == null;\n public OpenSessionCompletedArgs(Session session = null, string error = null) { Session = session; Error = error; }\n }\n public class OpenPlaylistItemCompletedArgs\n {\n public PlaylistItem Item;\n public PlaylistItem OldItem;\n public string Error;\n public bool Success => Error == null;\n public OpenPlaylistItemCompletedArgs(PlaylistItem item = null, PlaylistItem oldItem = null, string error = null) { Item = item; OldItem = oldItem; Error = error; }\n }\n public class StreamOpenedArgs\n {\n public StreamBase Stream;\n public StreamBase OldStream;\n public string Error;\n public bool Success => Error == null;\n public StreamOpenedArgs(StreamBase stream = null, StreamBase oldStream = null, string error = null) { Stream = stream; OldStream= oldStream; Error = error; }\n }\n public class OpenAudioStreamCompletedArgs : StreamOpenedArgs\n {\n public new AudioStream Stream => (AudioStream)base.Stream;\n public new AudioStream OldStream=> (AudioStream)base.OldStream;\n public OpenAudioStreamCompletedArgs(AudioStream stream = null, AudioStream oldStream = null, string error = null): base(stream, oldStream, error) { }\n }\n public class OpenVideoStreamCompletedArgs : StreamOpenedArgs\n {\n public new VideoStream Stream => (VideoStream)base.Stream;\n public new VideoStream OldStream=> (VideoStream)base.OldStream;\n public OpenVideoStreamCompletedArgs(VideoStream stream = null, VideoStream oldStream = null, string error = null): base(stream, oldStream, error) { }\n }\n public class OpenSubtitlesStreamCompletedArgs : StreamOpenedArgs\n {\n public new SubtitlesStream Stream => (SubtitlesStream)base.Stream;\n public new SubtitlesStream OldStream=> (SubtitlesStream)base.OldStream;\n public OpenSubtitlesStreamCompletedArgs(SubtitlesStream stream = null, SubtitlesStream oldStream = null, string error = null): base(stream, oldStream, error) { }\n }\n public class OpenDataStreamCompletedArgs : StreamOpenedArgs\n {\n public new DataStream Stream => (DataStream)base.Stream;\n public new DataStream OldStream => (DataStream)base.OldStream;\n public OpenDataStreamCompletedArgs(DataStream stream = null, DataStream oldStream = null, string error = null) : base(stream, oldStream, error) { }\n }\n public class ExternalStreamOpenedArgs : EventArgs\n {\n public ExternalStream ExtStream;\n public ExternalStream OldExtStream;\n public string Error;\n public bool Success => Error == null;\n public ExternalStreamOpenedArgs(ExternalStream extStream = null, ExternalStream oldExtStream = null, string error = null) { ExtStream = extStream; OldExtStream= oldExtStream; Error = error; }\n }\n public class OpenExternalAudioStreamCompletedArgs : ExternalStreamOpenedArgs\n {\n public new ExternalAudioStream ExtStream => (ExternalAudioStream)base.ExtStream;\n public new ExternalAudioStream OldExtStream=> (ExternalAudioStream)base.OldExtStream;\n public OpenExternalAudioStreamCompletedArgs(ExternalAudioStream extStream = null, ExternalAudioStream oldExtStream = null, string error = null) : base(extStream, oldExtStream, error) { }\n }\n public class OpenExternalVideoStreamCompletedArgs : ExternalStreamOpenedArgs\n {\n public new ExternalVideoStream ExtStream => (ExternalVideoStream)base.ExtStream;\n public new ExternalVideoStream OldExtStream=> (ExternalVideoStream)base.OldExtStream;\n public OpenExternalVideoStreamCompletedArgs(ExternalVideoStream extStream = null, ExternalVideoStream oldExtStream = null, string error = null) : base(extStream, oldExtStream, error) { }\n }\n public class OpenExternalSubtitlesStreamCompletedArgs : ExternalStreamOpenedArgs\n {\n public new ExternalSubtitlesStream ExtStream => (ExternalSubtitlesStream)base.ExtStream;\n public new ExternalSubtitlesStream OldExtStream=> (ExternalSubtitlesStream)base.OldExtStream;\n public OpenExternalSubtitlesStreamCompletedArgs(ExternalSubtitlesStream extStream = null, ExternalSubtitlesStream oldExtStream = null, string error = null) : base(extStream, oldExtStream, error) { }\n }\n\n private void OnOpenCompleted(OpenCompletedArgs args = null)\n {\n if (shouldDispose)\n {\n Dispose();\n return;\n }\n\n VideoDecoder.Renderer?.ClearScreen();\n if (CanInfo) Log.Info($\"[Open] {args.Url ?? \"None\"} {(!args.Success ? \" [Error: \" + args.Error + \"]\": \"\")}\");\n OpenCompleted?.Invoke(this, args);\n }\n private void OnOpenSessionCompleted(OpenSessionCompletedArgs args = null)\n {\n if (shouldDispose)\n {\n Dispose();\n return;\n }\n\n VideoDecoder.Renderer?.ClearScreen();\n if (CanInfo) Log.Info($\"[OpenSession] {args.Session.Url ?? \"None\"} - Item: {args.Session.PlaylistItem} {(!args.Success ? \" [Error: \" + args.Error + \"]\": \"\")}\");\n OpenSessionCompleted?.Invoke(this, args);\n }\n private void OnOpenSubtitles(OpenSubtitlesCompletedArgs args = null)\n {\n if (shouldDispose)\n {\n Dispose();\n return;\n }\n\n if (CanInfo) Log.Info($\"[OpenSubtitles] {args.Url ?? \"None\"} {(!args.Success ? \" [Error: \" + args.Error + \"]\": \"\")}\");\n OpenSubtitlesCompleted?.Invoke(this, args);\n }\n private void OnOpenPlaylistItemCompleted(OpenPlaylistItemCompletedArgs args = null)\n {\n if (shouldDispose)\n {\n Dispose();\n return;\n }\n\n VideoDecoder.Renderer?.ClearScreen();\n if (CanInfo) Log.Info($\"[OpenPlaylistItem] {(args.OldItem != null ? args.OldItem.Title : \"None\")} => {(args.Item != null ? args.Item.Title : \"None\")}{(!args.Success ? \" [Error: \" + args.Error + \"]\": \"\")}\");\n OpenPlaylistItemCompleted?.Invoke(this, args);\n }\n private void OnOpenAudioStreamCompleted(OpenAudioStreamCompletedArgs args = null)\n {\n if (shouldDispose)\n {\n Dispose();\n return;\n }\n\n ClosedAudioStream = null;\n MainDemuxer = !VideoDemuxer.Disposed ? VideoDemuxer : AudioDemuxer;\n\n if (CanInfo) Log.Info($\"[OpenAudioStream] #{(args.OldStream != null ? args.OldStream.StreamIndex.ToString() : \"_\")} => #{(args.Stream != null ? args.Stream.StreamIndex.ToString() : \"_\")}{(!args.Success ? \" [Error: \" + args.Error + \"]\": \"\")}\");\n OpenAudioStreamCompleted?.Invoke(this, args);\n }\n private void OnOpenVideoStreamCompleted(OpenVideoStreamCompletedArgs args = null)\n {\n if (shouldDispose)\n {\n Dispose();\n return;\n }\n\n ClosedVideoStream = null;\n MainDemuxer = !VideoDemuxer.Disposed ? VideoDemuxer : AudioDemuxer;\n\n if (CanInfo) Log.Info($\"[OpenVideoStream] #{(args.OldStream != null ? args.OldStream.StreamIndex.ToString() : \"_\")} => #{(args.Stream != null ? args.Stream.StreamIndex.ToString() : \"_\")}{(!args.Success ? \" [Error: \" + args.Error + \"]\": \"\")}\");\n OpenVideoStreamCompleted?.Invoke(this, args);\n }\n private void OnOpenSubtitlesStreamCompleted(OpenSubtitlesStreamCompletedArgs args = null)\n {\n if (shouldDispose)\n {\n Dispose();\n return;\n }\n\n if (CanInfo) Log.Info($\"[OpenSubtitlesStream] #{(args.OldStream != null ? args.OldStream.StreamIndex.ToString() : \"_\")} => #{(args.Stream != null ? args.Stream.StreamIndex.ToString() : \"_\")}{(!args.Success ? \" [Error: \" + args.Error + \"]\": \"\")}\");\n OpenSubtitlesStreamCompleted?.Invoke(this, args);\n }\n private void OnOpenDataStreamCompleted(OpenDataStreamCompletedArgs args = null)\n {\n if (shouldDispose)\n {\n Dispose();\n return;\n }\n\n if (CanInfo)\n Log.Info($\"[OpenDataStream] #{(args.OldStream != null ? args.OldStream.StreamIndex.ToString() : \"_\")} => #{(args.Stream != null ? args.Stream.StreamIndex.ToString() : \"_\")}{(!args.Success ? \" [Error: \" + args.Error + \"]\" : \"\")}\");\n OpenDataStreamCompleted?.Invoke(this, args);\n }\n private void OnOpenExternalAudioStreamCompleted(OpenExternalAudioStreamCompletedArgs args = null)\n {\n if (shouldDispose)\n {\n Dispose();\n return;\n }\n\n ClosedAudioStream = null;\n MainDemuxer = !VideoDemuxer.Disposed ? VideoDemuxer : AudioDemuxer;\n\n if (CanInfo) Log.Info($\"[OpenExternalAudioStream] {(args.OldExtStream != null ? args.OldExtStream.Url : \"None\")} => {(args.ExtStream != null ? args.ExtStream.Url : \"None\")}{(!args.Success ? \" [Error: \" + args.Error + \"]\": \"\")}\");\n OpenExternalAudioStreamCompleted?.Invoke(this, args);\n }\n private void OnOpenExternalVideoStreamCompleted(OpenExternalVideoStreamCompletedArgs args = null)\n {\n if (shouldDispose)\n {\n Dispose();\n return;\n }\n\n ClosedVideoStream = null;\n MainDemuxer = !VideoDemuxer.Disposed ? VideoDemuxer : AudioDemuxer;\n\n if (CanInfo) Log.Info($\"[OpenExternalVideoStream] {(args.OldExtStream != null ? args.OldExtStream.Url : \"None\")} => {(args.ExtStream != null ? args.ExtStream.Url : \"None\")}{(!args.Success ? \" [Error: \" + args.Error + \"]\": \"\")}\");\n OpenExternalVideoStreamCompleted?.Invoke(this, args);\n }\n private void OnOpenExternalSubtitlesStreamCompleted(OpenExternalSubtitlesStreamCompletedArgs args = null)\n {\n if (shouldDispose)\n {\n Dispose();\n return;\n }\n\n if (CanInfo) Log.Info($\"[OpenExternalSubtitlesStream] {(args.OldExtStream != null ? args.OldExtStream.Url : \"None\")} => {(args.ExtStream != null ? args.ExtStream.Url : \"None\")}{(!args.Success ? \" [Error: \" + args.Error + \"]\": \"\")}\");\n OpenExternalSubtitlesStreamCompleted?.Invoke(this, args);\n }\n #endregion\n\n #region Open\n public OpenCompletedArgs Open(string url, bool defaultPlaylistItem = true, bool defaultVideo = true, bool defaultAudio = true, bool defaultSubtitles = true)\n => Open((object)url, defaultPlaylistItem, defaultVideo, defaultAudio, defaultSubtitles);\n public OpenCompletedArgs Open(Stream iostream, bool defaultPlaylistItem = true, bool defaultVideo = true, bool defaultAudio = true, bool defaultSubtitles = true)\n => Open((object)iostream, defaultPlaylistItem, defaultVideo, defaultAudio, defaultSubtitles);\n\n internal OpenCompletedArgs Open(object input, bool defaultPlaylistItem = true, bool defaultVideo = true, bool defaultAudio = true, bool defaultSubtitles = true)\n {\n OpenCompletedArgs args = new();\n\n try\n {\n Initialize();\n\n if (input is Stream)\n {\n Playlist.IOStream = (Stream)input;\n }\n else\n Playlist.Url = input.ToString(); // TBR: check UI update\n\n args.Url = Playlist.Url;\n args.IOStream = Playlist.IOStream;\n args.Error = Open().Error;\n\n if (Playlist.Items.Count == 0 && args.Success)\n args.Error = \"No playlist items were found\";\n\n if (!args.Success)\n return args;\n\n if (!defaultPlaylistItem)\n return args;\n\n args.Error = Open(SuggestItem(), defaultVideo, defaultAudio, defaultSubtitles).Error;\n\n return args;\n\n } catch (Exception e)\n {\n args.Error = !args.Success ? args.Error + \"\\r\\n\" + e.Message : e.Message;\n return args;\n }\n finally\n {\n OnOpenCompleted(args);\n }\n }\n public new OpenSubtitlesCompletedArgs OpenSubtitles(string url)\n {\n OpenSubtitlesCompletedArgs args = new();\n\n try\n {\n var res = base.OpenSubtitles(url);\n args.Error = res == null ? \"No external subtitles stream found\" : res.Error;\n\n if (args.Success)\n args.Error = Open(res.ExternalSubtitlesStream).Error;\n\n return args;\n\n } catch (Exception e)\n {\n args.Error = !args.Success ? args.Error + \"\\r\\n\" + e.Message : e.Message;\n return args;\n }\n finally\n {\n OnOpenSubtitles(args);\n }\n }\n public OpenSessionCompletedArgs Open(Session session)\n {\n OpenSessionCompletedArgs args = new(session);\n\n try\n {\n // Open\n if (session.Url != null && session.Url != Playlist.Url) // && session.Url != Playlist.DirectUrl)\n {\n args.Error = Open(session.Url, false, false, false, false).Error;\n if (!args.Success)\n return args;\n }\n\n // Open Item\n if (session.PlaylistItem != -1)\n {\n args.Error = Open(Playlist.Items[session.PlaylistItem], false, false, false).Error;\n if (!args.Success)\n return args;\n }\n\n // Open Streams\n if (session.ExternalVideoStream != -1)\n {\n args.Error = Open(Playlist.Selected.ExternalVideoStreams[session.ExternalVideoStream], false, session.VideoStream).Error;\n if (!args.Success)\n return args;\n }\n else if (session.VideoStream != -1)\n {\n args.Error = Open(VideoDemuxer.AVStreamToStream[session.VideoStream], false).Error;\n if (!args.Success)\n return args;\n }\n\n string tmpErr = null;\n if (session.ExternalAudioStream != -1)\n tmpErr = Open(Playlist.Selected.ExternalAudioStreams[session.ExternalAudioStream], false, session.AudioStream).Error;\n else if (session.AudioStream != -1)\n tmpErr = Open(VideoDemuxer.AVStreamToStream[session.AudioStream], false).Error;\n\n if (tmpErr != null & VideoStream == null)\n {\n args.Error = tmpErr;\n return args;\n }\n\n if (session.ExternalSubtitlesUrl != null)\n OpenSubtitles(session.ExternalSubtitlesUrl);\n else if (session.SubtitlesStream != -1)\n Open(VideoDemuxer.AVStreamToStream[session.SubtitlesStream]);\n\n Config.Audio.SetDelay(session.AudioDelay);\n\n for (int i = 0; i < subNum; i++)\n {\n Config.Subtitles[i].SetDelay(session.SubtitlesDelay);\n }\n\n if (session.CurTime > 1 * (long)1000 * 10000)\n Seek(session.CurTime / 10000);\n\n return args;\n } catch (Exception e)\n {\n args.Error = !args.Success ? args.Error + \"\\r\\n\" + e.Message : e.Message;\n return args;\n } finally\n {\n OnOpenSessionCompleted(args);\n }\n }\n public OpenPlaylistItemCompletedArgs Open(PlaylistItem item, bool defaultVideo = true, bool defaultAudio = true, bool defaultSubtitles = true)\n {\n OpenPlaylistItemCompletedArgs args = new(item);\n\n try\n {\n long stoppedTime = GetCurTime();\n InitializeSwitch();\n\n // Disables old item\n if (Playlist.Selected != null)\n {\n args.OldItem = Playlist.Selected;\n Playlist.Selected.Enabled = false;\n }\n\n if (item == null)\n {\n args.Error = \"Cancelled\";\n return args;\n }\n\n Playlist.Selected = item;\n Playlist.Selected.Enabled = true;\n\n // We reset external streams of the current item and not the old one\n if (Playlist.Selected.ExternalAudioStream != null)\n {\n Playlist.Selected.ExternalAudioStream.Enabled = false;\n Playlist.Selected.ExternalAudioStream = null;\n }\n\n if (Playlist.Selected.ExternalVideoStream != null)\n {\n Playlist.Selected.ExternalVideoStream.Enabled = false;\n Playlist.Selected.ExternalVideoStream = null;\n }\n\n for (int i = 0; i < subNum; i++)\n {\n if (Playlist.Selected.ExternalSubtitlesStreams[i] != null)\n {\n Playlist.Selected.ExternalSubtitlesStreams[i].Enabled = false;\n Playlist.Selected.ExternalSubtitlesStreams[i] = null;\n }\n }\n\n args.Error = OpenItem().Error;\n\n if (!args.Success)\n return args;\n\n if (Playlist.Selected.Url != null || Playlist.Selected.IOStream != null)\n args.Error = OpenDemuxerInput(VideoDemuxer, Playlist.Selected);\n\n if (!args.Success)\n return args;\n\n if (defaultVideo && Config.Video.Enabled)\n args.Error = OpenSuggestedVideo(defaultAudio);\n else if (defaultAudio && Config.Audio.Enabled)\n args.Error = OpenSuggestedAudio();\n\n if ((defaultVideo || defaultAudio) && AudioStream == null && VideoStream == null)\n {\n args.Error ??= \"No audio/video found\";\n\n return args;\n }\n\n if (defaultSubtitles && Config.Subtitles.Enabled)\n {\n if (Playlist.Selected.ExternalSubtitlesStreams[0] != null)\n Open(Playlist.Selected.ExternalSubtitlesStreams[0]);\n else\n OpenSuggestedSubtitles();\n }\n\n if (Config.Data.Enabled)\n {\n OpenSuggestedData();\n }\n\n LoadPlaylistChapters();\n\n return args;\n } catch (Exception e)\n {\n args.Error = !args.Success ? args.Error + \"\\r\\n\" + e.Message : e.Message;\n return args;\n } finally\n {\n OnOpenPlaylistItemCompleted(args);\n }\n }\n public ExternalStreamOpenedArgs Open(ExternalStream extStream, bool defaultAudio = false, int streamIndex = -1) // -2: None, -1: Suggest, >=0: specified\n {\n ExternalStreamOpenedArgs args = null;\n\n try\n {\n Demuxer demuxer;\n\n if (extStream is ExternalVideoStream)\n {\n args = new OpenExternalVideoStreamCompletedArgs((ExternalVideoStream) extStream, Playlist.Selected.ExternalVideoStream);\n\n if (args.OldExtStream != null)\n args.OldExtStream.Enabled = false;\n\n Playlist.Selected.ExternalVideoStream = (ExternalVideoStream) extStream;\n\n foreach(var plugin in Plugins.Values)\n plugin.OnOpenExternalVideo();\n\n demuxer = VideoDemuxer;\n }\n else if (extStream is ExternalAudioStream)\n {\n args = new OpenExternalAudioStreamCompletedArgs((ExternalAudioStream) extStream, Playlist.Selected.ExternalAudioStream);\n\n if (args.OldExtStream != null)\n args.OldExtStream.Enabled = false;\n\n Playlist.Selected.ExternalAudioStream = (ExternalAudioStream) extStream;\n\n foreach(var plugin in Plugins.Values)\n plugin.OnOpenExternalAudio();\n\n demuxer = AudioDemuxer;\n }\n else\n {\n int i = SubtitlesSelectedHelper.CurIndex;\n args = new OpenExternalSubtitlesStreamCompletedArgs((ExternalSubtitlesStream) extStream, Playlist.Selected.ExternalSubtitlesStreams[i]);\n\n if (args.OldExtStream != null)\n args.OldExtStream.Enabled = false;\n\n Playlist.Selected.ExternalSubtitlesStreams[i] = (ExternalSubtitlesStream) extStream;\n\n if (!Playlist.Selected.ExternalSubtitlesStreams[i].Downloaded)\n DownloadSubtitles(Playlist.Selected.ExternalSubtitlesStreams[i]);\n\n foreach(var plugin in Plugins.Values)\n plugin.OnOpenExternalSubtitles();\n\n demuxer = SubtitlesDemuxers[i];\n }\n\n // Open external stream\n args.Error = OpenDemuxerInput(demuxer, extStream);\n\n if (!args.Success)\n return args;\n\n // Update embedded streams with the external stream pointer\n foreach (var embStream in demuxer.VideoStreams)\n embStream.ExternalStream = extStream;\n foreach (var embStream in demuxer.AudioStreams)\n embStream.ExternalStream = extStream;\n foreach (var embStream in demuxer.SubtitlesStreamsAll)\n {\n embStream.ExternalStream = extStream;\n embStream.ExternalStreamAdded(); // Copies VobSub's .idx file to extradata (based on external url .sub)\n }\n\n // Open embedded stream\n if (streamIndex != -2)\n {\n StreamBase suggestedStream = null;\n if (streamIndex != -1 && (streamIndex >= demuxer.AVStreamToStream.Count || streamIndex < 0 || demuxer.AVStreamToStream[streamIndex].Type != extStream.Type))\n {\n args.Error = $\"Invalid stream index {streamIndex}\";\n demuxer.Dispose();\n return args;\n }\n\n if (demuxer.Type == MediaType.Video)\n suggestedStream = streamIndex == -1 ? SuggestVideo(demuxer.VideoStreams) : demuxer.AVStreamToStream[streamIndex];\n else if (demuxer.Type == MediaType.Audio)\n suggestedStream = streamIndex == -1 ? SuggestAudio(demuxer.AudioStreams) : demuxer.AVStreamToStream[streamIndex];\n else if (demuxer.Type == MediaType.Subs)\n {\n System.Collections.Generic.List langs = Config.Subtitles.Languages.ToList();\n langs.Add(Language.Unknown);\n suggestedStream = streamIndex == -1 ? SuggestSubtitles(demuxer.SubtitlesStreamsAll, langs) : demuxer.AVStreamToStream[streamIndex];\n }\n else\n {\n suggestedStream = demuxer.AVStreamToStream[streamIndex];\n }\n\n if (suggestedStream == null)\n {\n demuxer.Dispose();\n args.Error = \"No embedded streams found\";\n return args;\n }\n\n args.Error = Open(suggestedStream, defaultAudio).Error;\n if (!args.Success)\n return args;\n }\n\n LoadPlaylistChapters();\n\n extStream.Enabled = true;\n\n return args;\n } catch (Exception e)\n {\n args.Error = !args.Success ? args.Error + \"\\r\\n\" + e.Message : e.Message;\n return args;\n } finally\n {\n if (extStream is ExternalVideoStream)\n OnOpenExternalVideoStreamCompleted((OpenExternalVideoStreamCompletedArgs)args);\n else if (extStream is ExternalAudioStream)\n OnOpenExternalAudioStreamCompleted((OpenExternalAudioStreamCompletedArgs)args);\n else\n OnOpenExternalSubtitlesStreamCompleted((OpenExternalSubtitlesStreamCompletedArgs)args);\n }\n }\n\n public StreamOpenedArgs OpenVideoStream(VideoStream stream, bool defaultAudio = true)\n => Open(stream, defaultAudio);\n public StreamOpenedArgs OpenAudioStream(AudioStream stream)\n => Open(stream);\n public StreamOpenedArgs OpenSubtitlesStream(SubtitlesStream stream)\n => Open(stream);\n public StreamOpenedArgs OpenDataStream(DataStream stream)\n => Open(stream);\n private StreamOpenedArgs Open(StreamBase stream, bool defaultAudio = false)\n {\n StreamOpenedArgs args = null;\n\n try\n {\n lock (stream.Demuxer.lockActions)\n lock (stream.Demuxer.lockFmtCtx)\n {\n var oldStream = stream.Type == MediaType.Video ? VideoStream : (stream.Type == MediaType.Audio ? AudioStream : (StreamBase)DataStream);\n if (stream.Type == MediaType.Subs)\n {\n oldStream = SubtitlesStreams[SubtitlesSelectedHelper.CurIndex];\n }\n\n // Close external demuxers when opening embedded\n if (stream.Demuxer.Type == MediaType.Video)\n {\n // TBR: if (stream.Type == MediaType.Video) | We consider that we can't have Embedded and External Video Streams at the same time\n if (stream.Type == MediaType.Audio) // TBR: && VideoStream != null)\n {\n if (!EnableDecoding) AudioDemuxer.Dispose();\n if (Playlist.Selected.ExternalAudioStream != null)\n {\n Playlist.Selected.ExternalAudioStream.Enabled = false;\n Playlist.Selected.ExternalAudioStream = null;\n }\n }\n else if (stream.Type == MediaType.Subs)\n {\n int i = SubtitlesSelectedHelper.CurIndex;\n if (!EnableDecoding) \n SubtitlesDemuxers[i].Dispose();\n\n if (Playlist.Selected.ExternalSubtitlesStreams[i] != null)\n {\n Playlist.Selected.ExternalSubtitlesStreams[i].Enabled = false;\n Playlist.Selected.ExternalSubtitlesStreams[i] = null;\n }\n }\n else if (stream.Type == MediaType.Data)\n {\n if (!EnableDecoding) DataDemuxer.Dispose();\n }\n }\n else if (!EnableDecoding)\n {\n // Disable embeded audio when enabling external audio (TBR)\n if (stream.Demuxer.Type == MediaType.Audio && stream.Type == MediaType.Audio && AudioStream != null && AudioStream.Demuxer.Type == MediaType.Video)\n {\n foreach (var aStream in VideoDemuxer.AudioStreams)\n VideoDemuxer.DisableStream(aStream);\n }\n }\n\n // Open Codec / Enable on demuxer\n if (EnableDecoding)\n {\n string ret = GetDecoderPtr(stream).Open(stream);\n\n if (ret != null)\n {\n return stream.Type == MediaType.Video\n ? (args = new OpenVideoStreamCompletedArgs((VideoStream)stream, (VideoStream)oldStream, $\"Failed to open video stream #{stream.StreamIndex}\\r\\n{ret}\"))\n : stream.Type == MediaType.Audio\n ? (args = new OpenAudioStreamCompletedArgs((AudioStream)stream, (AudioStream)oldStream, $\"Failed to open audio stream #{stream.StreamIndex}\\r\\n{ret}\"))\n : stream.Type == MediaType.Subs\n ? (args = new OpenSubtitlesStreamCompletedArgs((SubtitlesStream)stream, (SubtitlesStream)oldStream, $\"Failed to open subtitles stream #{stream.StreamIndex}\\r\\n{ret}\"))\n : (args = new OpenDataStreamCompletedArgs((DataStream)stream, (DataStream)oldStream, $\"Failed to open data stream #{stream.StreamIndex}\\r\\n{ret}\"));\n }\n }\n else\n stream.Demuxer.EnableStream(stream);\n\n // Open Audio based on new Video Stream (if not the same suggestion)\n if (defaultAudio && stream.Type == MediaType.Video && Config.Audio.Enabled)\n {\n bool requiresChange = true;\n SuggestAudio(out var aStream, out var aExtStream, VideoDemuxer.AudioStreams);\n\n if (AudioStream != null)\n {\n // External audio streams comparison\n if (Playlist.Selected.ExternalAudioStream != null && aExtStream != null && aExtStream.Index == Playlist.Selected.ExternalAudioStream.Index)\n requiresChange = false;\n // Embedded audio streams comparison\n else if (Playlist.Selected.ExternalAudioStream == null && aStream != null && aStream.StreamIndex == AudioStream.StreamIndex)\n requiresChange = false;\n }\n\n if (!requiresChange)\n {\n if (CanDebug) Log.Debug($\"Audio no need to follow video\");\n }\n else\n {\n if (aStream != null)\n Open(aStream);\n else if (aExtStream != null)\n Open(aExtStream);\n\n //RequiresResync = true;\n }\n }\n\n return stream.Type == MediaType.Video\n ? (args = new OpenVideoStreamCompletedArgs((VideoStream)stream, (VideoStream)oldStream))\n : stream.Type == MediaType.Audio\n ? (args = new OpenAudioStreamCompletedArgs((AudioStream)stream, (AudioStream)oldStream))\n : stream.Type == MediaType.Subs\n ? (args = new OpenSubtitlesStreamCompletedArgs((SubtitlesStream)stream, (SubtitlesStream)oldStream))\n : (args = new OpenDataStreamCompletedArgs((DataStream)stream, (DataStream)oldStream));\n }\n } catch(Exception e)\n {\n return args = new StreamOpenedArgs(null, null, e.Message);\n } finally\n {\n if (stream.Type == MediaType.Video)\n OnOpenVideoStreamCompleted((OpenVideoStreamCompletedArgs)args);\n else if (stream.Type == MediaType.Audio)\n OnOpenAudioStreamCompleted((OpenAudioStreamCompletedArgs)args);\n else if (stream.Type == MediaType.Subs)\n OnOpenSubtitlesStreamCompleted((OpenSubtitlesStreamCompletedArgs)args);\n else\n OnOpenDataStreamCompleted((OpenDataStreamCompletedArgs)args);\n }\n }\n\n public string OpenSuggestedVideo(bool defaultAudio = false)\n {\n VideoStream stream;\n ExternalVideoStream extStream;\n string error = null;\n\n if (ClosedVideoStream != null)\n {\n Log.Debug(\"[Video] Found previously closed stream\");\n\n extStream = ClosedVideoStream.Item1;\n if (extStream != null)\n return Open(extStream, false, ClosedVideoStream.Item2 >= 0 ? ClosedVideoStream.Item2 : -1).Error;\n\n stream = ClosedVideoStream.Item2 >= 0 ? (VideoStream)VideoDemuxer.AVStreamToStream[ClosedVideoStream.Item2] : null;\n }\n else\n SuggestVideo(out stream, out extStream, VideoDemuxer.VideoStreams);\n\n if (stream != null)\n error = Open(stream, defaultAudio).Error;\n else if (extStream != null)\n error = Open(extStream, defaultAudio).Error;\n else if (defaultAudio && Config.Audio.Enabled)\n error = OpenSuggestedAudio(); // We still need audio if no video exists\n\n return error;\n }\n public string OpenSuggestedAudio()\n {\n AudioStream stream = null;\n ExternalAudioStream extStream = null;\n string error = null;\n\n if (ClosedAudioStream != null)\n {\n Log.Debug(\"[Audio] Found previously closed stream\");\n\n extStream = ClosedAudioStream.Item1;\n if (extStream != null)\n return Open(extStream, false, ClosedAudioStream.Item2 >= 0 ? ClosedAudioStream.Item2 : -1).Error;\n\n stream = ClosedAudioStream.Item2 >= 0 ? (AudioStream)VideoDemuxer.AVStreamToStream[ClosedAudioStream.Item2] : null;\n }\n else\n SuggestAudio(out stream, out extStream, VideoDemuxer.AudioStreams);\n\n if (stream != null)\n error = Open(stream).Error;\n else if (extStream != null)\n error = Open(extStream).Error;\n\n return error;\n }\n public void OpenSuggestedSubtitles(int? subIndex = -1)\n {\n long sessionId = OpenItemCounter;\n\n try\n {\n // High Suggest (first lang priority + high rating + already converted/downloaded)\n // 1. Check embedded steams for high suggest\n if (Config.Subtitles.Languages.Count > 0)\n {\n foreach (var stream in VideoDemuxer.SubtitlesStreamsAll)\n {\n if (stream.Language == Config.Subtitles.Languages[0])\n {\n Log.Debug(\"[Subtitles] Found high suggested embedded stream\");\n Open(stream);\n return;\n }\n }\n }\n\n // 2. Check external streams for high suggest\n if (Playlist.Selected.ExternalSubtitlesStreamsAll.Count > 0)\n {\n var extStream = SuggestBestExternalSubtitles();\n if (extStream != null)\n {\n Log.Debug(\"[Subtitles] Found high suggested external stream\");\n Open(extStream);\n return;\n }\n }\n\n // 3. Search offline if allowed\n if (SearchLocalSubtitles())\n {\n // 3.1 Check external streams for high suggest (again for the new additions if any)\n ExternalSubtitlesStream extStream = SuggestBestExternalSubtitles();\n if (extStream != null)\n {\n Log.Debug(\"[Subtitles] Found high suggested local external stream\");\n Open(extStream);\n return;\n }\n }\n\n } catch (Exception e)\n {\n Log.Debug($\"OpenSuggestedSubtitles canceled? [{e.Message}]\");\n return;\n }\n\n Task.Run(() =>\n {\n try\n {\n if (sessionId != OpenItemCounter)\n {\n Log.Debug(\"OpenSuggestedSubtitles canceled\");\n return;\n }\n\n if (sessionId != OpenItemCounter)\n {\n Log.Debug(\"OpenSuggestedSubtitles canceled\");\n return;\n }\n\n // 4. Search online if allowed (not async)\n SearchOnlineSubtitles();\n\n if (sessionId != OpenItemCounter)\n {\n Log.Debug(\"OpenSuggestedSubtitles canceled\");\n return;\n }\n\n // 5. (Any) Check embedded/external streams for config languages (including 'undefined')\n SuggestSubtitles(out var stream, out ExternalSubtitlesStream extStream);\n\n if (stream != null)\n Open(stream);\n else if (extStream != null)\n Open(extStream);\n } catch (Exception e)\n {\n Log.Debug($\"OpenSuggestedSubtitles canceled? [{e.Message}]\");\n }\n });\n }\n public string OpenSuggestedData()\n {\n DataStream stream;\n string error = null;\n\n SuggestData(out stream, VideoDemuxer.DataStreams);\n\n if (stream != null)\n error = Open(stream).Error;\n\n return error;\n }\n\n public string OpenDemuxerInput(Demuxer demuxer, DemuxerInput demuxerInput)\n {\n OpenedPlugin?.OnBuffering();\n\n string error = null;\n\n Dictionary formatOpt = null;\n Dictionary copied = null;\n\n try\n {\n // Set HTTP Config\n if (Playlist.InputType == InputType.Web)\n {\n formatOpt = Config.Demuxer.GetFormatOptPtr(demuxer.Type);\n copied = new Dictionary();\n\n foreach (var opt in formatOpt)\n copied.Add(opt.Key, opt.Value);\n\n if (demuxerInput.UserAgent != null)\n formatOpt[\"user_agent\"] = demuxerInput.UserAgent;\n\n if (demuxerInput.Referrer != null)\n formatOpt[\"referer\"] = demuxerInput.Referrer;\n\n // this can cause issues\n //else if (!formatOpt.ContainsKey(\"referer\") && Playlist.Url != null)\n // formatOpt[\"referer\"] = Playlist.Url;\n\n if (demuxerInput.HTTPHeaders != null)\n {\n formatOpt[\"headers\"] = \"\";\n foreach(var header in demuxerInput.HTTPHeaders)\n formatOpt[\"headers\"] += header.Key + \": \" + header.Value + \"\\r\\n\";\n }\n }\n\n // Open Demuxer Input\n if (demuxerInput.Url != null)\n {\n error = demuxer.Open(demuxerInput.Url);\n\n if (error != null && !string.IsNullOrEmpty(demuxerInput.UrlFallback))\n {\n Log.Warn($\"Fallback to {demuxerInput.UrlFallback}\");\n error = demuxer.Open(demuxerInput.UrlFallback);\n }\n }\n else if (demuxerInput.IOStream != null)\n error = demuxer.Open(demuxerInput.IOStream);\n\n return error;\n } finally\n {\n // Restore HTTP Config\n if (Playlist.InputType == InputType.Web)\n {\n formatOpt.Clear();\n foreach(var opt in copied)\n formatOpt.Add(opt.Key, opt.Value);\n }\n\n OpenedPlugin?.OnBufferingCompleted();\n }\n }\n\n private void LoadPlaylistChapters()\n {\n if (Playlist.Selected != null && Playlist.Selected.Chapters.Count > 0 && MainDemuxer.Chapters.Count == 0)\n {\n foreach (var chapter in Playlist.Selected.Chapters)\n {\n MainDemuxer.Chapters.Add(chapter);\n }\n }\n }\n #endregion\n\n #region Close (Only For EnableDecoding)\n public void CloseAudio()\n {\n ClosedAudioStream = new Tuple(Playlist.Selected.ExternalAudioStream, AudioStream != null ? AudioStream.StreamIndex : -1);\n\n if (Playlist.Selected.ExternalAudioStream != null)\n {\n Playlist.Selected.ExternalAudioStream.Enabled = false;\n Playlist.Selected.ExternalAudioStream = null;\n }\n\n AudioDecoder.Dispose(true);\n }\n public void CloseVideo()\n {\n ClosedVideoStream = new Tuple(Playlist.Selected.ExternalVideoStream, VideoStream != null ? VideoStream.StreamIndex : -1);\n\n if (Playlist.Selected.ExternalVideoStream != null)\n {\n Playlist.Selected.ExternalVideoStream.Enabled = false;\n Playlist.Selected.ExternalVideoStream = null;\n }\n\n VideoDecoder.Dispose(true);\n VideoDecoder.Renderer?.ClearScreen();\n }\n public void CloseSubtitles(int subIndex)\n {\n if (Playlist.Selected.ExternalSubtitlesStreams[subIndex] != null)\n {\n Playlist.Selected.ExternalSubtitlesStreams[subIndex].Enabled = false;\n Playlist.Selected.ExternalSubtitlesStreams[subIndex] = null;\n }\n\n SubtitlesDecoders[subIndex].Dispose(true);\n }\n public void CloseData()\n {\n DataDecoder.Dispose(true);\n }\n #endregion\n}\n"], ["/LLPlayer/FlyleafLib/MediaFramework/MediaRemuxer/Remuxer.cs", "using System.Collections.Generic;\nusing System.Diagnostics;\n\nnamespace FlyleafLib.MediaFramework.MediaRemuxer;\n\npublic unsafe class Remuxer\n{\n public int UniqueId { get; set; }\n public bool Disposed { get; private set; } = true;\n public string Filename { get; private set; }\n public bool HasStreams => mapInOutStreams2.Count > 0 || mapInOutStreams.Count > 0;\n public bool HeaderWritten { get; private set; }\n\n Dictionary mapInOutStreams = new();\n Dictionary mapInInStream = new();\n Dictionary mapInStreamToDts = new();\n Dictionary mapInOutStreams2 = new();\n Dictionary mapInInStream2 = new();\n Dictionary mapInStreamToDts2 = new();\n\n AVFormatContext* fmtCtx;\n AVOutputFormat* fmt;\n\n public Remuxer(int uniqueId = -1)\n => UniqueId = uniqueId == -1 ? Utils.GetUniqueId() : uniqueId;\n\n public int Open(string filename)\n {\n int ret;\n Filename = filename;\n\n fixed (AVFormatContext** ptr = &fmtCtx)\n ret = avformat_alloc_output_context2(ptr, null, null, Filename);\n\n if (ret < 0) return ret;\n\n fmt = fmtCtx->oformat;\n mapInStreamToDts = new Dictionary();\n Disposed = false;\n\n return 0;\n }\n\n public int AddStream(AVStream* in_stream, bool isAudioDemuxer = false)\n {\n int ret = -1;\n\n if (in_stream == null || (in_stream->codecpar->codec_type != AVMediaType.Video && in_stream->codecpar->codec_type != AVMediaType.Audio)) return ret;\n\n AVStream *out_stream;\n var in_codecpar = in_stream->codecpar;\n\n out_stream = avformat_new_stream(fmtCtx, null);\n if (out_stream == null) return -1;\n\n ret = avcodec_parameters_copy(out_stream->codecpar, in_codecpar);\n if (ret < 0) return ret;\n\n // Copy metadata (currently only language)\n AVDictionaryEntry* b = null;\n while (true)\n {\n b = av_dict_get(in_stream->metadata, \"\", b, DictReadFlags.IgnoreSuffix);\n if (b == null) break;\n\n if (Utils.BytePtrToStringUTF8(b->key).ToLower() == \"language\" || Utils.BytePtrToStringUTF8(b->key).ToLower() == \"lang\")\n av_dict_set(&out_stream->metadata, Utils.BytePtrToStringUTF8(b->key), Utils.BytePtrToStringUTF8(b->value), 0);\n }\n\n out_stream->codecpar->codec_tag = 0;\n\n // TODO:\n // validate that the output format container supports the codecs (if not change the container?)\n // check whether we remux from mp4 to mpegts (requires bitstream filter h264_mp4toannexb)\n\n //if (av_codec_get_tag(fmtCtx->oformat->codec_tag, in_stream->codecpar->codec_id) == 0)\n // Log(\"Not Found\");\n //else\n // Log(\"Found\");\n\n if (isAudioDemuxer)\n {\n mapInOutStreams2.Add((IntPtr)in_stream, (IntPtr)out_stream);\n mapInInStream2.Add(in_stream->index, (IntPtr)in_stream);\n }\n else\n {\n mapInOutStreams.Add((IntPtr)in_stream, (IntPtr)out_stream);\n mapInInStream.Add(in_stream->index, (IntPtr)in_stream);\n }\n\n return 0;\n }\n\n public int WriteHeader()\n {\n if (!HasStreams) throw new Exception(\"No streams have been configured for the remuxer\");\n\n int ret;\n\n ret = avio_open(&fmtCtx->pb, Filename, IOFlags.Write);\n if (ret < 0) { Dispose(); return ret; }\n\n ret = avformat_write_header(fmtCtx, null);\n\n if (ret < 0) { Dispose(); return ret; }\n\n HeaderWritten = true;\n\n return 0;\n }\n\n public int Write(AVPacket* packet, bool isAudioDemuxer = false)\n {\n lock (this)\n {\n var mapInInStream = !isAudioDemuxer? this.mapInInStream : mapInInStream2;\n var mapInOutStreams = !isAudioDemuxer? this.mapInOutStreams : mapInOutStreams2;\n var mapInStreamToDts = !isAudioDemuxer? this.mapInStreamToDts: mapInStreamToDts2;\n\n AVStream* in_stream = (AVStream*) mapInInStream[packet->stream_index];\n AVStream* out_stream = (AVStream*) mapInOutStreams[(IntPtr)in_stream];\n\n if (packet->dts != AV_NOPTS_VALUE)\n {\n\n if (!mapInStreamToDts.ContainsKey(in_stream->index))\n {\n // TODO: In case of AudioDemuxer calculate the diff with the VideoDemuxer and add it in one of them - all stream - (in a way to have positive)\n mapInStreamToDts.Add(in_stream->index, packet->dts);\n }\n\n packet->pts = packet->pts == AV_NOPTS_VALUE ? AV_NOPTS_VALUE : av_rescale_q_rnd(packet->pts - mapInStreamToDts[in_stream->index], in_stream->time_base, out_stream->time_base, AVRounding.NearInf | AVRounding.PassMinmax);\n packet->dts = av_rescale_q_rnd(packet->dts - mapInStreamToDts[in_stream->index], in_stream->time_base, out_stream->time_base, AVRounding.NearInf | AVRounding.PassMinmax);\n }\n else\n {\n packet->pts = packet->pts == AV_NOPTS_VALUE ? AV_NOPTS_VALUE : av_rescale_q_rnd(packet->pts, in_stream->time_base, out_stream->time_base, AVRounding.NearInf | AVRounding.PassMinmax);\n packet->dts = AV_NOPTS_VALUE;\n }\n\n packet->duration = av_rescale_q(packet->duration,in_stream->time_base, out_stream->time_base);\n packet->stream_index = out_stream->index;\n packet->pos = -1;\n\n int ret = av_interleaved_write_frame(fmtCtx, packet);\n av_packet_free(&packet);\n\n return ret;\n }\n }\n\n public int WriteTrailer() => Dispose();\n public int Dispose()\n {\n if (Disposed) return -1;\n\n int ret = 0;\n\n if (fmtCtx != null)\n {\n if (HeaderWritten)\n {\n ret = av_write_trailer(fmtCtx);\n avio_closep(&fmtCtx->pb);\n }\n\n avformat_free_context(fmtCtx);\n }\n\n fmtCtx = null;\n Filename = null;\n Disposed = true;\n HeaderWritten = false;\n mapInOutStreams.Clear();\n mapInInStream.Clear();\n mapInOutStreams2.Clear();\n mapInInStream2.Clear();\n\n return ret;\n }\n\n private void Log(string msg)\n => Debug.WriteLine($\"[{DateTime.Now:hh.mm.ss.fff}] [#{UniqueId}] [Remuxer] {msg}\");\n}\n"], ["/LLPlayer/FlyleafLib/MediaPlayer/Subtitles.cs", "using System.Collections.ObjectModel;\nusing FlyleafLib.MediaFramework.MediaContext;\nusing FlyleafLib.MediaFramework.MediaStream;\nusing System.ComponentModel;\nusing System.Diagnostics;\nusing System.Linq;\nusing System.Threading.Tasks;\nusing System.Windows;\nusing System.Windows.Media.Imaging;\nusing static FlyleafLib.Utils;\n\nnamespace FlyleafLib.MediaPlayer;\n\npublic class SubsBitmap\n{\n public WriteableBitmap Source { get; set; }\n public int X { get; set; }\n public int Y { get; set; }\n public int Width { get; set; }\n public int Height { get; set; }\n}\n\npublic class SubsBitmapPosition : NotifyPropertyChanged\n{\n private readonly Player _player;\n private readonly int _subIndex;\n\n public SubsBitmapPosition(Player player, int subIndex)\n {\n _player = player;\n _subIndex = subIndex;\n\n Calculate();\n }\n\n #region Config\n\n public double ConfScale\n {\n get;\n set\n {\n if (value <= 0)\n {\n return;\n }\n\n if (Set(ref field, Math.Round(value, 2)))\n {\n Calculate();\n }\n }\n } = 1.0; // x 1.0\n\n public double ConfPos\n {\n get;\n set\n {\n if (value < 0 || value > 150)\n {\n return;\n }\n\n if (Set(ref field, Math.Round(value)))\n {\n Calculate();\n }\n }\n } = 100; // 0 - 150\n\n #endregion\n\n #region WPF Property\n\n public Thickness? Margin { get; private set => Set(ref field, value); }\n\n public double ScaleX { get; private set => Set(ref field, value); } = 1.0;\n\n public double ScaleY { get; private set => Set(ref field, value); } = 1.0;\n\n /// \n /// True for horizontal subtitles\n /// Bitmap subtitles may be displayed vertically\n /// \n public bool IsHorizontal { get; private set; }\n\n #endregion\n\n public void Reset()\n {\n ConfScale = 1.0;\n ConfPos = 100;\n\n Margin = null;\n ScaleX = 1.0;\n ScaleY = 1.0;\n IsHorizontal = false;\n }\n\n public void Calculate()\n {\n if (_player.Subtitles == null ||\n _player.Subtitles[_subIndex].Data.Bitmap == null ||\n _player.SubtitlesDecoders[_subIndex].SubtitlesStream == null ||\n (_player.SubtitlesDecoders[_subIndex].Width == 0 && _player.SubtitlesManager[_subIndex].Width == 0) ||\n (_player.SubtitlesDecoders[_subIndex].Height == 0 && _player.SubtitlesManager[_subIndex].Height == 0))\n {\n return;\n }\n\n SubsBitmap bitmap = _player.Subtitles[_subIndex].Data.Bitmap;\n\n // Calculate the ratio of the current width of the window to the width of the video\n double renderWidth = _player.VideoDecoder.Renderer.GetViewport.Width;\n double videoWidth = _player.SubtitlesDecoders[_subIndex].Width;\n if (videoWidth == 0)\n {\n // Restore from cache because Width/Height may not be taken if the subtitle is not decoded enough.\n videoWidth = _player.SubtitlesManager[_subIndex].Width;\n }\n\n // double videoHeight_ = (int)(videoWidth / Player.VideoDemuxer.VideoStream.AspectRatio.Value);\n double renderHeight = _player.VideoDecoder.Renderer.GetViewport.Height;\n double videoHeight = _player.SubtitlesDecoders[_subIndex].Height;\n if (videoHeight == 0)\n {\n videoHeight = _player.SubtitlesManager[_subIndex].Height;\n }\n\n // In aspect ratio like a movie, a black background may be added to the top and bottom.\n // In this case, the subtitles should be placed based on the video display area, so the offset from the image rendering area excluding the black background should be taken into consideration.\n double yOffset = _player.renderer.GetViewport.Y;\n double xOffset = _player.renderer.GetViewport.X;\n\n double scaleFactorX = renderWidth / videoWidth;\n // double scaleFactorY = renderHeight / videoHeight;\n\n // Adjust subtitle size by the calculated ratio\n double scaleX = scaleFactorX;\n // double scaleY = scaleFactorY;\n\n // Note that if you are cropping videos with mkv in Handbrake, the subtitles will be crushed vertically if you don't use this one. vlc will crush them, but mpv will not have a problem.\n // It may be nice to be able to choose between the two.\n double scaleY = scaleX;\n\n double x = bitmap.X * scaleFactorX + xOffset;\n\n double yPosition = bitmap.Y / videoHeight;\n double y = renderHeight * yPosition + yOffset;\n\n // Adjust subtitle position(y - axis) by config.\n // However, if it detects that the subtitle is not a normal subtitle such as vertical subtitle, it will not be adjusted.\n // (Adjust only when it is below the center of the screen)\n // mpv: https://github.com/mpv-player/mpv/blob/df166c1333694cbfe70980dbded1984d48b0685a/sub/sd_lavc.c#L491-L494\n IsHorizontal = (bitmap.Y >= videoHeight / 2);\n if (IsHorizontal)\n {\n // mpv: https://github.com/mpv-player/mpv/blob/df166c1333694cbfe70980dbded1984d48b0685a/sub/sd_lavc.c#L486\n double offset = (100.0 - ConfPos) / 100.0 * videoHeight;\n y -= offset * scaleY;\n }\n\n // Adjust x and y axes when changing subtitle size(centering)\n if (ConfScale != 1.0)\n {\n // mpv: https://github.com/mpv-player/mpv/blob/df166c1333694cbfe70980dbded1984d48b0685a/sub/sd_lavc.c#L508-L515\n double ratio = (ConfScale - 1.0) / 2;\n\n double dw = bitmap.Width * scaleX;\n double dy = bitmap.Height * scaleY;\n\n x -= dw * ratio;\n y -= dy * ratio;\n\n scaleX *= ConfScale;\n scaleY *= ConfScale;\n }\n\n Margin = new Thickness(x, y, 0, 0);\n ScaleX = scaleX;\n ScaleY = scaleY;\n }\n}\n\npublic class SubsData : NotifyPropertyChanged\n{\n#nullable enable\n private readonly Player _player;\n private readonly int _subIndex;\n private Subtitles Subs => _player.Subtitles;\n private Config Config => _player.Config;\n\n public SubsData(Player player, int subIndex)\n {\n _player = player;\n _subIndex = subIndex;\n\n BitmapPosition = new SubsBitmapPosition(_player, _subIndex);\n\n Config.Subtitles[_subIndex].PropertyChanged += SubConfigOnPropertyChanged;\n }\n\n private void SubConfigOnPropertyChanged(object? sender, PropertyChangedEventArgs e)\n {\n if (e.PropertyName == nameof(Config.SubConfig.Visible))\n {\n Raise(nameof(IsVisible));\n Raise(nameof(IsAbsoluteVisible));\n Raise(nameof(IsDisplaying));\n }\n }\n\n /// \n /// Subtitles Position (Position & Scale)\n /// \n public SubsBitmapPosition BitmapPosition { get; }\n\n /// \n /// Subtitles Bitmap\n /// \n public SubsBitmap? Bitmap\n {\n get;\n internal set\n {\n if (!Set(ref field, value))\n {\n return;\n }\n\n BitmapPosition.Calculate();\n\n if (Bitmap != null)\n {\n // TODO: L: When vertical and horizontal subtitles are displayed at the same time, the subtitles are displayed incorrectly\n // Absolute display of Primary sub\n // 1. If Primary is true and Secondary is false\n // 2. When a vertical subtitle is detected\n\n // Absolute display of Secondary sub\n // 1. When a vertical subtitle is detected\n bool isAbsolute = Subs[0].Enabled && !Subs[1].Enabled;\n if (!BitmapPosition.IsHorizontal)\n {\n isAbsolute = true;\n }\n\n IsAbsolute = isAbsolute;\n }\n\n Raise(nameof(IsDisplaying));\n }\n }\n\n /// \n /// Whether subtitles are currently displayed or not\n /// (unless bitmap subtitles are displayed absolutely)\n /// \n public bool IsDisplaying => IsVisible && (Bitmap != null && !IsAbsolute // Bitmap subtitles, not absolute display\n ||\n !string.IsNullOrEmpty(Text)); // When text subtitles are available\n\n /// \n /// When vertical subtitle is detected in the case of bitmap sub, it becomes True and is displayed as absolute.\n /// \n public bool IsAbsolute\n {\n get;\n private set\n {\n if (Set(ref field, value))\n {\n Raise(nameof(IsAbsoluteVisible));\n Raise(nameof(IsDisplaying));\n }\n }\n } = false;\n\n /// \n /// Bind target Used for switching Visibility\n /// \n public bool IsAbsoluteVisible => IsAbsolute && IsVisible;\n\n /// \n /// Bind target Used for switching Visibility\n /// \n public bool IsVisible => Config.Subtitles[_subIndex].Visible;\n\n /// \n /// Subtitles Text (updates dynamically while playing based on the duration that it should be displayed)\n /// \n public string Text\n {\n get;\n internal set\n {\n if (Set(ref field, value))\n {\n Raise(nameof(IsDisplaying));\n }\n }\n } = \"\";\n\n public bool IsTranslated { get; set => Set(ref field, value); }\n\n public Language? Language { get; set => Set(ref field, value); }\n\n public void Reset()\n {\n Clear();\n UI(() =>\n {\n // Clear does not reset because there is a config in SubsBitmapPosition\n BitmapPosition.Reset();\n });\n }\n\n public void Clear()\n {\n if (Text != \"\" || Bitmap != null)\n {\n UI(() =>\n {\n Text = \"\";\n Bitmap = null;\n });\n }\n }\n#nullable restore\n}\n\n/// \n/// Preserve the state of streamIndex, URL, etc. of the currently selected subtitle in a global variable.\n/// TODO: L: Cannot use multiple Players in one app, required to change this?\n/// \npublic static class SubtitlesSelectedHelper\n{\n#nullable enable\n public static ValueTuple? Primary { get; set; }\n public static ValueTuple? Secondary { get; set; }\n\n public static SelectSubMethod PrimaryMethod { get; set; } = SelectSubMethod.Original;\n public static SelectSubMethod SecondaryMethod { get; set; } = SelectSubMethod.Original;\n\n /// \n /// Holds the index to switch (0: Primary, 1: Secondary)\n /// \n public static int CurIndex { get; set; } = 0;\n\n public static void Reset(int subIndex)\n {\n Debug.Assert(subIndex is 0 or 1);\n\n if (subIndex == 1)\n {\n Secondary = null;\n SecondaryMethod = SelectSubMethod.Original;\n }\n else\n {\n Primary = null;\n PrimaryMethod = SelectSubMethod.Original;\n }\n }\n\n public static SelectSubMethod GetMethod(int subIndex)\n {\n Debug.Assert(subIndex is 0 or 1);\n\n return subIndex == 1 ? SecondaryMethod : PrimaryMethod;\n }\n\n public static void SetMethod(int subIndex, SelectSubMethod method)\n {\n Debug.Assert(subIndex is 0 or 1);\n\n if (subIndex == 1)\n {\n SecondaryMethod = method;\n }\n else\n {\n PrimaryMethod = method;\n }\n }\n\n public static ValueTuple? Get(int subIndex)\n {\n Debug.Assert(subIndex is 0 or 1);\n return subIndex == 1 ? Secondary : Primary;\n }\n\n public static void Set(int subIndex, ValueTuple? tuple)\n {\n Debug.Assert(subIndex is 0 or 1);\n if (subIndex == 1)\n {\n Secondary = tuple;\n }\n else\n {\n Primary = tuple;\n }\n }\n\n public static bool GetSubEnabled(this StreamBase stream, int subIndex)\n {\n Debug.Assert(subIndex is 0 or 1);\n var tuple = subIndex == 1 ? Secondary : Primary;\n\n if (!tuple.HasValue)\n {\n return false;\n }\n\n if (tuple.Value.Item1.HasValue)\n {\n // internal sub\n return tuple.Value.Item1 == stream.StreamIndex;\n }\n\n if (tuple.Value.Item2 is not null && stream.ExternalStream is not null)\n {\n // external sub\n return GetSubEnabled(stream.ExternalStream, subIndex);\n }\n\n return false;\n }\n\n public static bool GetSubEnabled(this ExternalStream stream, int subIndex)\n {\n ArgumentNullException.ThrowIfNull(stream);\n\n return GetSubEnabled(stream.Url, subIndex);\n }\n\n public static bool GetSubEnabled(this string url, int subIndex)\n {\n Debug.Assert(subIndex is 0 or 1);\n var tuple = subIndex == 1 ? Secondary : Primary;\n\n if (!tuple.HasValue || tuple.Value.Item2 is null)\n {\n return false;\n }\n\n return tuple.Value.Item2.Url == url;\n }\n#nullable restore\n}\n\npublic class Subtitle : NotifyPropertyChanged\n{\n private readonly Player _player;\n private readonly int _subIndex;\n\n private Config Config => _player.Config;\n private DecoderContext Decoder => _player?.decoder;\n\n public Subtitle(int subIndex, Player player)\n {\n _player = player;\n _subIndex = subIndex;\n\n Data = new SubsData(_player, _subIndex);\n }\n\n #pragma warning disable CS9266\n public bool EnabledASR { get => _enabledASR; private set => Set(ref field, value); }\n private bool _enabledASR;\n\n /// \n /// Whether the input has subtitles and it is configured\n /// \n public bool IsOpened { get => _isOpened; private set => Set(ref field, value); }\n private bool _isOpened;\n\n public string Codec { get => _codec; private set => Set(ref field, value); }\n private string _codec;\n\n public bool IsBitmap { get => _isBitmap; private set => Set(ref field, value); }\n private bool _isBitmap;\n #pragma warning restore CS9266\n\n public bool Enabled => IsOpened || EnabledASR;\n\n public SubsData Data { get; }\n\n private void UpdateUI()\n {\n UI(() =>\n {\n IsOpened = IsOpened;\n Codec = Codec;\n IsBitmap = IsBitmap;\n EnabledASR = EnabledASR;\n });\n }\n\n internal void Reset()\n {\n _codec = null;\n _isOpened = false;\n _isBitmap = false;\n _player.sFramesPrev[_subIndex] = null;\n // TODO: L: Here it may be null when switching subs while displaying.\n _player.sFrames[_subIndex] = null;\n _enabledASR = false;\n\n _player.SubtitlesASR.Reset(_subIndex);\n _player.SubtitlesOCR.Reset(_subIndex);\n _player.SubtitlesManager[_subIndex].Reset();\n\n _player.SubtitleClear(_subIndex);\n //_player.renderer?.ClearOverlayTexture();\n\n SubtitlesSelectedHelper.Reset(_subIndex);\n\n Data.Reset();\n UpdateUI();\n }\n\n internal void Refresh()\n {\n var subStream = Decoder.SubtitlesStreams[_subIndex];\n\n if (subStream == null)\n {\n Reset();\n return;\n }\n\n _codec = subStream.Codec;\n _isOpened = !Decoder.SubtitlesDecoders[_subIndex].Disposed;\n _isBitmap = subStream is { IsBitmap: true };\n\n // Update the selection state of automatically opened subtitles\n // (also manually updated but no problem as it is no change, necessary for primary subtitles)\n if (subStream.ExternalStream is ExternalSubtitlesStream extStream)\n {\n // external sub\n SubtitlesSelectedHelper.Set(_subIndex, (null, extStream));\n }\n else if (subStream.StreamIndex != -1)\n {\n // internal sub\n SubtitlesSelectedHelper.Set(_subIndex, (subStream.StreamIndex, null));\n }\n\n Data.Reset();\n _player.sFramesPrev[_subIndex] = null;\n _player.sFrames[_subIndex] = null;\n _player.SubtitleClear(_subIndex);\n //player.renderer?.ClearOverlayTexture();\n\n _enabledASR = false;\n _player.SubtitlesASR.Reset(_subIndex);\n _player.SubtitlesOCR.Reset(_subIndex);\n _player.SubtitlesManager[_subIndex].Reset();\n\n if (_player.renderer != null)\n {\n // Adjust bitmap subtitle size when resizing screen\n _player.renderer.ViewportChanged -= RendererOnViewportChanged;\n _player.renderer.ViewportChanged += RendererOnViewportChanged;\n }\n\n UpdateUI();\n\n // Create cache of the all subtitles in a separate thread\n Task.Run(Load)\n .ContinueWith(t =>\n {\n // TODO: L: error handling - restore state gracefully?\n if (t.IsFaulted)\n {\n var ex = t.Exception.Flatten().InnerException;\n\n _player.RaiseUnknownErrorOccurred($\"Cannot load all subtitles on worker thread: {ex?.Message}\", UnknownErrorType.Subtitles, ex);\n }\n }, TaskContinuationOptions.OnlyOnFaulted);\n }\n\n internal void Load()\n {\n SubtitlesStream stream = Decoder.SubtitlesStreams[_subIndex];\n ExternalSubtitlesStream extStream = stream.ExternalStream as ExternalSubtitlesStream;\n\n if (extStream != null)\n {\n // external sub\n // always load all bitmaps on memory with external subtitles\n _player.SubtitlesManager.Open(_subIndex, stream.Demuxer.Url, stream.StreamIndex, stream.Demuxer.Type, true, extStream.Language);\n }\n else\n {\n // internal sub\n // load all bitmaps on memory when cache enabled or OCR used\n bool useBitmap = Config.Subtitles.EnabledCached || SubtitlesSelectedHelper.GetMethod(_subIndex) == SelectSubMethod.OCR;\n _player.SubtitlesManager.Open(_subIndex, stream.Demuxer.Url, stream.StreamIndex, stream.Demuxer.Type, useBitmap, stream.Language);\n }\n\n TimeSpan curTime = new(_player.CurTime);\n\n _player.SubtitlesManager[_subIndex].SetCurrentTime(curTime);\n\n // Do OCR\n // TODO: L: When OCR is performed while bitmap stream is loaded, the stream is reset and the bitmap is loaded again.\n // Is it better to reuse loaded bitmap?\n if (SubtitlesSelectedHelper.GetMethod(_subIndex) == SelectSubMethod.OCR)\n {\n using (_player.SubtitlesManager[_subIndex].StartLoading())\n {\n _player.SubtitlesOCR.Do(_subIndex, _player.SubtitlesManager[_subIndex].Subs.ToList(), curTime);\n }\n }\n }\n\n internal void Enable()\n {\n if (!_player.CanPlay)\n return;\n\n // TODO: L: For some reason, there is a problem with subtitles temporarily not being\n // displayed, waiting for about 10 seconds will fix it.\n Decoder.OpenSuggestedSubtitles(_subIndex);\n\n _player.ReSync(Decoder.SubtitlesStreams[_subIndex], (int)(_player.CurTime / 10000), true);\n\n Refresh();\n UpdateUI();\n }\n internal void Disable()\n {\n if (!Enabled)\n return;\n\n Decoder.CloseSubtitles(_subIndex);\n Reset();\n UpdateUI();\n\n SubtitlesSelectedHelper.Reset(_subIndex);\n }\n\n private void RendererOnViewportChanged(object sender, EventArgs e)\n {\n Data.BitmapPosition.Calculate();\n }\n\n public void EnableASR()\n {\n _enabledASR = true;\n\n var url = _player.AudioDecoder.Demuxer.Url;\n var type = _player.AudioDecoder.Demuxer.Type;\n var streamIndex = _player.AudioDecoder.AudioStream.StreamIndex;\n\n TimeSpan curTime = new(_player.CurTime);\n\n Task.Run(() =>\n {\n bool isDone;\n\n using (_player.SubtitlesManager[_subIndex].StartLoading())\n {\n isDone = _player.SubtitlesASR.Execute(_subIndex, url, streamIndex, type, curTime);\n }\n\n if (!isDone)\n {\n // re-enable spinner because it is running\n _player.SubtitlesManager[_subIndex].StartLoading();\n }\n })\n .ContinueWith(t =>\n {\n if (t.IsFaulted)\n {\n if (_player.SubtitlesManager[_subIndex].Subs.Count == 0)\n {\n // reset if not single subtitles generated\n Disable();\n }\n\n var ex = t.Exception.Flatten().InnerException;\n\n _player.RaiseUnknownErrorOccurred($\"Cannot execute ASR: {ex?.Message}\", UnknownErrorType.ASR, t.Exception);\n }\n }, TaskContinuationOptions.OnlyOnFaulted);\n\n UpdateUI();\n }\n}\n\npublic class Subtitles\n{\n /// \n /// Embedded Streams\n /// \n public ObservableCollection\n Streams => _player.decoder?.VideoDemuxer.SubtitlesStreamsAll;\n\n private readonly Subtitle[] _subs;\n\n // indexer\n public Subtitle this[int i] => _subs[i];\n\n public Player Player => _player;\n\n private readonly Player _player;\n\n private Config Config => _player.Config;\n\n private int subNum => Config.Subtitles.Max;\n\n public Subtitles(Player player)\n {\n _player = player;\n _subs = new Subtitle[subNum];\n\n for (int i = 0; i < subNum; i++)\n {\n _subs[i] = new Subtitle(i, _player);\n }\n }\n\n internal void Enable()\n {\n for (int i = 0; i < subNum; i++)\n {\n this[i].Enable();\n }\n }\n\n internal void Disable()\n {\n for (int i = 0; i < subNum; i++)\n {\n this[i].Disable();\n }\n }\n\n internal void Reset()\n {\n for (int i = 0; i < subNum; i++)\n {\n this[i].Reset();\n }\n }\n\n internal void Refresh()\n {\n for (int i = 0; i < subNum; i++)\n {\n this[i].Refresh();\n }\n }\n\n // TODO: L: refactor\n public void DelayRemovePrimary() => Config.Subtitles[0].Delay -= Config.Player.SubtitlesDelayOffset;\n public void DelayAddPrimary() => Config.Subtitles[0].Delay += Config.Player.SubtitlesDelayOffset;\n public void DelayRemove2Primary() => Config.Subtitles[0].Delay -= Config.Player.SubtitlesDelayOffset2;\n public void DelayAdd2Primary() => Config.Subtitles[0].Delay += Config.Player.SubtitlesDelayOffset2;\n\n public void DelayRemoveSecondary() => Config.Subtitles[1].Delay -= Config.Player.SubtitlesDelayOffset;\n public void DelayAddSecondary() => Config.Subtitles[1].Delay += Config.Player.SubtitlesDelayOffset;\n public void DelayRemove2Secondary() => Config.Subtitles[1].Delay -= Config.Player.SubtitlesDelayOffset2;\n public void DelayAdd2Secondary() => Config.Subtitles[1].Delay += Config.Player.SubtitlesDelayOffset2;\n\n public void ToggleEnabled() => Config.Subtitles.Enabled = !Config.Subtitles.Enabled;\n\n public void ToggleVisibility()\n {\n Config.Subtitles[0].Visible = !Config.Subtitles[0].Visible;\n Config.Subtitles[1].Visible = Config.Subtitles[0].Visible;\n }\n public void ToggleVisibilityPrimary()\n {\n Config.Subtitles[0].Visible = !Config.Subtitles[0].Visible;\n }\n\n public void ToggleVisibilitySecondary()\n {\n Config.Subtitles[1].Visible = !Config.Subtitles[1].Visible;\n }\n\n private bool _prevSeek(int subIndex)\n {\n var prev = _player.SubtitlesManager[subIndex].GetPrev();\n if (prev is not null)\n {\n _player.SeekAccurate(prev.StartTime, subIndex);\n return true;\n }\n\n return false;\n }\n\n public void PrevSeek() => _prevSeek(0);\n public void PrevSeek2() => _prevSeek(1);\n\n public void PrevSeekFallback()\n {\n if (!_prevSeek(0))\n {\n _player.SeekBackward2();\n }\n }\n public void PrevSeekFallback2()\n {\n if (!_prevSeek(1))\n {\n _player.SeekBackward2();\n }\n }\n\n private void _curSeek(int subIndex)\n {\n var cur = _player.SubtitlesManager[subIndex].GetCurrent();\n if (cur is not null)\n {\n _player.SeekAccurate(cur.StartTime, subIndex);\n }\n else\n {\n // fallback to prevSeek (same as mpv)\n _prevSeek(subIndex);\n }\n }\n\n public void CurSeek() => _curSeek(0);\n public void CurSeek2() => _curSeek(1);\n\n private bool _nextSeek(int subIndex)\n {\n var next = _player.SubtitlesManager[subIndex].GetNext();\n if (next is not null)\n {\n _player.SeekAccurate(next.StartTime, subIndex);\n return true;\n }\n return false;\n }\n\n public void NextSeek() => _nextSeek(0);\n public void NextSeek2() => _nextSeek(1);\n\n public void NextSeekFallback()\n {\n if (!_nextSeek(0))\n {\n _player.SeekForward2();\n }\n }\n public void NextSeekFallback2()\n {\n if (!_nextSeek(1))\n {\n _player.SeekForward2();\n }\n }\n}\n"], ["/LLPlayer/LLPlayer/Extensions/TextBoxHelper.cs", "using System.Windows;\nusing System.Windows.Controls;\nusing System.Windows.Input;\n\nnamespace LLPlayer.Extensions;\n\n\n// ref: https://stackoverflow.com/a/50905766/9070784\npublic static class TextBoxHelper\n{\n #region Enum Declarations\n public enum NumericFormat\n {\n Double,\n Int,\n Uint,\n Natural\n }\n\n public enum EvenOddConstraint\n {\n All,\n OnlyEven,\n OnlyOdd\n }\n\n #endregion\n\n #region Dependency Properties & CLR Wrappers\n\n public static readonly DependencyProperty OnlyNumericProperty =\n DependencyProperty.RegisterAttached(\"OnlyNumeric\", typeof(NumericFormat?), typeof(TextBoxHelper),\n new PropertyMetadata(null, DependencyPropertiesChanged));\n public static void SetOnlyNumeric(TextBox element, NumericFormat value) =>\n element.SetValue(OnlyNumericProperty, value);\n public static NumericFormat GetOnlyNumeric(TextBox element) =>\n (NumericFormat)element.GetValue(OnlyNumericProperty);\n\n\n public static readonly DependencyProperty DefaultValueProperty =\n DependencyProperty.RegisterAttached(\"DefaultValue\", typeof(string), typeof(TextBoxHelper),\n new PropertyMetadata(null, DependencyPropertiesChanged));\n public static void SetDefaultValue(TextBox element, string value) =>\n element.SetValue(DefaultValueProperty, value);\n public static string GetDefaultValue(TextBox element) => (string)element.GetValue(DefaultValueProperty);\n\n\n public static readonly DependencyProperty EvenOddConstraintProperty =\n DependencyProperty.RegisterAttached(\"EvenOddConstraint\", typeof(EvenOddConstraint), typeof(TextBoxHelper),\n new PropertyMetadata(EvenOddConstraint.All, DependencyPropertiesChanged));\n public static void SetEvenOddConstraint(TextBox element, EvenOddConstraint value) =>\n element.SetValue(EvenOddConstraintProperty, value);\n public static EvenOddConstraint GetEvenOddConstraint(TextBox element) =>\n (EvenOddConstraint)element.GetValue(EvenOddConstraintProperty);\n\n #endregion\n\n #region Dependency Properties Methods\n\n private static void DependencyPropertiesChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)\n {\n if (!(d is TextBox textBox))\n throw new Exception(\"Attached property must be used with TextBox.\");\n\n switch (e.Property.Name)\n {\n case \"OnlyNumeric\":\n {\n var castedValue = (NumericFormat?)e.NewValue;\n\n if (castedValue.HasValue)\n {\n textBox.PreviewTextInput += TextBox_PreviewTextInput;\n DataObject.AddPastingHandler(textBox, TextBox_PasteEventHandler);\n }\n else\n {\n textBox.PreviewTextInput -= TextBox_PreviewTextInput;\n DataObject.RemovePastingHandler(textBox, TextBox_PasteEventHandler);\n }\n\n break;\n }\n\n case \"DefaultValue\":\n {\n var castedValue = (string)e.NewValue;\n\n if (castedValue != null)\n {\n textBox.TextChanged += TextBox_TextChanged;\n }\n else\n {\n textBox.TextChanged -= TextBox_TextChanged;\n }\n\n break;\n }\n }\n }\n\n #endregion\n\n private static void TextBox_PreviewTextInput(object sender, TextCompositionEventArgs e)\n {\n var textBox = (TextBox)sender;\n\n string newText;\n\n if (textBox.SelectionLength == 0)\n {\n newText = textBox.Text.Insert(textBox.SelectionStart, e.Text);\n }\n else\n {\n var textAfterDelete = textBox.Text.Remove(textBox.SelectionStart, textBox.SelectionLength);\n\n newText = textAfterDelete.Insert(textBox.SelectionStart, e.Text);\n }\n\n var evenOddConstraint = GetEvenOddConstraint(textBox);\n\n switch (GetOnlyNumeric(textBox))\n {\n case NumericFormat.Double:\n {\n if (double.TryParse(newText, out double number))\n {\n switch (evenOddConstraint)\n {\n case EvenOddConstraint.OnlyEven:\n\n if (number % 2 != 0)\n e.Handled = true;\n else\n e.Handled = false;\n\n break;\n\n case EvenOddConstraint.OnlyOdd:\n\n if (number % 2 == 0)\n e.Handled = true;\n else\n e.Handled = false;\n\n break;\n }\n }\n else\n e.Handled = true;\n\n break;\n }\n\n case NumericFormat.Int:\n {\n if (int.TryParse(newText, out int number))\n {\n switch (evenOddConstraint)\n {\n case EvenOddConstraint.OnlyEven:\n\n if (number % 2 != 0)\n e.Handled = true;\n else\n e.Handled = false;\n\n break;\n\n case EvenOddConstraint.OnlyOdd:\n\n if (number % 2 == 0)\n e.Handled = true;\n else\n e.Handled = false;\n\n break;\n }\n }\n else\n e.Handled = true;\n\n break;\n }\n\n case NumericFormat.Uint:\n {\n if (uint.TryParse(newText, out uint number))\n {\n switch (evenOddConstraint)\n {\n case EvenOddConstraint.OnlyEven:\n\n if (number % 2 != 0)\n e.Handled = true;\n else\n e.Handled = false;\n\n break;\n\n case EvenOddConstraint.OnlyOdd:\n\n if (number % 2 == 0)\n e.Handled = true;\n else\n e.Handled = false;\n\n break;\n }\n }\n else\n e.Handled = true;\n\n break;\n }\n\n case NumericFormat.Natural:\n {\n if (uint.TryParse(newText, out uint number))\n {\n if (number == 0)\n e.Handled = true;\n else\n {\n switch (evenOddConstraint)\n {\n case EvenOddConstraint.OnlyEven:\n\n if (number % 2 != 0)\n e.Handled = true;\n else\n e.Handled = false;\n\n break;\n\n case EvenOddConstraint.OnlyOdd:\n\n if (number % 2 == 0)\n e.Handled = true;\n else\n e.Handled = false;\n\n break;\n }\n }\n }\n else\n e.Handled = true;\n\n break;\n }\n }\n }\n\n private static void TextBox_PasteEventHandler(object sender, DataObjectPastingEventArgs e)\n {\n var textBox = (TextBox)sender;\n\n if (e.DataObject.GetDataPresent(typeof(string)))\n {\n var clipboardText = (string)e.DataObject.GetData(typeof(string));\n\n var newText = textBox.Text.Insert(textBox.SelectionStart, clipboardText);\n\n var evenOddConstraint = GetEvenOddConstraint(textBox);\n\n switch (GetOnlyNumeric(textBox))\n {\n case NumericFormat.Double:\n {\n if (double.TryParse(newText, out double number))\n {\n switch (evenOddConstraint)\n {\n case EvenOddConstraint.OnlyEven:\n\n if (number % 2 != 0)\n e.CancelCommand();\n\n break;\n\n case EvenOddConstraint.OnlyOdd:\n\n if (number % 2 == 0)\n e.CancelCommand();\n\n break;\n }\n }\n else\n e.CancelCommand();\n\n break;\n }\n\n case NumericFormat.Int:\n {\n if (int.TryParse(newText, out int number))\n {\n switch (evenOddConstraint)\n {\n case EvenOddConstraint.OnlyEven:\n\n if (number % 2 != 0)\n e.CancelCommand();\n\n break;\n\n case EvenOddConstraint.OnlyOdd:\n\n if (number % 2 == 0)\n e.CancelCommand();\n\n\n break;\n }\n }\n else\n e.CancelCommand();\n\n break;\n }\n\n case NumericFormat.Uint:\n {\n if (uint.TryParse(newText, out uint number))\n {\n switch (evenOddConstraint)\n {\n case EvenOddConstraint.OnlyEven:\n\n if (number % 2 != 0)\n e.CancelCommand();\n\n break;\n\n case EvenOddConstraint.OnlyOdd:\n\n if (number % 2 == 0)\n e.CancelCommand();\n\n\n break;\n }\n }\n else\n e.CancelCommand();\n\n break;\n }\n\n case NumericFormat.Natural:\n {\n if (uint.TryParse(newText, out uint number))\n {\n if (number == 0)\n e.CancelCommand();\n else\n {\n switch (evenOddConstraint)\n {\n case EvenOddConstraint.OnlyEven:\n\n if (number % 2 != 0)\n e.CancelCommand();\n\n break;\n\n case EvenOddConstraint.OnlyOdd:\n\n if (number % 2 == 0)\n e.CancelCommand();\n\n break;\n }\n }\n }\n else\n {\n e.CancelCommand();\n }\n\n break;\n }\n }\n }\n else\n {\n e.CancelCommand();\n }\n }\n\n private static void TextBox_TextChanged(object sender, TextChangedEventArgs e)\n {\n var textBox = (TextBox)sender;\n\n var defaultValue = GetDefaultValue(textBox);\n\n var evenOddConstraint = GetEvenOddConstraint(textBox);\n\n switch (GetOnlyNumeric(textBox))\n {\n case NumericFormat.Double:\n {\n if (double.TryParse(textBox.Text, out double number))\n {\n switch (evenOddConstraint)\n {\n case EvenOddConstraint.OnlyEven:\n\n if (number % 2 != 0)\n textBox.Text = defaultValue;\n\n break;\n\n case EvenOddConstraint.OnlyOdd:\n\n if (number % 2 == 0)\n textBox.Text = defaultValue;\n\n break;\n }\n }\n else\n textBox.Text = defaultValue;\n\n break;\n }\n\n case NumericFormat.Int:\n {\n if (int.TryParse(textBox.Text, out int number))\n {\n switch (evenOddConstraint)\n {\n case EvenOddConstraint.OnlyEven:\n\n if (number % 2 != 0)\n textBox.Text = defaultValue;\n\n break;\n\n case EvenOddConstraint.OnlyOdd:\n\n if (number % 2 == 0)\n textBox.Text = defaultValue;\n\n break;\n }\n }\n else\n textBox.Text = defaultValue;\n\n break;\n }\n\n case NumericFormat.Uint:\n {\n if (uint.TryParse(textBox.Text, out uint number))\n {\n switch (evenOddConstraint)\n {\n case EvenOddConstraint.OnlyEven:\n\n if (number % 2 != 0)\n textBox.Text = defaultValue;\n\n break;\n\n case EvenOddConstraint.OnlyOdd:\n\n if (number % 2 == 0)\n textBox.Text = defaultValue;\n\n break;\n }\n }\n else\n textBox.Text = defaultValue;\n\n break;\n }\n\n case NumericFormat.Natural:\n {\n if (uint.TryParse(textBox.Text, out uint number))\n {\n if (number == 0)\n textBox.Text = defaultValue;\n else\n {\n switch (evenOddConstraint)\n {\n case EvenOddConstraint.OnlyEven:\n\n if (number % 2 != 0)\n textBox.Text = defaultValue;\n\n break;\n\n case EvenOddConstraint.OnlyOdd:\n\n if (number % 2 == 0)\n textBox.Text = defaultValue;\n\n break;\n }\n }\n }\n else\n {\n textBox.Text = defaultValue;\n }\n\n break;\n }\n }\n }\n}\n"], ["/LLPlayer/FlyleafLib/MediaPlayer/Audio.cs", "using System;\nusing System.Collections.ObjectModel;\n\nusing Vortice.Multimedia;\nusing Vortice.XAudio2;\n\nusing static Vortice.XAudio2.XAudio2;\n\nusing FlyleafLib.MediaFramework.MediaContext;\nusing FlyleafLib.MediaFramework.MediaFrame;\nusing FlyleafLib.MediaFramework.MediaStream;\n\nusing static FlyleafLib.Logger;\n\nnamespace FlyleafLib.MediaPlayer;\n\npublic class Audio : NotifyPropertyChanged\n{\n public event EventHandler SamplesAdded;\n\n #region Properties\n /// \n /// Embedded Streams\n /// \n public ObservableCollection\n Streams => decoder?.VideoDemuxer.AudioStreams; // TBR: We miss AudioDemuxer embedded streams\n\n /// \n /// Whether the input has audio and it is configured\n /// \n public bool IsOpened { get => isOpened; internal set => Set(ref _IsOpened, value); }\n internal bool _IsOpened, isOpened;\n\n public string Codec { get => codec; internal set => Set(ref _Codec, value); }\n internal string _Codec, codec;\n\n ///// \n ///// Audio bitrate (Kbps)\n ///// \n public double BitRate { get => bitRate; internal set => Set(ref _BitRate, value); }\n internal double _BitRate, bitRate;\n\n public int Bits { get => bits; internal set => Set(ref _Bits, value); }\n internal int _Bits, bits;\n\n public int Channels { get => channels; internal set => Set(ref _Channels, value); }\n internal int _Channels, channels;\n\n /// \n /// Audio player's channels out (currently 2 channels supported only)\n /// \n public int ChannelsOut { get; } = 2;\n\n public string ChannelLayout { get => channelLayout; internal set => Set(ref _ChannelLayout, value); }\n internal string _ChannelLayout, channelLayout;\n\n ///// \n ///// Total Dropped Frames\n ///// \n public int FramesDropped { get => framesDropped; internal set => Set(ref _FramesDropped, value); }\n internal int _FramesDropped, framesDropped;\n\n public int FramesDisplayed { get => framesDisplayed; internal set => Set(ref _FramesDisplayed, value); }\n internal int _FramesDisplayed, framesDisplayed;\n\n public string SampleFormat { get => sampleFormat; internal set => Set(ref _SampleFormat, value); }\n internal string _SampleFormat, sampleFormat;\n\n /// \n /// Audio sample rate (in/out)\n /// \n public int SampleRate { get => sampleRate; internal set => Set(ref _SampleRate, value); }\n internal int _SampleRate, sampleRate;\n\n /// \n /// Audio player's volume / amplifier (valid values 0 - no upper limit)\n /// \n public int Volume\n {\n get\n {\n lock (locker)\n return sourceVoice == null || Mute ? _Volume : (int) ((decimal)sourceVoice.Volume * 100);\n }\n set\n {\n if (value > Config.Player.VolumeMax || value < 0)\n return;\n\n if (value == 0)\n Mute = true;\n else if (Mute)\n {\n _Volume = value;\n Mute = false;\n }\n else\n {\n if (sourceVoice != null)\n sourceVoice.Volume = Math.Max(0, value / 100.0f);\n }\n\n Set(ref _Volume, value, false);\n }\n }\n int _Volume;\n\n /// \n /// Audio player's mute\n /// \n public bool Mute\n {\n get => mute;\n set\n {\n lock (locker)\n {\n if (sourceVoice == null)\n return;\n\n sourceVoice.Volume = value ? 0 : _Volume / 100.0f;\n }\n\n Set(ref mute, value, false);\n }\n }\n private bool mute = false;\n\n /// \n /// Audio player's current device (available devices can be found on )/>\n /// \n public AudioEngine.AudioEndpoint Device\n {\n get => _Device;\n set\n {\n if ((value == null && _Device == Engine.Audio.DefaultDevice) || value == _Device)\n return;\n\n _Device = value ?? Engine.Audio.DefaultDevice;\n Initialize();\n RaiseUI(nameof(Device));\n }\n }\n internal AudioEngine.AudioEndpoint _Device = Engine.Audio.DefaultDevice;\n #endregion\n\n #region Declaration\n public Player Player => player;\n\n Player player;\n Config Config => player.Config;\n DecoderContext decoder => player?.decoder;\n\n Action uiAction;\n internal readonly object\n locker = new();\n\n IXAudio2 xaudio2;\n internal IXAudio2MasteringVoice\n masteringVoice;\n internal IXAudio2SourceVoice\n sourceVoice;\n WaveFormat waveFormat = new(48000, 16, 2); // Output Audio Device\n AudioBuffer audioBuffer = new();\n internal double Timebase;\n internal ulong submittedSamples;\n #endregion\n\n public Audio(Player player)\n {\n this.player = player;\n\n uiAction = () =>\n {\n IsOpened = IsOpened;\n Codec = Codec;\n BitRate = BitRate;\n Bits = Bits;\n Channels = Channels;\n ChannelLayout = ChannelLayout;\n SampleFormat = SampleFormat;\n SampleRate = SampleRate;\n\n FramesDisplayed = FramesDisplayed;\n FramesDropped = FramesDropped;\n };\n\n // Set default volume\n Volume = Math.Min(Config.Player.VolumeDefault, Config.Player.VolumeMax);\n Initialize();\n }\n\n internal void Initialize()\n {\n lock (locker)\n {\n if (Engine.Audio.Failed)\n {\n Config.Audio.Enabled = false;\n return;\n }\n\n sampleRate = decoder != null && decoder.AudioStream != null && decoder.AudioStream.SampleRate > 0 ? decoder.AudioStream.SampleRate : 48000;\n player.Log.Info($\"Initialiazing audio ({Device.Name} - {Device.Id} @ {SampleRate}Hz)\");\n\n Dispose();\n\n try\n {\n xaudio2 = XAudio2Create();\n\n try\n {\n masteringVoice = xaudio2.CreateMasteringVoice(0, 0, AudioStreamCategory.GameEffects, _Device == Engine.Audio.DefaultDevice ? null : _Device.Id);\n }\n catch (Exception) // Win 7/8 compatibility issue https://social.msdn.microsoft.com/Forums/en-US/4989237b-814c-4a7a-8a35-00714d36b327/xaudio2-how-to-get-device-id-for-mastering-voice?forum=windowspro-audiodevelopment\n {\n masteringVoice = xaudio2.CreateMasteringVoice(0, 0, AudioStreamCategory.GameEffects, _Device == Engine.Audio.DefaultDevice ? null : (@\"\\\\?\\swd#mmdevapi#\" + _Device.Id.ToLower() + @\"#{e6327cad-dcec-4949-ae8a-991e976a79d2}\"));\n }\n\n sourceVoice = xaudio2.CreateSourceVoice(waveFormat, false);\n sourceVoice.SetSourceSampleRate((uint)SampleRate);\n sourceVoice.Start();\n\n submittedSamples = 0;\n Timebase = 1000 * 10000.0 / sampleRate;\n masteringVoice.Volume = Config.Player.VolumeMax / 100.0f;\n sourceVoice.Volume = mute ? 0 : Math.Max(0, _Volume / 100.0f);\n }\n catch (Exception e)\n {\n player.Log.Info($\"Audio initialization failed ({e.Message})\");\n Config.Audio.Enabled = false;\n }\n }\n }\n internal void Dispose()\n {\n lock (locker)\n {\n if (xaudio2 == null)\n return;\n\n xaudio2. Dispose();\n sourceVoice?. Dispose();\n masteringVoice?.Dispose();\n xaudio2 = null;\n sourceVoice = null;\n masteringVoice = null;\n }\n }\n\n // TBR: Very rarely could crash the app on audio device change while playing? Requires two locks (Audio's locker and aFrame)\n // The process was terminated due to an internal error in the .NET Runtime at IP 00007FFA6725DA03 (00007FFA67090000) with exit code c0000005.\n [System.Security.SecurityCritical]\n internal void AddSamples(AudioFrame aFrame)\n {\n lock (locker) // required for submittedSamples only? (ClearBuffer() can be called during audio decocder circular buffer reallocation)\n {\n try\n {\n if (CanTrace)\n player.Log.Trace($\"[A] Presenting {Utils.TicksToTime(player.aFrame.timestamp)}\");\n\n framesDisplayed++;\n\n submittedSamples += (ulong) (aFrame.dataLen / 4); // ASampleBytes\n SamplesAdded?.Invoke(this, aFrame);\n\n audioBuffer.AudioDataPointer= aFrame.dataPtr;\n audioBuffer.AudioBytes = (uint)aFrame.dataLen;\n sourceVoice.SubmitSourceBuffer(audioBuffer);\n }\n catch (Exception e) // Happens on audio device changed/removed\n {\n if (CanDebug)\n player.Log.Debug($\"[Audio] Submitting samples failed ({e.Message})\");\n\n ClearBuffer(); // TBR: Inform player to resync audio?\n }\n }\n }\n internal long GetBufferedDuration() { lock (locker) { return (long) ((submittedSamples - sourceVoice.State.SamplesPlayed) * Timebase); } }\n internal long GetDeviceDelay() { lock (locker) { return (long) ((xaudio2.PerformanceData.CurrentLatencyInSamples * Timebase) - 80000); } } // TODO: VBlack delay (8ms correction for now)\n internal void ClearBuffer()\n {\n lock (locker)\n {\n if (sourceVoice == null)\n return;\n\n sourceVoice.Stop();\n sourceVoice.FlushSourceBuffers();\n sourceVoice.Start();\n submittedSamples = sourceVoice.State.SamplesPlayed;\n }\n }\n\n internal void Reset()\n {\n codec = null;\n bitRate = 0;\n bits = 0;\n channels = 0;\n channelLayout = null;\n sampleFormat = null;\n isOpened = false;\n\n ClearBuffer();\n player.UIAdd(uiAction);\n }\n internal void Refresh()\n {\n if (decoder.AudioStream == null) { Reset(); return; }\n\n codec = decoder.AudioStream.Codec;\n bits = decoder.AudioStream.Bits;\n channels = decoder.AudioStream.Channels;\n channelLayout = decoder.AudioStream.ChannelLayoutStr;\n sampleFormat = decoder.AudioStream.SampleFormatStr;\n isOpened =!decoder.AudioDecoder.Disposed;\n\n framesDisplayed = 0;\n framesDropped = 0;\n\n if (SampleRate!= decoder.AudioStream.SampleRate)\n Initialize();\n\n player.UIAdd(uiAction);\n }\n internal void Enable()\n {\n bool wasPlaying = player.IsPlaying;\n\n decoder.OpenSuggestedAudio();\n\n player.ReSync(decoder.AudioStream, (int) (player.CurTime / 10000), true);\n\n Refresh();\n player.UIAll();\n\n if (wasPlaying || Config.Player.AutoPlay)\n player.Play();\n }\n internal void Disable()\n {\n if (!IsOpened)\n return;\n\n decoder.CloseAudio();\n\n player.aFrame = null;\n\n if (!player.Video.IsOpened)\n {\n player.canPlay = false;\n player.UIAdd(() => player.CanPlay = player.CanPlay);\n }\n\n Reset();\n player.UIAll();\n }\n\n public void DelayAdd() => Config.Audio.Delay += Config.Player.AudioDelayOffset;\n public void DelayAdd2() => Config.Audio.Delay += Config.Player.AudioDelayOffset2;\n public void DelayRemove() => Config.Audio.Delay -= Config.Player.AudioDelayOffset;\n public void DelayRemove2() => Config.Audio.Delay -= Config.Player.AudioDelayOffset2;\n public void Toggle() => Config.Audio.Enabled = !Config.Audio.Enabled;\n public void ToggleMute() => Mute = !Mute;\n public void VolumeUp()\n {\n if (Volume == Config.Player.VolumeMax) return;\n Volume = Math.Min(Volume + Config.Player.VolumeOffset, Config.Player.VolumeMax);\n }\n public void VolumeDown()\n {\n if (Volume == 0) return;\n Volume = Math.Max(Volume - Config.Player.VolumeOffset, 0);\n }\n\n /// \n /// Reloads filters from Config.Audio.Filters (experimental)\n /// \n /// 0 on success\n public int ReloadFilters() => player.AudioDecoder.ReloadFilters();\n\n /// \n /// \n /// Updates filter's property (experimental)\n /// Note: This will not update the property value in Config.Audio.Filters\n /// \n /// \n /// Filter's unique id specified in Config.Audio.Filters\n /// Filter's property to change\n /// Filter's property value\n /// 0 on success\n public int UpdateFilter(string filterId, string key, string value) => player.AudioDecoder.UpdateFilter(filterId, key, value);\n}\n"], ["/LLPlayer/FlyleafLib/Engine/Language.cs", "using System.Collections.Generic;\nusing System.Globalization;\nusing System.Linq;\nusing System.Text.Json.Serialization;\n\nnamespace FlyleafLib;\n\npublic class Language : IEquatable\n{\n public string CultureName { get => _CultureName; set\n { // Required for XML load\n Culture = CultureInfo.GetCultureInfo(value);\n Refresh(this);\n }\n }\n string _CultureName;\n\n [JsonIgnore]\n public string TopEnglishName { get; private set; }\n [JsonIgnore]\n public string TopNativeName { get; private set; }\n\n [JsonIgnore]\n public CultureInfo Culture { get; private set; }\n\n [JsonIgnore]\n public CultureInfo TopCulture { get; private set; }\n [JsonIgnore]\n public string DisplayName => $\"{TopEnglishName} ({TopNativeName})\";\n\n [JsonIgnore]\n public string ISO6391 { get; private set; }\n\n [JsonIgnore]\n public string IdSubLanguage { get; private set; } // Can search for online subtitles with this id\n\n [JsonIgnore]\n public string OriginalInput { get; private set; } // Only for Undetermined language (return clone)\n\n [JsonIgnore]\n public bool IsRTL { get; private set; }\n\n public override string ToString() => OriginalInput ?? TopEnglishName;\n\n public override int GetHashCode() => ToString().GetHashCode();\n\n public override bool Equals(object obj) => Equals(obj as Language);\n\n public bool Equals(Language lang)\n {\n if (lang is null)\n return false;\n\n if (ReferenceEquals(this, lang))\n return true;\n\n if (lang.Culture == null && Culture == null)\n {\n if (OriginalInput != null || lang.OriginalInput != null)\n return OriginalInput == lang.OriginalInput;\n\n return true; // und\n }\n\n return lang.IdSubLanguage == IdSubLanguage; // TBR: top level will be equal with lower\n }\n\n public static bool operator ==(Language lang1, Language lang2) => lang1 is null ? lang2 is null ? true : false : lang1.Equals(lang2);\n\n public static bool operator !=(Language lang1, Language lang2) => !(lang1 == lang2);\n\n private static readonly HashSet RTLCodes =\n [\n \"ae\",\n \"ar\",\n \"dv\",\n \"fa\",\n \"ha\",\n \"he\",\n \"ks\",\n \"ku\",\n \"ps\",\n \"sd\",\n \"ug\",\n \"ur\",\n \"yi\"\n ];\n\n public static void Refresh(Language lang)\n {\n lang._CultureName = lang.Culture.Name;\n\n lang.TopCulture = lang.Culture;\n while (lang.TopCulture.Parent.Name != \"\")\n lang.TopCulture = lang.TopCulture.Parent;\n\n lang.TopEnglishName = lang.TopCulture.EnglishName;\n lang.TopNativeName = lang.TopCulture.NativeName;\n lang.IdSubLanguage = lang.Culture.ThreeLetterISOLanguageName;\n lang.ISO6391 = lang.Culture.TwoLetterISOLanguageName;\n lang.IsRTL = RTLCodes.Contains(lang.ISO6391);\n }\n\n public static Language Get(CultureInfo cult)\n {\n Language lang = new() { Culture = cult };\n Refresh(lang);\n\n return lang;\n }\n public static Language Get(string name)\n {\n Language lang = new() { Culture = StringToCulture(name) };\n if (lang.Culture != null)\n Refresh(lang);\n else\n {\n lang.IdSubLanguage = \"und\";\n lang.TopEnglishName = \"Unknown\";\n if (name != \"und\")\n lang.OriginalInput = name;\n }\n\n return lang;\n }\n\n public static CultureInfo StringToCulture(string lang)\n {\n if (string.IsNullOrWhiteSpace(lang) || lang.Length < 2 || lang == \"und\")\n return null;\n\n string langLower = lang.ToLower();\n CultureInfo ret = null;\n\n try\n {\n ret = lang.Length == 3 ? ThreeLetterToCulture(langLower) : CultureInfo.GetCultureInfo(langLower);\n } catch { }\n\n StringComparer cmp = StringComparer.OrdinalIgnoreCase;\n\n // TBR: Check also -Country/region two letters?\n if (ret == null || ret.ThreeLetterISOLanguageName == \"\")\n foreach (var cult in CultureInfo.GetCultures(CultureTypes.AllCultures))\n if (cmp.Equals(cult.Name, langLower) || cmp.Equals(cult.NativeName, langLower) || cmp.Equals(cult.EnglishName, langLower))\n return cult;\n\n return ret;\n }\n\n public static CultureInfo ThreeLetterToCulture(string lang)\n {\n if (lang == \"zht\")\n return CultureInfo.GetCultureInfo(\"zh-Hant\");\n else if (lang == \"pob\")\n return CultureInfo.GetCultureInfo(\"pt-BR\");\n else if (lang == \"nor\")\n return CultureInfo.GetCultureInfo(\"nob\");\n else if (lang == \"scc\")\n return CultureInfo.GetCultureInfo(\"srp\");\n else if (lang == \"tgl\")\n return CultureInfo.GetCultureInfo(\"fil\");\n\n CultureInfo ret = CultureInfo.GetCultureInfo(lang);\n\n if (ret.ThreeLetterISOLanguageName == \"\")\n {\n ISO639_2B_TO_2T.TryGetValue(lang, out string iso639_2t);\n if (iso639_2t != null)\n ret = CultureInfo.GetCultureInfo(iso639_2t);\n }\n\n return ret.ThreeLetterISOLanguageName == \"\" ? null : ret;\n }\n\n public static readonly Dictionary ISO639_2T_TO_2B = new()\n {\n { \"bod\",\"tib\" },\n { \"ces\",\"cze\" },\n { \"cym\",\"wel\" },\n { \"deu\",\"ger\" },\n { \"ell\",\"gre\" },\n { \"eus\",\"baq\" },\n { \"fas\",\"per\" },\n { \"fra\",\"fre\" },\n { \"hye\",\"arm\" },\n { \"isl\",\"ice\" },\n { \"kat\",\"geo\" },\n { \"mkd\",\"mac\" },\n { \"mri\",\"mao\" },\n { \"msa\",\"may\" },\n { \"mya\",\"bur\" },\n { \"nld\",\"dut\" },\n { \"ron\",\"rum\" },\n { \"slk\",\"slo\" },\n { \"sqi\",\"alb\" },\n { \"zho\",\"chi\" },\n };\n public static readonly Dictionary ISO639_2B_TO_2T = new()\n {\n { \"alb\",\"sqi\" },\n { \"arm\",\"hye\" },\n { \"baq\",\"eus\" },\n { \"bur\",\"mya\" },\n { \"chi\",\"zho\" },\n { \"cze\",\"ces\" },\n { \"dut\",\"nld\" },\n { \"fre\",\"fra\" },\n { \"geo\",\"kat\" },\n { \"ger\",\"deu\" },\n { \"gre\",\"ell\" },\n { \"ice\",\"isl\" },\n { \"mac\",\"mkd\" },\n { \"mao\",\"mri\" },\n { \"may\",\"msa\" },\n { \"per\",\"fas\" },\n { \"rum\",\"ron\" },\n { \"slo\",\"slk\" },\n { \"tib\",\"bod\" },\n { \"wel\",\"cym\" },\n };\n\n public static Language English = Get(\"eng\");\n public static Language Unknown = Get(\"und\");\n\n public static List AllLanguages\n {\n get\n {\n if (field != null)\n {\n return field;\n }\n\n var neutralCultures = CultureInfo\n .GetCultures(CultureTypes.NeutralCultures)\n .Where(c => !string.IsNullOrEmpty(c.Name));\n\n var uniqueCultures = neutralCultures\n .GroupBy(c => c.ThreeLetterISOLanguageName)\n .Select(g => g.First());\n\n List languages = new();\n foreach (var culture in uniqueCultures)\n {\n languages.Add(Get(culture));\n }\n languages = languages.OrderBy(l => l.TopEnglishName, StringComparer.InvariantCulture).ToList();\n\n field = languages;\n\n return field;\n }\n }\n}\n"], ["/LLPlayer/FlyleafLib/Engine/WhisperConfig.cs", "using System.Collections.Generic;\nusing System.Diagnostics;\nusing System.IO;\nusing System.Text.Json.Serialization;\nusing Whisper.net;\nusing Whisper.net.LibraryLoader;\n\nnamespace FlyleafLib;\n\n#nullable enable\n\n// Whisper Common Config (whisper.cpp, faster-whisper)\npublic class WhisperConfig : NotifyPropertyChanged\n{\n public static string ModelsDirectory { get; } = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, \"whispermodels\");\n public static string EnginesDirectory { get; } = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, \"Whisper\");\n\n // For UI\n public string LanguageName\n {\n get\n {\n string translate = Translate ? \", Trans\" : \"\";\n\n if (LanguageDetection)\n {\n return \"Auto\" + translate;\n }\n\n var lang = FlyleafLib.Language.Get(Language);\n\n if (lang != null)\n {\n return lang.TopEnglishName + translate;\n }\n\n return Language + translate;\n }\n }\n\n public string Language\n {\n get;\n set\n {\n if (Set(ref field, value))\n {\n Raise(LanguageName);\n }\n }\n } = \"en\";\n\n public bool LanguageDetection\n {\n get;\n set\n {\n if (Set(ref field, value))\n {\n Raise(LanguageName);\n }\n }\n } = true;\n\n public bool Translate\n {\n get;\n set\n {\n if (Set(ref field, value))\n {\n Raise(LanguageName);\n }\n }\n }\n\n public static void EnsureModelsDirectory()\n {\n if (!Directory.Exists(ModelsDirectory))\n {\n Directory.CreateDirectory(ModelsDirectory);\n }\n }\n\n public static void EnsureEnginesDirectory()\n {\n if (!Directory.Exists(EnginesDirectory))\n {\n Directory.CreateDirectory(EnginesDirectory);\n }\n }\n}\n\n// TODO: L: Add other options\npublic class WhisperCppConfig : NotifyPropertyChanged\n{\n public WhisperCppModel? Model\n {\n get;\n set\n {\n if (Set(ref field, value))\n {\n Raise(nameof(IsEnglishModel));\n }\n }\n }\n\n [JsonIgnore]\n public bool IsEnglishModel => Model != null && Model.Model.ToString().EndsWith(\"En\");\n\n public List RuntimeLibraries { get; set => Set(ref field, value); } = [RuntimeLibrary.Cpu, RuntimeLibrary.CpuNoAvx];\n public RuntimeLibrary? LoadedLibrary => RuntimeOptions.LoadedLibrary;\n\n public int? GpuDevice { get; set => Set(ref field, value); }\n\n public int? Threads { get; set => Set(ref field, value); }\n public int? MaxSegmentLength { get; set => Set(ref field, value); }\n public int? MaxTokensPerSegment { get; set => Set(ref field, value); }\n public bool SplitOnWord { get; set => Set(ref field, value); }\n public float? NoSpeechThreshold { get; set => Set(ref field, value); }\n public bool NoContext { get; set => Set(ref field, value); }\n public int? AudioContextSize { get; set => Set(ref field, value); }\n public string Prompt { get; set => Set(ref field, value); } = string.Empty;\n\n public WhisperFactoryOptions GetFactoryOptions()\n {\n WhisperFactoryOptions opts = WhisperFactoryOptions.Default;\n\n if (GpuDevice.HasValue)\n opts.GpuDevice = GpuDevice.Value;\n\n return opts;\n }\n\n public WhisperProcessorBuilder ConfigureBuilder(WhisperConfig whisperConfig, WhisperProcessorBuilder builder)\n {\n if (IsEnglishModel)\n {\n // set English forcefully if English-only models\n builder.WithLanguage(\"en\");\n }\n else\n {\n if (!string.IsNullOrEmpty(whisperConfig.Language))\n builder.WithLanguage(whisperConfig.Language);\n\n // prefer auto\n if (whisperConfig.LanguageDetection)\n builder.WithLanguageDetection();\n\n if (whisperConfig.Translate)\n builder.WithTranslate();\n }\n\n if (Threads is > 0)\n builder.WithThreads(Threads.Value);\n\n if (MaxSegmentLength is > 0)\n builder.WithMaxSegmentLength(MaxSegmentLength.Value);\n\n if (MaxTokensPerSegment is > 0)\n builder.WithMaxTokensPerSegment(MaxTokensPerSegment.Value);\n\n if (SplitOnWord)\n builder.SplitOnWord();\n\n if (NoSpeechThreshold is > 0)\n builder.WithNoSpeechThreshold(NoSpeechThreshold.Value);\n\n if (NoContext)\n builder.WithNoContext();\n\n if (AudioContextSize is > 0)\n builder.WithAudioContextSize(AudioContextSize.Value);\n\n if (!string.IsNullOrWhiteSpace(Prompt))\n builder.WithPrompt(Prompt);\n\n // auto set\n if (MaxSegmentLength is > 0 || MaxSegmentLength is > 0)\n builder.WithTokenTimestamps();\n\n return builder;\n }\n}\n\npublic class FasterWhisperConfig : NotifyPropertyChanged\n{\n public static string DefaultEnginePath { get; } = Path.Combine(WhisperConfig.EnginesDirectory, \"Faster-Whisper-XXL\", \"faster-whisper-xxl.exe\");\n\n // can get by faster-whisper-xxl.exe --model foo bar.wav\n public static List ModelOptions { get; } = [\n \"tiny\",\n \"tiny.en\",\n \"base\",\n \"base.en\",\n \"small\",\n \"small.en\",\n \"medium\",\n \"medium.en\",\n \"large-v1\",\n \"large-v2\",\n \"large-v3\",\n //\"large\", // = large-v3\n \"large-v3-turbo\",\n //\"turbo\", // = large-v3-turbo\n \"distil-large-v2\",\n \"distil-medium.en\",\n \"distil-small.en\",\n \"distil-large-v3\",\n \"distil-large-v3.5\"\n ];\n\n public bool UseManualEngine { get; set => Set(ref field, value); }\n public string? ManualEnginePath { get; set => Set(ref field, value); }\n public bool UseManualModel { get; set => Set(ref field, value); }\n public string? ManualModelDir { get; set => Set(ref field, value); }\n public string Model\n {\n get;\n set\n {\n if (Set(ref field, value))\n {\n Raise(nameof(IsEnglishModel));\n }\n }\n } = \"tiny\";\n [JsonIgnore]\n public bool IsEnglishModel => Model.EndsWith(\".en\") ||\n Model is \"distil-large-v2\"\n or \"distil-large-v3\"\n or \"distil-large-v3.5\";\n public string ExtraArguments { get; set => Set(ref field, value); } = string.Empty;\n\n public ProcessPriorityClass ProcessPriority { get; set => Set(ref field, value); } = ProcessPriorityClass.Normal;\n}\n"], ["/LLPlayer/FlyleafLib/MediaPlayer/Translation/SubtitlesTranslator.cs", "using System.Collections.Generic;\nusing System.ComponentModel;\nusing System.Diagnostics;\nusing System.Linq;\nusing System.Threading;\nusing System.Threading.Tasks;\nusing FlyleafLib.MediaPlayer.Translation.Services;\nusing static FlyleafLib.Logger;\n\nnamespace FlyleafLib.MediaPlayer.Translation;\n\n#nullable enable\n\npublic class SubTranslator\n{\n private readonly SubManager _subManager;\n private readonly Config.SubtitlesConfig _config;\n private readonly int _subIndex;\n\n private ITranslateService? _translateService;\n private CancellationTokenSource? _translationCancellation;\n private readonly TranslateServiceFactory _translateServiceFactory;\n private Task? _translateTask;\n private bool _isReset;\n private Language? _srcLang;\n\n private bool IsEnabled => _config[_subIndex].EnabledTranslated;\n\n private readonly LogHandler Log;\n\n public SubTranslator(SubManager subManager, Config.SubtitlesConfig config, int subIndex)\n {\n _subManager = subManager;\n _config = config;\n _subIndex = subIndex;\n\n _subManager.PropertyChanged += SubManager_OnPropertyChanged;\n\n // apply config changes\n _config.PropertyChanged += SubtitlesConfig_OnPropertyChanged;\n _config.SubConfigs[subIndex].PropertyChanged += SubConfig_OnPropertyChanged;\n _config.TranslateChatConfig.PropertyChanged += TranslateChatConfig_OnPropertyChanged;\n\n _translateServiceFactory = new TranslateServiceFactory(config);\n\n Log = new LogHandler((\"[#1]\").PadRight(8, ' ') + $\" [Translator{subIndex + 1} ] \");\n }\n\n private int _oldIndex = -1;\n private CancellationTokenSource? _translationStartCancellation;\n\n private void SubManager_OnPropertyChanged(object? sender, PropertyChangedEventArgs e)\n {\n switch (e.PropertyName)\n {\n case nameof(SubManager.CurrentIndex):\n if (!IsEnabled || _subManager.Subs.Count == 0 || _subManager.Language == null)\n return;\n\n if (_translateService == null)\n {\n // capture for later initialization\n _srcLang = _subManager.Language;\n }\n\n if (_translationStartCancellation != null)\n {\n _translationStartCancellation.Cancel();\n _translationStartCancellation.Dispose();\n _translationStartCancellation = null;\n }\n _translationStartCancellation = new CancellationTokenSource();\n _ = UpdateCurrentIndexAsync(_subManager.CurrentIndex, _translationStartCancellation.Token);\n break;\n case nameof(SubManager.Language):\n _ = Reset();\n break;\n }\n }\n\n private void SubtitlesConfig_OnPropertyChanged(object? sender, PropertyChangedEventArgs e)\n {\n string languageFallbackPropName = _subIndex == 0 ?\n nameof(Config.SubtitlesConfig.LanguageFallbackPrimary) :\n nameof(Config.SubtitlesConfig.LanguageFallbackSecondary);\n\n if (e.PropertyName is\n nameof(Config.SubtitlesConfig.TranslateServiceType) or\n nameof(Config.SubtitlesConfig.TranslateTargetLanguage)\n ||\n e.PropertyName == languageFallbackPropName)\n {\n // Apply translating config changes\n _ = Reset();\n }\n }\n\n private void SubConfig_OnPropertyChanged(object? sender, PropertyChangedEventArgs e)\n {\n // Reset when translation is off\n if (e.PropertyName is nameof(Config.SubConfig.EnabledTranslated))\n {\n if (!IsEnabled)\n {\n _ = Reset();\n }\n }\n }\n\n private void TranslateChatConfig_OnPropertyChanged(object? sender, PropertyChangedEventArgs e)\n {\n _ = Reset();\n }\n\n private async Task Reset()\n {\n if (_translateService == null)\n return;\n\n try\n {\n _isReset = true;\n await Cancel();\n\n _translateService?.Dispose();\n _translateService = null;\n _srcLang = null;\n }\n finally\n {\n _isReset = false;\n }\n }\n\n private async Task Cancel()\n {\n _translationCancellation?.Cancel();\n Task? pendingTask = _translateTask;\n if (pendingTask != null)\n {\n await pendingTask;\n }\n _translateTask = null;\n }\n\n private async Task UpdateCurrentIndexAsync(int newIndex, CancellationToken token)\n {\n if (newIndex != -1 && _subManager.Subs.Any())\n {\n int indexDiff = Math.Abs(_oldIndex - newIndex);\n bool isForward = newIndex > _oldIndex;\n _oldIndex = newIndex;\n\n if ((isForward && indexDiff > _config.TranslateCountForward) ||\n (!isForward && indexDiff > _config.TranslateCountBackward))\n {\n // Cancel a running translation request when a large seek is performed\n await Cancel();\n }\n else if (_translateTask != null)\n {\n // for performance\n return;\n }\n\n // Prevent continuous firing when continuously switching subtitles with sub seek\n if (indexDiff == 1)\n {\n if (_subManager.Subs[newIndex].Duration.TotalMilliseconds > 320)\n {\n await Task.Delay(300, token);\n }\n }\n token.ThrowIfCancellationRequested();\n\n if (_translateTask == null && !_isReset)\n {\n // singleton task\n // Ensure that it is not executed in the main thread because it scans all subtitles\n Task task = Task.Run(async () =>\n {\n try\n {\n await TranslateAheadAsync(newIndex, _config.TranslateCountBackward, _config.TranslateCountForward);\n }\n finally\n {\n _translateTask = null;\n }\n });\n _translateTask = task;\n }\n }\n }\n\n private readonly Lock _initLock = new();\n // initialize TranslateService lazily\n private void EnsureTranslationService()\n {\n if (_translateService != null)\n {\n return;\n }\n\n // double-check lock pattern\n lock (_initLock)\n {\n if (_translateService == null)\n {\n var service = _translateServiceFactory.GetService(_config.TranslateServiceType, false);\n service.Initialize(_srcLang!, _config.TranslateTargetLanguage);\n\n Volatile.Write(ref _translateService, service);\n }\n }\n }\n\n private async Task TranslateAheadAsync(int currentIndex, int countBackward, int countForward)\n {\n try\n {\n // Token for canceling translation, releasing previous one to prevent leakage\n _translationCancellation?.Dispose();\n _translationCancellation = new CancellationTokenSource();\n\n var token = _translationCancellation.Token;\n int start = Math.Max(0, currentIndex - countBackward);\n int end = Math.Min(start + countForward - 1, _subManager.Subs.Count - 1);\n\n List translateSubs = new();\n for (int i = start; i <= end; i++)\n {\n if (token.IsCancellationRequested)\n break;\n if (i >= _subManager.Subs.Count)\n break;\n\n var sub = _subManager.Subs[i];\n if (!sub.IsTranslated && !string.IsNullOrEmpty(sub.Text))\n {\n translateSubs.Add(sub);\n }\n }\n\n if (translateSubs.Count == 0)\n return;\n\n int concurrency = _config.TranslateMaxConcurrency;\n\n if (concurrency > 1 && _config.TranslateServiceType.IsLLM() &&\n _config.TranslateChatConfig.TranslateMethod == ChatTranslateMethod.KeepContext)\n {\n // fixed to 1\n // it must be sequential because of maintaining context\n concurrency = 1;\n }\n\n if (concurrency <= 1)\n {\n // sequentially (important to maintain execution order for LLM)\n foreach (var sub in translateSubs)\n {\n await TranslateSubAsync(sub, token);\n }\n }\n else\n {\n // concurrently\n ParallelOptions parallelOptions = new()\n {\n CancellationToken = token,\n MaxDegreeOfParallelism = concurrency\n };\n\n await Parallel.ForEachAsync(\n translateSubs,\n parallelOptions,\n async (sub, ct) =>\n {\n await TranslateSubAsync(sub, ct);\n });\n }\n }\n catch (OperationCanceledException)\n {\n // ignore\n }\n catch (Exception ex)\n {\n Log.Error($\"Translation failed: {ex.Message}\");\n\n bool isConfigError = ex is TranslationConfigException;\n\n // Unable to translate, so turn off the translation and notify\n _config[_subIndex].EnabledTranslated = false;\n _ = Reset().ContinueWith((_) =>\n {\n if (isConfigError)\n {\n _config.player.RaiseKnownErrorOccurred($\"Translation Failed: {ex.Message}\", KnownErrorType.Configuration);\n }\n else\n {\n _config.player.RaiseUnknownErrorOccurred($\"Translation Failed: {ex.Message}\", UnknownErrorType.Translation, ex);\n }\n });\n }\n }\n\n private async Task TranslateSubAsync(SubtitleData sub, CancellationToken token)\n {\n string? text = sub.Text;\n if (string.IsNullOrEmpty(text))\n return;\n\n try\n {\n long start = Stopwatch.GetTimestamp();\n string translateText = SubtitleTextUtil.FlattenText(text);\n if (CanDebug) Log.Debug($\"Translation Start {sub.Index} - {translateText}\");\n EnsureTranslationService();\n string translated = await _translateService!.TranslateAsync(translateText, token);\n sub.TranslatedText = translated;\n\n if (CanDebug)\n {\n TimeSpan elapsed = Stopwatch.GetElapsedTime(start);\n Log.Debug($\"Translation End {sub.Index} in {elapsed.TotalMilliseconds} - {translated}\");\n }\n }\n catch (OperationCanceledException)\n {\n if (CanDebug) Log.Debug($\"Translation Cancel {sub.Index}\");\n throw;\n }\n }\n}\n"], ["/LLPlayer/FlyleafLib/MediaFramework/MediaDecoder/DataDecoder.cs", "using System.Threading;\nusing System.Collections.Concurrent;\nusing System.Runtime.InteropServices;\n\nusing FlyleafLib.MediaFramework.MediaFrame;\nusing FlyleafLib.MediaFramework.MediaStream;\n\nnamespace FlyleafLib.MediaFramework.MediaDecoder;\npublic unsafe class DataDecoder : DecoderBase\n{\n public DataStream DataStream => (DataStream)Stream;\n\n public ConcurrentQueue\n Frames { get; protected set; } = new ConcurrentQueue();\n\n public DataDecoder(Config config, int uniqueId = -1) : base(config, uniqueId) { }\n\n\n protected override unsafe int Setup(AVCodec* codec) => 0;\n protected override void DisposeInternal()\n => Frames = new ConcurrentQueue();\n\n public void Flush()\n {\n lock (lockActions)\n lock (lockCodecCtx)\n {\n if (Disposed)\n return;\n\n if (Status == Status.Ended)\n Status = Status.Stopped;\n else if (Status == Status.Draining)\n Status = Status.Stopping;\n\n DisposeFrames();\n }\n }\n\n protected override void RunInternal()\n {\n int allowedErrors = Config.Decoder.MaxErrors;\n AVPacket *packet;\n\n do\n {\n // Wait until Queue not Full or Stopped\n if (Frames.Count >= Config.Decoder.MaxDataFrames)\n {\n lock (lockStatus)\n if (Status == Status.Running)\n Status = Status.QueueFull;\n\n while (Frames.Count >= Config.Decoder.MaxDataFrames && Status == Status.QueueFull)\n Thread.Sleep(20);\n\n lock (lockStatus)\n {\n if (Status != Status.QueueFull)\n break;\n Status = Status.Running;\n }\n }\n\n // While Packets Queue Empty (Ended | Quit if Demuxer stopped | Wait until we get packets)\n if (demuxer.DataPackets.Count == 0)\n {\n CriticalArea = true;\n\n lock (lockStatus)\n if (Status == Status.Running)\n Status = Status.QueueEmpty;\n\n while (demuxer.DataPackets.Count == 0 && Status == Status.QueueEmpty)\n {\n if (demuxer.Status == Status.Ended)\n {\n Status = Status.Draining;\n break;\n }\n else if (!demuxer.IsRunning)\n {\n int retries = 5;\n\n while (retries > 0)\n {\n retries--;\n Thread.Sleep(10);\n if (demuxer.IsRunning)\n break;\n }\n\n lock (demuxer.lockStatus)\n lock (lockStatus)\n {\n if (demuxer.Status == Status.Pausing || demuxer.Status == Status.Paused)\n Status = Status.Pausing;\n else if (demuxer.Status == Status.QueueFull)\n Status = Status.Draining;\n else if (demuxer.Status == Status.Running)\n continue;\n else if (demuxer.Status != Status.Ended)\n Status = Status.Stopping;\n else\n continue;\n }\n\n break;\n }\n\n Thread.Sleep(20);\n }\n\n lock (lockStatus)\n {\n CriticalArea = false;\n if (Status != Status.QueueEmpty && Status != Status.Draining)\n break;\n if (Status != Status.Draining)\n Status = Status.Running;\n }\n }\n\n lock (lockCodecCtx)\n {\n if (Status == Status.Stopped || demuxer.DataPackets.Count == 0)\n continue;\n packet = demuxer.DataPackets.Dequeue();\n\n if (packet->size > 0 && packet->data != null)\n {\n var mFrame = ProcessDataFrame(packet);\n Frames.Enqueue(mFrame);\n }\n\n av_packet_free(&packet);\n }\n } while (Status == Status.Running);\n\n if (Status == Status.Draining) Status = Status.Ended;\n }\n\n private DataFrame ProcessDataFrame(AVPacket* packet)\n {\n IntPtr ptr = new IntPtr(packet->data);\n byte[] dataFrame = new byte[packet->size];\n Marshal.Copy(ptr, dataFrame, 0, packet->size); // for performance/in case of large data we could just keep the avpacket data directly (DataFrame instead of byte[] Data just use AVPacket* and move ref?)\n\n DataFrame mFrame = new()\n {\n timestamp = (long)(packet->pts * DataStream.Timebase) - demuxer.StartTime,\n DataCodecId = DataStream.CodecID,\n Data = dataFrame\n };\n\n return mFrame;\n }\n\n public void DisposeFrames()\n => Frames = new ConcurrentQueue();\n}\n"], ["/LLPlayer/FlyleafLib/Plugins/OpenSubtitles.cs", "using System.Collections.Generic;\nusing System.IO;\nusing System.Linq;\nusing System.Text;\nusing FlyleafLib.MediaFramework.MediaStream;\nusing Lingua;\n\nnamespace FlyleafLib.Plugins;\n\npublic class OpenSubtitles : PluginBase, IOpenSubtitles, ISearchLocalSubtitles\n{\n public new int Priority { get; set; } = 3000;\n\n private static readonly Lazy LanguageDetector = new(() =>\n {\n LanguageDetector detector = LanguageDetectorBuilder\n .FromAllLanguages()\n .Build();\n\n return detector;\n }, true);\n\n private static readonly HashSet ExtSet = new(Utils.ExtensionsSubtitles, StringComparer.OrdinalIgnoreCase);\n\n public OpenSubtitlesResults Open(string url)\n {\n foreach (var extStream in Selected.ExternalSubtitlesStreamsAll)\n if (extStream.Url == url)\n return new(extStream);\n\n string title;\n\n if (File.Exists(url))\n {\n Selected.FillMediaParts();\n\n FileInfo fi = new(url);\n title = fi.Name;\n }\n else\n {\n try\n {\n Uri uri = new(url);\n title = Path.GetFileName(uri.LocalPath);\n\n if (title == null || title.Trim().Length == 0)\n title = url;\n\n } catch\n {\n title = url;\n }\n }\n\n ExternalSubtitlesStream newExtStream = new()\n {\n Url = url,\n Title = title,\n Downloaded = true,\n IsBitmap = IsSubtitleBitmap(url),\n };\n\n if (Config.Subtitles.LanguageAutoDetect && !newExtStream.IsBitmap)\n {\n newExtStream.Language = DetectLanguage(url);\n newExtStream.LanguageDetected = true;\n }\n\n AddExternalStream(newExtStream);\n\n return new(newExtStream);\n }\n\n public OpenSubtitlesResults Open(Stream iostream) => null;\n\n public void SearchLocalSubtitles()\n {\n try\n {\n string mediaDir = Path.GetDirectoryName(Playlist.Url);\n string mediaName = Path.GetFileNameWithoutExtension(Playlist.Url);\n\n OrderedDictionary result = new(StringComparer.OrdinalIgnoreCase);\n\n CollectFromDirectory(mediaDir, mediaName, result);\n\n // also search in subdirectories\n string paths = Config.Subtitles.SearchLocalPaths;\n if (!string.IsNullOrWhiteSpace(paths))\n {\n foreach (Range seg in paths.AsSpan().Split(';'))\n {\n var path = paths.AsSpan(seg).Trim();\n if (path.IsEmpty) continue;\n\n string searchDir = !Path.IsPathRooted(path)\n ? Path.Join(mediaDir, path)\n : path.ToString();\n\n if (Directory.Exists(searchDir))\n {\n CollectFromDirectory(searchDir, mediaName, result);\n }\n }\n }\n\n if (result.Count == 0)\n {\n return;\n }\n\n Selected.FillMediaParts();\n\n foreach (var (path, lang) in result)\n {\n if (Selected.ExternalSubtitlesStreamsAll.Any(s => s.Url == path))\n {\n continue;\n }\n\n FileInfo fi = new(path);\n string title = fi.Name;\n\n ExternalSubtitlesStream sub = new()\n {\n Url = path,\n Title = title,\n Downloaded = true,\n IsBitmap = IsSubtitleBitmap(path),\n Language = lang\n };\n\n if (Config.Subtitles.LanguageAutoDetect && !sub.IsBitmap && lang == Language.Unknown)\n {\n sub.Language = DetectLanguage(path);\n sub.LanguageDetected = true;\n }\n\n Log.Debug($\"Adding [{sub.Language.TopEnglishName}] {path}\");\n\n AddExternalStream(sub);\n }\n }\n catch (Exception e)\n {\n Log.Error($\"SearchLocalSubtitles failed ({e.Message})\");\n }\n }\n\n private static void CollectFromDirectory(string searchDir, string filename, IDictionary result)\n {\n HashSet added = null;\n\n // Get files starting with the same filename\n List fileList;\n try\n {\n fileList = Directory.GetFiles(searchDir, $\"{filename}.*\", new EnumerationOptions { MatchCasing = MatchCasing.CaseInsensitive })\n .ToList();\n }\n catch\n {\n return;\n }\n\n if (fileList.Count == 0)\n {\n return;\n }\n\n var files = fileList.Select(f => new\n {\n FullPath = f,\n FileName = Path.GetFileName(f)\n }).ToList();\n\n // full match with top priority (video.srt, video.ass)\n foreach (string ext in ExtSet)\n {\n string expect = $\"{filename}.{ext}\";\n int match = files.FindIndex(x => string.Equals(x.FileName, expect, StringComparison.OrdinalIgnoreCase));\n if (match != -1)\n {\n result.TryAdd(files[match].FullPath, Language.Unknown);\n added ??= new HashSet();\n added.Add(match);\n }\n }\n\n // head match (video.*.srt, video.*.ass)\n var extSetLookup = ExtSet.GetAlternateLookup>();\n foreach (var (i, x) in files.Index())\n {\n // skip full match\n if (added != null && added.Contains(i))\n {\n continue;\n }\n\n var span = x.FileName.AsSpan();\n var fileExt = Path.GetExtension(span).TrimStart('.');\n\n // Check if the file is a subtitle file by its extension\n if (extSetLookup.Contains(fileExt))\n {\n var name = Path.GetFileNameWithoutExtension(span);\n\n if (!name.StartsWith(filename + '.', StringComparison.OrdinalIgnoreCase))\n {\n continue;\n }\n\n Language lang = Language.Unknown;\n\n var extraPart = name.Slice(filename.Length + 1); // Skip file name and dot\n if (extraPart.Length > 0)\n {\n foreach (var codeSeg in extraPart.Split('.'))\n {\n var code = extraPart[codeSeg];\n if (code.Length > 0)\n {\n Language parsed = Language.Get(code.ToString());\n if (!string.IsNullOrEmpty(parsed.IdSubLanguage) && parsed.IdSubLanguage != \"und\")\n {\n lang = parsed;\n break;\n }\n }\n }\n }\n\n result.TryAdd(x.FullPath, lang);\n }\n }\n }\n\n // TODO: L: To check the contents of a file by determining the bitmap.\n private static bool IsSubtitleBitmap(string path)\n {\n try\n {\n FileInfo fi = new(path);\n\n return Utils.ExtensionsSubtitlesBitmap.Contains(fi.Extension.TrimStart('.').ToLower());\n }\n catch\n {\n return false;\n }\n }\n\n // TODO: L: Would it be better to check with SubtitlesManager for network subtitles?\n private static Language DetectLanguage(string path)\n {\n if (!File.Exists(path))\n {\n return Language.Unknown;\n }\n\n Encoding encoding = Encoding.Default;\n Encoding detected = TextEncodings.DetectEncoding(path);\n\n if (detected != null)\n {\n encoding = detected;\n }\n\n // TODO: L: refactor: use the code for reading subtitles in Demuxer\n byte[] data = new byte[100 * 1024];\n\n try\n {\n using FileStream fs = new(path, FileMode.Open, FileAccess.Read);\n int bytesRead = fs.Read(data, 0, data.Length);\n Array.Resize(ref data, bytesRead);\n }\n catch\n {\n return Language.Unknown;\n }\n\n string content = encoding.GetString(data);\n\n var detectedLanguage = LanguageDetector.Value.DetectLanguageOf(content);\n\n if (detectedLanguage == Lingua.Language.Unknown)\n {\n return Language.Unknown;\n }\n\n return Language.Get(detectedLanguage.IsoCode6391().ToString().ToLower());\n }\n}\n"], ["/LLPlayer/FlyleafLibTests/MediaPlayer/SubtitlesManagerTest.cs", "using FluentAssertions;\nusing FluentAssertions.Execution;\n\nnamespace FlyleafLib.MediaPlayer;\n\npublic class SubManagerTests\n{\n private readonly SubManager _subManager;\n\n public SubManagerTests()\n {\n SubManager subManager = new(new Config(true), 0, false);\n List subsData =\n [\n new() { StartTime = TimeSpan.FromSeconds(1), EndTime = TimeSpan.FromSeconds(5), Text = \"1. Hello World!\" },\n new() { StartTime = TimeSpan.FromSeconds(10), EndTime = TimeSpan.FromSeconds(15), Text = \"2. How are you\" },\n new() { StartTime = TimeSpan.FromSeconds(20), EndTime = TimeSpan.FromSeconds(25), Text = \"3. I'm fine\" },\n new() { StartTime = TimeSpan.FromSeconds(28), EndTime = TimeSpan.FromSeconds(29), Text = \"4. Thank you\" },\n new() { StartTime = TimeSpan.FromSeconds(30), EndTime = TimeSpan.FromSeconds(35), Text = \"5. Good bye\" }\n ];\n\n subManager.Load(subsData);\n\n _subManager = subManager;\n }\n\n #region Seek\n [Fact]\n public void SubManagerTest_First_Yet()\n {\n // before the first subtitle\n TimeSpan currentTime = TimeSpan.FromSeconds(0.5);\n _subManager.SetCurrentTime(currentTime);\n\n // 1. Hello World!\n var nextIndex = 0;\n\n var subsData = _subManager.Subs;\n\n using (new AssertionScope())\n {\n _subManager.State.Should().Be(SubManager.PositionState.First);\n _subManager.CurrentIndex.Should().Be(-1);\n\n _subManager.GetCurrent().Should().BeNull();\n _subManager.GetPrev().Should().BeNull();\n _subManager.GetNext().Should()\n .NotBeNull().And\n .Match(s => s.Text == subsData[nextIndex].Text);\n }\n }\n\n [Fact]\n public void SubManagerTest_First_Showing()\n {\n // During playback of the first subtitle\n TimeSpan currentTime = TimeSpan.FromSeconds(1);\n _subManager.SetCurrentTime(currentTime);\n\n // 1. Hello World!\n var curIndex = 0;\n\n var subsData = _subManager.Subs;\n\n using (new AssertionScope())\n {\n _subManager.State.Should().Be(SubManager.PositionState.Showing);\n _subManager.CurrentIndex.Should().Be(curIndex);\n\n _subManager.GetCurrent().Should()\n .NotBeNull().And\n .Match(s => s.Text == subsData[curIndex].Text);\n _subManager.GetPrev().Should().BeNull();\n _subManager.GetNext().Should()\n .NotBeNull().And\n .Match(s => s.Text == subsData[curIndex + 1].Text);\n }\n }\n\n [Fact]\n public void SubManagerTest_Middle_Showing()\n {\n // During playback of the middle subtitle\n TimeSpan currentTime = TimeSpan.FromSeconds(22);\n _subManager.SetCurrentTime(currentTime);\n\n // 3. I'm fine\n var curIndex = 2;\n\n var subsData = _subManager.Subs;\n\n using (new AssertionScope())\n {\n _subManager.State.Should().Be(SubManager.PositionState.Showing);\n _subManager.CurrentIndex.Should().Be(curIndex);\n\n _subManager.GetCurrent().Should()\n .NotBeNull().And\n .Match(s => s.Text == subsData[curIndex].Text);\n _subManager.GetPrev().Should()\n .NotBeNull().And\n .Match(s => s.Text == subsData[curIndex - 1].Text);\n _subManager.GetNext().Should()\n .NotBeNull().And\n .Match(s => s.Text == subsData[curIndex + 1].Text);\n }\n }\n\n [Fact]\n public void SubManagerTest_Middle_Yet()\n {\n // just before the middle subtitle\n TimeSpan currentTime = TimeSpan.FromSeconds(18);\n _subManager.SetCurrentTime(currentTime);\n\n // 3. I'm fine\n var nextIndex = 2;\n\n var subsData = _subManager.Subs;\n\n using (new AssertionScope())\n {\n _subManager.State.Should().Be(SubManager.PositionState.Around);\n _subManager.CurrentIndex.Should().Be(nextIndex - 1);\n\n // Seek falls back to PrevSeek so we can seek, this class returns null\n _subManager.GetCurrent().Should().BeNull();\n _subManager.GetPrev().Should()\n .NotBeNull().And\n .Match(s => s.Text == subsData[nextIndex - 1].Text);\n _subManager.GetNext().Should()\n .NotBeNull().And\n .Match(s => s.Text == subsData[nextIndex].Text);\n }\n }\n\n [Fact]\n public void SubManagerTest_Last_Showing()\n {\n // During playback of the last subtitle\n TimeSpan currentTime = TimeSpan.FromSeconds(35);\n _subManager.SetCurrentTime(currentTime);\n\n // 5. Good bye\n var curIndex = 4;\n\n var subsData = _subManager.Subs;\n\n using (new AssertionScope())\n {\n _subManager.State.Should().Be(SubManager.PositionState.Showing);\n _subManager.CurrentIndex.Should().Be(curIndex);\n\n _subManager.GetCurrent().Should()\n .NotBeNull().And\n .Match(s => s.Text == subsData[curIndex].Text);\n _subManager.GetPrev().Should()\n .NotBeNull().And\n .Match(s => s.Text == subsData[curIndex - 1].Text);\n _subManager.GetNext().Should().BeNull();\n }\n }\n\n [Fact]\n public void SubManagerTest_Last_Past()\n {\n // after the last subtitle\n TimeSpan currentTime = TimeSpan.FromSeconds(99);\n _subManager.SetCurrentTime(currentTime);\n\n // 5. Good bye\n var prevIndex = 4;\n\n var subsData = _subManager.Subs;\n\n using (new AssertionScope())\n {\n _subManager.State.Should().Be(SubManager.PositionState.Last);\n // OK?\n _subManager.CurrentIndex.Should().Be(prevIndex);\n\n // Seek falls back to PrevSeek so we can seek, this returns null\n _subManager.GetCurrent().Should().BeNull();\n _subManager.GetPrev().Should()\n .NotBeNull().And\n .Match(s => s.Text == subsData[prevIndex].Text);\n _subManager.GetNext().Should().BeNull();\n }\n }\n #endregion\n\n #region DeleteAfter\n [Fact]\n public void SubManagerTest_DeleteAfter_DeleteFromMiddle()\n {\n _subManager.DeleteAfter(TimeSpan.FromSeconds(20));\n\n using (new AssertionScope())\n {\n _subManager.Subs.Count.Should().Be(2);\n _subManager.Subs.Select(s => s.Text!.Substring(0, 1))\n .Should().BeEquivalentTo([\"1\", \"2\"]);\n }\n }\n\n [Fact]\n public void SubManagerTest_DeleteAfter_DeleteAll()\n {\n _subManager.DeleteAfter(TimeSpan.FromSeconds(3));\n\n _subManager.Subs.Count.Should().Be(0);\n }\n\n [Fact]\n public void SubManagerTest_DeleteAfter_DeleteLast()\n {\n _subManager.DeleteAfter(TimeSpan.FromSeconds(32));\n\n using (new AssertionScope())\n {\n _subManager.Subs.Count.Should().Be(4);\n _subManager.Subs.Select(s => s.Text!.Substring(0, 1))\n .Should().BeEquivalentTo([\"1\", \"2\", \"3\", \"4\"]);\n }\n }\n\n [Fact]\n public void SubManagerTest_DeleteAfter_NoDelete()\n {\n _subManager.DeleteAfter(TimeSpan.FromSeconds(36));\n\n _subManager.Subs.Count.Should().Be(5);\n }\n #endregion\n}\n"], ["/LLPlayer/FlyleafLib/Engine/WhisperLanguage.cs", "using System.Collections.Generic;\nusing System.Linq;\nusing System.Text;\n\nnamespace FlyleafLib;\n\npublic class WhisperLanguage : IEquatable\n{\n public string Code { get; set; }\n public string EnglishName { get; set; }\n\n // https://github.com/ggerganov/whisper.cpp/blob/d682e150908e10caa4c15883c633d7902d385237/src/whisper.cpp#L248-L348\n private static readonly Dictionary CodeToLanguage = new()\n {\n {\"en\", \"english\"},\n {\"zh\", \"chinese\"},\n {\"de\", \"german\"},\n {\"es\", \"spanish\"},\n {\"ru\", \"russian\"},\n {\"ko\", \"korean\"},\n {\"fr\", \"french\"},\n {\"ja\", \"japanese\"},\n {\"pt\", \"portuguese\"},\n {\"tr\", \"turkish\"},\n {\"pl\", \"polish\"},\n {\"ca\", \"catalan\"},\n {\"nl\", \"dutch\"},\n {\"ar\", \"arabic\"},\n {\"sv\", \"swedish\"},\n {\"it\", \"italian\"},\n {\"id\", \"indonesian\"},\n {\"hi\", \"hindi\"},\n {\"fi\", \"finnish\"},\n {\"vi\", \"vietnamese\"},\n {\"he\", \"hebrew\"},\n {\"uk\", \"ukrainian\"},\n {\"el\", \"greek\"},\n {\"ms\", \"malay\"},\n {\"cs\", \"czech\"},\n {\"ro\", \"romanian\"},\n {\"da\", \"danish\"},\n {\"hu\", \"hungarian\"},\n {\"ta\", \"tamil\"},\n {\"no\", \"norwegian\"},\n {\"th\", \"thai\"},\n {\"ur\", \"urdu\"},\n {\"hr\", \"croatian\"},\n {\"bg\", \"bulgarian\"},\n {\"lt\", \"lithuanian\"},\n {\"la\", \"latin\"},\n {\"mi\", \"maori\"},\n {\"ml\", \"malayalam\"},\n {\"cy\", \"welsh\"},\n {\"sk\", \"slovak\"},\n {\"te\", \"telugu\"},\n {\"fa\", \"persian\"},\n {\"lv\", \"latvian\"},\n {\"bn\", \"bengali\"},\n {\"sr\", \"serbian\"},\n {\"az\", \"azerbaijani\"},\n {\"sl\", \"slovenian\"},\n {\"kn\", \"kannada\"},\n {\"et\", \"estonian\"},\n {\"mk\", \"macedonian\"},\n {\"br\", \"breton\"},\n {\"eu\", \"basque\"},\n {\"is\", \"icelandic\"},\n {\"hy\", \"armenian\"},\n {\"ne\", \"nepali\"},\n {\"mn\", \"mongolian\"},\n {\"bs\", \"bosnian\"},\n {\"kk\", \"kazakh\"},\n {\"sq\", \"albanian\"},\n {\"sw\", \"swahili\"},\n {\"gl\", \"galician\"},\n {\"mr\", \"marathi\"},\n {\"pa\", \"punjabi\"},\n {\"si\", \"sinhala\"},\n {\"km\", \"khmer\"},\n {\"sn\", \"shona\"},\n {\"yo\", \"yoruba\"},\n {\"so\", \"somali\"},\n {\"af\", \"afrikaans\"},\n {\"oc\", \"occitan\"},\n {\"ka\", \"georgian\"},\n {\"be\", \"belarusian\"},\n {\"tg\", \"tajik\"},\n {\"sd\", \"sindhi\"},\n {\"gu\", \"gujarati\"},\n {\"am\", \"amharic\"},\n {\"yi\", \"yiddish\"},\n {\"lo\", \"lao\"},\n {\"uz\", \"uzbek\"},\n {\"fo\", \"faroese\"},\n {\"ht\", \"haitian creole\"},\n {\"ps\", \"pashto\"},\n {\"tk\", \"turkmen\"},\n {\"nn\", \"nynorsk\"},\n {\"mt\", \"maltese\"},\n {\"sa\", \"sanskrit\"},\n {\"lb\", \"luxembourgish\"},\n {\"my\", \"myanmar\"},\n {\"bo\", \"tibetan\"},\n {\"tl\", \"tagalog\"},\n {\"mg\", \"malagasy\"},\n {\"as\", \"assamese\"},\n {\"tt\", \"tatar\"},\n {\"haw\", \"hawaiian\"},\n {\"ln\", \"lingala\"},\n {\"ha\", \"hausa\"},\n {\"ba\", \"bashkir\"},\n {\"jw\", \"javanese\"},\n {\"su\", \"sundanese\"},\n {\"yue\", \"cantonese\"},\n };\n\n // https://github.com/Purfview/whisper-standalone-win/issues/430#issuecomment-2743029023\n // https://github.com/openai/whisper/blob/517a43ecd132a2089d85f4ebc044728a71d49f6e/whisper/tokenizer.py#L10-L110\n public static Dictionary LanguageToCode { get; } = CodeToLanguage.ToDictionary(kv => kv.Value, kv => kv.Key, StringComparer.OrdinalIgnoreCase);\n\n public static List GetWhisperLanguages()\n {\n return CodeToLanguage.Select(kv => new WhisperLanguage\n {\n Code = kv.Key,\n EnglishName = UpperFirstOfWords(kv.Value)\n }).OrderBy(l => l.EnglishName).ToList();\n }\n\n private static string UpperFirstOfWords(string input)\n {\n if (string.IsNullOrEmpty(input))\n return input;\n\n StringBuilder result = new();\n bool isNewWord = true;\n\n foreach (char c in input)\n {\n if (char.IsWhiteSpace(c))\n {\n isNewWord = true;\n result.Append(c);\n }\n else if (isNewWord)\n {\n result.Append(char.ToUpper(c));\n isNewWord = false;\n }\n else\n {\n result.Append(c);\n }\n }\n\n return result.ToString();\n }\n\n public bool Equals(WhisperLanguage other)\n {\n if (other is null) return false;\n if (ReferenceEquals(this, other)) return true;\n return Code == other.Code;\n }\n\n public override bool Equals(object obj) => obj is WhisperLanguage o && Equals(o);\n\n public override int GetHashCode()\n {\n return (Code != null ? Code.GetHashCode() : 0);\n }\n}\n"], ["/LLPlayer/FlyleafLib/MediaPlayer/Player.Open.cs", "using System;\nusing System.Collections.Concurrent;\nusing System.IO;\nusing System.Threading.Tasks;\n\nusing FlyleafLib.MediaFramework.MediaDecoder;\nusing FlyleafLib.MediaFramework.MediaPlaylist;\nusing FlyleafLib.MediaFramework.MediaStream;\n\nusing static FlyleafLib.Logger;\nusing static FlyleafLib.MediaFramework.MediaContext.DecoderContext;\nusing static FlyleafLib.Utils;\n\nnamespace FlyleafLib.MediaPlayer;\n\nunsafe partial class Player\n{\n #region Events\n\n public event EventHandler Opening; // Will be also used for subtitles\n public event EventHandler OpenCompleted; // Will be also used for subtitles\n public event EventHandler OpenPlaylistItemCompleted;\n public event EventHandler OpenSessionCompleted;\n\n public event EventHandler OpenAudioStreamCompleted;\n public event EventHandler OpenVideoStreamCompleted;\n public event EventHandler OpenSubtitlesStreamCompleted;\n public event EventHandler OpenDataStreamCompleted;\n\n public event EventHandler OpenExternalAudioStreamCompleted;\n public event EventHandler OpenExternalVideoStreamCompleted;\n public event EventHandler OpenExternalSubtitlesStreamCompleted;\n\n private void OnOpening(OpeningArgs args = null)\n => Opening?.Invoke(this, args);\n private void OnOpenCompleted(OpenCompletedArgs args = null)\n => OpenCompleted?.Invoke(this, args);\n private void OnOpenSessionCompleted(OpenSessionCompletedArgs args = null)\n => OpenSessionCompleted?.Invoke(this, args);\n private void OnOpenPlaylistItemCompleted(OpenPlaylistItemCompletedArgs args = null)\n => OpenPlaylistItemCompleted?.Invoke(this, args);\n\n private void OnOpenAudioStreamCompleted(OpenAudioStreamCompletedArgs args = null)\n => OpenAudioStreamCompleted?.Invoke(this, args);\n private void OnOpenVideoStreamCompleted(OpenVideoStreamCompletedArgs args = null)\n => OpenVideoStreamCompleted?.Invoke(this, args);\n private void OnOpenSubtitlesStreamCompleted(OpenSubtitlesStreamCompletedArgs args = null)\n => OpenSubtitlesStreamCompleted?.Invoke(this, args);\n private void OnOpenDataStreamCompleted(OpenDataStreamCompletedArgs args = null)\n => OpenDataStreamCompleted?.Invoke(this, args);\n\n private void OnOpenExternalAudioStreamCompleted(OpenExternalAudioStreamCompletedArgs args = null)\n => OpenExternalAudioStreamCompleted?.Invoke(this, args);\n private void OnOpenExternalVideoStreamCompleted(OpenExternalVideoStreamCompletedArgs args = null)\n => OpenExternalVideoStreamCompleted?.Invoke(this, args);\n private void OnOpenExternalSubtitlesStreamCompleted(OpenExternalSubtitlesStreamCompletedArgs args = null)\n => OpenExternalSubtitlesStreamCompleted?.Invoke(this, args);\n #endregion\n\n #region Decoder Events\n private void Decoder_AudioCodecChanged(DecoderBase x)\n {\n Audio.Refresh();\n UIAll();\n }\n private void Decoder_VideoCodecChanged(DecoderBase x)\n {\n Video.Refresh();\n UIAll();\n }\n\n private void Decoder_OpenAudioStreamCompleted(object sender, OpenAudioStreamCompletedArgs e)\n {\n Config.Audio.SetDelay(0);\n Audio.Refresh();\n canPlay = Video.IsOpened || Audio.IsOpened;\n isLive = MainDemuxer.IsLive;\n duration= MainDemuxer.Duration;\n\n UIAdd(() =>\n {\n IsLive = IsLive;\n CanPlay = CanPlay;\n Duration=Duration;\n });\n UIAll();\n }\n private void Decoder_OpenVideoStreamCompleted(object sender, OpenVideoStreamCompletedArgs e)\n {\n Video.Refresh();\n canPlay = Video.IsOpened || Audio.IsOpened;\n isLive = MainDemuxer.IsLive;\n duration= MainDemuxer.Duration;\n\n UIAdd(() =>\n {\n IsLive = IsLive;\n CanPlay = CanPlay;\n Duration=Duration;\n });\n UIAll();\n }\n private void Decoder_OpenSubtitlesStreamCompleted(object sender, OpenSubtitlesStreamCompletedArgs e)\n {\n int i = SubtitlesSelectedHelper.CurIndex;\n\n Config.Subtitles[i].SetDelay(0);\n Subtitles[i].Refresh();\n UIAll();\n\n if (IsPlaying && Config.Subtitles.Enabled) // TBR (First run mainly with -from DecoderContext->OpenSuggestedSubtitles-> Task.Run causes late open, possible resync?)\n {\n if (!Subtitles[i].IsOpened)\n {\n return;\n }\n\n lock (lockSubtitles)\n {\n if (SubtitlesDecoders[i].OnVideoDemuxer)\n {\n SubtitlesDecoders[i].Start();\n }\n //else// if (!decoder.RequiresResync)\n //{\n // SubtitlesDemuxers[i].Start();\n // SubtitlesDecoders[i].Start();\n //}\n }\n }\n }\n\n private void Decoder_OpenDataStreamCompleted(object sender, OpenDataStreamCompletedArgs e)\n {\n Data.Refresh();\n UIAll();\n if (Config.Data.Enabled)\n {\n lock (lockSubtitles)\n if (DataDecoder.OnVideoDemuxer)\n DataDecoder.Start();\n else// if (!decoder.RequiresResync)\n {\n DataDemuxer.Start();\n DataDecoder.Start();\n }\n }\n }\n\n private void Decoder_OpenExternalAudioStreamCompleted(object sender, OpenExternalAudioStreamCompletedArgs e)\n {\n if (!e.Success)\n {\n canPlay = Video.IsOpened || Audio.IsOpened;\n UIAdd(() => CanPlay = CanPlay);\n UIAll();\n }\n }\n private void Decoder_OpenExternalVideoStreamCompleted(object sender, OpenExternalVideoStreamCompletedArgs e)\n {\n if (!e.Success)\n {\n canPlay = Video.IsOpened || Audio.IsOpened;\n UIAdd(() => CanPlay = CanPlay);\n UIAll();\n }\n }\n private void Decoder_OpenExternalSubtitlesStreamCompleted(object sender, OpenExternalSubtitlesStreamCompletedArgs e)\n {\n if (e.Success)\n {\n lock (lockSubtitles)\n ReSync(decoder.SubtitlesStreams[SubtitlesSelectedHelper.CurIndex], decoder.GetCurTimeMs());\n }\n }\n #endregion\n\n #region Open Implementation\n private OpenCompletedArgs OpenInternal(object url_iostream, bool defaultPlaylistItem = true, bool defaultVideo = true, bool defaultAudio = true, bool defaultSubtitles = true)\n {\n OpenCompletedArgs args = new();\n\n try\n {\n if (url_iostream == null)\n {\n args.Error = \"Invalid empty/null input\";\n return args;\n }\n\n if (CanInfo) Log.Info($\"Opening {url_iostream}\");\n\n Initialize(Status.Opening);\n var args2 = decoder.Open(url_iostream, defaultPlaylistItem, defaultVideo, defaultAudio, defaultSubtitles);\n\n args.Url = args2.Url;\n args.IOStream = args2.IOStream;\n args.Error = args2.Error;\n\n if (!args.Success)\n {\n status = Status.Failed;\n lastError = args.Error;\n }\n else if (CanPlay)\n {\n status = Status.Paused;\n\n if (Config.Player.AutoPlay)\n Play();\n }\n else if (!defaultVideo && !defaultAudio)\n {\n isLive = MainDemuxer.IsLive;\n duration= MainDemuxer.Duration;\n UIAdd(() =>\n {\n IsLive = IsLive;\n Duration=Duration;\n });\n }\n\n UIAdd(() =>\n {\n LastError=LastError;\n Status = Status;\n });\n\n UIAll();\n\n return args;\n\n } catch (Exception e)\n {\n args.Error = !args.Success ? args.Error + \"\\r\\n\" + e.Message : e.Message;\n return args;\n } finally\n {\n OnOpenCompleted(args);\n }\n }\n private OpenCompletedArgs OpenSubtitles(string url)\n {\n OpenCompletedArgs args = new(url, null, null, true);\n\n try\n {\n if (CanInfo) Log.Info($\"Opening subtitles {url}\");\n\n if (!Video.IsOpened)\n {\n args.Error = \"Cannot open subtitles without video\";\n return args;\n }\n\n Config.Subtitles.SetEnabled(true);\n args.Error = decoder.OpenSubtitles(url).Error;\n\n if (args.Success)\n ReSync(decoder.SubtitlesStreams[SubtitlesSelectedHelper.CurIndex]);\n\n return args;\n\n } catch (Exception e)\n {\n args.Error = !args.Success ? args.Error + \"\\r\\n\" + e.Message : e.Message;\n return args;\n } finally\n {\n OnOpenCompleted(args);\n }\n }\n\n /// \n /// Opens a new media file (audio/subtitles/video)\n /// \n /// Media file's url\n /// Whether to open the first/default item in case of playlist\n /// Whether to open the default video stream from plugin suggestions\n /// Whether to open the default audio stream from plugin suggestions\n /// Whether to open the default subtitles stream from plugin suggestions\n /// Forces input url to be handled as subtitles\n /// \n public OpenCompletedArgs Open(string url, bool defaultPlaylistItem = true, bool defaultVideo = true, bool defaultAudio = true, bool defaultSubtitles = true, bool forceSubtitles = false)\n {\n if (forceSubtitles || ExtensionsSubtitles.Contains(GetUrlExtention(url)))\n {\n OnOpening(new() { Url = url, IsSubtitles = true});\n return OpenSubtitles(url);\n }\n else\n {\n OnOpening(new() { Url = url });\n return OpenInternal(url, defaultPlaylistItem, defaultVideo, defaultAudio, defaultSubtitles);\n }\n }\n\n /// \n /// Opens a new media file (audio/subtitles/video) without blocking\n /// You can get the results from \n /// \n /// Media file's url\n /// Whether to open the first/default item in case of playlist\n /// Whether to open the default video stream from plugin suggestions\n /// Whether to open the default audio stream from plugin suggestions\n /// Whether to open the default subtitles stream from plugin suggestions\n public void OpenAsync(string url, bool defaultPlaylistItem = true, bool defaultVideo = true, bool defaultAudio = true, bool defaultSubtitles = true)\n => OpenAsyncPush(url, defaultPlaylistItem, defaultVideo, defaultAudio, defaultSubtitles);\n\n /// \n /// Opens a new media I/O stream (audio/video) without blocking\n /// \n /// Media stream\n /// Whether to open the first/default item in case of playlist\n /// Whether to open the default video stream from plugin suggestions\n /// Whether to open the default audio stream from plugin suggestions\n /// Whether to open the default subtitles stream from plugin suggestions\n /// \n public OpenCompletedArgs Open(Stream iostream, bool defaultPlaylistItem = true, bool defaultVideo = true, bool defaultAudio = true, bool defaultSubtitles = true)\n {\n OnOpening(new() { IOStream = iostream });\n return OpenInternal(iostream, defaultPlaylistItem, defaultVideo, defaultAudio, defaultSubtitles);\n }\n\n /// \n /// Opens a new media I/O stream (audio/video) without blocking\n /// You can get the results from \n /// \n /// Media stream\n /// Whether to open the first/default item in case of playlist\n /// Whether to open the default video stream from plugin suggestions\n /// Whether to open the default audio stream from plugin suggestions\n /// Whether to open the default subtitles stream from plugin suggestions\n public void OpenAsync(Stream iostream, bool defaultPlaylistItem = true, bool defaultVideo = true, bool defaultAudio = true, bool defaultSubtitles = true)\n => OpenAsyncPush(iostream, defaultPlaylistItem, defaultVideo, defaultAudio, defaultSubtitles);\n\n /// \n /// Opens a new media session\n /// \n /// Media session\n /// \n public OpenSessionCompletedArgs Open(Session session)\n {\n OpenSessionCompletedArgs args = new(session);\n\n try\n {\n Playlist.Selected?.AddTag(GetCurrentSession(), playerSessionTag);\n\n Initialize(Status.Opening, true, session.isReopen);\n args.Error = decoder.Open(session).Error;\n\n if (!args.Success || !CanPlay)\n {\n status = Status.Failed;\n lastError = args.Error;\n }\n else\n {\n status = Status.Paused;\n\n if (Config.Player.AutoPlay)\n Play();\n }\n\n UIAdd(() =>\n {\n LastError=LastError;\n Status = Status;\n });\n\n UIAll();\n\n return args;\n } catch (Exception e)\n {\n args.Error = !args.Success ? args.Error + \"\\r\\n\" + e.Message : e.Message;\n return args;\n } finally\n {\n OnOpenSessionCompleted(args);\n }\n }\n\n /// \n /// Opens a new media session without blocking\n /// \n /// Media session\n public void OpenAsync(Session session) => OpenAsyncPush(session);\n\n /// \n /// Opens a playlist item \n /// \n /// The playlist item to open\n /// Whether to open the default video stream from plugin suggestions\n /// Whether to open the default audio stream from plugin suggestions\n /// Whether to open the default subtitles stream from plugin suggestions\n /// \n public OpenPlaylistItemCompletedArgs Open(PlaylistItem item, bool defaultVideo = true, bool defaultAudio = true, bool defaultSubtitles = true)\n {\n OpenPlaylistItemCompletedArgs args = new(item, Playlist.Selected);\n\n try\n {\n Playlist.Selected?.AddTag(GetCurrentSession(), playerSessionTag);\n\n Initialize(Status.Opening, true, true);\n\n // TODO: Config.Player.Reopen? to reopen session if (item.OpenedCounter > 0)\n args = decoder.Open(item, defaultVideo, defaultAudio, defaultSubtitles);\n\n if (!args.Success)\n {\n status = Status.Failed;\n lastError = args.Error;\n }\n else if (CanPlay)\n {\n status = Status.Paused;\n\n if (Config.Player.AutoPlay)\n Play();\n // TODO: else Show on frame?\n }\n else if (!defaultVideo && !defaultAudio)\n {\n isLive = MainDemuxer.IsLive;\n duration= MainDemuxer.Duration;\n UIAdd(() =>\n {\n IsLive = IsLive;\n Duration=Duration;\n });\n }\n\n UIAdd(() =>\n {\n LastError=LastError;\n Status = Status;\n });\n\n UIAll();\n\n return args;\n\n } catch (Exception e)\n {\n args.Error = !args.Success ? args.Error + \"\\r\\n\" + e.Message : e.Message;\n return args;\n } finally\n {\n OnOpenPlaylistItemCompleted(args);\n }\n }\n\n /// \n /// Opens a playlist item without blocking\n /// You can get the results from \n /// \n /// The playlist item to open\n /// Whether to open the default video stream from plugin suggestions\n /// Whether to open the default audio stream from plugin suggestions\n /// Whether to open the default subtitles stream from plugin suggestions\n /// \n public void OpenAsync(PlaylistItem item, bool defaultVideo = true, bool defaultAudio = true, bool defaultSubtitles = true)\n => OpenAsyncPush(item, defaultVideo, defaultAudio, defaultSubtitles);\n\n /// \n /// Opens an external stream (audio/subtitles/video)\n /// \n /// The external stream to open\n /// Whether to force resync with other streams\n /// Whether to open the default audio stream from plugin suggestions\n /// -2: None, -1: Suggested/Default, X: Specified embedded stream index\n /// \n public ExternalStreamOpenedArgs Open(ExternalStream extStream, bool resync = true, bool defaultAudio = true, int streamIndex = -1)\n {\n /* TODO\n *\n * Decoder.Stop() should not be called on video input switch as it will close the other inputs as well (audio/subs)\n * If the input is from different plugin we don't dispose the current plugin (eg. switching between recent/history plugin with torrents) (?)\n */\n\n ExternalStreamOpenedArgs args = null;\n\n try\n {\n int syncMs = decoder.GetCurTimeMs();\n\n if (LastError != null)\n {\n lastError = null;\n UI(() => LastError = LastError);\n }\n\n if (extStream is ExternalAudioStream)\n {\n if (decoder.VideoStream == null)\n requiresBuffering = true;\n\n isAudioSwitch = true;\n Config.Audio.SetEnabled(true);\n args = decoder.Open(extStream, false, streamIndex);\n\n if (!args.Success)\n {\n isAudioSwitch = false;\n return args;\n }\n\n if (resync)\n ReSync(decoder.AudioStream, syncMs);\n\n if (VideoDemuxer.VideoStream == null)\n {\n isLive = MainDemuxer.IsLive;\n duration = MainDemuxer.Duration;\n }\n\n isAudioSwitch = false;\n }\n else if (extStream is ExternalVideoStream)\n {\n bool shouldPlay = false;\n if (IsPlaying)\n {\n shouldPlay = true;\n Pause();\n }\n\n Initialize(Status.Opening, false, true);\n args = decoder.Open(extStream, defaultAudio, streamIndex);\n\n if (!args.Success || !CanPlay)\n return args;\n\n decoder.Seek(syncMs, false, false);\n decoder.GetVideoFrame(syncMs * (long)10000);\n VideoDemuxer.Start();\n AudioDemuxer.Start();\n //for (int i = 0; i < subNum; i++)\n //{\n // SubtitlesDemuxers[i].Start();\n //}\n DataDemuxer.Start();\n decoder.PauseOnQueueFull();\n\n // Initialize will Reset those and is posible that Codec Changed will not be called (as they are not chaning necessary)\n Decoder_OpenAudioStreamCompleted(null, null);\n Decoder_OpenSubtitlesStreamCompleted(null, null);\n\n if (shouldPlay)\n Play();\n else\n ShowOneFrame();\n }\n else // ExternalSubtitlesStream\n {\n if (!Video.IsOpened)\n {\n args.Error = \"Subtitles require opened video stream\";\n return args;\n }\n\n Config.Subtitles.SetEnabled(true);\n args = decoder.Open(extStream, false, streamIndex);\n }\n\n return args;\n\n } catch (Exception e)\n {\n args.Error = !args.Success ? args.Error + \"\\r\\n\" + e.Message : e.Message;\n return args;\n } finally\n {\n if (extStream is ExternalVideoStream)\n OnOpenExternalVideoStreamCompleted((OpenExternalVideoStreamCompletedArgs)args);\n else if (extStream is ExternalAudioStream)\n OnOpenExternalAudioStreamCompleted((OpenExternalAudioStreamCompletedArgs)args);\n else\n OnOpenExternalSubtitlesStreamCompleted((OpenExternalSubtitlesStreamCompletedArgs)args);\n }\n }\n\n /// \n /// Opens an external stream (audio/subtitles/video) without blocking\n /// You can get the results from , , \n /// \n /// The external stream to open\n /// Whether to force resync with other streams\n /// Whether to open the default audio stream from plugin suggestions\n public void OpenAsync(ExternalStream extStream, bool resync = true, bool defaultAudio = true)\n => OpenAsyncPush(extStream, resync, defaultAudio);\n\n /// \n /// Opens an embedded stream (audio/subtitles/video)\n /// \n /// An existing Player's media stream\n /// Whether to force resync with other streams\n /// Whether to re-suggest audio based on the new video stream (has effect only on VideoStream)\n /// \n public StreamOpenedArgs Open(StreamBase stream, bool resync = true, bool defaultAudio = true)\n {\n StreamOpenedArgs args = new();\n\n try\n {\n long delay = DateTime.UtcNow.Ticks;\n long fromEnd = Duration - CurTime;\n\n if (stream.Demuxer.Type == MediaType.Video)\n {\n isVideoSwitch = true;\n requiresBuffering = true;\n }\n\n if (stream is AudioStream astream)\n {\n Config.Audio.SetEnabled(true);\n args = decoder.OpenAudioStream(astream);\n }\n else if (stream is VideoStream vstream)\n args = decoder.OpenVideoStream(vstream, defaultAudio);\n else if (stream is SubtitlesStream sstream)\n {\n Config.Subtitles.SetEnabled(true);\n args = decoder.OpenSubtitlesStream(sstream);\n }\n else if (stream is DataStream dstream)\n {\n Config.Data.SetEnabled(true);\n args = decoder.OpenDataStream(dstream);\n }\n\n if (resync)\n {\n // Wait for at least on package before seek to update the HLS context first_time\n if (stream.Demuxer.IsHLSLive)\n {\n while (stream.Demuxer.IsRunning && stream.Demuxer.GetPacketsPtr(stream).Count < 3)\n System.Threading.Thread.Sleep(20);\n\n ReSync(stream, (int) ((Duration - fromEnd - (DateTime.UtcNow.Ticks - delay))/ 10000));\n }\n else\n ReSync(stream, (int) (CurTime / 10000), true);\n }\n else\n isVideoSwitch = false;\n\n return args;\n\n } catch (Exception e)\n {\n args.Error = !args.Success ? args.Error + \"\\r\\n\" + e.Message : e.Message;\n return args;\n } finally\n {\n if (stream is VideoStream)\n OnOpenVideoStreamCompleted((OpenVideoStreamCompletedArgs)args);\n else if (stream is AudioStream)\n OnOpenAudioStreamCompleted((OpenAudioStreamCompletedArgs)args);\n else if (stream is SubtitlesStream)\n OnOpenSubtitlesStreamCompleted((OpenSubtitlesStreamCompletedArgs)args);\n else\n OnOpenDataStreamCompleted((OpenDataStreamCompletedArgs)args);\n }\n }\n\n /// \n /// Opens an embedded stream (audio/subtitles/video) without blocking\n /// You can get the results from , , \n /// \n /// An existing Player's media stream\n /// Whether to force resync with other streams\n /// Whether to re-suggest audio based on the new video stream (has effect only on VideoStream)\n public void OpenAsync(StreamBase stream, bool resync = true, bool defaultAudio = true)\n => OpenAsyncPush(stream, resync, defaultAudio);\n\n /// \n /// Gets a session that can be re-opened later on with \n /// \n /// The current selected playlist item if null\n /// \n public Session GetSession(PlaylistItem item = null)\n => Playlist.Selected != null && (item == null || item.Index == Playlist.Selected.Index)\n ? GetCurrentSession()\n : item != null && item.GetTag(playerSessionTag) != null ? (Session)item.GetTag(playerSessionTag) : null;\n string playerSessionTag = \"_session\";\n private Session GetCurrentSession()\n {\n Session session = new();\n var item = Playlist.Selected;\n\n session.Url = Playlist.Url;\n session.PlaylistItem = item.Index;\n\n if (item.ExternalAudioStream != null)\n session.ExternalAudioStream = item.ExternalAudioStream.Index;\n\n if (item.ExternalVideoStream != null)\n session.ExternalVideoStream = item.ExternalVideoStream.Index;\n\n // TODO: L: Support secondary subtitles\n if (item.ExternalSubtitlesStreams[0] != null)\n session.ExternalSubtitlesUrl = item.ExternalSubtitlesStreams[0].Url;\n else if (decoder.SubtitlesStreams[0] != null)\n session.SubtitlesStream = decoder.SubtitlesStreams[0].StreamIndex;\n\n if (decoder.AudioStream != null)\n session.AudioStream = decoder.AudioStream.StreamIndex;\n\n if (decoder.VideoStream != null)\n session.VideoStream = decoder.VideoStream.StreamIndex;\n\n session.CurTime = CurTime;\n session.AudioDelay = Config.Audio.Delay;\n // TODO: L: Support secondary subtitles\n session.SubtitlesDelay = Config.Subtitles[0].Delay;\n\n return session;\n }\n\n internal void ReSync(StreamBase stream, int syncMs = -1, bool accurate = false)\n {\n /* TODO\n *\n * HLS live resync on stream switch should be from the end not from the start (could have different cache/duration)\n */\n\n if (stream == null) return;\n //if (stream == null || (syncMs == 0 || (syncMs == -1 && decoder.GetCurTimeMs() == 0))) return; // Avoid initial open resync?\n\n if (stream.Demuxer.Type == MediaType.Video)\n {\n isVideoSwitch = true;\n isAudioSwitch = true;\n for (int i = 0; i < subNum; i++)\n {\n isSubsSwitches[i] = true;\n }\n isDataSwitch = true;\n requiresBuffering = true;\n\n if (accurate && Video.IsOpened)\n {\n decoder.PauseDecoders();\n decoder.Seek(syncMs, false, false);\n decoder.GetVideoFrame(syncMs * (long)10000); // TBR: syncMs should not be -1 here\n }\n else\n decoder.Seek(syncMs, false, false);\n\n aFrame = null;\n isAudioSwitch = false;\n isVideoSwitch = false;\n for (int i = 0; i < subNum; i++)\n {\n sFrames[i] = sFramesPrev[i] = null;\n isSubsSwitches[i] = false;\n }\n dFrame = null;\n isDataSwitch = false;\n\n if (!IsPlaying)\n {\n decoder.PauseDecoders();\n decoder.GetVideoFrame();\n ShowOneFrame();\n }\n else\n {\n SubtitleClear();\n }\n }\n else\n {\n if (stream.Demuxer.Type == MediaType.Audio)\n {\n isAudioSwitch = true;\n decoder.SeekAudio();\n aFrame = null;\n isAudioSwitch = false;\n }\n else if (stream.Demuxer.Type == MediaType.Subs)\n {\n int i = SubtitlesSelectedHelper.CurIndex;\n\n isSubsSwitches[i] = true;\n\n //decoder.SeekSubtitles(i);\n sFrames[i] = sFramesPrev[i] = null;\n SubtitleClear(i);\n isSubsSwitches[i] = false;\n\n // do not start demuxer and decoder for external subs\n return;\n }\n else if (stream.Demuxer.Type == MediaType.Data)\n {\n isDataSwitch = true;\n decoder.SeekData();\n dFrame = null;\n isDataSwitch = false;\n }\n\n if (IsPlaying)\n {\n stream.Demuxer.Start();\n decoder.GetDecoderPtr(stream).Start();\n }\n }\n }\n #endregion\n\n #region OpenAsync Implementation\n private void OpenAsync()\n {\n lock (lockActions)\n if (taskOpenAsyncRuns)\n return;\n\n taskOpenAsyncRuns = true;\n\n Task.Run(() =>\n {\n if (IsDisposed)\n return;\n\n while (true)\n {\n if (openInputs.TryPop(out var data))\n {\n openInputs.Clear();\n decoder.Interrupt = true;\n OpenInternal(data.url_iostream, data.defaultPlaylistItem, data.defaultVideo, data.defaultAudio, data.defaultSubtitles);\n }\n else if (openSessions.TryPop(out data))\n {\n openSessions.Clear();\n decoder.Interrupt = true;\n Open(data.session);\n }\n else if (openItems.TryPop(out data))\n {\n openItems.Clear();\n decoder.Interrupt = true;\n Open(data.playlistItem, data.defaultVideo, data.defaultAudio, data.defaultSubtitles);\n }\n else if (openVideo.TryPop(out data))\n {\n openVideo.Clear();\n if (data.extStream != null)\n Open(data.extStream, data.resync, data.defaultAudio);\n else\n Open(data.stream, data.resync, data.defaultAudio);\n }\n else if (openAudio.TryPop(out data))\n {\n openAudio.Clear();\n if (data.extStream != null)\n Open(data.extStream, data.resync);\n else\n Open(data.stream, data.resync);\n }\n else if (openSubtitles.TryPop(out data))\n {\n openSubtitles.Clear();\n if (data.url_iostream != null)\n OpenSubtitles(data.url_iostream.ToString());\n else if (data.extStream != null)\n Open(data.extStream, data.resync);\n else if (data.stream != null)\n Open(data.stream, data.resync);\n }\n else\n {\n lock (lockActions)\n {\n if (openInputs.IsEmpty && openSessions.IsEmpty && openItems.IsEmpty && openVideo.IsEmpty && openAudio.IsEmpty && openSubtitles.IsEmpty)\n {\n taskOpenAsyncRuns = false;\n break;\n }\n }\n }\n }\n });\n }\n\n private void OpenAsyncPush(object url_iostream, bool defaultPlaylistItem = true, bool defaultVideo = true, bool defaultAudio = true, bool defaultSubtitles = true)\n {\n lock (lockActions)\n {\n if (url_iostream is string url_iostream_str)\n {\n // convert Windows lnk file to targetPath\n if (Path.GetExtension(url_iostream_str).Equals(\".lnk\", StringComparison.OrdinalIgnoreCase))\n {\n var targetPath = GetLnkTargetPath(url_iostream_str);\n if (targetPath != null)\n url_iostream = targetPath;\n }\n }\n\n if ((url_iostream is string) && ExtensionsSubtitles.Contains(GetUrlExtention(url_iostream.ToString())))\n {\n OnOpening(new() { Url = url_iostream.ToString(), IsSubtitles = true});\n openSubtitles.Push(new OpenAsyncData(url_iostream));\n }\n else\n {\n decoder.Interrupt = true;\n\n if (url_iostream is string)\n OnOpening(new() { Url = url_iostream.ToString() });\n else\n OnOpening(new() { IOStream = (Stream)url_iostream });\n\n openInputs.Push(new OpenAsyncData(url_iostream, defaultPlaylistItem, defaultVideo, defaultAudio, defaultSubtitles));\n }\n\n // Select primary subtitle & original mode when dropped\n SubtitlesSelectedHelper.CurIndex = 0;\n SubtitlesSelectedHelper.PrimaryMethod = SelectSubMethod.Original;\n\n OpenAsync();\n }\n }\n private void OpenAsyncPush(Session session)\n {\n lock (lockActions)\n {\n if (!openInputs.IsEmpty)\n return;\n\n decoder.Interrupt = true;\n openSessions.Clear();\n openSessions.Push(new OpenAsyncData(session));\n\n OpenAsync();\n }\n }\n private void OpenAsyncPush(PlaylistItem playlistItem, bool defaultVideo = true, bool defaultAudio = true, bool defaultSubtitles = true)\n {\n lock (lockActions)\n {\n if (!openInputs.IsEmpty || !openSessions.IsEmpty)\n return;\n\n decoder.Interrupt = true;\n openItems.Push(new OpenAsyncData(playlistItem, defaultVideo, defaultAudio, defaultSubtitles));\n\n OpenAsync();\n }\n }\n private void OpenAsyncPush(ExternalStream extStream, bool resync = true, bool defaultAudio = true, int streamIndex = -1)\n {\n lock (lockActions)\n {\n if (!openInputs.IsEmpty || !openItems.IsEmpty || !openSessions.IsEmpty)\n return;\n\n if (extStream is ExternalAudioStream)\n {\n openAudio.Clear();\n openAudio.Push(new OpenAsyncData(extStream, resync, false, streamIndex));\n }\n else if (extStream is ExternalVideoStream)\n {\n openVideo.Clear();\n openVideo.Push(new OpenAsyncData(extStream, resync, defaultAudio, streamIndex));\n }\n else\n {\n openSubtitles.Clear();\n openSubtitles.Push(new OpenAsyncData(extStream, resync, false, streamIndex));\n }\n\n OpenAsync();\n }\n }\n private void OpenAsyncPush(StreamBase stream, bool resync = true, bool defaultAudio = true)\n {\n lock (lockActions)\n {\n if (!openInputs.IsEmpty || !openItems.IsEmpty || !openSessions.IsEmpty)\n return;\n\n if (stream is AudioStream)\n {\n openAudio.Clear();\n openAudio.Push(new OpenAsyncData(stream, resync));\n }\n else if (stream is VideoStream)\n {\n openVideo.Clear();\n openVideo.Push(new OpenAsyncData(stream, resync, defaultAudio));\n }\n else\n {\n openSubtitles.Clear();\n openSubtitles.Push(new OpenAsyncData(stream, resync));\n }\n\n OpenAsync();\n }\n }\n\n ConcurrentStack openInputs = new();\n ConcurrentStack openSessions = new();\n ConcurrentStack openItems = new();\n ConcurrentStack openVideo = new();\n ConcurrentStack openAudio = new();\n ConcurrentStack openSubtitles= new();\n #endregion\n}\n\npublic class OpeningArgs\n{\n public string Url;\n public Stream IOStream;\n public bool IsSubtitles;\n}\n\npublic class OpenCompletedArgs\n{\n public string Url;\n public Stream IOStream;\n public string Error;\n public bool Success => Error == null;\n public bool IsSubtitles;\n\n public OpenCompletedArgs(string url = null, Stream iostream = null, string error = null, bool isSubtitles = false) { Url = url; IOStream = iostream; Error = error; IsSubtitles = isSubtitles; }\n}\n\nclass OpenAsyncData\n{\n public object url_iostream;\n public Session session;\n public PlaylistItem playlistItem;\n public ExternalStream extStream;\n public int streamIndex;\n public StreamBase stream;\n public bool resync;\n public bool defaultPlaylistItem;\n public bool defaultAudio;\n public bool defaultVideo;\n public bool defaultSubtitles;\n\n public OpenAsyncData(object url_iostream, bool defaultPlaylistItem = true, bool defaultVideo = true, bool defaultAudio = true, bool defaultSubtitles = true)\n { this.url_iostream = url_iostream; this.defaultPlaylistItem = defaultPlaylistItem; this.defaultVideo = defaultVideo; this.defaultAudio = defaultAudio; this.defaultSubtitles = defaultSubtitles; }\n public OpenAsyncData(Session session) => this.session = session;\n public OpenAsyncData(PlaylistItem playlistItem, bool defaultVideo = true, bool defaultAudio = true, bool defaultSubtitles = true)\n { this.playlistItem = playlistItem; this.defaultVideo = defaultVideo; this.defaultAudio = defaultAudio; this.defaultSubtitles = defaultSubtitles; }\n public OpenAsyncData(ExternalStream extStream, bool resync = true, bool defaultAudio = true, int streamIndex = -1)\n { this.extStream = extStream; this.resync = resync; this.defaultAudio = defaultAudio; this.streamIndex = streamIndex; }\n public OpenAsyncData(StreamBase stream, bool resync = true, bool defaultAudio = true)\n { this.stream = stream; this.resync = resync; this.defaultAudio = defaultAudio; }\n}\n"], ["/LLPlayer/LLPlayer/ViewModels/TesseractDownloadDialogVM.cs", "using System.Collections.ObjectModel;\nusing System.Diagnostics;\nusing System.IO;\nusing System.Net.Http;\nusing FlyleafLib;\nusing LLPlayer.Extensions;\nusing LLPlayer.Services;\n\nnamespace LLPlayer.ViewModels;\n\n// TODO: L: consider commonization with WhisperModelDownloadDialogVM\npublic class TesseractDownloadDialogVM : Bindable, IDialogAware\n{\n public FlyleafManager FL { get; }\n\n public TesseractDownloadDialogVM(FlyleafManager fl)\n {\n FL = fl;\n\n List models = TesseractModelLoader.LoadAllModels();\n foreach (var model in models)\n {\n Models.Add(model);\n }\n\n SelectedModel = Models.First();\n\n CmdDownloadModel!.PropertyChanged += (sender, args) =>\n {\n if (args.PropertyName == nameof(CmdDownloadModel.IsExecuting))\n {\n OnPropertyChanged(nameof(CanDownload));\n OnPropertyChanged(nameof(CanDelete));\n }\n };\n }\n\n private const string TempExtension = \".tmp\";\n\n public ObservableCollection Models { get; set => Set(ref field, value); } = new();\n\n public TesseractModel SelectedModel\n {\n get;\n set\n {\n if (Set(ref field, value))\n {\n OnPropertyChanged(nameof(CanDownload));\n OnPropertyChanged(nameof(CanDelete));\n }\n }\n }\n\n public string StatusText { get; set => Set(ref field, value); } = \"Select a model to download.\";\n\n public long DownloadedSize { get; set => Set(ref field, value); }\n\n public bool CanDownload =>\n SelectedModel is { Downloaded: false } && !CmdDownloadModel!.IsExecuting;\n\n public bool CanDelete =>\n SelectedModel is { Downloaded: true } && !CmdDownloadModel!.IsExecuting;\n\n private CancellationTokenSource? _cts;\n\n public AsyncDelegateCommand? CmdDownloadModel => field ??= new AsyncDelegateCommand(async () =>\n {\n _cts = new CancellationTokenSource();\n CancellationToken token = _cts.Token;\n\n TesseractModel downloadModel = SelectedModel;\n string tempModelPath = downloadModel.ModelFilePath + TempExtension;\n\n try\n {\n if (downloadModel.Downloaded)\n {\n StatusText = $\"Model '{SelectedModel}' is already downloaded\";\n return;\n }\n\n // Delete temporary files if they exist (forces re-download)\n if (!DeleteTempModel())\n {\n StatusText = \"Failed to remove temp model\";\n return;\n }\n\n StatusText = $\"Model '{downloadModel}' downloading..\";\n\n long modelSize = await DownloadModelWithProgressAsync(downloadModel.LangCode, tempModelPath, token);\n\n // After successful download, rename temporary file to final file\n File.Move(tempModelPath, downloadModel.ModelFilePath);\n\n // Update downloaded status\n downloadModel.Size = modelSize;\n OnDownloadStatusChanged();\n\n StatusText = $\"Model '{SelectedModel}' is downloaded successfully\";\n }\n catch (OperationCanceledException ex)\n when (!ex.Message.StartsWith(\"The request was canceled due to the configured HttpClient.Timeout\"))\n {\n StatusText = \"Download canceled\";\n }\n catch (Exception ex)\n {\n StatusText = $\"Failed to download: {ex.Message}\";\n }\n finally\n {\n _cts = null;\n DeleteTempModel();\n }\n\n return;\n\n bool DeleteTempModel()\n {\n // Delete temporary files if they exist\n if (File.Exists(tempModelPath))\n {\n try\n {\n File.Delete(tempModelPath);\n }\n catch (Exception)\n {\n // ignore\n\n return false;\n }\n }\n\n return true;\n }\n }).ObservesCanExecute(() => CanDownload);\n\n public DelegateCommand? CmdCancelDownloadModel => field ??= new(() =>\n {\n _cts?.Cancel();\n });\n\n public DelegateCommand? CmdDeleteModel => field ??= new DelegateCommand(() =>\n {\n try\n {\n StatusText = $\"Model '{SelectedModel}' deleting...\";\n\n TesseractModel deleteModel = SelectedModel;\n\n // Delete model file if exists\n if (File.Exists(deleteModel.ModelFilePath))\n {\n File.Delete(deleteModel.ModelFilePath);\n }\n\n // Update downloaded status\n deleteModel.Size = 0;\n OnDownloadStatusChanged();\n\n StatusText = $\"Model '{deleteModel}' is deleted successfully\";\n }\n catch (Exception ex)\n {\n StatusText = $\"Failed to delete model: {ex.Message}\";\n }\n }).ObservesCanExecute(() => CanDelete);\n\n public DelegateCommand? CmdOpenFolder => field ??= new(() =>\n {\n if (!Directory.Exists(TesseractModel.ModelsDirectory))\n return;\n\n Process.Start(new ProcessStartInfo\n {\n FileName = TesseractModel.ModelsDirectory,\n UseShellExecute = true,\n CreateNoWindow = true\n });\n });\n\n private void OnDownloadStatusChanged()\n {\n OnPropertyChanged(nameof(CanDownload));\n OnPropertyChanged(nameof(CanDelete));\n }\n\n private async Task DownloadModelWithProgressAsync(string langCode, string destinationPath, CancellationToken token)\n {\n DownloadedSize = 0;\n\n using HttpClient httpClient = new();\n httpClient.Timeout = TimeSpan.FromSeconds(10);\n\n using var response = await httpClient.GetAsync($\"https://github.com/tesseract-ocr/tessdata/raw/refs/heads/main/{langCode}.traineddata\", HttpCompletionOption.ResponseHeadersRead, token);\n\n response.EnsureSuccessStatusCode();\n\n await using Stream modelStream = await response.Content.ReadAsStreamAsync(token);\n await using FileStream fileWriter = File.OpenWrite(destinationPath);\n\n byte[] buffer = new byte[1024 * 128];\n int bytesRead;\n long totalBytesRead = 0;\n\n Stopwatch sw = new();\n sw.Start();\n\n while ((bytesRead = await modelStream.ReadAsync(buffer, 0, buffer.Length, token)) > 0)\n {\n await fileWriter.WriteAsync(buffer, 0, bytesRead, token);\n totalBytesRead += bytesRead;\n\n if (sw.Elapsed > TimeSpan.FromMilliseconds(50))\n {\n DownloadedSize = totalBytesRead;\n sw.Restart();\n }\n\n token.ThrowIfCancellationRequested();\n }\n\n return totalBytesRead;\n }\n\n #region IDialogAware\n public string Title { get; set => Set(ref field, value); } = $\"Tesseract Downloader - {App.Name}\";\n public double WindowWidth { get; set => Set(ref field, value); } = 400;\n public double WindowHeight { get; set => Set(ref field, value); } = 200;\n\n public bool CanCloseDialog() => !CmdDownloadModel!.IsExecuting;\n public void OnDialogClosed() { }\n public void OnDialogOpened(IDialogParameters parameters) { }\n public DialogCloseListener RequestClose { get; }\n #endregion IDialogAware\n}\n"], ["/LLPlayer/FlyleafLib/Utils/SubtitleTextUtil.cs", "using System.Text;\n\nnamespace FlyleafLib;\n\npublic static class SubtitleTextUtil\n{\n /// \n /// Flattens the text into a single line.\n /// - If every line (excluding empty lines) starts with dash, returns the original string.\n /// - For all other text, replaces newlines with spaces and flattens into a single line.\n /// \n public static string FlattenText(string text)\n {\n ArgumentNullException.ThrowIfNull(text);\n\n ReadOnlySpan span = text.AsSpan();\n\n // If there are no newlines, return the text as-is\n if (!span.ContainsAny('\\r', '\\n'))\n {\n return text;\n }\n\n int length = span.Length;\n\n // Determine if the first character is dash to enter list mode\n bool startDash = span.Length > 0 && IsDash(span[0]);\n\n if (startDash)\n {\n char dashChar = span[0];\n\n // Check if all lines start with dash (ignore empty lines)\n bool allDash = true;\n bool atLineStart = true;\n int i;\n for (i = 0; i < length; i++)\n {\n if (atLineStart)\n {\n // Skip empty lines\n if (span[i] == '\\r' || span[i] == '\\n')\n {\n continue;\n }\n if (span[i] != dashChar)\n {\n allDash = false;\n // Done checking\n break;\n }\n atLineStart = false;\n }\n else\n {\n if (span[i] == '\\r')\n {\n if (i + 1 < length && span[i + 1] == '\\n') i++;\n atLineStart = true;\n }\n else if (span[i] == '\\n')\n {\n atLineStart = true;\n }\n }\n }\n\n // If every line starts with dash, return original text\n if (allDash)\n {\n return text;\n }\n\n // list mode\n StringBuilder sb = new(length);\n bool firstItem = true;\n i = 0;\n\n while (i < length)\n {\n int start;\n\n // Start of a dash line\n if (span[i] == dashChar)\n {\n if (!firstItem)\n {\n sb.Append('\\n');\n }\n // Append until end of line\n start = i;\n while (i < length && span[i] != '\\r' && span[i] != '\\n') i++;\n sb.Append(span.Slice(start, i - start));\n firstItem = false;\n continue;\n }\n\n // Skip empty lines\n if (span[i] == '\\r' || span[i] == '\\n')\n {\n i++;\n continue;\n }\n\n // Continuation line\n start = i;\n while (i < length && span[i] != '\\r' && span[i] != '\\n') i++;\n sb.Append(' ');\n sb.Append(span.Slice(start, i - start));\n }\n return sb.ToString();\n }\n\n // Default mode: replace all newlines with spaces in one pass\n char[] buffer = new char[length];\n int pos = 0;\n bool lastWasNewline = false;\n for (int i = 0; i < length; i++)\n {\n char c = span[i];\n if (c == '\\r' || c == '\\n')\n {\n if (!lastWasNewline)\n {\n buffer[pos++] = ' ';\n lastWasNewline = true;\n }\n }\n else\n {\n buffer[pos++] = c;\n lastWasNewline = false;\n }\n }\n return new string(buffer, 0, pos);\n }\n\n private static bool IsDash(char c)\n {\n switch (c)\n {\n case '-':\n case '\\u2043': // ⁃ Hyphen bullet\n case '\\u2010': // ‐ Hyphen\n case '\\u2012': // ‒ Figure dash\n case '\\u2013': // – En dash\n case '\\u2014': // — Em dash\n case '\\u2015': // ― Horizontal bar\n case '\\u2212': // − Minus Sign\n return true;\n }\n\n return false;\n }\n}\n"], ["/LLPlayer/LLPlayer/ViewModels/ErrorDialogVM.cs", "using System.Collections;\nusing System.Diagnostics.CodeAnalysis;\nusing System.Media;\nusing System.Text;\nusing System.Windows;\nusing LLPlayer.Extensions;\nusing LLPlayer.Services;\n\nnamespace LLPlayer.ViewModels;\n\npublic class ErrorDialogVM : Bindable, IDialogAware\n{\n public FlyleafManager FL { get; }\n\n public ErrorDialogVM(FlyleafManager fl)\n {\n FL = fl;\n }\n\n public string Message { get; set => Set(ref field, value); } = \"\";\n\n public Exception? Exception\n {\n get;\n set\n {\n if (Set(ref field, value))\n {\n OnPropertyChanged(nameof(HasException));\n ExceptionDetail = value == null ? \"\" : GetExceptionWithAllData(value);\n }\n }\n }\n public bool HasException => Exception != null;\n\n public string ExceptionDetail { get; set => Set(ref field, value); } = \"\";\n\n public bool IsUnknown\n {\n get;\n set\n {\n if (Set(ref field, value))\n {\n OnPropertyChanged(nameof(ErrorTitle));\n }\n }\n }\n\n public string ErrorType\n {\n get;\n set\n {\n if (Set(ref field, value))\n {\n OnPropertyChanged(nameof(ErrorTitle));\n }\n }\n } = \"\";\n\n public string ErrorTitle => IsUnknown ? $\"{ErrorType} Unknown Error\" : $\"{ErrorType} Error\";\n\n [field: AllowNull, MaybeNull]\n public DelegateCommand CmdCopyMessage => field ??= new(() =>\n {\n string text = $\"\"\"\n [{ErrorTitle}]\n {Message}\n \"\"\";\n\n if (Exception != null)\n {\n text += $\"\"\"\n\n\n ```\n {ExceptionDetail}\n ```\n \"\"\";\n }\n\n text += $\"\"\"\n\n\n Version: {App.Version}, CommitHash: {App.CommitHash}\n OS Architecture: {App.OSArchitecture}, Process Architecture: {App.ProcessArchitecture}\n \"\"\";\n Clipboard.SetText(text);\n });\n\n [field: AllowNull, MaybeNull]\n public DelegateCommand CmdCloseDialog => field ??= new(() =>\n {\n RequestClose.Invoke(ButtonResult.OK);\n });\n\n private static string GetExceptionWithAllData(Exception ex)\n {\n string exceptionInfo = ex.ToString();\n\n // Collect all Exception.Data to dictionary\n Dictionary allData = new();\n CollectExceptionData(ex, allData);\n\n if (allData.Count == 0)\n {\n // not found Exception.Data\n return exceptionInfo;\n }\n\n // found Exception.Data\n StringBuilder sb = new();\n sb.Append(exceptionInfo);\n\n sb.AppendLine();\n sb.AppendLine();\n sb.AppendLine(\"---------------------- All Exception Data ----------------------\");\n foreach (var (i, entry) in allData.Index())\n {\n sb.AppendLine($\" [{entry.Key}]: {entry.Value}\");\n if (i != allData.Count - 1)\n {\n sb.AppendLine();\n }\n }\n\n return sb.ToString();\n }\n\n private static void CollectExceptionData(Exception? ex, Dictionary allData)\n {\n if (ex == null) return;\n\n foreach (DictionaryEntry entry in ex.Data)\n {\n if (entry.Value != null)\n {\n allData.TryAdd(entry.Key, entry.Value);\n }\n }\n\n if (ex.InnerException != null)\n {\n CollectExceptionData(ex.InnerException, allData);\n }\n\n if (ex is AggregateException aggregateEx)\n {\n foreach (var innerEx in aggregateEx.InnerExceptions)\n {\n CollectExceptionData(innerEx, allData);\n }\n }\n }\n\n #region IDialogAware\n public string Title => \"Error Occured\";\n public double WindowWidth { get; set => Set(ref field, value); } = 450;\n public double WindowHeight { get; set => Set(ref field, value); } = 250;\n\n public bool CanCloseDialog() => true;\n\n public void OnDialogClosed()\n {\n FL.Player.Activity.Timeout = _prevTimeout;\n FL.Player.Activity.IsEnabled = true;\n }\n\n private int _prevTimeout;\n\n public void OnDialogOpened(IDialogParameters parameters)\n {\n _prevTimeout = FL.Player.Activity.Timeout;\n FL.Player.Activity.Timeout = 0;\n FL.Player.Activity.IsEnabled = false;\n\n switch (parameters.GetValue(\"type\"))\n {\n case \"known\":\n Message = parameters.GetValue(\"message\");\n ErrorType = parameters.GetValue(\"errorType\");\n IsUnknown = false;\n\n break;\n case \"unknown\":\n Message = parameters.GetValue(\"message\");\n ErrorType = parameters.GetValue(\"errorType\");\n IsUnknown = true;\n\n if (parameters.ContainsKey(\"exception\"))\n {\n Exception = parameters.GetValue(\"exception\");\n }\n\n WindowHeight += 100;\n WindowWidth += 20;\n\n // Play alert sound\n SystemSounds.Hand.Play();\n\n break;\n }\n }\n\n public DialogCloseListener RequestClose { get; }\n #endregion IDialogAware\n}\n"], ["/LLPlayer/LLPlayer/ViewModels/SubtitlesExportDialogVM.cs", "using System.Diagnostics;\nusing System.IO;\nusing System.Diagnostics.CodeAnalysis;\nusing System.Text;\nusing FlyleafLib.MediaPlayer;\nusing LLPlayer.Extensions;\nusing LLPlayer.Services;\nusing SaveFileDialog = Microsoft.Win32.SaveFileDialog;\n\nnamespace LLPlayer.ViewModels;\n\npublic class SubtitlesExportDialogVM : Bindable, IDialogAware\n{\n public FlyleafManager FL { get; }\n\n public SubtitlesExportDialogVM(FlyleafManager fl)\n {\n FL = fl;\n\n IsUtf8Bom = FL.Config.Subs.SubsExportUTF8WithBom;\n }\n\n public List SubIndexList { get; } = [0, 1];\n public int SelectedSubIndex\n {\n get;\n set\n {\n if (Set(ref field, value))\n {\n OnPropertyChanged(nameof(SubManager));\n }\n }\n }\n\n public SubManager SubManager => FL.Player.SubtitlesManager[SelectedSubIndex];\n\n public bool IsUtf8Bom { get; set => Set(ref field, value); }\n\n public TranslateExportOptions SelectedTranslateOpts { get; set => Set(ref field, value); }\n\n [field: AllowNull, MaybeNull]\n public DelegateCommand CmdExport => field ??= new(() =>\n {\n var playlist = FL.Player.Playlist.Selected;\n if (playlist == null)\n {\n return;\n }\n\n List lines = FL.Player.SubtitlesManager[SelectedSubIndex].Subs\n .Where(s =>\n {\n if (!s.IsText)\n {\n return false;\n }\n\n if (SelectedTranslateOpts == TranslateExportOptions.TranslatedOnly)\n {\n return s.IsTranslated;\n }\n\n return true;\n })\n .Select(s => new SubtitleLine()\n {\n Text = (SelectedTranslateOpts != TranslateExportOptions.Original\n ? s.DisplayText : s.Text)!,\n Start = s.StartTime,\n End = s.EndTime\n }).ToList();\n\n if (lines.Count == 0)\n {\n ErrorDialogHelper.ShowKnownErrorPopup(\"There were no subtitles to export.\", \"Export\");\n return;\n }\n\n string? initDir = null;\n string fileName;\n\n if (FL.Player.Playlist.Url != null && File.Exists(playlist.Url))\n {\n fileName = Path.GetFileNameWithoutExtension(playlist.Url);\n\n // If there is currently an open file, set that folder as the base folder\n initDir = Path.GetDirectoryName(playlist.Url);\n }\n else\n {\n // If live video, use title instead\n fileName = playlist.Title;\n }\n\n SaveFileDialog saveFileDialog = new()\n {\n Filter = \"SRT files (*.srt)|*.srt|All files (*.*)|*.*\",\n FileName = fileName + \".srt\",\n InitialDirectory = initDir\n };\n\n if (SelectedTranslateOpts != TranslateExportOptions.Original)\n {\n saveFileDialog.FileName = fileName + \".translated.srt\";\n }\n\n if (saveFileDialog.ShowDialog() == true)\n {\n SrtExporter.ExportSrt(lines, saveFileDialog.FileName, new UTF8Encoding(IsUtf8Bom));\n\n // open saved file in explorer\n Process.Start(\"explorer.exe\", $@\"/select,\"\"{saveFileDialog.FileName}\"\"\");\n }\n });\n\n #region IDialogAware\n public string Title { get; set => Set(ref field, value); }\n = $\"Subtitles Exporter - {App.Name}\";\n public double WindowWidth { get; set => Set(ref field, value); } = 350;\n public double WindowHeight { get; set => Set(ref field, value); } = 240;\n\n public DialogCloseListener RequestClose { get; }\n\n public bool CanCloseDialog()\n {\n return true;\n }\n public void OnDialogClosed() { }\n\n public void OnDialogOpened(IDialogParameters parameters) { }\n #endregion\n\n public enum TranslateExportOptions\n {\n Original,\n TranslatedOnly,\n TranslatedWithFallback\n }\n}\n"], ["/LLPlayer/LLPlayer/ViewModels/SubtitlesDownloaderDialogVM.cs", "using System.Collections.ObjectModel;\nusing System.ComponentModel;\nusing System.IO;\nusing FlyleafLib;\nusing FlyleafLib.MediaFramework.MediaPlaylist;\nusing FlyleafLib.MediaPlayer;\nusing LLPlayer.Extensions;\nusing LLPlayer.Services;\nusing Microsoft.Win32;\nusing static FlyleafLib.MediaFramework.MediaContext.DecoderContext;\n\nnamespace LLPlayer.ViewModels;\n\npublic class SubtitlesDownloaderDialogVM : Bindable, IDialogAware\n{\n public FlyleafManager FL { get; }\n private readonly OpenSubtitlesProvider _subProvider;\n\n public SubtitlesDownloaderDialogVM(\n FlyleafManager fl,\n OpenSubtitlesProvider subProvider\n )\n {\n FL = fl;\n _subProvider = subProvider;\n }\n\n public ObservableCollection Subs { get; } = new();\n\n public SearchResponse? SelectedSub\n {\n get;\n set\n {\n if (Set(ref field, value))\n {\n OnPropertyChanged(nameof(CanAction));\n }\n }\n } = null;\n\n public string Query\n {\n get;\n set\n {\n if (Set(ref field, value))\n {\n OnPropertyChanged(nameof(CanSearch));\n }\n }\n } = string.Empty;\n\n public bool CanSearch => !string.IsNullOrWhiteSpace(Query);\n public bool CanAction => SelectedSub != null;\n\n public AsyncDelegateCommand? CmdSearch => field ??= new AsyncDelegateCommand(async () =>\n {\n Subs.Clear();\n\n IList result;\n\n try\n {\n result = await _subProvider.Search(Query);\n }\n catch (Exception ex)\n {\n ErrorDialogHelper.ShowUnknownErrorPopup($\"Cannot search subtitles from opensubtitles.org: {ex.Message}\", UnknownErrorType.Network, ex);\n return;\n }\n\n var query = result\n .OrderByDescending(r =>\n {\n // prefer user-configured languages\n return FL.PlayerConfig.Subtitles.Languages.Any(l =>\n l.Equals(Language.Get(r.ISO639)));\n })\n .ThenBy(r => r.LanguageName)\n .ThenByDescending(r => r.SubDownloadsCnt)\n .ThenBy(r => r.SubFileName);\n\n foreach (var record in query)\n {\n Subs.Add(record);\n }\n }).ObservesCanExecute(() => CanSearch);\n\n public AsyncDelegateCommand? CmdLoad => field ??= new AsyncDelegateCommand(async () =>\n {\n var sub = SelectedSub;\n if (sub == null)\n {\n return;\n }\n\n byte[] subData;\n\n try\n {\n (subData, _) = await _subProvider.Download(sub);\n }\n catch (Exception ex)\n {\n ErrorDialogHelper.ShowUnknownErrorPopup($\"Cannot load the subtitle from opensubtitles.org: {ex.Message}\", UnknownErrorType.Network, ex);\n return;\n }\n\n string subDir = Path.Combine(Path.GetTempPath(), App.Name, \"Subs\");\n string subPath = Path.Combine(subDir, sub.SubFileName);\n if (!Directory.Exists(subDir))\n {\n Directory.CreateDirectory(subDir);\n }\n\n var ext = Path.GetExtension(subPath).ToLower();\n if (ext.StartsWith(\".\"))\n {\n ext = ext.Substring(1);\n }\n\n if (!Utils.ExtensionsSubtitles.Contains(ext))\n {\n throw new InvalidOperationException($\"'{ext}' extension is not supported\");\n }\n\n await File.WriteAllBytesAsync(subPath, subData);\n\n // TODO: L: Refactor to pass language directly at Open\n // TODO: L: Allow to load as a secondary subtitle\n FL.Player.decoder.OpenExternalSubtitlesStreamCompleted += DecoderOnOpenExternalSubtitlesStreamCompleted;\n\n void DecoderOnOpenExternalSubtitlesStreamCompleted(object? sender, OpenExternalSubtitlesStreamCompletedArgs e)\n {\n FL.Player.decoder.OpenExternalSubtitlesStreamCompleted -= DecoderOnOpenExternalSubtitlesStreamCompleted;\n\n if (e.Success)\n {\n var stream = e.ExtStream;\n if (stream != null && stream.Url == subPath)\n {\n // Override if different from auto-detected language\n stream.ManualDownloaded = true;\n\n if (stream.Language.ISO6391 != sub.ISO639)\n {\n var lang = Language.Get(sub.ISO639);\n if (!string.IsNullOrEmpty(lang.IdSubLanguage) && lang.IdSubLanguage != \"und\")\n {\n stream.Language = lang;\n FL.Player.SubtitlesManager[0].LanguageSource = stream.Language;\n }\n }\n }\n }\n }\n\n FL.Player.OpenAsync(subPath);\n\n }).ObservesCanExecute(() => CanAction);\n\n public AsyncDelegateCommand? CmdDownload => field ??= new AsyncDelegateCommand(async () =>\n {\n var sub = SelectedSub;\n if (sub == null)\n {\n return;\n }\n\n string fileName = sub.SubFileName;\n\n string? initDir = null;\n if (FL.Player.Playlist.Selected != null)\n {\n var url = FL.Player.Playlist.Selected.DirectUrl;\n if (File.Exists(url))\n {\n initDir = Path.GetDirectoryName(url);\n }\n }\n\n SaveFileDialog dialog = new()\n {\n Title = \"Save subtitles to file\",\n InitialDirectory = initDir,\n FileName = fileName,\n Filter = \"All Files (*.*)|*.*\",\n };\n\n if (dialog.ShowDialog() == true)\n {\n byte[] subData;\n\n try\n {\n (subData, _) = await _subProvider.Download(sub);\n }\n catch (Exception ex)\n {\n ErrorDialogHelper.ShowUnknownErrorPopup($\"Cannot download the subtitle from opensubtitles.org: {ex.Message}\", UnknownErrorType.Network, ex);\n return;\n }\n\n await File.WriteAllBytesAsync(dialog.FileName, subData);\n }\n }).ObservesCanExecute(() => CanAction);\n\n private void Playlist_OnPropertyChanged(object? sender, PropertyChangedEventArgs e)\n {\n if (e.PropertyName == nameof(FL.Player.Playlist.Selected) &&\n FL.Player.Playlist.Selected != null)\n {\n // Update query when video changes\n UpdateQuery(FL.Player.Playlist.Selected);\n }\n }\n\n private void UpdateQuery(PlaylistItem selected)\n {\n string title = selected.Title;\n if (title == selected.OriginalTitle && File.Exists(selected.Url))\n {\n FileInfo fi = new(selected.Url);\n if (!string.IsNullOrEmpty(fi.Extension) && title.EndsWith(fi.Extension))\n {\n // remove extension part\n title = title[..^fi.Extension.Length];\n }\n }\n\n Query = title;\n }\n\n #region IDialogAware\n public string Title { get; set => Set(ref field, value); }\n = $\"Subtitles Downloader - {App.Name}\";\n public double WindowWidth { get; set => Set(ref field, value); } = 900;\n public double WindowHeight { get; set => Set(ref field, value); } = 600;\n\n public DialogCloseListener RequestClose { get; }\n\n public bool CanCloseDialog()\n {\n return true;\n }\n public void OnDialogClosed()\n {\n FL.Player.Playlist.PropertyChanged -= Playlist_OnPropertyChanged;\n }\n public void OnDialogOpened(IDialogParameters parameters)\n {\n // Set query from current video\n var selected = FL.Player.Playlist.Selected;\n if (selected != null)\n {\n UpdateQuery(selected);\n }\n\n // Register update playlist event\n FL.Player.Playlist.PropertyChanged += Playlist_OnPropertyChanged;\n }\n #endregion\n}\n"], ["/LLPlayer/FlyleafLib/MediaPlayer/Translation/Services/GoogleV1TranslateService.cs", "using System.Collections.Generic;\nusing System.Linq;\nusing System.Net.Http;\nusing System.Text.Json;\nusing System.Threading;\nusing System.Threading.Tasks;\n\nnamespace FlyleafLib.MediaPlayer.Translation.Services;\n\n#nullable enable\n\npublic class GoogleV1TranslateService : ITranslateService\n{\n internal static Dictionary DefaultRegions { get; } = new()\n {\n [\"zh\"] = \"zh-CN\",\n [\"pt\"] = \"pt-PT\",\n [\"fr\"] = \"fr-FR\",\n };\n\n private readonly HttpClient _httpClient;\n private string? _srcLang;\n private string? _targetLang;\n private readonly GoogleV1TranslateSettings _settings;\n\n public GoogleV1TranslateService(GoogleV1TranslateSettings settings)\n {\n if (string.IsNullOrWhiteSpace(settings.Endpoint))\n {\n throw new TranslationConfigException(\n $\"Endpoint for {ServiceType} is not configured.\");\n }\n\n _settings = settings;\n _httpClient = new HttpClient();\n _httpClient.BaseAddress = new Uri(settings.Endpoint);\n _httpClient.Timeout = TimeSpan.FromMilliseconds(settings.TimeoutMs);\n }\n\n public TranslateServiceType ServiceType => TranslateServiceType.GoogleV1;\n\n public void Dispose()\n {\n _httpClient.Dispose();\n }\n\n public void Initialize(Language src, TargetLanguage target)\n {\n (TranslateLanguage srcLang, _) = this.TryGetLanguage(src, target);\n\n _srcLang = ToSourceCode(srcLang.ISO6391);\n _targetLang = ToTargetCode(target);\n }\n\n private string ToSourceCode(string iso6391)\n {\n if (iso6391 == \"nb\")\n {\n // handle 'Norwegian Bokmål' as 'Norwegian'\n return \"no\";\n }\n\n // ref: https://cloud.google.com/translate/docs/languages?hl=en\n if (!DefaultRegions.TryGetValue(iso6391, out string? defaultRegion))\n {\n // no region languages\n return iso6391;\n }\n\n // has region languages\n return _settings.Regions.GetValueOrDefault(iso6391, defaultRegion);\n }\n\n private static string ToTargetCode(TargetLanguage target)\n {\n return target switch\n {\n TargetLanguage.ChineseSimplified => \"zh-CN\",\n TargetLanguage.ChineseTraditional => \"zh-TW\",\n TargetLanguage.French => \"fr-FR\",\n TargetLanguage.FrenchCanadian => \"fr-CA\",\n TargetLanguage.Portuguese => \"pt-PT\",\n TargetLanguage.PortugueseBrazilian => \"pt-BR\",\n _ => target.ToISO6391()\n };\n }\n\n public async Task TranslateAsync(string text, CancellationToken token)\n {\n string jsonResultString = \"\";\n int statusCode = -1;\n\n try\n {\n var url = $\"/translate_a/single?client=gtx&sl={_srcLang}&tl={_targetLang}&dt=t&q={Uri.EscapeDataString(text)}\";\n\n using var result = await _httpClient.GetAsync(url, token).ConfigureAwait(false);\n jsonResultString = await result.Content.ReadAsStringAsync(token).ConfigureAwait(false);\n\n statusCode = (int)result.StatusCode;\n result.EnsureSuccessStatusCode();\n\n List resultTexts = new();\n using JsonDocument doc = JsonDocument.Parse(jsonResultString);\n resultTexts.AddRange(doc.RootElement[0].EnumerateArray().Select(arr => arr[0].GetString()!.Trim()));\n\n return string.Join(Environment.NewLine, resultTexts);\n }\n // Distinguish between timeout and cancel errors\n catch (OperationCanceledException ex)\n when (!ex.Message.StartsWith(\"The request was canceled due to the configured HttpClient.Timeout\"))\n {\n // cancel\n throw;\n }\n catch (Exception ex)\n {\n // timeout and other error\n throw new TranslationException($\"Cannot request to {ServiceType}: {ex.Message}\", ex)\n {\n Data =\n {\n [\"status_code\"] = statusCode.ToString(),\n [\"response\"] = jsonResultString\n }\n };\n }\n }\n}\n"], ["/LLPlayer/FlyleafLib/Utils/Logger.cs", "using System.Collections.Generic;\nusing System.Collections.Concurrent;\nusing System.IO;\nusing System.Text;\nusing System.Threading.Tasks;\n\nnamespace FlyleafLib;\n\npublic static class Logger\n{\n public static bool CanError => Engine.Config.LogLevel >= LogLevel.Error;\n public static bool CanWarn => Engine.Config.LogLevel >= LogLevel.Warn;\n public static bool CanInfo => Engine.Config.LogLevel >= LogLevel.Info;\n public static bool CanDebug => Engine.Config.LogLevel >= LogLevel.Debug;\n public static bool CanTrace => Engine.Config.LogLevel >= LogLevel.Trace;\n\n\n public static Action\n CustomOutput = DevNullPtr;\n internal static Action\n Output = DevNullPtr;\n static string lastOutput = \"\";\n\n static ConcurrentQueue\n fileData = new();\n static bool fileTaskRunning;\n static FileStream fileStream;\n static object lockFileStream = new();\n static Dictionary\n logLevels = new();\n\n static Logger()\n {\n foreach (LogLevel loglevel in Enum.GetValues(typeof(LogLevel)))\n logLevels.Add(loglevel, loglevel.ToString().PadRight(5, ' '));\n\n // Flush File Data on Application Exit\n System.Windows.Application.Current.Exit += (o, e) =>\n {\n lock (lockFileStream)\n {\n if (fileStream != null)\n {\n while (fileData.TryDequeue(out byte[] data))\n fileStream.Write(data, 0, data.Length);\n fileStream.Dispose();\n }\n }\n };\n }\n\n internal static void SetOutput()\n {\n string output = Engine.Config.LogOutput;\n\n if (string.IsNullOrEmpty(output))\n {\n if (lastOutput != \"\")\n {\n Output = DevNullPtr;\n lastOutput = \"\";\n }\n }\n else if (output.StartsWith(\":\"))\n {\n if (output == \":console\")\n {\n if (lastOutput != \":console\")\n {\n Output = Console.WriteLine;\n lastOutput = \":console\";\n }\n }\n else if (output == \":debug\")\n {\n if (lastOutput != \":debug\")\n {\n Output = DebugPtr;\n lastOutput = \":debug\";\n }\n }\n else if (output == \":custom\")\n {\n if (lastOutput != \":custom\")\n {\n Output = CustomOutput;\n lastOutput = \":custom\";\n }\n }\n else\n throw new Exception(\"Invalid log output\");\n }\n else\n {\n lock (lockFileStream)\n {\n // Flush File Data on Previously Opened File Stream\n if (fileStream != null)\n {\n while (fileData.TryDequeue(out byte[] data))\n fileStream.Write(data, 0, data.Length);\n fileStream.Dispose();\n }\n\n string dir = Path.GetDirectoryName(output);\n if (!string.IsNullOrEmpty(dir))\n Directory.CreateDirectory(dir);\n\n fileStream = new FileStream(output, Engine.Config.LogAppend ? FileMode.Append : FileMode.Create, FileAccess.Write);\n if (lastOutput != \":file\")\n {\n Output = FilePtr;\n lastOutput = \":file\";\n }\n }\n }\n }\n static void DebugPtr(string msg) => System.Diagnostics.Debug.WriteLine(msg);\n static void DevNullPtr(string msg) { }\n static void FilePtr(string msg)\n {\n fileData.Enqueue(Encoding.UTF8.GetBytes($\"{msg}\\r\\n\"));\n\n if (!fileTaskRunning && fileData.Count > Engine.Config.LogCachedLines)\n FlushFileData();\n }\n\n static void FlushFileData()\n {\n fileTaskRunning = true;\n\n Task.Run(() =>\n {\n lock (lockFileStream)\n {\n while (fileData.TryDequeue(out byte[] data))\n fileStream.Write(data, 0, data.Length);\n\n fileStream.Flush();\n }\n\n fileTaskRunning = false;\n });\n }\n\n /// \n /// Forces cached file data to be written to the file\n /// \n public static void ForceFlush()\n {\n if (!fileTaskRunning && fileStream != null)\n FlushFileData();\n }\n\n internal static void Log(string msg, LogLevel logLevel)\n {\n if (logLevel <= Engine.Config.LogLevel)\n Output($\"{DateTime.Now.ToString(Engine.Config.LogDateTimeFormat)} | {logLevels[logLevel]} | {msg}\");\n }\n}\n\npublic class LogHandler\n{\n public string Prefix;\n\n public LogHandler(string prefix = \"\")\n => Prefix = prefix;\n\n public void Error(string msg) => Logger.Log($\"{Prefix}{msg}\", LogLevel.Error);\n public void Info(string msg) => Logger.Log($\"{Prefix}{msg}\", LogLevel.Info);\n public void Warn(string msg) => Logger.Log($\"{Prefix}{msg}\", LogLevel.Warn);\n public void Debug(string msg) => Logger.Log($\"{Prefix}{msg}\", LogLevel.Debug);\n public void Trace(string msg) => Logger.Log($\"{Prefix}{msg}\", LogLevel.Trace);\n}\n\npublic enum LogLevel\n{\n Quiet = 0x00,\n Error = 0x10,\n Warn = 0x20,\n Info = 0x30,\n Debug = 0x40,\n Trace = 0x50\n}\n"], ["/LLPlayer/LLPlayer/Converters/SubtitleConverters.cs", "using System.Globalization;\nusing System.Windows;\nusing System.Windows.Data;\nusing System.Windows.Media.Imaging;\nusing FlyleafLib.MediaPlayer;\nusing LLPlayer.Services;\n\nnamespace LLPlayer.Converters;\n\npublic class WidthPercentageMultiConverter : IMultiValueConverter\n{\n public object Convert(object[] values, Type targetType, object parameter, CultureInfo culture)\n {\n if (values[0] is double actualWidth &&\n values[1] is double maxWidth &&\n values[2] is double percentage)\n {\n if (percentage >= 100.0)\n {\n // respect line break\n return actualWidth;\n }\n\n var calcWidth = actualWidth * (percentage / 100.0);\n\n if (maxWidth > 0)\n {\n return Math.Min(maxWidth, calcWidth);\n }\n\n return calcWidth;\n }\n return 0;\n }\n\n public object[] ConvertBack(object value, Type[] targetTypes, object parameter, CultureInfo culture)\n {\n throw new NotImplementedException();\n }\n}\n\npublic class SubTextMaskConverter : IMultiValueConverter\n{\n public object Convert(object[] values, Type targetType, object parameter, CultureInfo culture)\n {\n if (values.Length != 6)\n return DependencyProperty.UnsetValue;\n\n if (values[0] is int index && // Index of sub to be processed\n values[1] is string displayText && // Sub text to be processed (may be translated)\n values[2] is string text && // Sub text to be processed\n values[3] is int selectedIndex && // Index of the selected ListItem\n values[4] is bool isEnabled && // whether to enable this feature\n values[5] is bool showOriginal) // whether to show original text\n {\n string show = showOriginal ? text : displayText;\n\n if (isEnabled && index > selectedIndex && !string.IsNullOrEmpty(show))\n {\n return new string('_', show.Length);\n }\n\n return show;\n }\n return DependencyProperty.UnsetValue;\n }\n\n public object[] ConvertBack(object value, Type[] targetTypes, object parameter, CultureInfo culture)\n {\n throw new NotSupportedException();\n }\n}\n\npublic class SubTextFlowDirectionConverter : IMultiValueConverter\n{\n public object Convert(object[] values, Type targetType, object parameter, CultureInfo culture)\n {\n if (values.Length != 3)\n {\n return DependencyProperty.UnsetValue;\n }\n\n if (values[0] is bool isTranslated &&\n values[1] is int subIndex &&\n values[2] is FlyleafManager fl)\n {\n var language = isTranslated ? fl.PlayerConfig.Subtitles.TranslateLanguage : fl.Player.SubtitlesManager[subIndex].Language;\n if (language != null && language.IsRTL)\n {\n return FlowDirection.RightToLeft;\n }\n\n return FlowDirection.LeftToRight;\n }\n\n return DependencyProperty.UnsetValue;\n }\n\n public object[] ConvertBack(object value, Type[] targetTypes, object parameter, CultureInfo culture)\n {\n throw new NotSupportedException();\n }\n}\n\npublic class SubIsPlayingConverter : IMultiValueConverter\n{\n public object Convert(object[] values, Type targetType, object parameter, CultureInfo culture)\n {\n if (values.Length != 3)\n {\n return DependencyProperty.UnsetValue;\n }\n\n if (values[0] is int index &&\n values[1] is int currentIndex &&\n values[2] is bool isDisplaying)\n {\n return isDisplaying && index == currentIndex;\n }\n\n return DependencyProperty.UnsetValue;\n }\n\n public object[] ConvertBack(object value, Type[] targetTypes, object parameter, CultureInfo culture)\n {\n throw new NotSupportedException();\n }\n}\n\npublic class ListItemIndexVisibilityConverter : IMultiValueConverter\n{\n public object Convert(object[] values, Type targetType, object parameter, CultureInfo culture)\n {\n if (values.Length != 3)\n {\n return DependencyProperty.UnsetValue;\n }\n\n if (values[0] is int itemIndex && // Index of sub to be processed\n values[1] is int selectedIndex && // Index of the selected ListItem\n values[2] is bool isEnabled) // whether to enable this feature\n {\n if (isEnabled && itemIndex > selectedIndex)\n {\n return Visibility.Collapsed;\n }\n\n return Visibility.Visible;\n }\n return DependencyProperty.UnsetValue;\n }\n\n public object[] ConvertBack(object value, Type[] targetTypes, object parameter, CultureInfo culture)\n {\n throw new NotSupportedException();\n }\n}\n\n[ValueConversion(typeof(TimeSpan), typeof(string))]\npublic class TimeSpanToStringConverter : IValueConverter\n{\n public object Convert(object value, Type targetType, object parameter, CultureInfo culture)\n {\n if (value is TimeSpan ts)\n {\n if (ts.TotalHours >= 1)\n {\n return ts.ToString(@\"hh\\:mm\\:ss\");\n }\n else\n {\n return ts.ToString(@\"mm\\:ss\");\n }\n }\n\n return DependencyProperty.UnsetValue;\n }\n\n public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)\n {\n throw new NotImplementedException();\n }\n}\n\n[ValueConversion(typeof(SubtitleData), typeof(WriteableBitmap))]\npublic class SubBitmapImageSourceConverter : IValueConverter\n{\n public object? Convert(object? value, Type targetType, object? parameter, CultureInfo culture)\n {\n if (value is not SubtitleData item)\n {\n return null;\n }\n\n if (!item.IsBitmap || item.Bitmap == null || !string.IsNullOrEmpty(item.Text))\n {\n return null;\n }\n\n WriteableBitmap wb = item.Bitmap.SubToWritableBitmap(false);\n\n return wb;\n }\n\n public object ConvertBack(object? value, Type targetType, object? parameter, CultureInfo culture)\n => throw new NotImplementedException();\n}\n\n[ValueConversion(typeof(int), typeof(string))]\npublic class SubIndexToDisplayStringConverter : IValueConverter\n{\n public object Convert(object value, Type targetType, object parameter, CultureInfo culture)\n {\n if (value is int subIndex)\n {\n return subIndex == 0 ? \"Primary\" : \"Secondary\";\n }\n return DependencyProperty.UnsetValue;\n }\n\n public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)\n {\n if (value is string str)\n {\n return str == \"Primary\" ? 0 : 1;\n }\n return DependencyProperty.UnsetValue;\n }\n}\n"], ["/LLPlayer/FlyleafLib/MediaFramework/MediaContext/Downloader.cs", "using System.IO;\nusing System.Threading;\nusing System.Threading.Tasks;\n\nusing FlyleafLib.MediaFramework.MediaDemuxer;\nusing FlyleafLib.MediaFramework.MediaRemuxer;\n\nusing static FlyleafLib.Logger;\n\n/* TODO\n * Don't let audio go further than video (because of large duration without video)?\n *\n */\n\nnamespace FlyleafLib.MediaFramework.MediaContext;\n\n/// \n/// Downloads or remuxes to different format any ffmpeg valid input url\n/// \npublic unsafe class Downloader : RunThreadBase\n{\n /// \n /// The backend demuxer. Access this to enable the required streams for downloading\n /// \n //public Demuxer Demuxer { get; private set; }\n\n public DecoderContext DecCtx { get; private set; }\n internal Demuxer AudioDemuxer => DecCtx.AudioDemuxer;\n\n /// \n /// The backend remuxer. Normally you shouldn't access this\n /// \n public Remuxer Remuxer { get; private set; }\n\n /// \n /// The current timestamp of the frame starting from 0 (Ticks)\n /// \n public long CurTime { get => _CurTime; private set => Set(ref _CurTime, value); }\n long _CurTime;\n\n /// \n /// The total duration of the input (Ticks)\n /// \n public long Duration { get => _Duration; private set => Set(ref _Duration, value); }\n long _Duration;\n\n /// \n /// The percentage of the current download process (0 for live streams)\n /// \n public double DownloadPercentage { get => _DownloadPercentage; set => Set(ref _DownloadPercentage, value); }\n double _DownloadPercentage;\n double downPercentageFactor;\n\n public Downloader(Config config, int uniqueId = -1) : base(uniqueId)\n {\n DecCtx = new DecoderContext(config, UniqueId, false);\n DecCtx.AudioDemuxer.Config = config.Demuxer.Clone(); // We change buffer duration and we need to avoid changing video demuxer's config\n\n //DecCtx.VideoInputOpened += (o, e) => { if (!e.Success) OnDownloadCompleted(false); };\n Remuxer = new Remuxer(UniqueId);\n threadName = \"Downloader\";\n }\n\n /// \n /// Fires on download completed or failed\n /// \n public event EventHandler DownloadCompleted;\n protected virtual void OnDownloadCompleted(bool success)\n => Task.Run(() => { Dispose(); DownloadCompleted?.Invoke(this, success); });\n\n /// \n /// Opens a new media file (audio/video) and prepares it for download (blocking)\n /// \n /// Media file's url\n /// Whether to open the default input (in case of multiple inputs eg. from bitswarm/youtube-dl, you might want to choose yours)\n /// Whether to open the default video stream from plugin suggestions\n /// Whether to open the default audio stream from plugin suggestions\n /// \n public string Open(string url, bool defaultPlaylistItem = true, bool defaultVideo = true, bool defaultAudio = true) => Open((object) url, defaultPlaylistItem, defaultVideo, defaultAudio);\n\n /// \n /// Opens a new media file (audio/video) and prepares it for download (blocking)\n /// \n /// Media Stream\n /// Whether to open the default input (in case of multiple inputs eg. from bitswarm/youtube-dl, you might want to choose yours)\n /// Whether to open the default video stream from plugin suggestions\n /// Whether to open the default audio stream from plugin suggestions\n /// \n public string Open(Stream stream, bool defaultPlaylistItem = true, bool defaultVideo = true, bool defaultAudio = true) => Open((object) stream, defaultPlaylistItem, defaultVideo, defaultAudio);\n\n internal string Open(object url, bool defaultPlaylistItem = true, bool defaultVideo = true, bool defaultAudio = true)\n {\n lock (lockActions)\n {\n Dispose();\n\n Disposed= false;\n Status = Status.Opening;\n var ret = DecCtx.Open(url, defaultPlaylistItem, defaultVideo, defaultAudio, false);\n if (ret != null && ret.Error != null) return ret.Error;\n\n CurTime = 0;\n DownloadPercentage = 0;\n\n var Demuxer = !DecCtx.VideoDemuxer.Disposed ? DecCtx.VideoDemuxer : DecCtx.AudioDemuxer;\n Duration = Demuxer.IsLive ? 0 : Demuxer.Duration;\n downPercentageFactor = Duration / 100.0;\n\n return null;\n }\n }\n\n /// \n /// Downloads the currently configured AVS streams\n /// \n /// The filename for the downloaded video. The file extension will let the demuxer to choose the output format (eg. mp4). If you useRecommendedExtension will be updated with the extension.\n /// Will try to match the output container with the input container\n public void Download(ref string filename, bool useRecommendedExtension = true)\n {\n lock (lockActions)\n {\n if (Status != Status.Opening || Disposed)\n { OnDownloadCompleted(false); return; }\n\n if (useRecommendedExtension)\n filename = $\"{filename}.{(!DecCtx.VideoDemuxer.Disposed ? DecCtx.VideoDemuxer.Extension : DecCtx.AudioDemuxer.Extension)}\";\n\n int ret = Remuxer.Open(filename);\n if (ret != 0)\n { OnDownloadCompleted(false); return; }\n\n AddStreams(DecCtx.VideoDemuxer);\n AddStreams(DecCtx.AudioDemuxer);\n\n if (!Remuxer.HasStreams || Remuxer.WriteHeader() != 0)\n { OnDownloadCompleted(false); return; }\n\n Start();\n }\n }\n\n private void AddStreams(Demuxer demuxer)\n {\n for(int i=0; i\n /// Stops and disposes the downloader\n /// \n public void Dispose()\n {\n if (Disposed) return;\n\n lock (lockActions)\n {\n if (Disposed) return;\n\n Stop();\n\n DecCtx.Dispose();\n Remuxer.Dispose();\n\n Status = Status.Stopped;\n Disposed = true;\n }\n }\n\n protected override void RunInternal()\n {\n if (!Remuxer.HasStreams) { OnDownloadCompleted(false); return; }\n\n // Don't allow audio to change our duration without video (TBR: requires timestamp of videodemuxer to wait)\n long resetBufferDuration = -1;\n bool hasAVDemuxers = !DecCtx.VideoDemuxer.Disposed && !DecCtx.AudioDemuxer.Disposed;\n if (hasAVDemuxers)\n {\n resetBufferDuration = DecCtx.AudioDemuxer.Config.BufferDuration;\n DecCtx.AudioDemuxer.Config.BufferDuration = 100 * 10000;\n }\n\n DecCtx.Start();\n\n var Demuxer = !DecCtx.VideoDemuxer.Disposed ? DecCtx.VideoDemuxer : DecCtx.AudioDemuxer;\n long startTime = Demuxer.hlsCtx == null ? Demuxer.StartTime : Demuxer.hlsCtx->first_timestamp * 10;\n Duration = Demuxer.IsLive ? 0 : Demuxer.Duration;\n downPercentageFactor = Duration / 100.0;\n\n long startedAt = DateTime.UtcNow.Ticks;\n long secondTicks = startedAt;\n bool isAudioDemuxer = DecCtx.VideoDemuxer.Disposed && !DecCtx.AudioDemuxer.Disposed;\n IntPtr pktPtr = IntPtr.Zero;\n AVPacket* packet = null;\n AVPacket* packet2 = null;\n\n do\n {\n if ((Demuxer.Packets.Count == 0 && AudioDemuxer.Packets.Count == 0) || (hasAVDemuxers && (Demuxer.Packets.Count == 0 || AudioDemuxer.Packets.Count == 0)))\n {\n lock (lockStatus)\n if (Status == Status.Running) Status = Status.QueueEmpty;\n\n while (Demuxer.Packets.Count == 0 && Status == Status.QueueEmpty)\n {\n if (Demuxer.Status == Status.Ended)\n {\n Status = Status.Ended;\n if (Demuxer.Interrupter.Interrupted == 0)\n {\n CurTime = _Duration;\n DownloadPercentage = 100;\n }\n break;\n }\n else if (!Demuxer.IsRunning)\n {\n if (CanDebug) Log.Debug($\"Demuxer is not running [Demuxer Status: {Demuxer.Status}]\");\n\n lock (Demuxer.lockStatus)\n lock (lockStatus)\n {\n if (Demuxer.Status == Status.Pausing || Demuxer.Status == Status.Paused)\n Status = Status.Pausing;\n else if (Demuxer.Status != Status.Ended)\n Status = Status.Stopping;\n else\n continue;\n }\n\n break;\n }\n\n Thread.Sleep(20);\n }\n\n if (hasAVDemuxers && Status == Status.QueueEmpty && AudioDemuxer.Packets.Count == 0)\n {\n while (AudioDemuxer.Packets.Count == 0 && Status == Status.QueueEmpty && AudioDemuxer.IsRunning)\n Thread.Sleep(20);\n }\n\n lock (lockStatus)\n {\n if (Status != Status.QueueEmpty) break;\n Status = Status.Running;\n }\n }\n\n if (hasAVDemuxers)\n {\n if (AudioDemuxer.Packets.Count == 0)\n {\n packet = Demuxer.Packets.Dequeue();\n isAudioDemuxer = false;\n }\n else if (Demuxer.Packets.Count == 0)\n {\n packet = AudioDemuxer.Packets.Dequeue();\n isAudioDemuxer = true;\n }\n else\n {\n packet = Demuxer.Packets.Peek();\n packet2 = AudioDemuxer.Packets.Peek();\n\n long ts1 = (long) ((packet->dts * Demuxer.AVStreamToStream[packet->stream_index].Timebase) - Demuxer.StartTime);\n long ts2 = (long) ((packet2->dts * AudioDemuxer.AVStreamToStream[packet2->stream_index].Timebase) - AudioDemuxer.StartTime);\n\n if (ts2 <= ts1)\n {\n AudioDemuxer.Packets.Dequeue();\n isAudioDemuxer = true;\n packet = packet2;\n }\n else\n {\n Demuxer.Packets.Dequeue();\n isAudioDemuxer = false;\n }\n\n //Log($\"[{isAudioDemuxer}] {Utils.TicksToTime(ts1)} | {Utils.TicksToTime(ts2)}\");\n }\n }\n else\n {\n packet = Demuxer.Packets.Dequeue();\n }\n\n long curDT = DateTime.UtcNow.Ticks;\n if (curDT - secondTicks > 1000 * 10000 && (!isAudioDemuxer || DecCtx.VideoDemuxer.Disposed))\n {\n secondTicks = curDT;\n\n CurTime = Demuxer.hlsCtx != null\n ? (long) ((packet->dts * Demuxer.AVStreamToStream[packet->stream_index].Timebase) - startTime)\n : Demuxer.CurTime + Demuxer.BufferedDuration;\n\n if (_Duration > 0) DownloadPercentage = CurTime / downPercentageFactor;\n }\n\n Remuxer.Write(packet, isAudioDemuxer);\n\n } while (Status == Status.Running);\n\n if (resetBufferDuration != -1) DecCtx.AudioDemuxer.Config.BufferDuration = resetBufferDuration;\n\n if (Status != Status.Pausing && Status != Status.Paused)\n OnDownloadCompleted(Remuxer.WriteTrailer() == 0);\n else\n Demuxer.Pause();\n }\n}\n"], ["/LLPlayer/FlyleafLib/MediaFramework/MediaDecoder/SubtitlesDecoder.cs", "using System.Collections.Concurrent;\nusing System.Diagnostics;\nusing System.Threading;\nusing FlyleafLib.MediaFramework.MediaDemuxer;\nusing FlyleafLib.MediaFramework.MediaStream;\nusing FlyleafLib.MediaFramework.MediaFrame;\nusing FlyleafLib.MediaFramework.MediaRenderer;\nusing static FlyleafLib.Logger;\n\nnamespace FlyleafLib.MediaFramework.MediaDecoder;\n\npublic unsafe class SubtitlesDecoder : DecoderBase\n{\n public SubtitlesStream SubtitlesStream => (SubtitlesStream) Stream;\n\n public ConcurrentQueue\n Frames { get; protected set; } = new ConcurrentQueue();\n\n public PacketQueue SubtitlesPackets;\n\n public SubtitlesDecoder(Config config, int uniqueId = -1, int subIndex = 0) : base(config, uniqueId)\n {\n this.subIndex = subIndex;\n }\n\n private readonly int subIndex;\n protected override int Setup(AVCodec* codec)\n {\n lock (lockCodecCtx)\n {\n if (demuxer.avioCtx != null)\n {\n // Disable check since already converted to UTF-8\n codecCtx->sub_charenc_mode = SubCharencModeFlags.Ignore;\n }\n }\n\n return 0;\n }\n\n protected override void DisposeInternal()\n => DisposeFrames();\n\n public void Flush()\n {\n lock (lockActions)\n lock (lockCodecCtx)\n {\n if (Disposed) return;\n\n if (Status == Status.Ended) Status = Status.Stopped;\n //else if (Status == Status.Draining) Status = Status.Stopping;\n\n DisposeFrames();\n avcodec_flush_buffers(codecCtx);\n }\n }\n\n protected override void RunInternal()\n {\n int ret = 0;\n int allowedErrors = Config.Decoder.MaxErrors;\n AVPacket *packet;\n\n SubtitlesPackets = demuxer.SubtitlesPackets[subIndex];\n\n do\n {\n // Wait until Queue not Full or Stopped\n if (Frames.Count >= Config.Decoder.MaxSubsFrames)\n {\n lock (lockStatus)\n if (Status == Status.Running) Status = Status.QueueFull;\n\n while (Frames.Count >= Config.Decoder.MaxSubsFrames && Status == Status.QueueFull) Thread.Sleep(20);\n\n lock (lockStatus)\n {\n if (Status != Status.QueueFull) break;\n Status = Status.Running;\n }\n }\n\n // While Packets Queue Empty (Ended | Quit if Demuxer stopped | Wait until we get packets)\n if (SubtitlesPackets.Count == 0)\n {\n CriticalArea = true;\n\n lock (lockStatus)\n if (Status == Status.Running) Status = Status.QueueEmpty;\n\n while (SubtitlesPackets.Count == 0 && Status == Status.QueueEmpty)\n {\n if (demuxer.Status == Status.Ended)\n {\n Status = Status.Ended;\n break;\n }\n else if (!demuxer.IsRunning)\n {\n if (CanDebug) Log.Debug($\"Demuxer is not running [Demuxer Status: {demuxer.Status}]\");\n\n int retries = 5;\n\n while (retries > 0)\n {\n retries--;\n Thread.Sleep(10);\n if (demuxer.IsRunning) break;\n }\n\n lock (demuxer.lockStatus)\n lock (lockStatus)\n {\n if (demuxer.Status == Status.Pausing || demuxer.Status == Status.Paused)\n Status = Status.Pausing;\n else if (demuxer.Status != Status.Ended)\n Status = Status.Stopping;\n else\n continue;\n }\n\n break;\n }\n\n Thread.Sleep(20);\n }\n\n lock (lockStatus)\n {\n CriticalArea = false;\n if (Status != Status.QueueEmpty) break;\n Status = Status.Running;\n }\n }\n\n lock (lockCodecCtx)\n {\n if (Status == Status.Stopped || SubtitlesPackets.Count == 0) continue;\n packet = SubtitlesPackets.Dequeue();\n\n int gotFrame = 0;\n SubtitlesFrame subFrame = new();\n\n fixed(AVSubtitle* subPtr = &subFrame.sub)\n ret = avcodec_decode_subtitle2(codecCtx, subPtr, &gotFrame, packet);\n\n if (ret < 0)\n {\n allowedErrors--;\n if (CanWarn) Log.Warn($\"{FFmpegEngine.ErrorCodeToMsg(ret)} ({ret})\");\n\n if (allowedErrors == 0) { Log.Error(\"Too many errors!\"); Status = Status.Stopping; break; }\n\n continue;\n }\n\n if (gotFrame == 0)\n {\n av_packet_free(&packet);\n continue;\n }\n\n long pts = subFrame.sub.pts != AV_NOPTS_VALUE ? subFrame.sub.pts /*mcs*/ * 10 : (packet->pts != AV_NOPTS_VALUE ? (long)(packet->pts * SubtitlesStream.Timebase) : AV_NOPTS_VALUE);\n av_packet_free(&packet);\n\n if (pts == AV_NOPTS_VALUE)\n continue;\n\n pts += subFrame.sub.start_display_time /*ms*/ * 10000L;\n\n if (!filledFromCodec) // TODO: CodecChanged? And when findstreaminfo is disabled as it is an external demuxer will not know the main demuxer's start time\n {\n filledFromCodec = true;\n avcodec_parameters_from_context(Stream.AVStream->codecpar, codecCtx);\n SubtitlesStream.Refresh();\n\n CodecChanged?.Invoke(this);\n }\n\n if (subFrame.sub.num_rects < 1)\n {\n if (SubtitlesStream.IsBitmap) // clear prev subs frame\n {\n subFrame.duration = uint.MaxValue;\n subFrame.timestamp = pts - demuxer.StartTime + Config.Subtitles[subIndex].Delay;\n subFrame.isBitmap = true;\n Frames.Enqueue(subFrame);\n }\n\n fixed(AVSubtitle* subPtr = &subFrame.sub)\n avsubtitle_free(subPtr);\n\n continue;\n }\n\n subFrame.duration = subFrame.sub.end_display_time;\n subFrame.timestamp = pts - demuxer.StartTime + Config.Subtitles[subIndex].Delay;\n\n if (subFrame.sub.rects[0]->type == AVSubtitleType.Ass)\n {\n subFrame.text = Utils.BytePtrToStringUTF8(subFrame.sub.rects[0]->ass).Trim();\n Config.Subtitles.Parser(subFrame);\n\n fixed(AVSubtitle* subPtr = &subFrame.sub)\n avsubtitle_free(subPtr);\n\n if (string.IsNullOrEmpty(subFrame.text))\n continue;\n }\n else if (subFrame.sub.rects[0]->type == AVSubtitleType.Text)\n {\n subFrame.text = Utils.BytePtrToStringUTF8(subFrame.sub.rects[0]->text).Trim();\n\n fixed(AVSubtitle* subPtr = &subFrame.sub)\n avsubtitle_free(subPtr);\n\n if (string.IsNullOrEmpty(subFrame.text))\n continue;\n }\n else if (subFrame.sub.rects[0]->type == AVSubtitleType.Bitmap)\n {\n var rect = subFrame.sub.rects[0];\n byte[] data = Renderer.ConvertBitmapSub(subFrame.sub, false);\n\n subFrame.isBitmap = true;\n subFrame.bitmap = new SubtitlesFrameBitmap()\n {\n data = data,\n width = rect->w,\n height = rect->h,\n x = rect->x,\n y = rect->y,\n };\n }\n\n if (CanTrace) Log.Trace($\"Processes {Utils.TicksToTime(subFrame.timestamp)}\");\n\n Frames.Enqueue(subFrame);\n }\n } while (Status == Status.Running);\n }\n\n public static void DisposeFrame(SubtitlesFrame frame)\n {\n Debug.Assert(frame != null, \"frame is already disposed (race condition)\");\n if (frame != null && frame.sub.num_rects > 0)\n fixed(AVSubtitle* ptr = &frame.sub)\n avsubtitle_free(ptr);\n }\n\n public void DisposeFrames()\n {\n if (!SubtitlesStream.IsBitmap)\n Frames = new ConcurrentQueue();\n else\n {\n while (!Frames.IsEmpty)\n {\n Frames.TryDequeue(out var frame);\n DisposeFrame(frame);\n }\n }\n }\n}\n"], ["/LLPlayer/LLPlayer/ViewModels/WhisperModelDownloadDialogVM.cs", "using System.Collections.ObjectModel;\nusing System.Diagnostics;\nusing System.IO;\nusing System.Windows;\nusing FlyleafLib;\nusing LLPlayer.Extensions;\nusing LLPlayer.Services;\nusing Whisper.net.Ggml;\n\nnamespace LLPlayer.ViewModels;\n\npublic class WhisperModelDownloadDialogVM : Bindable, IDialogAware\n{\n public FlyleafManager FL { get; }\n\n public WhisperModelDownloadDialogVM(FlyleafManager fl)\n {\n FL = fl;\n\n List models = WhisperCppModelLoader.LoadAllModels();\n foreach (var model in models)\n {\n Models.Add(model);\n }\n\n SelectedModel = Models.First();\n\n CmdDownloadModel!.PropertyChanged += (sender, args) =>\n {\n if (args.PropertyName == nameof(CmdDownloadModel.IsExecuting))\n {\n OnPropertyChanged(nameof(CanDownload));\n OnPropertyChanged(nameof(CanDelete));\n }\n };\n }\n\n private const string TempExtension = \".tmp\";\n\n public ObservableCollection Models { get; set => Set(ref field, value); } = new();\n\n public WhisperCppModel SelectedModel\n {\n get;\n set\n {\n if (Set(ref field, value))\n {\n OnPropertyChanged(nameof(CanDownload));\n OnPropertyChanged(nameof(CanDelete));\n }\n }\n }\n\n public string StatusText { get; set => Set(ref field, value); } = \"Select a model to download.\";\n\n public long DownloadedSize { get; set => Set(ref field, value); }\n\n public bool CanDownload =>\n SelectedModel is { Downloaded: false } && !CmdDownloadModel!.IsExecuting;\n\n public bool CanDelete =>\n SelectedModel is { Downloaded: true } && !CmdDownloadModel!.IsExecuting;\n\n private CancellationTokenSource? _cts;\n\n public AsyncDelegateCommand? CmdDownloadModel => field ??= new AsyncDelegateCommand(async () =>\n {\n _cts = new CancellationTokenSource();\n CancellationToken token = _cts.Token;\n\n WhisperCppModel downloadModel = SelectedModel;\n string tempModelPath = downloadModel.ModelFilePath + TempExtension;\n\n try\n {\n if (downloadModel.Downloaded)\n {\n StatusText = $\"Model '{SelectedModel}' is already downloaded\";\n return;\n }\n\n // Delete temporary files if they exist (forces re-download)\n if (!DeleteTempModel())\n {\n StatusText = $\"Failed to remove temp model\";\n return;\n }\n\n StatusText = $\"Model '{downloadModel}' downloading..\";\n\n long modelSize = await DownloadModelWithProgressAsync(downloadModel.Model, tempModelPath, token);\n\n // After successful download, rename temporary file to final file\n File.Move(tempModelPath, downloadModel.ModelFilePath);\n\n // Update downloaded status\n downloadModel.Size = modelSize;\n OnDownloadStatusChanged();\n\n StatusText = $\"Model '{SelectedModel}' is downloaded successfully\";\n }\n catch (OperationCanceledException)\n {\n StatusText = \"Download canceled\";\n }\n catch (Exception ex)\n {\n StatusText = $\"Failed to download: {ex.Message}\";\n }\n finally\n {\n _cts = null;\n DeleteTempModel();\n }\n\n return;\n\n bool DeleteTempModel()\n {\n // Delete temporary files if they exist\n if (File.Exists(tempModelPath))\n {\n try\n {\n File.Delete(tempModelPath);\n }\n catch (Exception)\n {\n // ignore\n\n return false;\n }\n }\n\n return true;\n }\n }).ObservesCanExecute(() => CanDownload);\n\n public DelegateCommand? CmdCancelDownloadModel => field ??= new(() =>\n {\n _cts?.Cancel();\n });\n\n public DelegateCommand? CmdDeleteModel => field ??= new DelegateCommand(() =>\n {\n try\n {\n StatusText = $\"Model '{SelectedModel}' deleting...\";\n\n WhisperCppModel deleteModel = SelectedModel;\n\n // Delete model file if exists\n if (File.Exists(deleteModel.ModelFilePath))\n {\n File.Delete(deleteModel.ModelFilePath);\n }\n\n // Update downloaded status\n deleteModel.Size = 0;\n OnDownloadStatusChanged();\n\n StatusText = $\"Model '{deleteModel}' is deleted successfully\";\n }\n catch (Exception ex)\n {\n StatusText = $\"Failed to delete model: {ex.Message}\";\n }\n }).ObservesCanExecute(() => CanDelete);\n\n public DelegateCommand? CmdOpenFolder => field ??= new(() =>\n {\n if (!Directory.Exists(WhisperConfig.ModelsDirectory))\n return;\n\n try\n {\n Process.Start(new ProcessStartInfo\n {\n FileName = WhisperConfig.ModelsDirectory,\n UseShellExecute = true,\n CreateNoWindow = true\n });\n }\n catch (Exception ex)\n {\n MessageBox.Show($\"Failed to open folder: {ex.Message}\", \"Error\", MessageBoxButton.OK, MessageBoxImage.Error);\n }\n });\n\n private void OnDownloadStatusChanged()\n {\n OnPropertyChanged(nameof(CanDownload));\n OnPropertyChanged(nameof(CanDelete));\n }\n\n private async Task DownloadModelWithProgressAsync(GgmlType modelType, string destinationPath, CancellationToken token)\n {\n DownloadedSize = 0;\n\n await using Stream modelStream = await WhisperGgmlDownloader.Default.GetGgmlModelAsync(modelType, default, token);\n await using FileStream fileWriter = File.OpenWrite(destinationPath);\n\n byte[] buffer = new byte[1024 * 128];\n int bytesRead;\n long totalBytesRead = 0;\n\n Stopwatch sw = new();\n sw.Start();\n\n while ((bytesRead = await modelStream.ReadAsync(buffer, 0, buffer.Length, token)) > 0)\n {\n await fileWriter.WriteAsync(buffer, 0, bytesRead, token);\n totalBytesRead += bytesRead;\n\n if (sw.Elapsed > TimeSpan.FromMilliseconds(50))\n {\n DownloadedSize = totalBytesRead;\n sw.Restart();\n }\n\n token.ThrowIfCancellationRequested();\n }\n\n return totalBytesRead;\n }\n\n #region IDialogAware\n public string Title { get; set => Set(ref field, value); } = $\"Whisper Downloader - {App.Name}\";\n public double WindowWidth { get; set => Set(ref field, value); } = 400;\n public double WindowHeight { get; set => Set(ref field, value); } = 200;\n\n public bool CanCloseDialog() => !CmdDownloadModel!.IsExecuting;\n public void OnDialogClosed() { }\n public void OnDialogOpened(IDialogParameters parameters) { }\n public DialogCloseListener RequestClose { get; }\n #endregion IDialogAware\n}\n"], ["/LLPlayer/LLPlayer/Controls/FlyleafBar.xaml.cs", "using System.Windows;\nusing System.Windows.Controls;\nusing System.Windows.Controls.Primitives;\nusing System.Windows.Documents;\nusing System.Windows.Input;\nusing System.Windows.Media;\nusing System.Windows.Media.Animation;\nusing FlyleafLib;\nusing FlyleafLib.MediaFramework.MediaDemuxer;\nusing FlyleafLib.MediaPlayer;\nusing LLPlayer.Services;\nusing Microsoft.Xaml.Behaviors;\n\nnamespace LLPlayer.Controls;\n\npublic partial class FlyleafBar : UserControl\n{\n public FlyleafManager FL { get; }\n\n public FlyleafBar()\n {\n InitializeComponent();\n\n FL = ((App)Application.Current).Container.Resolve();\n\n DataContext = this;\n\n // Do not hide the cursor when it is on the seek bar\n MouseEnter += OnMouseEnter;\n LostFocus += OnMouseLeave;\n MouseLeave += OnMouseLeave;\n\n FL.Config.PropertyChanged += (sender, args) =>\n {\n if (args.PropertyName == nameof(FL.Config.SeekBarShowOnlyMouseOver))\n {\n // Avoided a problem in which Opacity was set to 0 when switching settings and was not displayed.\n FL.Player.Activity.ForceFullActive();\n IsShowing = true;\n\n if (FL.Config.SeekBarShowOnlyMouseOver && !MyCard.IsMouseOver)\n {\n IsShowing = false;\n }\n }\n };\n\n FL.Player.Activity.PropertyChanged += (sender, args) =>\n {\n switch (args.PropertyName)\n {\n case nameof(FL.Player.Activity.IsEnabled):\n if (FL.Config.SeekBarShowOnlyMouseOver)\n {\n IsShowing = !FL.Player.Activity.IsEnabled || MyCard.IsMouseOver;\n }\n break;\n\n case nameof(FL.Player.Activity.Mode):\n if (!FL.Config.SeekBarShowOnlyMouseOver)\n {\n IsShowing = FL.Player.Activity.Mode == ActivityMode.FullActive;\n }\n break;\n }\n };\n\n if (FL.Config.SeekBarShowOnlyMouseOver)\n {\n // start in hide\n MyCard.Opacity = 0.01;\n }\n else\n {\n // start in show\n IsShowing = true;\n }\n }\n\n public bool IsShowing\n {\n get;\n set\n {\n if (field == value)\n return;\n\n field = value;\n if (value)\n {\n // Fade In\n MyCard.BeginAnimation(OpacityProperty, new DoubleAnimation()\n {\n BeginTime = TimeSpan.Zero,\n To = 1,\n Duration = new Duration(TimeSpan.FromMilliseconds(FL.Config.SeekBarFadeInTimeMs))\n });\n }\n else\n {\n // Fade Out\n MyCard.BeginAnimation(OpacityProperty, new DoubleAnimation()\n {\n BeginTime = TimeSpan.Zero,\n // TODO: L: needs to be almost transparent to receive MouseEnter events\n To = FL.Config.SeekBarShowOnlyMouseOver ? 0.01 : 0,\n Duration = new Duration(TimeSpan.FromMilliseconds(FL.Config.SeekBarFadeOutTimeMs))\n });\n }\n }\n }\n\n private void OnMouseLeave(object sender, RoutedEventArgs e)\n {\n if (FL.Config.SeekBarShowOnlyMouseOver && FL.Player.Activity.IsEnabled)\n {\n IsShowing = false;\n }\n else\n {\n SetActivity(true);\n }\n }\n\n private void OnMouseEnter(object sender, MouseEventArgs e)\n {\n if (FL.Config.SeekBarShowOnlyMouseOver && FL.Player.Activity.IsEnabled)\n {\n IsShowing = true;\n }\n else\n {\n SetActivity(false);\n }\n }\n\n private void SetActivity(bool isActive)\n {\n FL.Player.Activity.IsEnabled = isActive;\n }\n\n // Left-click on button to open context menu\n private void ButtonBase_OnClick(object sender, RoutedEventArgs e)\n {\n if (sender is not Button btn)\n {\n return;\n }\n\n if (btn.ContextMenu == null)\n {\n return;\n }\n\n if (btn.ContextMenu.PlacementTarget == null)\n {\n // Do not hide seek bar when context menu is displayed (register once)\n btn.ContextMenu.Opened += OnContextMenuOnOpened;\n btn.ContextMenu.Closed += OnContextMenuOnClosed;\n btn.ContextMenu.MouseMove += OnContextMenuOnMouseMove;\n btn.ContextMenu.PlacementTarget = btn;\n }\n btn.ContextMenu.IsOpen = true;\n }\n\n private void OnContextMenuOnOpened(object o, RoutedEventArgs args)\n {\n SetActivity(false);\n }\n\n private void OnContextMenuOnClosed(object o, RoutedEventArgs args)\n {\n SetActivity(true);\n }\n\n private void OnContextMenuOnMouseMove(object o, MouseEventArgs args)\n {\n // this is necessary to keep PopupMenu visible when opened in succession when SeekBarShowOnlyMouseOver\n SetActivity(false);\n }\n}\n\npublic class SliderToolTipBehavior : Behavior\n{\n private const int PaddingSize = 5;\n private Popup? _valuePopup;\n private TextBlock? _tooltipText;\n private Border? _tooltipBorder;\n private Track? _track;\n\n public static readonly DependencyProperty ChaptersProperty =\n DependencyProperty.Register(nameof(Chapters), typeof(IList), typeof(SliderToolTipBehavior), new PropertyMetadata(null));\n\n public IList? Chapters\n {\n get => (IList)GetValue(ChaptersProperty);\n set => SetValue(ChaptersProperty, value);\n }\n\n protected override void OnAttached()\n {\n base.OnAttached();\n\n _tooltipText = new TextBlock\n {\n Foreground = Brushes.White,\n FontSize = 12,\n TextAlignment = TextAlignment.Center\n };\n\n _tooltipBorder = new Border\n {\n Background = new SolidColorBrush(Colors.Black) { Opacity = 0.7 },\n CornerRadius = new CornerRadius(4),\n Padding = new Thickness(PaddingSize),\n Child = _tooltipText\n };\n\n _valuePopup = new Popup\n {\n AllowsTransparency = true,\n Placement = PlacementMode.Absolute,\n PlacementTarget = AssociatedObject,\n Child = _tooltipBorder\n };\n\n AssociatedObject.MouseMove += Slider_MouseMove;\n AssociatedObject.MouseLeave += Slider_MouseLeave;\n }\n\n protected override void OnDetaching()\n {\n base.OnDetaching();\n\n AssociatedObject.MouseMove -= Slider_MouseMove;\n AssociatedObject.MouseLeave -= Slider_MouseLeave;\n }\n\n private void Slider_MouseMove(object sender, MouseEventArgs e)\n {\n _track ??= (Track)AssociatedObject.Template.FindName(\"PART_Track\", AssociatedObject);\n Point pos = e.GetPosition(_track);\n double value = _track.ValueFromPoint(pos);\n TimeSpan hoverTime = TimeSpan.FromSeconds(value);\n\n string dateFormat = hoverTime.Hours >= 1 ? @\"hh\\:mm\\:ss\" : @\"mm\\:ss\";\n string timestamp = hoverTime.ToString(dateFormat);\n\n // TODO: L: Allow customizable chapter display functionality\n string? chapterTitle = GetChapterTitleAtTime(hoverTime);\n\n _tooltipText!.Inlines.Clear();\n if (chapterTitle != null)\n {\n _tooltipText.Inlines.Add(chapterTitle);\n _tooltipText.Inlines.Add(new LineBreak());\n }\n\n _tooltipText.Inlines.Add(timestamp);\n\n Window window = Window.GetWindow(AssociatedObject)!;\n Point cursorPoint = window.PointToScreen(e.GetPosition(window));\n Point sliderPoint = AssociatedObject.PointToScreen(default);\n\n // Fix for high dpi because PointToScreen returns physical coords\n cursorPoint.X /= Utils.NativeMethods.DpiX;\n cursorPoint.Y /= Utils.NativeMethods.DpiY;\n\n sliderPoint.X /= Utils.NativeMethods.DpiX;\n sliderPoint.Y /= Utils.NativeMethods.DpiY;\n\n // Display on top of slider near mouse\n _valuePopup!.HorizontalOffset = cursorPoint.X - (_tooltipText.ActualWidth + PaddingSize * 2) / 2;\n _valuePopup!.VerticalOffset = sliderPoint.Y - _tooltipBorder!.ActualHeight - 5;\n\n // display popup\n _valuePopup.IsOpen = true;\n }\n\n private void Slider_MouseLeave(object sender, MouseEventArgs e)\n {\n _valuePopup!.IsOpen = false;\n }\n\n private string? GetChapterTitleAtTime(TimeSpan time)\n {\n if (Chapters == null || Chapters.Count <= 1)\n {\n return null;\n }\n\n var chapter = Chapters.FirstOrDefault(c => c.StartTime <= time.Ticks && time.Ticks <= c.EndTime);\n return chapter?.Title;\n }\n}\n"], ["/LLPlayer/LLPlayer/Converters/GeneralConverters.cs", "using System.Globalization;\nusing System.Windows;\nusing System.Windows.Data;\nusing System.Windows.Input;\nusing System.Windows.Media;\nusing LLPlayer.Services;\n\nnamespace LLPlayer.Converters;\n[ValueConversion(typeof(bool), typeof(bool))]\npublic class InvertBooleanConverter : IValueConverter\n{\n public object Convert(object value, Type targetType, object parameter, CultureInfo culture)\n {\n if (value is bool boolValue)\n {\n return !boolValue;\n }\n return false;\n }\n\n public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)\n {\n if (value is bool boolValue)\n {\n return !boolValue;\n }\n return false;\n }\n}\n\n[ValueConversion(typeof(bool), typeof(Visibility))]\npublic class BooleanToVisibilityMiscConverter : IValueConverter\n{\n public Visibility FalseVisibility { get; set; } = Visibility.Collapsed;\n public bool Invert { get; set; } = false;\n\n public object Convert(object value, Type targetType, object parameter, CultureInfo culture)\n {\n if (Invert)\n {\n return (bool)value ? FalseVisibility : Visibility.Visible;\n }\n\n return (bool)value ? Visibility.Visible : FalseVisibility;\n }\n\n public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture) => throw new NotImplementedException();\n}\n\n[ValueConversion(typeof(double), typeof(double))]\npublic class DoubleToPercentageConverter : IValueConverter\n{\n // Model → View (0.0–1.0 → 0–100)\n public object Convert(object value, Type targetType, object parameter, CultureInfo culture)\n {\n if (value is double d)\n return Math.Round(d * 100.0, 0);\n return 0.0;\n }\n\n // View → Model (0–100 → 0.0–1.0)\n public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)\n {\n if (value is double d)\n return ToDouble(d);\n\n if (value is string sd)\n {\n if (double.TryParse(sd, out d))\n {\n if (d < 0)\n d = 0;\n else if (d > 100)\n d = 100;\n }\n\n return ToDouble(d);\n }\n\n return 0.0;\n\n static double ToDouble(double value)\n {\n return Math.Max(0.0, Math.Min(1.0, Math.Round(value / 100.0, 2)));\n }\n }\n}\n\n[ValueConversion(typeof(Enum), typeof(string))]\npublic class EnumToStringConverter : IValueConverter\n{\n public object Convert(object value, Type targetType, object parameter, CultureInfo culture)\n {\n string str;\n try\n {\n str = Enum.GetName(value.GetType(), value)!;\n return str;\n }\n catch\n {\n return string.Empty;\n }\n }\n\n public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture) => throw new NotImplementedException();\n}\n\n[ValueConversion(typeof(Enum), typeof(string))]\npublic class EnumToDescriptionConverter : IValueConverter\n{\n public object Convert(object value, Type targetType, object parameter, CultureInfo culture)\n {\n if (value is Enum enumValue)\n {\n return enumValue.GetDescription();\n }\n return value.ToString() ?? \"\";\n }\n\n public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)\n {\n throw new NotImplementedException();\n }\n}\n\n[ValueConversion(typeof(Enum), typeof(bool))]\npublic class EnumToBooleanConverter : IValueConverter\n{\n // value, parameter = Enum\n public object Convert(object value, Type targetType, object parameter, CultureInfo culture)\n {\n if (value is not Enum enumValue || parameter is not Enum enumTarget)\n return false;\n\n return enumValue.Equals(enumTarget);\n }\n\n public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)\n {\n return parameter;\n }\n}\n\n[ValueConversion(typeof(Enum), typeof(Visibility))]\npublic class EnumToVisibilityConverter : IValueConverter\n{\n // value, parameter = Enum\n public object Convert(object value, Type targetType, object parameter, CultureInfo culture)\n {\n if (value is not Enum enumValue || parameter is not Enum enumTarget)\n return false;\n\n return enumValue.Equals(enumTarget) ? Visibility.Visible : Visibility.Collapsed;\n }\n\n public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)\n {\n throw new NotImplementedException();\n }\n}\n\n[ValueConversion(typeof(Color), typeof(Brush))]\npublic class ColorToBrushConverter : IValueConverter\n{\n public object Convert(object value, Type targetType, object parameter, CultureInfo culture)\n {\n if (value is Color color)\n {\n return new SolidColorBrush(color);\n }\n return Binding.DoNothing;\n }\n\n public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)\n {\n if (value is SolidColorBrush brush)\n {\n return brush.Color;\n }\n return default(Color);\n }\n}\n\n/// \n/// Converts from System.Windows.Input.Key to human readable string\n/// \n[ValueConversion(typeof(Key), typeof(string))]\npublic class KeyToStringConverter : IValueConverter\n{\n public static readonly Dictionary KeyMappings = new()\n {\n { Key.D0, \"0\" },\n { Key.D1, \"1\" },\n { Key.D2, \"2\" },\n { Key.D3, \"3\" },\n { Key.D4, \"4\" },\n { Key.D5, \"5\" },\n { Key.D6, \"6\" },\n { Key.D7, \"7\" },\n { Key.D8, \"8\" },\n { Key.D9, \"9\" },\n { Key.Prior, \"PageUp\" },\n { Key.Next, \"PageDown\" },\n { Key.Return, \"Enter\" },\n { Key.Oem1, \";\" },\n { Key.Oem2, \"/\" },\n { Key.Oem3, \"`\" },\n { Key.Oem4, \"[\" },\n { Key.Oem5, \"\\\\\" },\n { Key.Oem6, \"]\" },\n { Key.Oem7, \"'\" },\n { Key.OemPlus, \"Plus\" },\n { Key.OemMinus, \"Minus\" },\n { Key.OemComma, \",\" },\n { Key.OemPeriod, \".\" }\n };\n\n public object Convert(object? value, Type targetType, object? parameter, CultureInfo culture)\n {\n if (value is Key key)\n {\n if (KeyMappings.TryGetValue(key, out var mappedValue))\n {\n return mappedValue;\n }\n\n return key.ToString();\n }\n\n return Binding.DoNothing;\n }\n\n public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)\n {\n throw new NotImplementedException();\n }\n}\n\n[ValueConversion(typeof(long), typeof(string))]\npublic class FileSizeHumanConverter : IValueConverter\n{\n public object Convert(object value, Type targetType, object parameter, CultureInfo culture)\n {\n if (value is long size)\n {\n return FormatBytes(size);\n }\n\n return Binding.DoNothing;\n }\n\n public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)\n {\n throw new NotImplementedException();\n }\n\n private static string FormatBytes(long bytes)\n {\n string[] sizes = [\"B\", \"KB\", \"MB\", \"GB\"];\n double len = bytes;\n int order = 0;\n while (len >= 1024 && order < sizes.Length - 1)\n {\n order++;\n len /= 1024;\n }\n return $\"{len:0.##} {sizes[order]}\";\n }\n}\n\n[ValueConversion(typeof(int?), typeof(string))]\npublic class NullableIntConverter : IValueConverter\n{\n public object Convert(object? value, Type targetType, object? parameter, CultureInfo culture)\n {\n return value is int intValue ? intValue.ToString() : string.Empty;\n }\n\n public object? ConvertBack(object? value, Type targetType, object? parameter, CultureInfo culture)\n {\n string? str = value as string;\n if (string.IsNullOrWhiteSpace(str))\n return null;\n\n if (int.TryParse(str, out int result))\n return result;\n\n return null;\n }\n}\n"], ["/LLPlayer/FlyleafLib/Plugins/OpenDefault.cs", "using System;\nusing System.IO;\n\nusing FlyleafLib.MediaFramework.MediaPlaylist;\n\nnamespace FlyleafLib.Plugins;\n\npublic class OpenDefault : PluginBase, IOpen, IScrapeItem\n{\n /* TODO\n *\n * 1) Current Url Syntax issues\n * ..\\..\\..\\..\\folder\\file.mp3 | Cannot handle this\n * file:///C:/folder/fi%20le.mp3 | FFmpeg & File.Exists cannot handle this\n *\n */\n\n public new int Priority { get; set; } = 3000;\n\n public bool CanOpen() => true;\n\n public OpenResults Open()\n {\n try\n {\n if (Playlist.IOStream != null)\n {\n AddPlaylistItem(new()\n {\n IOStream= Playlist.IOStream,\n Title = \"Custom IO Stream\",\n FileSize= Playlist.IOStream.Length\n });\n\n Handler.OnPlaylistCompleted();\n\n return new();\n }\n\n // Proper Url Format\n string scheme;\n bool isWeb = false;\n string uriType = \"\";\n string ext = Utils.GetUrlExtention(Playlist.Url);\n string localPath= null;\n\n try\n {\n Uri uri = new(Playlist.Url);\n scheme = uri.Scheme.ToLower();\n isWeb = scheme.StartsWith(\"http\");\n uriType = uri.IsFile ? \"file\" : (uri.IsUnc ? \"unc\" : \"\");\n localPath = uri.LocalPath;\n } catch { }\n\n\n // Playlists (M3U, M3U8, PLS | TODO: WPL, XSPF)\n if (ext == \"m3u\")// || ext == \"m3u8\")\n {\n Playlist.InputType = InputType.Web; // TBR: Can be mixed\n Playlist.FolderBase = Path.GetTempPath();\n\n var items = isWeb ? M3UPlaylist.ParseFromHttp(Playlist.Url) : M3UPlaylist.Parse(Playlist.Url);\n\n foreach(var mitem in items)\n {\n AddPlaylistItem(new()\n {\n Title = mitem.Title,\n Url = mitem.Url,\n DirectUrl = mitem.Url,\n UserAgent = mitem.UserAgent,\n Referrer = mitem.Referrer\n });\n }\n\n Handler.OnPlaylistCompleted();\n\n return new();\n }\n else if (ext == \"pls\")\n {\n Playlist.InputType = InputType.Web; // TBR: Can be mixed\n Playlist.FolderBase = Path.GetTempPath();\n\n var items = PLSPlaylist.Parse(Playlist.Url);\n\n foreach(var mitem in items)\n {\n AddPlaylistItem(new PlaylistItem()\n {\n Title = mitem.Title,\n Url = mitem.Url,\n DirectUrl = mitem.Url,\n // Duration\n });\n }\n\n Handler.OnPlaylistCompleted();\n\n return new();\n }\n\n FileInfo fi = null;\n // Single Playlist Item\n if (uriType == \"file\")\n {\n Playlist.InputType = InputType.File;\n if (File.Exists(Playlist.Url))\n {\n fi = new(Playlist.Url);\n Playlist.FolderBase = fi.DirectoryName;\n }\n }\n else if (isWeb)\n {\n Playlist.InputType = InputType.Web;\n Playlist.FolderBase = Path.GetTempPath();\n }\n else if (uriType == \"unc\")\n {\n Playlist.InputType = InputType.UNC;\n Playlist.FolderBase = Path.GetTempPath();\n }\n else\n {\n //Playlist.InputType = InputType.Unknown;\n Playlist.FolderBase = Path.GetTempPath();\n }\n\n PlaylistItem item = new()\n {\n Url = Playlist.Url,\n DirectUrl = Playlist.Url\n };\n\n if (fi == null && File.Exists(Playlist.Url))\n {\n fi = new(Playlist.Url);\n item.Title = fi.Name;\n item.FileSize = fi.Length;\n }\n else\n {\n if (localPath != null)\n item.Title = Path.GetFileName(localPath);\n\n if (item.Title == null || item.Title.Trim().Length == 0)\n item.Title = Playlist.Url;\n }\n\n AddPlaylistItem(item);\n Handler.OnPlaylistCompleted();\n\n return new();\n } catch (Exception e)\n {\n return new(e.Message);\n }\n }\n\n public OpenResults OpenItem() => new();\n\n public void ScrapeItem(PlaylistItem item)\n {\n // Update Title (TBR: don't mess with other media types - only movies/tv shows)\n if (Playlist.InputType != InputType.File && Playlist.InputType != InputType.UNC && Playlist.InputType != InputType.Torrent)\n return;\n\n item.FillMediaParts();\n }\n}\n"], ["/LLPlayer/FlyleafLib/MediaFramework/MediaFrame/SubtitlesFrame.cs", "using System.Collections.Generic;\nusing System.Drawing;\nusing System.Globalization;\n\nnamespace FlyleafLib.MediaFramework.MediaFrame;\n\npublic class SubtitlesFrame : FrameBase\n{\n public bool isBitmap;\n public uint duration;\n public string text;\n public List subStyles;\n public AVSubtitle sub;\n public SubtitlesFrameBitmap bitmap;\n\n // for translation switch\n public bool isTranslated;\n}\n\npublic class SubtitlesFrameBitmap\n{\n // Buffer to hold decoded pixels\n public byte[] data;\n public int width;\n public int height;\n public int x;\n public int y;\n}\n\npublic struct SubStyle\n{\n public SubStyles style;\n public Color value;\n\n public int from;\n public int len;\n\n public SubStyle(int from, int len, Color value) : this(SubStyles.COLOR, from, len, value) { }\n public SubStyle(SubStyles style, int from = -1, int len = -1, Color? value = null)\n {\n this.style = style;\n this.value = value == null ? Color.White : (Color)value;\n this.from = from;\n this.len = len;\n }\n}\n\npublic enum SubStyles\n{\n BOLD,\n ITALIC,\n UNDERLINE,\n STRIKEOUT,\n FONTSIZE,\n FONTNAME,\n COLOR\n}\n\n/// \n/// Default Subtitles Parser\n/// \npublic static class ParseSubtitles\n{\n public static void Parse(SubtitlesFrame sFrame)\n {\n sFrame.text = SSAtoSubStyles(sFrame.text, out var subStyles);\n sFrame.subStyles = subStyles;\n }\n public static string SSAtoSubStyles(string s, out List styles)\n {\n int pos = 0;\n string sout = \"\";\n styles = new List();\n\n SubStyle bold = new(SubStyles.BOLD);\n SubStyle italic = new(SubStyles.ITALIC);\n SubStyle underline = new(SubStyles.UNDERLINE);\n SubStyle strikeout = new(SubStyles.STRIKEOUT);\n SubStyle color = new(SubStyles.COLOR);\n\n //SubStyle fontname = new SubStyle(SubStyles.FONTNAME);\n //SubStyle fontsize = new SubStyle(SubStyles.FONTSIZE);\n\n if (string.IsNullOrEmpty(s))\n {\n return sout;\n }\n\n s = s.LastIndexOf(\",,\") == -1 ? s : s[(s.LastIndexOf(\",,\") + 2)..].Replace(\"\\\\N\", \"\\n\").Trim();\n\n for (int i = 0; i < s.Length; i++)\n {\n if (s[i] == '{') continue;\n\n if (s[i] == '\\\\' && s[i - 1] == '{')\n {\n int codeLen = s.IndexOf('}', i) - i;\n if (codeLen == -1) continue;\n\n string code = s.Substring(i, codeLen).Trim();\n\n switch (code[1])\n {\n case 'c':\n if (code.Length == 2)\n {\n if (color.from == -1) break;\n\n color.len = pos - color.from;\n if (color.value != Color.Transparent)\n styles.Add(color);\n\n color = new SubStyle(SubStyles.COLOR);\n }\n else\n {\n color.from = pos;\n color.value = Color.Transparent;\n if (code.Length < 7) break;\n\n int colorEnd = code.LastIndexOf('&');\n if (colorEnd < 6) break;\n\n string hexColor = code[4..colorEnd];\n\n int red = int.Parse(hexColor.Substring(hexColor.Length - 2, 2), NumberStyles.HexNumber);\n int green = 0;\n int blue = 0;\n\n if (hexColor.Length - 2 > 0)\n {\n hexColor = hexColor[..^2];\n if (hexColor.Length == 1)\n hexColor = \"0\" + hexColor;\n\n green = int.Parse(hexColor.Substring(hexColor.Length - 2, 2), NumberStyles.HexNumber);\n }\n\n if (hexColor.Length - 2 > 0)\n {\n hexColor = hexColor[..^2];\n if (hexColor.Length == 1)\n hexColor = \"0\" + hexColor;\n\n blue = int.Parse(hexColor.Substring(hexColor.Length - 2, 2), NumberStyles.HexNumber);\n }\n\n color.value = Color.FromArgb(255, red, green, blue);\n }\n break;\n\n case 'b':\n if (code[2] == '0')\n {\n if (bold.from == -1) break;\n\n bold.len = pos - bold.from;\n styles.Add(bold);\n bold = new SubStyle(SubStyles.BOLD);\n }\n else\n {\n bold.from = pos;\n //bold.value = code.Substring(2, code.Length-2);\n }\n\n break;\n\n case 'u':\n if (code[2] == '0')\n {\n if (underline.from == -1) break;\n\n underline.len = pos - underline.from;\n styles.Add(underline);\n underline = new SubStyle(SubStyles.UNDERLINE);\n }\n else\n {\n underline.from = pos;\n }\n\n break;\n\n case 's':\n if (code[2] == '0')\n {\n if (strikeout.from == -1) break;\n\n strikeout.len = pos - strikeout.from;\n styles.Add(strikeout);\n strikeout = new SubStyle(SubStyles.STRIKEOUT);\n }\n else\n {\n strikeout.from = pos;\n }\n\n break;\n\n case 'i':\n if (code.Length > 2 && code[2] == '0')\n {\n if (italic.from == -1) break;\n\n italic.len = pos - italic.from;\n styles.Add(italic);\n italic = new SubStyle(SubStyles.ITALIC);\n }\n else\n {\n italic.from = pos;\n }\n\n break;\n }\n\n i += codeLen;\n continue;\n }\n\n sout += s[i];\n pos++;\n }\n\n // Non-Closing Codes\n int soutPostLast = sout.Length;\n if (bold.from != -1) { bold.len = soutPostLast - bold.from; styles.Add(bold); }\n if (italic.from != -1) { italic.len = soutPostLast - italic.from; styles.Add(italic); }\n if (strikeout.from != -1) { strikeout.len = soutPostLast - strikeout.from; styles.Add(strikeout); }\n if (underline.from != -1) { underline.len = soutPostLast - underline.from; styles.Add(underline); }\n if (color.from != -1 && color.value != Color.Transparent) { color.len = soutPostLast - color.from; styles.Add(color); }\n\n // Greek issue?\n sout = sout.Replace(\"ʼ\", \"Ά\");\n\n return sout;\n }\n}\n"], ["/LLPlayer/FlyleafLib/MediaFramework/MediaDecoder/DecoderBase.cs", "using FlyleafLib.MediaFramework.MediaDemuxer;\nusing FlyleafLib.MediaFramework.MediaStream;\n\nnamespace FlyleafLib.MediaFramework.MediaDecoder;\n\npublic abstract unsafe class DecoderBase : RunThreadBase\n{\n public MediaType Type { get; protected set; }\n\n public bool OnVideoDemuxer => demuxer?.Type == MediaType.Video;\n public Demuxer Demuxer => demuxer;\n public StreamBase Stream { get; protected set; }\n public AVCodecContext* CodecCtx => codecCtx;\n public int Width => codecCtx != null ? codecCtx->width : 0; // for subtitle\n public int Height => codecCtx != null ? codecCtx->height : 0; // for subtitle\n\n public Action CodecChanged { get; set; }\n public Config Config { get; protected set; }\n public double Speed { get => speed; set { if (Disposed) { speed = value; return; } if (speed != value) OnSpeedChanged(value); } }\n protected double speed = 1, oldSpeed = 1;\n protected virtual void OnSpeedChanged(double value) { }\n\n internal bool filledFromCodec;\n protected AVFrame* frame;\n protected AVCodecContext* codecCtx;\n internal object lockCodecCtx = new();\n\n protected Demuxer demuxer;\n\n public DecoderBase(Config config, int uniqueId = -1) : base(uniqueId)\n {\n Config = config;\n\n if (this is VideoDecoder)\n Type = MediaType.Video;\n else if (this is AudioDecoder)\n Type = MediaType.Audio;\n else if (this is SubtitlesDecoder)\n Type = MediaType.Subs;\n else if (this is DataDecoder)\n Type = MediaType.Data;\n\n threadName = $\"Decoder: {Type,5}\";\n }\n\n public string Open(StreamBase stream)\n {\n lock (lockActions)\n {\n var prevStream = Stream;\n Dispose();\n Status = Status.Opening;\n string error = Open2(stream, prevStream);\n if (!Disposed)\n frame = av_frame_alloc();\n\n return error;\n }\n }\n protected string Open2(StreamBase stream, StreamBase prevStream, bool openStream = true)\n {\n string error = null;\n\n try\n {\n lock (stream.Demuxer.lockActions)\n {\n if (stream == null || stream.Demuxer.Interrupter.ForceInterrupt == 1 || stream.Demuxer.Disposed)\n return \"Cancelled\";\n\n int ret = -1;\n Disposed= false;\n Stream = stream;\n demuxer = stream.Demuxer;\n\n if (stream is not DataStream) // if we don't open/use a data codec context why not just push the Data Frames directly from the Demuxer? no need to have DataDecoder*\n {\n // avcodec_find_decoder will use libdav1d which does not support hardware decoding (software fallback with openStream = false from av1 to default:libdav1d) [#340]\n var codec = stream.CodecID == AVCodecID.Av1 && openStream && Config.Video.VideoAcceleration ? avcodec_find_decoder_by_name(\"av1\") : avcodec_find_decoder(stream.CodecID);\n if (codec == null)\n return error = $\"[{Type} avcodec_find_decoder] No suitable codec found\";\n\n codecCtx = avcodec_alloc_context3(codec); // Pass codec to use default settings\n if (codecCtx == null)\n return error = $\"[{Type} avcodec_alloc_context3] Failed to allocate context3\";\n\n ret = avcodec_parameters_to_context(codecCtx, stream.AVStream->codecpar);\n if (ret < 0)\n return error = $\"[{Type} avcodec_parameters_to_context] {FFmpegEngine.ErrorCodeToMsg(ret)} ({ret})\";\n\n codecCtx->pkt_timebase = stream.AVStream->time_base;\n codecCtx->codec_id = codec->id; // avcodec_parameters_to_context will change this we need to set Stream's Codec Id (eg we change mp2 to mp3)\n\n if (Config.Decoder.ShowCorrupted)\n codecCtx->flags |= CodecFlags.OutputCorrupt;\n\n if (Config.Decoder.LowDelay)\n codecCtx->flags |= CodecFlags.LowDelay;\n\n try { ret = Setup(codec); } catch(Exception e) { return error = $\"[{Type} Setup] {e.Message}\"; }\n if (ret < 0)\n return error = $\"[{Type} Setup] {ret}\";\n\n var codecOpts = Config.Decoder.GetCodecOptPtr(stream.Type);\n AVDictionary* avopt = null;\n foreach(var optKV in codecOpts)\n av_dict_set(&avopt, optKV.Key, optKV.Value, 0);\n\n ret = avcodec_open2(codecCtx, null, avopt == null ? null : &avopt);\n\n if (avopt != null)\n {\n if (ret >= 0)\n {\n AVDictionaryEntry *t = null;\n\n while ((t = av_dict_get(avopt, \"\", t, DictReadFlags.IgnoreSuffix)) != null)\n Log.Debug($\"Ignoring codec option {Utils.BytePtrToStringUTF8(t->key)}\");\n }\n\n av_dict_free(&avopt);\n }\n\n if (ret < 0)\n return error = $\"[{Type} avcodec_open2] {FFmpegEngine.ErrorCodeToMsg(ret)} ({ret})\";\n }\n\n if (openStream)\n {\n if (prevStream != null)\n {\n if (prevStream.Demuxer.Type == stream.Demuxer.Type)\n stream.Demuxer.SwitchStream(stream);\n else if (!prevStream.Demuxer.Disposed)\n {\n if (prevStream.Demuxer.Type == MediaType.Video)\n prevStream.Demuxer.DisableStream(prevStream);\n else if (prevStream.Demuxer.Type == MediaType.Audio || prevStream.Demuxer.Type == MediaType.Subs)\n prevStream.Demuxer.Dispose();\n\n stream.Demuxer.EnableStream(stream);\n }\n }\n else\n stream.Demuxer.EnableStream(stream);\n\n Status = Status.Stopped;\n CodecChanged?.Invoke(this);\n }\n\n return null;\n }\n }\n finally\n {\n if (error != null)\n Dispose(true);\n }\n }\n protected abstract int Setup(AVCodec* codec);\n\n public void Dispose(bool closeStream = false)\n {\n if (Disposed)\n return;\n\n lock (lockActions)\n {\n if (Disposed)\n return;\n\n Stop();\n DisposeInternal();\n\n if (closeStream && Stream != null && !Stream.Demuxer.Disposed)\n {\n if (Stream.Demuxer.Type == MediaType.Video)\n Stream.Demuxer.DisableStream(Stream);\n else\n Stream.Demuxer.Dispose();\n }\n\n if (frame != null)\n fixed (AVFrame** ptr = &frame)\n av_frame_free(ptr);\n\n if (codecCtx != null)\n fixed (AVCodecContext** ptr = &codecCtx)\n avcodec_free_context(ptr);\n\n codecCtx = null;\n demuxer = null;\n Stream = null;\n Status = Status.Stopped;\n Disposed = true;\n Log.Info(\"Disposed\");\n }\n }\n protected abstract void DisposeInternal();\n}\n"], ["/LLPlayer/FlyleafLib/MediaPlayer/Translation/Services/DeepLTranslateService.cs", "using System.Threading;\nusing System.Threading.Tasks;\nusing DeepL;\nusing DeepL.Model;\n\nnamespace FlyleafLib.MediaPlayer.Translation.Services;\n\n#nullable enable\n\npublic class DeepLTranslateService : ITranslateService\n{\n private string? _srcLang;\n private string? _targetLang;\n private readonly Translator _translator;\n private readonly DeepLTranslateSettings _settings;\n\n public DeepLTranslateService(DeepLTranslateSettings settings)\n {\n if (string.IsNullOrWhiteSpace(settings.ApiKey))\n {\n throw new TranslationConfigException(\n $\"API Key for {ServiceType} is not configured.\");\n }\n\n _settings = settings;\n _translator = new Translator(_settings.ApiKey, new TranslatorOptions()\n {\n OverallConnectionTimeout = TimeSpan.FromMilliseconds(settings.TimeoutMs)\n });\n }\n\n public TranslateServiceType ServiceType => TranslateServiceType.DeepL;\n\n public void Dispose()\n {\n _translator.Dispose();\n }\n\n public void Initialize(Language src, TargetLanguage target)\n {\n (TranslateLanguage srcLang, _) = this.TryGetLanguage(src, target);\n\n _srcLang = ToSourceCode(srcLang.ISO6391);\n _targetLang = ToTargetCode(target);\n }\n\n internal static string ToSourceCode(string iso6391)\n {\n // ref: https://developers.deepl.com/docs/resources/supported-languages\n\n // Just capitalize ISO6391.\n return iso6391.ToUpper();\n }\n\n internal static string ToTargetCode(TargetLanguage target)\n {\n return target switch\n {\n TargetLanguage.EnglishAmerican => \"EN-US\",\n TargetLanguage.EnglishBritish => \"EN-GB\",\n TargetLanguage.Portuguese => \"PT-PT\",\n TargetLanguage.PortugueseBrazilian => \"PT-BR\",\n TargetLanguage.ChineseSimplified => \"ZH-HANS\",\n TargetLanguage.ChineseTraditional => \"ZH-HANT\",\n _ => target.ToISO6391().ToUpper()\n };\n }\n\n public async Task TranslateAsync(string text, CancellationToken token)\n {\n if (_srcLang == null || _targetLang == null)\n throw new InvalidOperationException(\"must be initialized\");\n\n try\n {\n TextResult result = await _translator.TranslateTextAsync(text, _srcLang, _targetLang,\n new TextTranslateOptions\n {\n Formality = Formality.Default,\n }, token).ConfigureAwait(false);\n\n return result.Text;\n }\n catch (OperationCanceledException)\n {\n throw;\n }\n catch (Exception ex)\n {\n // Timeout: DeepL.ConnectionException\n throw new TranslationException($\"Cannot request to {ServiceType}: {ex.Message}\", ex);\n }\n }\n}\n"], ["/LLPlayer/FlyleafLib/MediaPlayer/Activity.cs", "using System.Diagnostics;\nusing System.Windows.Forms;\n\nnamespace FlyleafLib.MediaPlayer;\n\npublic class Activity : NotifyPropertyChanged\n{\n /* Player Activity Mode ( Idle / Active / FullActive )\n *\n * Required Engine's Thread (UIRefresh)\n *\n * TODO: Static?\n */\n\n public ActivityMode Mode\n {\n get => mode;\n set {\n\n if (value == mode)\n return;\n\n mode = value;\n\n if (value == ActivityMode.Idle)\n {\n swKeyboard.Reset();\n swMouse.Reset();\n }\n else if (value == ActivityMode.Active)\n swKeyboard.Restart();\n else\n swMouse.Restart();\n\n Utils.UI(() => SetMode());\n }\n }\n internal ActivityMode _Mode = ActivityMode.FullActive, mode = ActivityMode.FullActive;\n\n /// \n /// Should use Timeout to Enable/Disable it. Use this only for temporary disable.\n /// \n public bool IsEnabled { get => _IsEnabled;\n set {\n\n if (value && _Timeout <= 0)\n {\n if (_IsEnabled)\n {\n _IsEnabled = false;\n RaiseUI(nameof(IsEnabled));\n }\n else\n _IsEnabled = false;\n\n }\n else\n {\n if (_IsEnabled == value)\n return;\n\n if (value)\n {\n swKeyboard.Restart();\n swMouse.Restart();\n }\n\n _IsEnabled = value;\n RaiseUI(nameof(IsEnabled));\n }\n }\n }\n bool _IsEnabled;\n\n public int Timeout { get => _Timeout; set { _Timeout = value; IsEnabled = value > 0; } }\n int _Timeout;\n\n Player player;\n Stopwatch swKeyboard = new();\n Stopwatch swMouse = new();\n\n public Activity(Player player) => this.player = player;\n\n /// \n /// Updates Mode UI value and shows/hides mouse cursor if required\n /// Must be called from a UI Thread\n /// \n internal void SetMode()\n {\n _Mode = mode;\n Raise(nameof(Mode));\n player.Log.Trace(mode.ToString());\n\n if (player.Activity.Mode == ActivityMode.Idle && player.Host != null /*&& player.Host.Player_GetFullScreen() */&& player.Host.Player_CanHideCursor())\n {\n lock (cursorLocker)\n {\n while (Utils.NativeMethods.ShowCursor(false) >= 0) { }\n isCursorHidden = true;\n }\n\n }\n else if (isCursorHidden && player.Activity.Mode == ActivityMode.FullActive)\n {\n lock (cursorLocker)\n {\n while (Utils.NativeMethods.ShowCursor(true) < 0) { }\n isCursorHidden = false;\n }\n }\n }\n\n /// \n /// Refreshes mode value based on current timestamps\n /// \n internal void RefreshMode()\n {\n if (!IsEnabled)\n mode = ActivityMode.FullActive;\n else mode = swMouse.IsRunning && swMouse.ElapsedMilliseconds < Timeout\n ? ActivityMode.FullActive\n : swKeyboard.IsRunning && swKeyboard.ElapsedMilliseconds < Timeout ? ActivityMode.Active : ActivityMode.Idle;\n }\n\n /// \n /// Sets Mode to Idle\n /// \n public void ForceIdle()\n {\n if (Timeout > 0)\n Mode = ActivityMode.Idle;\n }\n /// \n /// Sets Mode to Active\n /// \n public void ForceActive() => Mode = ActivityMode.Active;\n /// \n /// Sets Mode to Full Active\n /// \n public void ForceFullActive() => Mode = ActivityMode.FullActive;\n\n /// \n /// Updates Active Timestamp\n /// \n public void RefreshActive() => swKeyboard.Restart();\n\n /// \n /// Updates Full Active Timestamp\n /// \n public void RefreshFullActive() => swMouse.Restart();\n\n #region Ensures we catch the mouse move even when the Cursor is hidden\n static bool isCursorHidden;\n static object cursorLocker = new();\n public class GlobalMouseHandler : IMessageFilter\n {\n public bool PreFilterMessage(ref Message m)\n {\n if (isCursorHidden && m.Msg == 0x0200)\n {\n try\n {\n lock (cursorLocker)\n {\n while (Utils.NativeMethods.ShowCursor(true) < 0) { }\n isCursorHidden = false;\n foreach(var player in Engine.Players)\n player.Activity.RefreshFullActive();\n }\n\n } catch { }\n }\n\n return false;\n }\n }\n static Activity()\n {\n GlobalMouseHandler gmh = new();\n Application.AddMessageFilter(gmh);\n }\n #endregion\n}\n\npublic enum ActivityMode\n{\n Idle,\n Active, // Keyboard only\n FullActive // Mouse\n}\n"], ["/LLPlayer/FlyleafLib/MediaFramework/MediaContext/DecoderContext.cs", "using FlyleafLib.MediaFramework.MediaDecoder;\nusing FlyleafLib.MediaFramework.MediaDemuxer;\nusing FlyleafLib.MediaFramework.MediaRemuxer;\nusing FlyleafLib.MediaFramework.MediaStream;\nusing FlyleafLib.MediaPlayer;\nusing FlyleafLib.Plugins;\n\nusing static FlyleafLib.Logger;\nusing static FlyleafLib.Utils;\n\nnamespace FlyleafLib.MediaFramework.MediaContext;\n\npublic unsafe partial class DecoderContext : PluginHandler\n{\n /* TODO\n *\n * 1) Lock delay on demuxers' Format Context (for network streams)\n * Ensure we interrupt if we are planning to seek\n * Merge Seek witih GetVideoFrame (To seek accurate or to ensure keyframe)\n * Long delay on Enable/Disable demuxer's streams (lock might not required)\n *\n * 2) Resync implementation / CurTime\n * Transfer player's resync implementation here\n * Ensure we can trust CurTime on lower level (eg. on decoders - demuxers using dts)\n *\n * 3) Timestamps / Memory leak\n * If we have embedded audio/video and the audio decoder will stop/fail for some reason the demuxer will keep filling audio packets\n * Should also check at lower level (demuxer) to prevent wrong packet timestamps (too early or too late)\n * This is normal if it happens on live HLS (probably an ffmpeg bug)\n */\n\n #region Properties\n public object Tag { get; set; } // Upper Layer Object (eg. Player, Downloader) - mainly for plugins to access it\n public bool EnableDecoding { get; set; }\n public new bool Interrupt\n {\n get => base.Interrupt;\n set\n {\n base.Interrupt = value;\n\n if (value)\n {\n VideoDemuxer.Interrupter.ForceInterrupt = 1;\n AudioDemuxer.Interrupter.ForceInterrupt = 1;\n\n for (int i = 0; i < subNum; i++)\n {\n SubtitlesDemuxers[i].Interrupter.ForceInterrupt = 1;\n }\n DataDemuxer.Interrupter.ForceInterrupt = 1;\n }\n else\n {\n VideoDemuxer.Interrupter.ForceInterrupt = 0;\n AudioDemuxer.Interrupter.ForceInterrupt = 0;\n\n for (int i = 0; i < subNum; i++)\n {\n SubtitlesDemuxers[i].Interrupter.ForceInterrupt = 0;\n }\n DataDemuxer.Interrupter.ForceInterrupt = 0;\n }\n }\n }\n\n /// \n /// It will not resync by itself. Requires manual call to ReSync()\n /// \n public bool RequiresResync { get; set; }\n\n public string Extension => VideoDemuxer.Disposed ? AudioDemuxer.Extension : VideoDemuxer.Extension;\n\n // Demuxers\n public Demuxer MainDemuxer { get; private set; }\n public Demuxer AudioDemuxer { get; private set; }\n public Demuxer VideoDemuxer { get; private set; }\n // Demuxer for external subtitles, currently not used for subtitles, just used for stream info\n // Subtitles are displayed using SubtitlesManager\n public Demuxer[] SubtitlesDemuxers { get; private set; }\n public SubtitlesManager SubtitlesManager { get; private set; }\n\n public SubtitlesOCR SubtitlesOCR { get; private set; }\n public SubtitlesASR SubtitlesASR { get; private set; }\n\n public Demuxer DataDemuxer { get; private set; }\n\n // Decoders\n public AudioDecoder AudioDecoder { get; private set; }\n public VideoDecoder VideoDecoder { get; internal set;}\n public SubtitlesDecoder[] SubtitlesDecoders { get; private set; }\n public DataDecoder DataDecoder { get; private set; }\n public DecoderBase GetDecoderPtr(StreamBase stream)\n {\n switch (stream.Type)\n {\n case MediaType.Audio:\n return AudioDecoder;\n case MediaType.Video:\n return VideoDecoder;\n case MediaType.Data:\n return DataDecoder;\n case MediaType.Subs:\n return SubtitlesDecoders[SubtitlesSelectedHelper.CurIndex];\n default:\n throw new InvalidOperationException();\n }\n }\n // Streams\n public AudioStream AudioStream => (VideoDemuxer?.AudioStream) ?? AudioDemuxer.AudioStream;\n public VideoStream VideoStream => VideoDemuxer?.VideoStream;\n public SubtitlesStream[] SubtitlesStreams\n {\n get\n {\n SubtitlesStream[] streams = new SubtitlesStream[subNum];\n\n for (int i = 0; i < subNum; i++)\n {\n if (VideoDemuxer?.SubtitlesStreams?[i] != null)\n {\n streams[i] = VideoDemuxer.SubtitlesStreams[i];\n }\n else if (SubtitlesDemuxers[i]?.SubtitlesStreams?[i] != null)\n {\n streams[i] = SubtitlesDemuxers[i].SubtitlesStreams[i];\n }\n }\n\n return streams;\n }\n }\n public DataStream DataStream => (VideoDemuxer?.DataStream) ?? DataDemuxer.DataStream;\n\n public Tuple ClosedAudioStream { get; private set; }\n public Tuple ClosedVideoStream { get; private set; }\n #endregion\n\n #region Initialize\n LogHandler Log;\n bool shouldDispose;\n int subNum => Config.Subtitles.Max;\n\n public DecoderContext(Config config = null, int uniqueId = -1, bool enableDecoding = true) : base(config, uniqueId)\n {\n Log = new LogHandler((\"[#\" + UniqueId + \"]\").PadRight(8, ' ') + \" [DecoderContext] \");\n Playlist.decoder = this;\n\n EnableDecoding = enableDecoding;\n\n AudioDemuxer = new Demuxer(Config.Demuxer, MediaType.Audio, UniqueId, EnableDecoding);\n VideoDemuxer = new Demuxer(Config.Demuxer, MediaType.Video, UniqueId, EnableDecoding);\n SubtitlesDemuxers = new Demuxer[subNum];\n for (int i = 0; i < subNum; i++)\n {\n SubtitlesDemuxers[i] = new Demuxer(Config.Demuxer, MediaType.Subs, UniqueId, EnableDecoding);\n }\n DataDemuxer = new Demuxer(Config.Demuxer, MediaType.Data, UniqueId, EnableDecoding);\n\n SubtitlesManager = new SubtitlesManager(Config, subNum);\n SubtitlesOCR = new SubtitlesOCR(Config.Subtitles, subNum);\n SubtitlesASR = new SubtitlesASR(SubtitlesManager, Config);\n\n Recorder = new Remuxer(UniqueId);\n\n VideoDecoder = new VideoDecoder(Config, UniqueId);\n AudioDecoder = new AudioDecoder(Config, UniqueId, VideoDecoder);\n SubtitlesDecoders = new SubtitlesDecoder[subNum];\n for (int i = 0; i < subNum; i++)\n {\n SubtitlesDecoders[i] = new SubtitlesDecoder(Config, UniqueId, i);\n }\n DataDecoder = new DataDecoder(Config, UniqueId);\n\n if (EnableDecoding && config.Player.Usage != MediaPlayer.Usage.Audio)\n VideoDecoder.CreateRenderer();\n\n VideoDecoder.recCompleted = RecordCompleted;\n AudioDecoder.recCompleted = RecordCompleted;\n }\n\n public void Initialize()\n {\n VideoDecoder.Renderer?.ClearScreen();\n RequiresResync = false;\n\n OnInitializing();\n Stop();\n OnInitialized();\n }\n public void InitializeSwitch()\n {\n VideoDecoder.Renderer?.ClearScreen();\n RequiresResync = false;\n ClosedAudioStream = null;\n ClosedVideoStream = null;\n\n OnInitializingSwitch();\n Stop();\n OnInitializedSwitch();\n }\n #endregion\n\n #region Seek\n public int Seek(long ms = -1, bool forward = false, bool seekInQueue = true)\n {\n int ret = 0;\n\n if (ms == -1) ms = GetCurTimeMs();\n\n // Review decoder locks (lockAction should be added to avoid dead locks with flush mainly before lockCodecCtx)\n AudioDecoder.resyncWithVideoRequired = false; // Temporary to avoid dead lock on AudioDecoder.lockCodecCtx\n lock (VideoDecoder.lockCodecCtx)\n lock (AudioDecoder.lockCodecCtx)\n lock (SubtitlesDecoders[0].lockCodecCtx)\n lock (SubtitlesDecoders[1].lockCodecCtx)\n lock (DataDecoder.lockCodecCtx)\n {\n long seekTimestamp = CalcSeekTimestamp(VideoDemuxer, ms, ref forward);\n\n // Should exclude seek in queue for all \"local/fast\" files\n lock (VideoDemuxer.lockActions)\n if (Playlist.InputType == InputType.Torrent || ms == 0 || !seekInQueue || VideoDemuxer.SeekInQueue(seekTimestamp, forward) != 0)\n {\n VideoDemuxer.Interrupter.ForceInterrupt = 1;\n OpenedPlugin.OnBuffering();\n lock (VideoDemuxer.lockFmtCtx)\n {\n if (VideoDemuxer.Disposed) { VideoDemuxer.Interrupter.ForceInterrupt = 0; return -1; }\n ret = VideoDemuxer.Seek(seekTimestamp, forward);\n }\n }\n\n VideoDecoder.Flush();\n if (ms == 0)\n VideoDecoder.keyPacketRequired = false; // TBR\n\n if (AudioStream != null && AudioDecoder.OnVideoDemuxer)\n {\n AudioDecoder.Flush();\n if (ms == 0)\n AudioDecoder.nextPts = AudioDecoder.Stream.StartTimePts;\n }\n\n for (int i = 0; i < subNum; i++)\n {\n if (SubtitlesStreams[i] != null && SubtitlesDecoders[i].OnVideoDemuxer)\n {\n SubtitlesDecoders[i].Flush();\n }\n }\n\n if (DataStream != null && DataDecoder.OnVideoDemuxer)\n DataDecoder.Flush();\n }\n\n if (AudioStream != null && !AudioDecoder.OnVideoDemuxer)\n {\n AudioDecoder.Pause();\n AudioDecoder.Flush();\n AudioDemuxer.PauseOnQueueFull = true;\n RequiresResync = true;\n }\n\n //for (int i = 0; i < subNum; i++)\n //{\n // if (SubtitlesStreams[i] != null && !SubtitlesDecoders[i].OnVideoDemuxer)\n // {\n // SubtitlesDecoders[i].Pause();\n // SubtitlesDecoders[i].Flush();\n // SubtitlesDemuxers[i].PauseOnQueueFull = true;\n // RequiresResync = true;\n // }\n //}\n\n if (DataStream != null && !DataDecoder.OnVideoDemuxer)\n {\n DataDecoder.Pause();\n DataDecoder.Flush();\n DataDemuxer.PauseOnQueueFull = true;\n RequiresResync = true;\n }\n\n return ret;\n }\n public int SeekAudio(long ms = -1, bool forward = false)\n {\n int ret = 0;\n\n if (AudioDemuxer.Disposed || AudioDecoder.OnVideoDemuxer || !Config.Audio.Enabled) return -1;\n\n if (ms == -1) ms = GetCurTimeMs();\n\n long seekTimestamp = CalcSeekTimestamp(AudioDemuxer, ms, ref forward);\n\n AudioDecoder.resyncWithVideoRequired = false; // Temporary to avoid dead lock on AudioDecoder.lockCodecCtx\n lock (AudioDecoder.lockActions)\n lock (AudioDecoder.lockCodecCtx)\n {\n lock (AudioDemuxer.lockActions)\n if (AudioDemuxer.SeekInQueue(seekTimestamp, forward) != 0)\n ret = AudioDemuxer.Seek(seekTimestamp, forward);\n\n AudioDecoder.Flush();\n if (VideoDecoder.IsRunning)\n {\n AudioDemuxer.Start();\n AudioDecoder.Start();\n }\n }\n\n return ret;\n }\n\n //public int SeekSubtitles(int subIndex = -1, long ms = -1, bool forward = false)\n //{\n // int ret = -1;\n\n // if (!Config.Subtitles.Enabled)\n // return ret;\n\n // // all sub streams\n // int startIndex = 0;\n // int endIndex = subNum - 1;\n // if (subIndex != -1)\n // {\n // // specific sub stream\n // startIndex = subIndex;\n // endIndex = subIndex;\n // }\n\n // for (int i = startIndex; i <= endIndex; i++)\n // {\n // // Perform seek only for external subtitles\n // if (SubtitlesDemuxers[i].Disposed || SubtitlesDecoders[i].OnVideoDemuxer)\n // {\n // continue;\n // }\n\n // long localMs = ms;\n // if (localMs == -1)\n // {\n // localMs = GetCurTimeMs();\n // }\n\n // long seekTimestamp = CalcSeekTimestamp(SubtitlesDemuxers[i], localMs, ref forward);\n\n // lock (SubtitlesDecoders[i].lockActions)\n // lock (SubtitlesDecoders[i].lockCodecCtx)\n // {\n // // Currently disabled as it will fail to seek within the queue the most of the times\n // //lock (SubtitlesDemuxer.lockActions)\n // //if (SubtitlesDemuxer.SeekInQueue(seekTimestamp, forward) != 0)\n // ret = SubtitlesDemuxers[i].Seek(seekTimestamp, forward);\n\n // SubtitlesDecoders[i].Flush();\n // if (VideoDecoder.IsRunning)\n // {\n // SubtitlesDemuxers[i].Start();\n // SubtitlesDecoders[i].Start();\n // }\n // }\n // }\n // return ret;\n //}\n\n public int SeekData(long ms = -1, bool forward = false)\n {\n int ret = 0;\n\n if (DataDemuxer.Disposed || DataDecoder.OnVideoDemuxer)\n return -1;\n\n if (ms == -1)\n ms = GetCurTimeMs();\n\n long seekTimestamp = CalcSeekTimestamp(DataDemuxer, ms, ref forward);\n\n lock (DataDecoder.lockActions)\n lock (DataDecoder.lockCodecCtx)\n {\n ret = DataDemuxer.Seek(seekTimestamp, forward);\n\n DataDecoder.Flush();\n if (VideoDecoder.IsRunning)\n {\n DataDemuxer.Start();\n DataDecoder.Start();\n }\n }\n\n return ret;\n }\n\n public long GetCurTime() => !VideoDemuxer.Disposed ? VideoDemuxer.CurTime : !AudioDemuxer.Disposed ? AudioDemuxer.CurTime : 0;\n public int GetCurTimeMs() => !VideoDemuxer.Disposed ? (int)(VideoDemuxer.CurTime / 10000) : (!AudioDemuxer.Disposed ? (int)(AudioDemuxer.CurTime / 10000) : 0);\n\n private long CalcSeekTimestamp(Demuxer demuxer, long ms, ref bool forward)\n {\n long startTime = demuxer.hlsCtx == null ? demuxer.StartTime : demuxer.hlsCtx->first_timestamp * 10;\n long ticks = (ms * 10000) + startTime;\n\n if (demuxer.Type == MediaType.Audio) ticks -= Config.Audio.Delay;\n //if (demuxer.Type == MediaType.Subs)\n //{\n // int i = SubtitlesDemuxers[0] == demuxer ? 0 : 1;\n // ticks -= Config.Subtitles[i].Delay + (2 * 1000 * 10000); // We even want the previous subtitles\n //}\n\n if (ticks < startTime)\n {\n ticks = startTime;\n forward = true;\n }\n else if (ticks > startTime + (!VideoDemuxer.Disposed ? VideoDemuxer.Duration : AudioDemuxer.Duration) - (50 * 10000))\n {\n ticks = Math.Max(startTime, startTime + demuxer.Duration - (50 * 10000));\n forward = false;\n }\n\n return ticks;\n }\n #endregion\n\n #region Start/Pause/Stop\n public void Pause()\n {\n VideoDecoder.Pause();\n AudioDecoder.Pause();\n for (int i = 0; i < subNum; i++)\n {\n SubtitlesDecoders[i].Pause();\n }\n DataDecoder.Pause();\n\n VideoDemuxer.Pause();\n AudioDemuxer.Pause();\n for (int i = 0; i < subNum; i++)\n {\n SubtitlesDemuxers[i].Pause();\n }\n DataDemuxer.Pause();\n }\n public void PauseDecoders()\n {\n VideoDecoder.Pause();\n AudioDecoder.Pause();\n for (int i = 0; i < subNum; i++)\n {\n SubtitlesDecoders[i].Pause();\n }\n DataDecoder.Pause();\n }\n public void PauseOnQueueFull()\n {\n VideoDemuxer.PauseOnQueueFull = true;\n AudioDemuxer.PauseOnQueueFull = true;\n for (int i = 0; i < subNum; i++)\n {\n SubtitlesDemuxers[i].PauseOnQueueFull = true;\n }\n DataDecoder.PauseOnQueueFull = true;\n }\n public void Start()\n {\n //if (RequiresResync) Resync();\n\n if (Config.Audio.Enabled)\n {\n AudioDemuxer.Start();\n AudioDecoder.Start();\n }\n\n if (Config.Video.Enabled)\n {\n VideoDemuxer.Start();\n VideoDecoder.Start();\n }\n\n if (Config.Subtitles.Enabled)\n {\n for (int i = 0; i < subNum; i++)\n {\n //if (SubtitlesStreams[i] != null && !SubtitlesDecoders[i].OnVideoDemuxer)\n // SubtitlesDemuxers[i].Start();\n\n //if (SubtitlesStreams[i] != null)\n if (SubtitlesStreams[i] != null && SubtitlesDecoders[i].OnVideoDemuxer)\n SubtitlesDecoders[i].Start();\n }\n }\n\n if (Config.Data.Enabled)\n {\n DataDemuxer.Start();\n DataDecoder.Start();\n }\n }\n public void Stop()\n {\n Interrupt = true;\n\n VideoDecoder.Dispose();\n AudioDecoder.Dispose();\n for (int i = 0; i < subNum; i++)\n {\n SubtitlesDecoders[i].Dispose();\n }\n\n DataDecoder.Dispose();\n AudioDemuxer.Dispose();\n for (int i = 0; i < subNum; i++)\n {\n SubtitlesDemuxers[i].Dispose();\n }\n\n DataDemuxer.Dispose();\n VideoDemuxer.Dispose();\n\n Interrupt = false;\n }\n public void StopThreads()\n {\n Interrupt = true;\n\n VideoDecoder.Stop();\n AudioDecoder.Stop();\n for (int i = 0; i < subNum; i++)\n {\n SubtitlesDecoders[i].Stop();\n }\n\n DataDecoder.Stop();\n AudioDemuxer.Stop();\n for (int i = 0; i < subNum; i++)\n {\n SubtitlesDemuxers[i].Stop();\n }\n DataDemuxer.Stop();\n VideoDemuxer.Stop();\n\n Interrupt = false;\n }\n #endregion\n\n public void Resync(long timestamp = -1)\n {\n bool isRunning = VideoDemuxer.IsRunning;\n\n if (AudioStream != null && AudioStream.Demuxer.Type != MediaType.Video && Config.Audio.Enabled)\n {\n if (timestamp == -1) timestamp = VideoDemuxer.CurTime;\n if (CanInfo) Log.Info($\"Resync audio to {TicksToTime(timestamp)}\");\n\n SeekAudio(timestamp / 10000);\n if (isRunning)\n {\n AudioDemuxer.Start();\n AudioDecoder.Start();\n }\n }\n\n //for (int i = 0; i < subNum; i++)\n //{\n // if (SubtitlesStreams[i] != null && SubtitlesStreams[i].Demuxer.Type != MediaType.Video && Config.Subtitles.Enabled)\n // {\n // if (timestamp == -1)\n // timestamp = VideoDemuxer.CurTime;\n // if (CanInfo)\n // Log.Info($\"Resync subs:{i} to {TicksToTime(timestamp)}\");\n\n // SeekSubtitles(i, timestamp / 10000, false);\n // if (isRunning)\n // {\n // SubtitlesDemuxers[i].Start();\n // SubtitlesDecoders[i].Start();\n // }\n // }\n //}\n\n if (DataStream != null && Config.Data.Enabled) // Should check if it actually an external (not embedded) stream DataStream.Demuxer.Type != MediaType.Video ?\n {\n if (timestamp == -1)\n timestamp = VideoDemuxer.CurTime;\n if (CanInfo)\n Log.Info($\"Resync data to {TicksToTime(timestamp)}\");\n\n SeekData(timestamp / 10000);\n if (isRunning)\n {\n DataDemuxer.Start();\n DataDecoder.Start();\n }\n }\n\n RequiresResync = false;\n }\n\n //public void ResyncSubtitles(long timestamp = -1)\n //{\n // if (SubtitlesStream != null && Config.Subtitles.Enabled)\n // {\n // if (timestamp == -1) timestamp = VideoDemuxer.CurTime;\n // if (CanInfo) Log.Info($\"Resync subs to {TicksToTime(timestamp)}\");\n\n // if (SubtitlesStream.Demuxer.Type != MediaType.Video)\n // SeekSubtitles(timestamp / 10000);\n // else\n\n // if (VideoDemuxer.IsRunning)\n // {\n // SubtitlesDemuxer.Start();\n // SubtitlesDecoder.Start();\n // }\n // }\n //}\n public void Flush()\n {\n VideoDemuxer.DisposePackets();\n AudioDemuxer.DisposePackets();\n for (int i = 0; i < subNum; i++)\n {\n SubtitlesDemuxers[i].DisposePackets();\n }\n DataDemuxer.DisposePackets();\n\n VideoDecoder.Flush();\n AudioDecoder.Flush();\n for (int i = 0; i < subNum; i++)\n {\n SubtitlesDecoders[i].Flush();\n }\n DataDecoder.Flush();\n }\n\n // !!! NEEDS RECODING\n public long GetVideoFrame(long timestamp = -1)\n {\n // TBR: Between seek and GetVideoFrame lockCodecCtx is lost and if VideoDecoder is running will already have decoded some frames (Currently ensure you pause VideDecoder before seek)\n\n int ret;\n int allowedErrors = Config.Decoder.MaxErrors;\n AVPacket* packet;\n\n lock (VideoDemuxer.lockFmtCtx)\n lock (VideoDecoder.lockCodecCtx)\n while (VideoDemuxer.VideoStream != null && !Interrupt)\n {\n if (VideoDemuxer.VideoPackets.IsEmpty)\n {\n packet = av_packet_alloc();\n VideoDemuxer.Interrupter.ReadRequest();\n ret = av_read_frame(VideoDemuxer.FormatContext, packet);\n if (ret != 0)\n {\n av_packet_free(&packet);\n return -1;\n }\n }\n else\n packet = VideoDemuxer.VideoPackets.Dequeue();\n\n if (!VideoDemuxer.EnabledStreams.Contains(packet->stream_index)) { av_packet_free(&packet); continue; }\n\n if (CanTrace)\n {\n var stream = VideoDemuxer.AVStreamToStream[packet->stream_index];\n long dts = packet->dts == AV_NOPTS_VALUE ? -1 : (long)(packet->dts * stream.Timebase);\n long pts = packet->pts == AV_NOPTS_VALUE ? -1 : (long)(packet->pts * stream.Timebase);\n Log.Trace($\"[{stream.Type}] DTS: {(dts == -1 ? \"-\" : TicksToTime(dts))} PTS: {(pts == -1 ? \"-\" : TicksToTime(pts))} | FLPTS: {(pts == -1 ? \"-\" : TicksToTime(pts - VideoDemuxer.StartTime))} | CurTime: {TicksToTime(VideoDemuxer.CurTime)} | Buffered: {TicksToTime(VideoDemuxer.BufferedDuration)}\");\n }\n\n var codecType = VideoDemuxer.FormatContext->streams[packet->stream_index]->codecpar->codec_type;\n\n if (codecType == AVMediaType.Video && VideoDecoder.keyPacketRequired)\n {\n if (packet->flags.HasFlag(PktFlags.Key))\n VideoDecoder.keyPacketRequired = false;\n else\n {\n if (CanWarn) Log.Warn(\"Ignoring non-key packet\");\n av_packet_free(&packet);\n continue;\n }\n }\n\n if (VideoDemuxer.IsHLSLive)\n VideoDemuxer.UpdateHLSTime();\n\n switch (codecType)\n {\n case AVMediaType.Audio:\n if (timestamp == -1 || (long)(packet->pts * AudioStream.Timebase) - VideoDemuxer.StartTime + (VideoStream.FrameDuration / 2) > timestamp)\n VideoDemuxer.AudioPackets.Enqueue(packet);\n else\n av_packet_free(&packet);\n\n continue;\n\n case AVMediaType.Subtitle:\n for (int i = 0; i < subNum; i++)\n {\n if (SubtitlesStreams[i]?.StreamIndex != packet->stream_index)\n {\n continue;\n }\n\n if (timestamp == -1 ||\n (long)(packet->pts * SubtitlesStreams[i].Timebase) - VideoDemuxer.StartTime +\n (VideoStream.FrameDuration / 2) > timestamp)\n {\n // Clone packets to support simultaneous display of the same subtitle\n VideoDemuxer.SubtitlesPackets[i].Enqueue(av_packet_clone(packet));\n }\n }\n\n // cloned, so free packet\n av_packet_free(&packet);\n\n continue;\n\n case AVMediaType.Data: // this should catch the data stream packets until we have a valid vidoe keyframe (it should fill the pts if NOPTS with lastVideoPacketPts similarly to the demuxer)\n if ((timestamp == -1 && VideoDecoder.StartTime != NoTs) || (long)(packet->pts * DataStream.Timebase) - VideoDemuxer.StartTime + (VideoStream.FrameDuration / 2) > timestamp)\n VideoDemuxer.DataPackets.Enqueue(packet);\n\n packet = av_packet_alloc();\n\n continue;\n\n case AVMediaType.Video:\n ret = avcodec_send_packet(VideoDecoder.CodecCtx, packet);\n\n if (VideoDecoder.swFallback)\n {\n VideoDecoder.SWFallback();\n ret = avcodec_send_packet(VideoDecoder.CodecCtx, packet);\n }\n\n av_packet_free(&packet);\n\n if (ret != 0)\n {\n allowedErrors--;\n if (CanWarn) Log.Warn($\"{FFmpegEngine.ErrorCodeToMsg(ret)} ({ret})\");\n\n if (allowedErrors == 0) { Log.Error(\"Too many errors!\"); return -1; }\n\n continue;\n }\n\n //VideoDemuxer.UpdateCurTime();\n\n var frame = av_frame_alloc();\n while (VideoDemuxer.VideoStream != null && !Interrupt)\n {\n ret = avcodec_receive_frame(VideoDecoder.CodecCtx, frame);\n if (ret != 0) { av_frame_unref(frame); break; }\n\n if (frame->best_effort_timestamp != AV_NOPTS_VALUE)\n frame->pts = frame->best_effort_timestamp;\n else if (frame->pts == AV_NOPTS_VALUE)\n {\n if (!VideoStream.FixTimestamps)\n {\n av_frame_unref(frame);\n continue;\n }\n\n frame->pts = VideoDecoder.lastFixedPts + VideoStream.StartTimePts;\n VideoDecoder.lastFixedPts += av_rescale_q(VideoStream.FrameDuration / 10, Engine.FFmpeg.AV_TIMEBASE_Q, VideoStream.AVStream->time_base);\n }\n\n if (!VideoDecoder.filledFromCodec)\n {\n ret = VideoDecoder.FillFromCodec(frame);\n\n if (ret == -1234)\n {\n av_frame_free(&frame);\n return -1;\n }\n }\n\n // Accurate seek with +- half frame distance\n if (timestamp != -1 && (long)(frame->pts * VideoStream.Timebase) - VideoDemuxer.StartTime + (VideoStream.FrameDuration / 2) < timestamp)\n {\n av_frame_unref(frame);\n continue;\n }\n\n //if (CanInfo) Info($\"Asked for {Utils.TicksToTime(timestamp)} and got {Utils.TicksToTime((long)(frame->pts * VideoStream.Timebase) - VideoDemuxer.StartTime)} | Diff {Utils.TicksToTime(timestamp - ((long)(frame->pts * VideoStream.Timebase) - VideoDemuxer.StartTime))}\");\n VideoDecoder.StartTime = (long)(frame->pts * VideoStream.Timebase) - VideoDemuxer.StartTime;\n\n var mFrame = VideoDecoder.Renderer.FillPlanes(frame);\n if (mFrame != null) VideoDecoder.Frames.Enqueue(mFrame);\n\n do\n {\n ret = avcodec_receive_frame(VideoDecoder.CodecCtx, frame);\n if (ret != 0) break;\n mFrame = VideoDecoder.Renderer.FillPlanes(frame);\n if (mFrame != null) VideoDecoder.Frames.Enqueue(mFrame);\n } while (!VideoDemuxer.Disposed && !Interrupt);\n\n av_frame_free(&frame);\n return mFrame.timestamp;\n }\n\n av_frame_free(&frame);\n\n break; // Switch break\n\n default:\n av_packet_free(&packet);\n continue;\n\n } // Switch\n\n } // While\n\n return -1;\n }\n public new void Dispose()\n {\n shouldDispose = true;\n Stop();\n Interrupt = true;\n VideoDecoder.DestroyRenderer();\n base.Dispose();\n }\n\n public void PrintStats()\n {\n string dump = \"\\r\\n-===== Streams / Packets / Frames =====-\\r\\n\";\n dump += $\"\\r\\n AudioPackets ({VideoDemuxer.AudioStreams.Count}): {VideoDemuxer.AudioPackets.Count}\";\n dump += $\"\\r\\n VideoPackets ({VideoDemuxer.VideoStreams.Count}): {VideoDemuxer.VideoPackets.Count}\";\n for (int i = 0; i < subNum; i++)\n {\n dump += $\"\\r\\n SubtitlesPackets{i+1} ({VideoDemuxer.SubtitlesStreamsAll.Count}): {VideoDemuxer.SubtitlesPackets[i].Count}\";\n }\n\n dump += $\"\\r\\n AudioPackets ({AudioDemuxer.AudioStreams.Count}): {AudioDemuxer.AudioPackets.Count} (AudioDemuxer)\";\n\n for (int i = 0; i < subNum; i++)\n {\n dump += $\"\\r\\n SubtitlesPackets{i+1} ({SubtitlesDemuxers[i].SubtitlesStreamsAll.Count}): {SubtitlesDemuxers[i].SubtitlesPackets[0].Count} (SubtitlesDemuxer)\";\n }\n\n dump += $\"\\r\\n Video Frames : {VideoDecoder.Frames.Count}\";\n dump += $\"\\r\\n Audio Frames : {AudioDecoder.Frames.Count}\";\n for (int i = 0; i < subNum; i++)\n {\n dump += $\"\\r\\n Subtitles Frames{i+1} : {SubtitlesDecoders[i].Frames.Count}\";\n }\n\n if (CanInfo) Log.Info(dump);\n }\n\n #region Recorder\n Remuxer Recorder;\n public event EventHandler RecordingCompleted;\n public bool IsRecording => VideoDecoder.isRecording || AudioDecoder.isRecording;\n int oldMaxAudioFrames;\n bool recHasVideo;\n public void StartRecording(ref string filename, bool useRecommendedExtension = true)\n {\n if (IsRecording) StopRecording();\n\n oldMaxAudioFrames = -1;\n recHasVideo = false;\n\n if (CanInfo) Log.Info(\"Record Start\");\n\n recHasVideo = !VideoDecoder.Disposed && VideoDecoder.Stream != null;\n\n if (useRecommendedExtension)\n filename = $\"{filename}.{(recHasVideo ? VideoDecoder.Stream.Demuxer.Extension : AudioDecoder.Stream.Demuxer.Extension)}\";\n\n Recorder.Open(filename);\n\n bool failed;\n\n if (recHasVideo)\n {\n failed = Recorder.AddStream(VideoDecoder.Stream.AVStream) != 0;\n if (CanInfo) Log.Info(failed ? \"Failed to add video stream\" : \"Video stream added to the recorder\");\n }\n\n if (!AudioDecoder.Disposed && AudioDecoder.Stream != null)\n {\n failed = Recorder.AddStream(AudioDecoder.Stream.AVStream, !AudioDecoder.OnVideoDemuxer) != 0;\n if (CanInfo) Log.Info(failed ? \"Failed to add audio stream\" : \"Audio stream added to the recorder\");\n }\n\n if (!Recorder.HasStreams || Recorder.WriteHeader() != 0) return; //throw new Exception(\"Invalid remuxer configuration\");\n\n // Check also buffering and possible Diff of first audio/video timestamp to remuxer to ensure sync between each other (shouldn't be more than 30-50ms)\n oldMaxAudioFrames = Config.Decoder.MaxAudioFrames;\n //long timestamp = Math.Max(VideoDemuxer.CurTime + VideoDemuxer.BufferedDuration, AudioDemuxer.CurTime + AudioDemuxer.BufferedDuration) + 1500 * 10000;\n Config.Decoder.MaxAudioFrames = Config.Decoder.MaxVideoFrames;\n\n VideoDecoder.StartRecording(Recorder);\n AudioDecoder.StartRecording(Recorder);\n }\n public void StopRecording()\n {\n if (oldMaxAudioFrames != -1) Config.Decoder.MaxAudioFrames = oldMaxAudioFrames;\n\n VideoDecoder.StopRecording();\n AudioDecoder.StopRecording();\n Recorder.Dispose();\n oldMaxAudioFrames = -1;\n if (CanInfo) Log.Info(\"Record Completed\");\n }\n internal void RecordCompleted(MediaType type)\n {\n if (!recHasVideo || (recHasVideo && type == MediaType.Video))\n {\n StopRecording();\n RecordingCompleted?.Invoke(this, new EventArgs());\n }\n }\n #endregion\n}\n"], ["/LLPlayer/LLPlayer/Extensions/ScrollParentWhenAtMax.cs", "using System.Windows;\nusing System.Windows.Controls;\nusing System.Windows.Input;\nusing System.Windows.Media;\nusing Microsoft.Xaml.Behaviors;\n\nnamespace LLPlayer.Extensions;\n\n/// \n/// Behavior to disable scrolling in ListView\n/// ref: https://stackoverflow.com/questions/1585462/bubbling-scroll-events-from-a-listview-to-its-parent\n/// \npublic class ScrollParentWhenAtMax : Behavior\n{\n protected override void OnAttached()\n {\n base.OnAttached();\n AssociatedObject.PreviewMouseWheel += PreviewMouseWheel;\n }\n\n protected override void OnDetaching()\n {\n AssociatedObject.PreviewMouseWheel -= PreviewMouseWheel;\n base.OnDetaching();\n }\n\n private void PreviewMouseWheel(object sender, MouseWheelEventArgs e)\n {\n var scrollViewer = GetVisualChild(AssociatedObject);\n var scrollPos = scrollViewer!.ContentVerticalOffset;\n if ((scrollPos == scrollViewer.ScrollableHeight && e.Delta < 0)\n || (scrollPos == 0 && e.Delta > 0))\n {\n e.Handled = true;\n MouseWheelEventArgs e2 = new(e.MouseDevice, e.Timestamp, e.Delta);\n e2.RoutedEvent = UIElement.MouseWheelEvent;\n AssociatedObject.RaiseEvent(e2);\n }\n }\n\n private static T? GetVisualChild(DependencyObject parent) where T : Visual\n {\n T? child = null;\n\n int numVisuals = VisualTreeHelper.GetChildrenCount(parent);\n for (int i = 0; i < numVisuals; i++)\n {\n Visual v = (Visual)VisualTreeHelper.GetChild(parent, i);\n child = v as T;\n if (child == null)\n {\n child = GetVisualChild(v);\n }\n\n if (child != null)\n {\n break;\n }\n }\n\n return child;\n }\n}\n"], ["/LLPlayer/FlyleafLib/MediaFramework/MediaDevice/VideoDeviceStream.cs", "using System.Collections.Generic;\nusing System.Linq;\nusing System.Reflection;\n\nusing Vortice.MediaFoundation;\n\nnamespace FlyleafLib.MediaFramework.MediaDevice;\n\npublic class VideoDeviceStream : DeviceStreamBase\n{\n public string MajorType { get; }\n public string SubType { get; }\n public int FrameSizeWidth { get; }\n public int FrameSizeHeight { get; }\n public int FrameRate { get; }\n private string FFmpegFormat { get; }\n\n public VideoDeviceStream(string deviceName, Guid majorType, Guid subType, int frameSizeWidth, int frameSizeHeight, int frameRate, int frameRateDenominator) : base(deviceName)\n {\n MajorType = MediaTypeGuids.Video == majorType ? \"Video\" : \"Unknown\";\n SubType = GetPropertyName(subType);\n FrameSizeWidth = frameSizeWidth;\n FrameSizeHeight = frameSizeHeight;\n FrameRate = frameRate / frameRateDenominator;\n FFmpegFormat = GetFFmpegFormat(SubType);\n Url = $\"fmt://dshow?video={DeviceFriendlyName}&video_size={FrameSizeWidth}x{FrameSizeHeight}&framerate={FrameRate}&{FFmpegFormat}\";\n }\n\n private static string GetPropertyName(Guid guid)\n {\n var type = typeof(VideoFormatGuids);\n foreach (var property in type.GetFields(BindingFlags.Public | BindingFlags.Static))\n if (property.FieldType == typeof(Guid))\n {\n object temp = property.GetValue(null);\n if (temp is Guid value)\n if (value == guid)\n return property.Name.ToUpper();\n }\n\n return null;\n }\n private static unsafe string GetFFmpegFormat(string subType)\n {\n switch (subType)\n {\n case \"MJPG\":\n var descriptorPtr = avcodec_descriptor_get(AVCodecID.Mjpeg);\n return $\"vcodec={Utils.BytePtrToStringUTF8(descriptorPtr->name)}\";\n case \"YUY2\":\n return $\"pixel_format={av_get_pix_fmt_name(AVPixelFormat.Yuyv422)}\";\n case \"NV12\":\n return $\"pixel_format={av_get_pix_fmt_name(AVPixelFormat.Nv12)}\";\n default:\n return \"\";\n }\n }\n public override string ToString() => $\"{SubType}, {FrameSizeWidth}x{FrameSizeHeight}, {FrameRate}FPS\";\n\n #region VideoFormatsViaMediaSource\n public static IList GetVideoFormatsForVideoDevice(string friendlyName, string symbolicLink)\n {\n List formatList = new();\n\n using (var mediaSource = GetMediaSourceFromVideoDevice(symbolicLink))\n {\n if (mediaSource == null)\n return null;\n\n using var sourcePresentationDescriptor = mediaSource.CreatePresentationDescriptor();\n int sourceStreamCount = sourcePresentationDescriptor.StreamDescriptorCount;\n\n for (int i = 0; i < sourceStreamCount; i++)\n {\n var guidMajorType = GetMajorMediaTypeFromPresentationDescriptor(sourcePresentationDescriptor, i);\n if (guidMajorType != MediaTypeGuids.Video)\n continue;\n\n sourcePresentationDescriptor.GetStreamDescriptorByIndex(i, out var streamIsSelected, out var videoStreamDescriptor);\n\n using (videoStreamDescriptor)\n {\n if (streamIsSelected == false)\n continue;\n\n using var typeHandler = videoStreamDescriptor.MediaTypeHandler;\n int mediaTypeCount = typeHandler.MediaTypeCount;\n\n for (int mediaTypeId = 0; mediaTypeId < mediaTypeCount; mediaTypeId++)\n using (var workingMediaType = typeHandler.GetMediaTypeByIndex(mediaTypeId))\n {\n var videoFormat = GetVideoFormatFromMediaType(friendlyName, workingMediaType);\n\n if (videoFormat.SubType != \"NV12\") // NV12 is not playable TODO check support for video formats\n formatList.Add(videoFormat);\n }\n }\n }\n }\n\n return formatList.OrderBy(format => format.SubType).ThenBy(format => format.FrameSizeHeight).ThenBy(format => format.FrameRate).ToList();\n }\n\n private static IMFMediaSource GetMediaSourceFromVideoDevice(string symbolicLink)\n {\n using var attributeContainer = MediaFactory.MFCreateAttributes(2);\n attributeContainer.Set(CaptureDeviceAttributeKeys.SourceType, CaptureDeviceAttributeKeys.SourceTypeVidcap);\n attributeContainer.Set(CaptureDeviceAttributeKeys.SourceTypeVidcapSymbolicLink, symbolicLink);\n\n IMFMediaSource ret = null;\n try\n { ret = MediaFactory.MFCreateDeviceSource(attributeContainer); }\n catch (Exception) { }\n\n return ret;\n }\n\n private static Guid GetMajorMediaTypeFromPresentationDescriptor(IMFPresentationDescriptor presentationDescriptor, int streamIndex)\n {\n presentationDescriptor.GetStreamDescriptorByIndex(streamIndex, out _, out var streamDescriptor);\n\n using (streamDescriptor)\n return GetMajorMediaTypeFromStreamDescriptor(streamDescriptor);\n }\n\n private static Guid GetMajorMediaTypeFromStreamDescriptor(IMFStreamDescriptor streamDescriptor)\n {\n using var pHandler = streamDescriptor.MediaTypeHandler;\n var guidMajorType = pHandler.MajorType;\n\n return guidMajorType;\n }\n\n private static VideoDeviceStream GetVideoFormatFromMediaType(string videoDeviceName, IMFMediaType mediaType)\n {\n // MF_MT_MAJOR_TYPE\n // Major type GUID, we return this as human readable text\n var majorType = mediaType.MajorType;\n\n // MF_MT_SUBTYPE\n // Subtype GUID which describes the basic media type, we return this as human readable text\n var subType = mediaType.GetGUID(MediaTypeAttributeKeys.Subtype);\n\n // MF_MT_FRAME_SIZE\n // the Width and height of a video frame, in pixels\n MediaFactory.MFGetAttributeSize(mediaType, MediaTypeAttributeKeys.FrameSize, out uint frameSizeWidth, out uint frameSizeHeight);\n\n // MF_MT_FRAME_RATE\n // The frame rate is expressed as a ratio.The upper 32 bits of the attribute value contain the numerator and the lower 32 bits contain the denominator.\n // For example, if the frame rate is 30 frames per second(fps), the ratio is 30 / 1.If the frame rate is 29.97 fps, the ratio is 30,000 / 1001.\n // we report this back to the user as a decimal\n MediaFactory.MFGetAttributeRatio(mediaType, MediaTypeAttributeKeys.FrameRate, out uint frameRate, out uint frameRateDenominator);\n\n VideoDeviceStream videoFormat = new(videoDeviceName, majorType, subType, (int)frameSizeWidth,\n (int)frameSizeHeight,\n (int)frameRate,\n (int)frameRateDenominator);\n\n return videoFormat;\n }\n #endregion\n}\n"], ["/LLPlayer/LLPlayer/Controls/Settings/SettingsKeys.xaml.cs", "using System.Collections.ObjectModel;\nusing System.ComponentModel;\nusing System.Configuration;\nusing System.Diagnostics;\nusing System.Windows;\nusing System.Windows.Controls;\nusing System.Windows.Data;\nusing System.Windows.Input;\nusing FlyleafLib.MediaPlayer;\nusing LLPlayer.Converters;\nusing LLPlayer.Extensions;\nusing LLPlayer.Services;\nusing KeyBinding = FlyleafLib.MediaPlayer.KeyBinding;\n\nnamespace LLPlayer.Controls.Settings;\n\npublic partial class SettingsKeys : UserControl\n{\n private SettingsKeysVM VM => (SettingsKeysVM)DataContext;\n\n public SettingsKeys()\n {\n InitializeComponent();\n\n DataContext = ((App)Application.Current).Container.Resolve();\n }\n\n // Enable ComboBox to open when double-clicking a cell in Action\n private void ComboBox_Loaded(object sender, RoutedEventArgs e)\n {\n if (sender is ComboBox comboBox)\n {\n comboBox.IsDropDownOpen = true;\n }\n }\n\n // Scroll to the added record when a new record is added.\n private void KeyBindingsDataGrid_OnSelectionChanged(object sender, SelectionChangedEventArgs e)\n {\n if (VM.CmdLoad!.IsExecuting)\n {\n return;\n }\n\n if (KeyBindingsDataGrid.SelectedItem != null)\n {\n KeyBindingsDataGrid.UpdateLayout();\n KeyBindingsDataGrid.ScrollIntoView(KeyBindingsDataGrid.SelectedItem);\n }\n }\n}\n\npublic class SettingsKeysVM : Bindable\n{\n public FlyleafManager FL { get; }\n\n public SettingsKeysVM(FlyleafManager fl)\n {\n FL = fl;\n\n CmdLoad!.PropertyChanged += (sender, args) =>\n {\n if (args.PropertyName == nameof(CmdLoad.IsExecuting))\n {\n OnPropertyChanged(nameof(CanApply));\n }\n };\n\n List mergeActions = new();\n\n foreach (KeyBindingAction action in Enum.GetValues())\n {\n if (action != KeyBindingAction.Custom)\n {\n mergeActions.Add(new ActionData()\n {\n Action = action,\n Description = action.GetDescription(),\n DisplayName = action.ToString(),\n Group = action.ToGroup()\n });\n }\n }\n\n foreach (CustomKeyBindingAction action in Enum.GetValues())\n {\n mergeActions.Add(new ActionData()\n {\n Action = KeyBindingAction.Custom,\n CustomAction = action,\n Description = action.GetDescription(),\n DisplayName = action.ToString() + @\" ©︎\", // c=custom\n Group = action.ToGroup()\n });\n }\n\n mergeActions.Sort();\n\n Actions = mergeActions;\n\n // Grouping when displaying actions in ComboBox\n _actionsView = (ListCollectionView)CollectionViewSource.GetDefaultView(Actions);\n _actionsView.SortDescriptions.Add(new SortDescription(nameof(ActionData.Group), ListSortDirection.Ascending));\n _actionsView.SortDescriptions.Add(new SortDescription(nameof(ActionData.DisplayName), ListSortDirection.Ascending));\n\n _actionsView.GroupDescriptions!.Add(new PropertyGroupDescription(nameof(ActionData.Group)));\n }\n\n public List Actions { get; }\n private readonly ListCollectionView _actionsView;\n\n public ObservableCollection KeyBindings { get; } = new();\n\n public KeyBindingWrapper? SelectedKeyBinding { get; set => Set(ref field, value); }\n\n public int DuplicationCount\n {\n get;\n set\n {\n if (Set(ref field, value))\n {\n OnPropertyChanged(nameof(CanApply));\n }\n }\n }\n\n // Disable Apply button if there are duplicates or during loading\n public bool CanApply => DuplicationCount == 0 && !CmdLoad!.IsExecuting;\n\n public DelegateCommand? CmdAdd => field ??= new(() =>\n {\n KeyBindingWrapper added = new(new KeyBinding { Action = KeyBindingAction.AudioDelayAdd }, this);\n KeyBindings.Add(added);\n SelectedKeyBinding = added;\n\n added.ValidateShortcut();\n });\n\n public AsyncDelegateCommand? CmdLoad => field ??= new(async () =>\n {\n KeyBindings.Clear();\n DuplicationCount = 0;\n\n var keys = FL.PlayerConfig.Player.KeyBindings.Keys;\n\n var keyBindings = await Task.Run(() =>\n {\n List keyBindings = new(keys.Count);\n\n foreach (var k in keys)\n {\n try\n {\n keyBindings.Add(new KeyBindingWrapper(k, this));\n }\n catch (SettingsPropertyNotFoundException)\n {\n // ignored\n // TODO: L: error handling\n Debug.Fail(\"Weird custom key for settings?\");\n }\n }\n\n return Task.FromResult(keyBindings);\n });\n\n foreach (var b in keyBindings)\n {\n KeyBindings.Add(b);\n }\n });\n\n /// \n /// Reflect customized key settings to Config.\n /// \n public DelegateCommand? CmdApply => field ??= new DelegateCommand(() =>\n {\n foreach (var b in KeyBindings)\n {\n Debug.Assert(!b.Duplicated, \"Duplicate check not working\");\n }\n\n var newKeys = KeyBindings.Select(k => k.ToKeyBinding()).ToList();\n\n foreach (var k in newKeys)\n {\n if (k.Action == KeyBindingAction.Custom)\n {\n if (!Enum.TryParse(k.ActionName, out CustomKeyBindingAction customAction))\n {\n Guards.Fail();\n }\n k.SetAction(FL.Action.CustomActions[customAction], k.IsKeyUp);\n }\n else\n {\n k.SetAction(FL.PlayerConfig.Player.KeyBindings.GetKeyBindingAction(k.Action), k.IsKeyUp);\n }\n }\n\n FL.PlayerConfig.Player.KeyBindings.RemoveAll();\n FL.PlayerConfig.Player.KeyBindings.Keys = newKeys;\n\n }).ObservesCanExecute(() => CanApply);\n}\n\npublic class ActionData : IComparable, IEquatable\n{\n public string Description { get; set; } = null!;\n public string DisplayName { get; set; } = null!;\n public KeyBindingActionGroup Group { get; set; }\n public KeyBindingAction Action { get; set; }\n public CustomKeyBindingAction? CustomAction { get; set; }\n\n public int CompareTo(ActionData? other)\n {\n if (ReferenceEquals(this, other))\n return 0;\n if (other is null)\n return 1;\n return string.Compare(DisplayName, other.DisplayName, StringComparison.Ordinal);\n }\n\n public bool Equals(ActionData? other)\n {\n if (other is null) return false;\n if (ReferenceEquals(this, other)) return true;\n return Action == other.Action && CustomAction == other.CustomAction;\n }\n\n public override bool Equals(object? obj) => obj is ActionData o && Equals(o);\n\n public override int GetHashCode()\n {\n return HashCode.Combine((int)Action, CustomAction);\n }\n}\n\npublic class KeyBindingWrapper : Bindable\n{\n private readonly SettingsKeysVM _parent;\n\n /// \n /// constructor\n /// \n /// \n /// \n /// \n public KeyBindingWrapper(KeyBinding keyBinding, SettingsKeysVM parent)\n {\n ArgumentNullException.ThrowIfNull(parent);\n\n // TODO: L: performance issues when initializing?\n _parent = parent;\n\n Key = keyBinding.Key;\n\n ActionData action = new()\n {\n Action = keyBinding.Action,\n };\n\n if (keyBinding.Action != KeyBindingAction.Custom)\n {\n action.Description = keyBinding.Action.GetDescription();\n action.DisplayName = keyBinding.Action.ToString();\n }\n else if (Enum.TryParse(keyBinding.ActionName, out CustomKeyBindingAction customAction))\n {\n action.CustomAction = customAction;\n action.Description = customAction.GetDescription();\n action.DisplayName = keyBinding.ActionName + @\" ©︎\";\n }\n else\n {\n throw new SettingsPropertyNotFoundException($\"Custom Action '{keyBinding.ActionName}' does not exist.\");\n }\n\n Action = action;\n Alt = keyBinding.Alt;\n Ctrl = keyBinding.Ctrl;\n Shift = keyBinding.Shift;\n IsKeyUp = keyBinding.IsKeyUp;\n IsEnabled = keyBinding.IsEnabled;\n }\n\n public bool IsEnabled\n {\n get;\n set\n {\n if (Set(ref field, value))\n {\n if (!value)\n {\n Duplicated = false;\n DuplicatedInfo = null;\n }\n else\n {\n ValidateShortcut();\n }\n\n ValidateKey(Key);\n }\n }\n }\n\n public bool Alt\n {\n get;\n set\n {\n if (Set(ref field, value) && IsEnabled)\n {\n ValidateShortcut();\n ValidateKey(Key);\n }\n }\n }\n\n public bool Ctrl\n {\n get;\n set\n {\n if (Set(ref field, value) && IsEnabled)\n {\n ValidateShortcut();\n ValidateKey(Key);\n }\n }\n }\n\n public bool Shift\n {\n get;\n set\n {\n if (Set(ref field, value) && IsEnabled)\n {\n ValidateShortcut();\n ValidateKey(Key);\n }\n }\n }\n\n public Key Key\n {\n get;\n set\n {\n Key prevKey = field;\n if (Set(ref field, value) && IsEnabled)\n {\n ValidateShortcut();\n ValidateKey(Key); // maybe don't need?\n // When the key is changed from A -> B, the state of A also needs to be updated.\n ValidateKey(prevKey);\n }\n }\n }\n\n public ActionData Action { get; set => Set(ref field, value); }\n\n public bool IsKeyUp { get; set => Set(ref field, value); }\n\n public bool Duplicated\n {\n get;\n private set\n {\n if (Set(ref field, value))\n {\n // Update duplicate counters held by the parent.\n _parent.DuplicationCount += value ? 1 : -1;\n }\n }\n }\n\n public string? DuplicatedInfo { get; private set => Set(ref field, value); }\n\n private bool IsSameKey(KeyBindingWrapper key)\n {\n return key.Key == Key && key.Alt == Alt && key.Shift == Shift && key.Ctrl == Ctrl;\n }\n\n private void ValidateKey(Key key)\n {\n foreach (var b in _parent.KeyBindings.Where(k => k.IsEnabled && k != this && k.Key == key))\n {\n b.ValidateShortcut();\n }\n }\n\n public KeyBindingWrapper Clone()\n {\n KeyBindingWrapper clone = (KeyBindingWrapper)MemberwiseClone();\n\n return clone;\n }\n\n /// \n /// Convert Wrapper to KeyBinding\n /// \n /// \n public KeyBinding ToKeyBinding()\n {\n KeyBinding binding = new()\n {\n Key = Key,\n Action = Action.Action,\n Ctrl = Ctrl,\n Alt = Alt,\n Shift = Shift,\n IsKeyUp = IsKeyUp,\n IsEnabled = IsEnabled\n };\n\n if (Action.Action == KeyBindingAction.Custom)\n {\n binding.ActionName = Action.CustomAction.ToString();\n }\n\n return binding;\n }\n\n // TODO: L: This validation might be better done in the parent with event firing (I want to eliminate references to the parent).\n public void ValidateShortcut()\n {\n List sameKeys = _parent.KeyBindings\n .Where(k => k != this && k.IsEnabled && k.IsSameKey(this)).ToList();\n\n bool isDuplicate = sameKeys.Count > 0;\n\n UpdateDuplicated(isDuplicate);\n\n // Other records with the same key also update duplicate status\n foreach (KeyBindingWrapper b in sameKeys)\n {\n b.UpdateDuplicated(isDuplicate);\n }\n }\n\n private void UpdateDuplicated(bool duplicated)\n {\n Duplicated = duplicated;\n\n if (duplicated)\n {\n List duplicateActions = _parent.KeyBindings\n .Where(k => k != this && k.IsSameKey(this)).Select(k => k.Action.DisplayName)\n .ToList();\n\n DuplicatedInfo = $\"Key:{Key} is conflicted.\\r\\nAction:{string.Join(',', duplicateActions)} already uses.\";\n }\n else\n {\n DuplicatedInfo = null;\n }\n }\n\n // TODO: L: Enable firing for multiple selections\n public DelegateCommand CmdDeleteRow => new((binding) =>\n {\n if (binding.Duplicated)\n {\n // Reduce duplicate counters of parents\n binding.Duplicated = false;\n }\n _parent.KeyBindings.Remove(binding);\n\n // Update other keys\n if (binding.IsEnabled)\n {\n ValidateKey(binding.Key);\n }\n });\n\n public DelegateCommand CmdSetKey => new((key) =>\n {\n if (key.HasValue)\n {\n Key = key.Value;\n }\n });\n\n public DelegateCommand CmdCloneRow => new((keyBinding) =>\n {\n int index = _parent.KeyBindings.IndexOf(keyBinding);\n if (index != -1)\n {\n KeyBindingWrapper clone = Clone();\n\n _parent.KeyBindings.Insert(index + 1, clone);\n\n // Select added record\n _parent.SelectedKeyBinding = clone;\n\n // validate it\n clone.ValidateShortcut();\n }\n });\n}\n\npublic class KeyCaptureTextBox : TextBox\n{\n private static readonly HashSet IgnoreKeys =\n [\n Key.LeftShift,\n Key.RightShift,\n Key.LeftCtrl,\n Key.RightCtrl,\n Key.LeftAlt,\n Key.RightAlt,\n Key.LWin,\n Key.RWin,\n Key.CapsLock,\n Key.NumLock,\n Key.Scroll\n ];\n\n public static readonly DependencyProperty KeyProperty =\n DependencyProperty.Register(nameof(Key), typeof(Key), typeof(KeyCaptureTextBox),\n new FrameworkPropertyMetadata(Key.None, FrameworkPropertyMetadataOptions.BindsTwoWayByDefault));\n public Key Key\n {\n get => (Key)GetValue(KeyProperty);\n set => SetValue(KeyProperty, value);\n }\n\n public KeyCaptureTextBox()\n {\n Loaded += KeyCaptureTextBox_Loaded;\n }\n\n // Key input does not get focus when mouse clicked, so it gets it.\n private void KeyCaptureTextBox_Loaded(object sender, RoutedEventArgs e)\n {\n Focus();\n Keyboard.Focus(this);\n }\n\n protected override void OnPreviewKeyDown(KeyEventArgs e)\n {\n if (IgnoreKeys.Contains(e.Key))\n {\n return;\n }\n\n // Press Enter to confirm.\n if (e.Key == Key.Enter)\n {\n // This would go to the right cell.\n //MoveFocus(new TraversalRequest(FocusNavigationDirection.Down));\n\n // If the Enter key is pressed, it remains in place and the edit is confirmed\n var dataGrid = UIHelper.FindParent(this);\n if (dataGrid != null)\n {\n dataGrid.CommitEdit(DataGridEditingUnit.Cell, true);\n }\n\n e.Handled = true; // Suppress default behavior (focus movement)\n }\n else\n {\n // Capture other key\n Key = e.Key;\n\n // Converts input key into human understandable name.\n if (KeyToStringConverter.KeyMappings.TryGetValue(e.Key, out string? keyName))\n {\n Text = keyName;\n }\n else\n {\n Text = e.Key.ToString();\n }\n e.Handled = true;\n }\n\n base.OnPreviewKeyDown(e);\n }\n}\n"], ["/LLPlayer/LLPlayer/ViewModels/SubtitlesSidebarVM.cs", "using System.ComponentModel;\nusing System.Windows.Data;\nusing FlyleafLib.MediaPlayer;\nusing LLPlayer.Extensions;\nusing LLPlayer.Services;\n\nnamespace LLPlayer.ViewModels;\n\npublic class SubtitlesSidebarVM : Bindable, IDisposable\n{\n public FlyleafManager FL { get; }\n\n public SubtitlesSidebarVM(FlyleafManager fl)\n {\n FL = fl;\n\n FL.Config.PropertyChanged += OnConfigOnPropertyChanged;\n\n // Initialize filtered view for the sidebar\n for (int i = 0; i < _filteredSubs.Length; i++)\n {\n _filteredSubs[i] = (ListCollectionView)CollectionViewSource.GetDefaultView(FL.Player.SubtitlesManager[i].Subs);\n }\n }\n\n public void Dispose()\n {\n FL.Config.PropertyChanged -= OnConfigOnPropertyChanged;\n }\n\n private void OnConfigOnPropertyChanged(object? sender, PropertyChangedEventArgs args)\n {\n switch (args.PropertyName)\n {\n case nameof(FL.Config.SidebarShowSecondary):\n OnPropertyChanged(nameof(SubIndex));\n OnPropertyChanged(nameof(SubManager));\n\n // prevent unnecessary filter update\n if (_lastSearchText[SubIndex] != _trimSearchText)\n {\n ApplyFilter(); // ensure filter applied\n }\n break;\n case nameof(FL.Config.SidebarShowOriginalText):\n // Update ListBox\n OnPropertyChanged(nameof(SubManager));\n\n if (_trimSearchText.Length != 0)\n {\n // because of switch between Text and DisplayText\n ApplyFilter();\n }\n break;\n }\n }\n\n public int SubIndex => !FL.Config.SidebarShowSecondary ? 0 : 1;\n\n public SubManager SubManager => FL.Player.SubtitlesManager[SubIndex];\n\n private readonly ListCollectionView[] _filteredSubs = new ListCollectionView[2];\n\n private string _searchText = string.Empty;\n public string SearchText\n {\n get => _searchText;\n set\n {\n if (Set(ref _searchText, value))\n {\n DebounceFilter();\n }\n }\n }\n\n private string _trimSearchText = string.Empty; // for performance\n\n public string HitCount { get; set => Set(ref field, value); } = string.Empty;\n\n public event EventHandler? RequestScrollToTop;\n\n // TODO: L: Fix implicit changes to reflect\n public DelegateCommand? CmdSubFontSizeChange => field ??= new(increase =>\n {\n if (int.TryParse(increase, out var value))\n {\n FL.Config.SidebarFontSize += value;\n }\n });\n\n public DelegateCommand? CmdSubTextMaskToggle => field ??= new(() =>\n {\n FL.Config.SidebarTextMask = !FL.Config.SidebarTextMask;\n\n // Update ListBox\n OnPropertyChanged(nameof(SubManager));\n });\n\n public DelegateCommand? CmdShowDownloadSubsDialog => field ??= new(() =>\n {\n FL.Action.CmdOpenWindowSubsDownloader.Execute();\n });\n\n public DelegateCommand? CmdShowExportSubsDialog => field ??= new(() =>\n {\n FL.Action.CmdOpenWindowSubsExporter.Execute();\n });\n\n public DelegateCommand? CmdSwapSidebarPosition => field ??= new(() =>\n {\n FL.Config.SidebarLeft = !FL.Config.SidebarLeft;\n });\n\n public DelegateCommand? CmdSubPlay => field ??= new((index) =>\n {\n if (!index.HasValue)\n {\n return;\n }\n\n var sub = SubManager.Subs[index.Value];\n FL.Player.SeekAccurate(sub.StartTime, SubIndex);\n });\n\n public DelegateCommand? CmdSubSync => field ??= new((index) =>\n {\n if (!index.HasValue)\n {\n return;\n }\n\n var sub = SubManager.Subs[index.Value];\n var newDelay = FL.Player.CurTime - sub.StartTime.Ticks;\n\n // Delay's OSD is not displayed, temporarily set to Active\n FL.Player.Activity.ForceActive();\n\n FL.PlayerConfig.Subtitles[SubIndex].Delay = newDelay;\n });\n\n public DelegateCommand? CmdClearSearch => field ??= new(() =>\n {\n if (!FL.Config.SidebarSearchActive)\n return;\n\n Set(ref _searchText, string.Empty, nameof(SearchText));\n _trimSearchText = string.Empty;\n HitCount = string.Empty;\n\n _debounceCts?.Cancel();\n _debounceCts?.Dispose();\n _debounceCts = null;\n\n for (int i = 0; i < _filteredSubs.Length; i++)\n {\n _lastSearchText[i] = string.Empty;\n _filteredSubs[i].Filter = null; // remove filter completely\n _filteredSubs[i].Refresh();\n }\n\n FL.Config.SidebarSearchActive = false;\n\n // move focus to video and enable keybindings\n FL.FlyleafHost!.Surface.Focus();\n\n // for scrolling to current sub\n var prev = SubManager.SelectedSub;\n SubManager.SelectedSub = null;\n SubManager.SelectedSub = prev;\n });\n\n public DelegateCommand? CmdNextMatch => field ??= new(() =>\n {\n if (_filteredSubs[SubIndex].IsEmpty)\n return;\n\n if (!_filteredSubs[SubIndex].MoveCurrentToNext())\n {\n // if last, move to first\n _filteredSubs[SubIndex].MoveCurrentToFirst();\n }\n\n var nextItem = (SubtitleData)_filteredSubs[SubIndex].CurrentItem;\n if (nextItem != null)\n {\n FL.Player.SeekAccurate(nextItem.StartTime, SubIndex);\n FL.Player.Activity.RefreshFullActive();\n }\n });\n\n public DelegateCommand? CmdPrevMatch => field ??= new(() =>\n {\n if (_filteredSubs[SubIndex].IsEmpty)\n return;\n\n if (!_filteredSubs[SubIndex].MoveCurrentToPrevious())\n {\n // if first, move to last\n _filteredSubs[SubIndex].MoveCurrentToLast();\n }\n\n var prevItem = (SubtitleData)_filteredSubs[SubIndex].CurrentItem;\n if (prevItem != null)\n {\n FL.Player.SeekAccurate(prevItem.StartTime, SubIndex);\n FL.Player.Activity.RefreshFullActive();\n }\n });\n\n // Debounce logic\n private CancellationTokenSource? _debounceCts;\n private async void DebounceFilter()\n {\n _debounceCts?.Cancel();\n _debounceCts?.Dispose();\n _debounceCts = new CancellationTokenSource();\n var token = _debounceCts.Token;\n\n try\n {\n await Task.Delay(300, token); // 300ms debounce\n\n if (!token.IsCancellationRequested)\n {\n ApplyFilter();\n }\n }\n catch (OperationCanceledException)\n {\n // ignore\n }\n }\n\n private readonly string[] _lastSearchText = [string.Empty, string.Empty];\n\n private void ApplyFilter()\n {\n _trimSearchText = SearchText.Trim();\n _lastSearchText[SubIndex] = _trimSearchText;\n\n // initialize filter lazily\n _filteredSubs[SubIndex].Filter ??= SubFilter;\n _filteredSubs[SubIndex].Refresh();\n\n int count = _filteredSubs[SubIndex].Count;\n HitCount = count > 0 ? $\"{count} hits\" : \"No hits\";\n\n if (SubManager.SelectedSub != null && _filteredSubs[SubIndex].MoveCurrentTo(SubManager.SelectedSub))\n {\n // scroll to current playing item\n var prev = SubManager.SelectedSub;\n SubManager.SelectedSub = null;\n SubManager.SelectedSub = prev;\n }\n else\n {\n // scroll to top\n if (!_filteredSubs[SubIndex].IsEmpty)\n {\n RequestScrollToTop?.Invoke(this, EventArgs.Empty);\n }\n }\n }\n\n private bool SubFilter(object obj)\n {\n if (_trimSearchText.Length == 0) return true;\n if (obj is not SubtitleData sub) return false;\n\n string? source = FL.Config.SidebarShowOriginalText ? sub.Text : sub.DisplayText;\n return source?.IndexOf(_trimSearchText, StringComparison.OrdinalIgnoreCase) >= 0;\n }\n}\n"], ["/LLPlayer/LLPlayer/Extensions/ExtendedDialogService.cs", "using System.Windows;\n\nnamespace LLPlayer.Extensions;\n\n/// \n/// Customize DialogService's Show(), which sets the Owner of the Window and sets it to always-on-top.\n/// ref: https://stackoverflow.com/questions/64420093/prism-idialogservice-show-non-modal-dialog-acts-as-modal\n/// \npublic class ExtendedDialogService(IContainerExtension containerExtension) : DialogService(containerExtension)\n{\n private bool _isOrphan;\n\n protected override void ConfigureDialogWindowContent(string dialogName, IDialogWindow window, IDialogParameters parameters)\n {\n base.ConfigureDialogWindowContent(dialogName, window, parameters);\n\n if (parameters != null &&\n parameters.ContainsKey(MyKnownDialogParameters.OrphanWindow))\n {\n _isOrphan = true;\n }\n }\n\n protected override void ShowDialogWindow(IDialogWindow dialogWindow, bool isModal)\n {\n base.ShowDialogWindow(dialogWindow, isModal);\n\n if (_isOrphan)\n {\n // Show and then clear Owner to place the window based on the parent window and then make it an orphan window.\n _isOrphan = false;\n dialogWindow.Owner = null;\n }\n }\n}\n\n// ref: https://github.com/PrismLibrary/Prism/blob/master/src/Wpf/Prism.Wpf/Dialogs/IDialogServiceCompatExtensions.cs\npublic static class ExtendedDialogServiceExtensions\n{\n /// \n /// Shows a non-modal and singleton dialog.\n /// \n /// The DialogService\n /// The name of the dialog to show.\n /// Whether to set owner to window\n public static void ShowSingleton(this IDialogService dialogService, string name, bool orphan)\n {\n ShowSingleton(dialogService, name, null!, orphan);\n }\n\n /// \n /// Shows a non-modal and singleton dialog.\n /// \n /// The DialogService\n /// The name of the dialog to show.\n /// The action to perform when the dialog is closed.\n /// Whether to set owner to window\n public static void ShowSingleton(this IDialogService dialogService, string name, Action callback, bool orphan)\n {\n var parameters = EnsureShowNonModalParameter(null);\n\n var windows = Application.Current.Windows.OfType();\n if (windows.Any())\n {\n var curWindow = windows.FirstOrDefault(w => w.Content.GetType().Name == name);\n if (curWindow != null && curWindow is Window win)\n {\n // If minimized, it will not be displayed after Activate, so set it back to Normal in advance.\n if (win.WindowState == WindowState.Minimized)\n {\n win.WindowState = WindowState.Normal;\n }\n // TODO: L: Notify to ViewModel to update query\n win.Activate();\n return;\n }\n }\n\n if (orphan)\n {\n parameters.Add(MyKnownDialogParameters.OrphanWindow, true);\n }\n\n dialogService.Show(name, parameters, callback);\n }\n\n private static IDialogParameters EnsureShowNonModalParameter(IDialogParameters? parameters)\n {\n parameters ??= new DialogParameters();\n\n if (!parameters.ContainsKey(KnownDialogParameters.ShowNonModal))\n parameters.Add(KnownDialogParameters.ShowNonModal, true);\n\n return parameters;\n }\n}\n\npublic static class MyKnownDialogParameters\n{\n public const string OrphanWindow = \"orphanWindow\";\n}\n"], ["/LLPlayer/FlyleafLib/MediaPlayer/Translation/TranslateLanguage.cs", "using FlyleafLib.MediaPlayer.Translation.Services;\nusing System.Collections.Generic;\nusing System.Reflection;\nusing System.Runtime.Serialization;\n\nnamespace FlyleafLib.MediaPlayer.Translation;\n\npublic class TranslateLanguage\n{\n public static Dictionary Langs { get; } = new()\n {\n // Google: https://cloud.google.com/translate/docs/languages\n // DeepL: https://developers.deepl.com/docs/resources/supported-languages\n [\"ab\"] = new(\"Abkhaz\", \"ab\", TranslateServiceType.GoogleV1),\n [\"af\"] = new(\"Afrikaans\", \"af\", TranslateServiceType.GoogleV1),\n [\"sq\"] = new(\"Albanian\", \"sq\", TranslateServiceType.GoogleV1),\n [\"am\"] = new(\"Amharic\", \"am\", TranslateServiceType.GoogleV1),\n [\"ar\"] = new(\"Arabic\", \"ar\"),\n [\"hy\"] = new(\"Armenian\", \"hy\", TranslateServiceType.GoogleV1),\n [\"as\"] = new(\"Assamese\", \"as\", TranslateServiceType.GoogleV1),\n [\"ay\"] = new(\"Aymara\", \"ay\", TranslateServiceType.GoogleV1),\n [\"az\"] = new(\"Azerbaijani\", \"az\", TranslateServiceType.GoogleV1),\n [\"bm\"] = new(\"Bambara\", \"bm\", TranslateServiceType.GoogleV1),\n [\"ba\"] = new(\"Bashkir\", \"ba\", TranslateServiceType.GoogleV1),\n [\"eu\"] = new(\"Basque\", \"eu\", TranslateServiceType.GoogleV1),\n [\"be\"] = new(\"Belarusian\", \"be\", TranslateServiceType.GoogleV1),\n [\"bn\"] = new(\"Bengali\", \"bn\", TranslateServiceType.GoogleV1),\n [\"bs\"] = new(\"Bosnian\", \"bs\", TranslateServiceType.GoogleV1),\n [\"br\"] = new(\"Breton\", \"br\", TranslateServiceType.GoogleV1),\n [\"bg\"] = new(\"Bulgarian\", \"bg\"),\n [\"ca\"] = new(\"Catalan\", \"ca\", TranslateServiceType.GoogleV1),\n [\"ny\"] = new(\"Chichewa (Nyanja)\", \"ny\", TranslateServiceType.GoogleV1),\n\n // special handling\n [\"zh\"] = new(\"Chinese\", \"zh\"),\n\n [\"cv\"] = new(\"Chuvash\", \"cv\", TranslateServiceType.GoogleV1),\n [\"co\"] = new(\"Corsican\", \"co\", TranslateServiceType.GoogleV1),\n [\"hr\"] = new(\"Croatian\", \"hr\", TranslateServiceType.GoogleV1),\n [\"cs\"] = new(\"Czech\", \"cs\"),\n [\"da\"] = new(\"Danish\", \"da\"),\n [\"dv\"] = new(\"Divehi\", \"dv\", TranslateServiceType.GoogleV1),\n [\"nl\"] = new(\"Dutch\", \"nl\"),\n [\"dz\"] = new(\"Dzongkha\", \"dz\", TranslateServiceType.GoogleV1),\n [\"en\"] = new(\"English\", \"en\"),\n [\"eo\"] = new(\"Esperanto\", \"eo\", TranslateServiceType.GoogleV1),\n [\"et\"] = new(\"Estonian\", \"et\"),\n [\"ee\"] = new(\"Ewe\", \"ee\", TranslateServiceType.GoogleV1),\n [\"fj\"] = new(\"Fijian\", \"fj\", TranslateServiceType.GoogleV1),\n [\"tl\"] = new(\"Tagalog\", \"tl\", TranslateServiceType.GoogleV1),\n [\"fi\"] = new(\"Finnish\", \"fi\"),\n\n // special handling\n [\"fr\"] = new(\"French\", \"fr\"),\n\n [\"fy\"] = new(\"Frisian\", \"fy\", TranslateServiceType.GoogleV1),\n [\"ff\"] = new(\"Fulfulde\", \"ff\", TranslateServiceType.GoogleV1),\n [\"gl\"] = new(\"Galician\", \"gl\", TranslateServiceType.GoogleV1),\n [\"lg\"] = new(\"Ganda (Luganda)\", \"lg\", TranslateServiceType.GoogleV1),\n [\"ka\"] = new(\"Georgian\", \"ka\", TranslateServiceType.GoogleV1),\n [\"de\"] = new(\"German\", \"de\"),\n [\"el\"] = new(\"Greek\", \"el\"),\n [\"gn\"] = new(\"Guarani\", \"gn\", TranslateServiceType.GoogleV1),\n [\"gu\"] = new(\"Gujarati\", \"gu\", TranslateServiceType.GoogleV1),\n [\"ht\"] = new(\"Haitian Creole\", \"ht\", TranslateServiceType.GoogleV1),\n [\"ha\"] = new(\"Hausa\", \"ha\", TranslateServiceType.GoogleV1),\n [\"he\"] = new(\"Hebrew\", \"he\", TranslateServiceType.GoogleV1),\n [\"hi\"] = new(\"Hindi\", \"hi\", TranslateServiceType.GoogleV1),\n [\"hu\"] = new(\"Hungarian\", \"hu\"),\n [\"is\"] = new(\"Icelandic\", \"is\", TranslateServiceType.GoogleV1),\n [\"ig\"] = new(\"Igbo\", \"ig\", TranslateServiceType.GoogleV1),\n [\"id\"] = new(\"Indonesian\", \"id\"),\n [\"ga\"] = new(\"Irish\", \"ga\", TranslateServiceType.GoogleV1),\n [\"it\"] = new(\"Italian\", \"it\"),\n [\"ja\"] = new(\"Japanese\", \"ja\"),\n [\"jv\"] = new(\"Javanese\", \"jv\", TranslateServiceType.GoogleV1),\n [\"kn\"] = new(\"Kannada\", \"kn\", TranslateServiceType.GoogleV1),\n [\"kk\"] = new(\"Kazakh\", \"kk\", TranslateServiceType.GoogleV1),\n [\"km\"] = new(\"Khmer\", \"km\", TranslateServiceType.GoogleV1),\n [\"rw\"] = new(\"Kinyarwanda\", \"rw\", TranslateServiceType.GoogleV1),\n [\"ko\"] = new(\"Korean\", \"ko\"),\n [\"ku\"] = new(\"Kurdish (Kurmanji)\", \"ku\", TranslateServiceType.GoogleV1),\n [\"ky\"] = new(\"Kyrgyz\", \"ky\", TranslateServiceType.GoogleV1),\n [\"lo\"] = new(\"Lao\", \"lo\", TranslateServiceType.GoogleV1),\n [\"la\"] = new(\"Latin\", \"la\", TranslateServiceType.GoogleV1),\n [\"lv\"] = new(\"Latvian\", \"lv\"),\n [\"li\"] = new(\"Limburgan\", \"li\", TranslateServiceType.GoogleV1),\n [\"ln\"] = new(\"Lingala\", \"ln\", TranslateServiceType.GoogleV1),\n [\"lt\"] = new(\"Lithuanian\", \"lt\"),\n [\"lb\"] = new(\"Luxembourgish\", \"lb\", TranslateServiceType.GoogleV1),\n [\"mk\"] = new(\"Macedonian\", \"mk\", TranslateServiceType.GoogleV1),\n [\"mg\"] = new(\"Malagasy\", \"mg\", TranslateServiceType.GoogleV1),\n [\"ms\"] = new(\"Malay\", \"ms\", TranslateServiceType.GoogleV1),\n [\"ml\"] = new(\"Malayalam\", \"ml\", TranslateServiceType.GoogleV1),\n [\"mt\"] = new(\"Maltese\", \"mt\", TranslateServiceType.GoogleV1),\n [\"mi\"] = new(\"Maori\", \"mi\", TranslateServiceType.GoogleV1),\n [\"mr\"] = new(\"Marathi\", \"mr\", TranslateServiceType.GoogleV1),\n [\"mn\"] = new(\"Mongolian\", \"mn\", TranslateServiceType.GoogleV1),\n [\"my\"] = new(\"Myanmar (Burmese)\", \"my\", TranslateServiceType.GoogleV1),\n [\"nr\"] = new(\"Ndebele (South)\", \"nr\", TranslateServiceType.GoogleV1),\n [\"ne\"] = new(\"Nepali\", \"ne\", TranslateServiceType.GoogleV1),\n\n // TODO: L: review handling\n // special handling\n [\"no\"] = new(\"Norwegian\", \"no\"),\n [\"nb\"] = new(\"Norwegian Bokmål\", \"nb\"),\n\n [\"oc\"] = new(\"Occitan\", \"oc\", TranslateServiceType.GoogleV1),\n [\"or\"] = new(\"Odia (Oriya)\", \"or\", TranslateServiceType.GoogleV1),\n [\"om\"] = new(\"Oromo\", \"om\", TranslateServiceType.GoogleV1),\n [\"ps\"] = new(\"Pashto\", \"ps\", TranslateServiceType.GoogleV1),\n [\"fa\"] = new(\"Persian\", \"fa\", TranslateServiceType.GoogleV1),\n [\"pl\"] = new(\"Polish\", \"pl\"),\n\n // special handling\n [\"pt\"] = new(\"Portuguese\", \"pt\"),\n\n [\"pa\"] = new(\"Punjabi\", \"pa\", TranslateServiceType.GoogleV1),\n [\"qu\"] = new(\"Quechua\", \"qu\", TranslateServiceType.GoogleV1),\n [\"ro\"] = new(\"Romanian\", \"ro\"),\n [\"rn\"] = new(\"Rundi\", \"rn\", TranslateServiceType.GoogleV1),\n [\"ru\"] = new(\"Russian\", \"ru\"),\n [\"sm\"] = new(\"Samoan\", \"sm\", TranslateServiceType.GoogleV1),\n [\"sg\"] = new(\"Sango\", \"sg\", TranslateServiceType.GoogleV1),\n [\"sa\"] = new(\"Sanskrit\", \"sa\", TranslateServiceType.GoogleV1),\n [\"gd\"] = new(\"Scots Gaelic\", \"gd\", TranslateServiceType.GoogleV1),\n [\"sr\"] = new(\"Serbian\", \"sr\", TranslateServiceType.GoogleV1),\n [\"st\"] = new(\"Sesotho\", \"st\", TranslateServiceType.GoogleV1),\n [\"sn\"] = new(\"Shona\", \"sn\", TranslateServiceType.GoogleV1),\n [\"sd\"] = new(\"Sindhi\", \"sd\", TranslateServiceType.GoogleV1),\n [\"si\"] = new(\"Sinhala (Sinhalese)\", \"si\", TranslateServiceType.GoogleV1),\n [\"sk\"] = new(\"Slovak\", \"sk\"),\n [\"sl\"] = new(\"Slovenian\", \"sl\"),\n [\"so\"] = new(\"Somali\", \"so\", TranslateServiceType.GoogleV1),\n [\"es\"] = new(\"Spanish\", \"es\"),\n [\"su\"] = new(\"Sundanese\", \"su\", TranslateServiceType.GoogleV1),\n [\"sw\"] = new(\"Swahili\", \"sw\", TranslateServiceType.GoogleV1),\n [\"ss\"] = new(\"Swati\", \"ss\", TranslateServiceType.GoogleV1),\n [\"sv\"] = new(\"Swedish\", \"sv\"),\n [\"tg\"] = new(\"Tajik\", \"tg\", TranslateServiceType.GoogleV1),\n [\"ta\"] = new(\"Tamil\", \"ta\", TranslateServiceType.GoogleV1),\n [\"tt\"] = new(\"Tatar\", \"tt\", TranslateServiceType.GoogleV1),\n [\"te\"] = new(\"Telugu\", \"te\", TranslateServiceType.GoogleV1),\n [\"th\"] = new(\"Thai\", \"th\", TranslateServiceType.GoogleV1),\n [\"ti\"] = new(\"Tigrinya\", \"ti\", TranslateServiceType.GoogleV1),\n [\"ts\"] = new(\"Tsonga\", \"ts\", TranslateServiceType.GoogleV1),\n [\"tn\"] = new(\"Tswana\", \"tn\", TranslateServiceType.GoogleV1),\n [\"tr\"] = new(\"Turkish\", \"tr\"),\n [\"tk\"] = new(\"Turkmen\", \"tk\", TranslateServiceType.GoogleV1),\n [\"ak\"] = new(\"Twi (Akan)\", \"ak\", TranslateServiceType.GoogleV1),\n [\"uk\"] = new(\"Ukrainian\", \"uk\"),\n [\"ur\"] = new(\"Urdu\", \"ur\", TranslateServiceType.GoogleV1),\n [\"ug\"] = new(\"Uyghur\", \"ug\", TranslateServiceType.GoogleV1),\n [\"uz\"] = new(\"Uzbek\", \"uz\", TranslateServiceType.GoogleV1),\n [\"vi\"] = new(\"Vietnamese\", \"vi\", TranslateServiceType.GoogleV1),\n [\"cy\"] = new(\"Welsh\", \"cy\", TranslateServiceType.GoogleV1),\n [\"xh\"] = new(\"Xhosa\", \"xh\", TranslateServiceType.GoogleV1),\n [\"yi\"] = new(\"Yiddish\", \"yi\", TranslateServiceType.GoogleV1),\n [\"yo\"] = new(\"Yoruba\", \"yo\", TranslateServiceType.GoogleV1),\n [\"zu\"] = new(\"Zulu\", \"zu\", TranslateServiceType.GoogleV1),\n };\n\n public TranslateLanguage(string name, string iso6391,\n TranslateServiceType supportedServices =\n TranslateServiceType.GoogleV1 | TranslateServiceType.DeepL)\n {\n // all LLMs support all languages\n supportedServices |= TranslateServiceTypeExtensions.LLMServices;\n\n // DeepL = DeepLX, so flag is same\n if (supportedServices.HasFlag(TranslateServiceType.DeepL))\n {\n supportedServices |= TranslateServiceType.DeepLX;\n }\n\n Name = name;\n ISO6391 = iso6391;\n SupportedServices = supportedServices;\n }\n\n public string Name { get; }\n\n public string ISO6391 { get; }\n\n public TranslateServiceType SupportedServices { get; }\n}\n\n[DataContract]\npublic enum TargetLanguage\n{\n // Supported by Google and DeepL\n [EnumMember(Value = \"ar\")] Arabic,\n [EnumMember(Value = \"bg\")] Bulgarian,\n [EnumMember(Value = \"zh-CN\")] ChineseSimplified,\n [EnumMember(Value = \"zh-TW\")] ChineseTraditional,\n [EnumMember(Value = \"cs\")] Czech,\n [EnumMember(Value = \"da\")] Danish,\n [EnumMember(Value = \"nl\")] Dutch,\n [EnumMember(Value = \"en-US\")] EnglishAmerican,\n [EnumMember(Value = \"en-GB\")] EnglishBritish,\n [EnumMember(Value = \"et\")] Estonian,\n [EnumMember(Value = \"fr-FR\")] French,\n [EnumMember(Value = \"fr-CA\")] FrenchCanadian,\n [EnumMember(Value = \"de\")] German,\n [EnumMember(Value = \"el\")] Greek,\n [EnumMember(Value = \"hu\")] Hungarian,\n [EnumMember(Value = \"id\")] Indonesian,\n [EnumMember(Value = \"it\")] Italian,\n [EnumMember(Value = \"ja\")] Japanese,\n [EnumMember(Value = \"ko\")] Korean,\n [EnumMember(Value = \"lt\")] Lithuanian,\n [EnumMember(Value = \"nb\")] NorwegianBokmål,\n [EnumMember(Value = \"pl\")] Polish,\n [EnumMember(Value = \"pt-PT\")] Portuguese,\n [EnumMember(Value = \"pt-BR\")] PortugueseBrazilian,\n [EnumMember(Value = \"ro\")] Romanian,\n [EnumMember(Value = \"ru\")] Russian,\n [EnumMember(Value = \"sk\")] Slovak,\n [EnumMember(Value = \"sl\")] Slovenian,\n [EnumMember(Value = \"es\")] Spanish,\n [EnumMember(Value = \"sv\")] Swedish,\n [EnumMember(Value = \"tr\")] Turkish,\n [EnumMember(Value = \"uk\")] Ukrainian,\n\n // Only supported in Google\n [EnumMember(Value = \"ab\")] Abkhaz,\n [EnumMember(Value = \"af\")] Afrikaans,\n [EnumMember(Value = \"sq\")] Albanian,\n [EnumMember(Value = \"am\")] Amharic,\n [EnumMember(Value = \"hy\")] Armenian,\n [EnumMember(Value = \"as\")] Assamese,\n [EnumMember(Value = \"ay\")] Aymara,\n [EnumMember(Value = \"az\")] Azerbaijani,\n [EnumMember(Value = \"bm\")] Bambara,\n [EnumMember(Value = \"ba\")] Bashkir,\n [EnumMember(Value = \"eu\")] Basque,\n [EnumMember(Value = \"be\")] Belarusian,\n [EnumMember(Value = \"bn\")] Bengali,\n [EnumMember(Value = \"bs\")] Bosnian,\n [EnumMember(Value = \"br\")] Breton,\n [EnumMember(Value = \"ca\")] Catalan,\n [EnumMember(Value = \"ny\")] Chichewa,\n [EnumMember(Value = \"cv\")] Chuvash,\n [EnumMember(Value = \"co\")] Corsican,\n [EnumMember(Value = \"hr\")] Croatian,\n [EnumMember(Value = \"dv\")] Divehi,\n [EnumMember(Value = \"dz\")] Dzongkha,\n [EnumMember(Value = \"eo\")] Esperanto,\n [EnumMember(Value = \"ee\")] Ewe,\n [EnumMember(Value = \"fj\")] Fijian,\n [EnumMember(Value = \"tl\")] Tagalog,\n [EnumMember(Value = \"fy\")] Frisian,\n [EnumMember(Value = \"ff\")] Fulfulde,\n [EnumMember(Value = \"gl\")] Galician,\n [EnumMember(Value = \"lg\")] Ganda,\n [EnumMember(Value = \"ka\")] Georgian,\n [EnumMember(Value = \"gn\")] Guarani,\n [EnumMember(Value = \"gu\")] Gujarati,\n [EnumMember(Value = \"ht\")] Haitian,\n [EnumMember(Value = \"ha\")] Hausa,\n [EnumMember(Value = \"he\")] Hebrew,\n [EnumMember(Value = \"hi\")] Hindi,\n [EnumMember(Value = \"is\")] Icelandic,\n [EnumMember(Value = \"ig\")] Igbo,\n [EnumMember(Value = \"ga\")] Irish,\n [EnumMember(Value = \"jv\")] Javanese,\n [EnumMember(Value = \"kn\")] Kannada,\n [EnumMember(Value = \"kk\")] Kazakh,\n [EnumMember(Value = \"km\")] Khmer,\n [EnumMember(Value = \"rw\")] Kinyarwanda,\n [EnumMember(Value = \"ku\")] Kurdish,\n [EnumMember(Value = \"ky\")] Kyrgyz,\n [EnumMember(Value = \"lo\")] Lao,\n [EnumMember(Value = \"la\")] Latin,\n [EnumMember(Value = \"li\")] Limburgan,\n [EnumMember(Value = \"ln\")] Lingala,\n [EnumMember(Value = \"lb\")] Luxembourgish,\n [EnumMember(Value = \"mk\")] Macedonian,\n [EnumMember(Value = \"mg\")] Malagasy,\n [EnumMember(Value = \"ms\")] Malay,\n [EnumMember(Value = \"ml\")] Malayalam,\n [EnumMember(Value = \"mt\")] Maltese,\n [EnumMember(Value = \"mi\")] Maori,\n [EnumMember(Value = \"mr\")] Marathi,\n [EnumMember(Value = \"mn\")] Mongolian,\n [EnumMember(Value = \"my\")] Myanmar,\n [EnumMember(Value = \"nr\")] Ndebele,\n [EnumMember(Value = \"ne\")] Nepali,\n [EnumMember(Value = \"oc\")] Occitan,\n [EnumMember(Value = \"or\")] Odia,\n [EnumMember(Value = \"om\")] Oromo,\n [EnumMember(Value = \"ps\")] Pashto,\n [EnumMember(Value = \"fa\")] Persian,\n [EnumMember(Value = \"pa\")] Punjabi,\n [EnumMember(Value = \"qu\")] Quechua,\n [EnumMember(Value = \"rn\")] Rundi,\n [EnumMember(Value = \"sm\")] Samoan,\n [EnumMember(Value = \"sg\")] Sango,\n [EnumMember(Value = \"sa\")] Sanskrit,\n [EnumMember(Value = \"gd\")] ScotsGaelic,\n [EnumMember(Value = \"sr\")] Serbian,\n [EnumMember(Value = \"st\")] Sesotho,\n [EnumMember(Value = \"sn\")] Shona,\n [EnumMember(Value = \"sd\")] Sindhi,\n [EnumMember(Value = \"si\")] Sinhala,\n [EnumMember(Value = \"so\")] Somali,\n [EnumMember(Value = \"su\")] Sundanese,\n [EnumMember(Value = \"sw\")] Swahili,\n [EnumMember(Value = \"ss\")] Swati,\n [EnumMember(Value = \"tg\")] Tajik,\n [EnumMember(Value = \"ta\")] Tamil,\n [EnumMember(Value = \"tt\")] Tatar,\n [EnumMember(Value = \"te\")] Telugu,\n [EnumMember(Value = \"th\")] Thai,\n [EnumMember(Value = \"ti\")] Tigrinya,\n [EnumMember(Value = \"ts\")] Tsonga,\n [EnumMember(Value = \"tn\")] Tswana,\n [EnumMember(Value = \"tk\")] Turkmen,\n [EnumMember(Value = \"ak\")] Twi,\n [EnumMember(Value = \"ur\")] Urdu,\n [EnumMember(Value = \"ug\")] Uyghur,\n [EnumMember(Value = \"uz\")] Uzbek,\n [EnumMember(Value = \"vi\")] Vietnamese,\n [EnumMember(Value = \"cy\")] Welsh,\n [EnumMember(Value = \"xh\")] Xhosa,\n [EnumMember(Value = \"yi\")] Yiddish,\n [EnumMember(Value = \"yo\")] Yoruba,\n [EnumMember(Value = \"zu\")] Zulu,\n}\n\npublic static class TargetLanguageExtensions\n{\n public static string DisplayName(this TargetLanguage targetLang)\n {\n return targetLang switch\n {\n TargetLanguage.EnglishAmerican => \"English (American)\",\n TargetLanguage.EnglishBritish => \"English (British)\",\n TargetLanguage.French => \"French\",\n TargetLanguage.FrenchCanadian => \"French (Canadian)\",\n TargetLanguage.Portuguese => \"Portuguese\",\n TargetLanguage.PortugueseBrazilian => \"Portuguese (Brazilian)\",\n TargetLanguage.ChineseSimplified => \"Chinese (Simplified)\",\n TargetLanguage.ChineseTraditional => \"Chinese (Traditional)\",\n TargetLanguage.NorwegianBokmål => \"Norwegian Bokmål\",\n\n TargetLanguage.Chichewa => \"Chichewa (Nyanja)\",\n TargetLanguage.Ganda => \"Ganda (Luganda)\",\n TargetLanguage.Haitian => \"Haitian Creole\",\n TargetLanguage.Kurdish => \"Kurdish (Kurmanji)\",\n TargetLanguage.Myanmar => \"Myanmar (Burmese)\",\n TargetLanguage.Ndebele => \"Ndebele (South)\",\n TargetLanguage.Odia => \"Odia (Oriya)\",\n TargetLanguage.ScotsGaelic => \"Scots Gaelic\",\n TargetLanguage.Sinhala => \"Sinhala (Sinhalese)\",\n TargetLanguage.Twi => \"Twi (Akan)\",\n _ => targetLang.ToString()\n };\n }\n\n public static TranslateServiceType SupportedServiceType(this TargetLanguage targetLang)\n {\n string iso6391 = targetLang.ToISO6391();\n\n TranslateLanguage lang = TranslateLanguage.Langs[iso6391];\n\n return lang.SupportedServices;\n }\n\n public static string ToISO6391(this TargetLanguage targetLang)\n {\n // Get EnumMember language code\n Type type = targetLang.GetType();\n MemberInfo[] memInfo = type.GetMember(targetLang.ToString());\n object[] attributes = memInfo[0].GetCustomAttributes(typeof(EnumMemberAttribute), false);\n string enumValue = ((EnumMemberAttribute)attributes[0]).Value;\n\n // ISO6391 code is the first half of a hyphen\n if (enumValue != null && enumValue.Contains(\"-\"))\n {\n return enumValue.Split('-')[0];\n }\n\n return enumValue;\n }\n\n public static TargetLanguage? ToTargetLanguage(this Language lang)\n {\n // language with region first\n switch (lang.ISO6391)\n {\n case \"en\" when lang.CultureName == \"en-GB\":\n return TargetLanguage.EnglishBritish;\n case \"en\":\n return TargetLanguage.EnglishAmerican;\n\n case \"zh\" when lang.CultureName.StartsWith(\"zh-Hant\"): // zh-Hant, zh-Hant-XX\n return TargetLanguage.ChineseTraditional;\n case \"zh\": // zh-Hans, zh-Hans-XX, or others\n return TargetLanguage.ChineseSimplified;\n\n case \"fr\" when lang.CultureName == \"fr-CA\":\n return TargetLanguage.FrenchCanadian;\n case \"fr\":\n return TargetLanguage.French;\n\n case \"pt\" when lang.CultureName == \"pt-BR\":\n return TargetLanguage.PortugueseBrazilian;\n case \"pt\":\n return TargetLanguage.Portuguese;\n }\n\n // other languages with no region\n foreach (var tl in Enum.GetValues())\n {\n if (tl.ToISO6391() == lang.ISO6391)\n {\n return tl;\n }\n }\n\n // not match\n return null;\n }\n}\n"], ["/LLPlayer/LLPlayer/ViewModels/SelectLanguageDialogVM.cs", "using System.Collections.ObjectModel;\nusing System.ComponentModel;\nusing System.Windows.Data;\nusing FlyleafLib;\nusing LLPlayer.Extensions;\nusing LLPlayer.Services;\n\nnamespace LLPlayer.ViewModels;\n\npublic class SelectLanguageDialogVM : Bindable, IDialogAware\n{\n public FlyleafManager FL { get; }\n\n public SelectLanguageDialogVM(FlyleafManager fl)\n {\n FL = fl;\n\n _filteredAvailableLanguages = CollectionViewSource.GetDefaultView(AvailableLanguages);\n _filteredAvailableLanguages.Filter = obj =>\n {\n if (obj is not Language lang)\n return false;\n\n if (string.IsNullOrWhiteSpace(SearchText))\n return true;\n\n string query = SearchText.Trim();\n\n if (lang.TopEnglishName.Contains(query, StringComparison.OrdinalIgnoreCase))\n return true;\n\n return lang.TopNativeName.Contains(query, StringComparison.OrdinalIgnoreCase);\n };\n }\n\n public string SearchText\n {\n get;\n set\n {\n if (Set(ref field, value))\n {\n _filteredAvailableLanguages.Refresh();\n }\n }\n } = string.Empty;\n\n private readonly ICollectionView _filteredAvailableLanguages;\n public ObservableCollection AvailableLanguages { get; } = new();\n public ObservableCollection SelectedLanguages { get; } = new();\n\n public Language? SelectedAvailable\n {\n get;\n set\n {\n if (Set(ref field, value))\n {\n OnPropertyChanged(nameof(CanMoveRight));\n }\n }\n }\n\n // TODO: L: weird naming\n public Language? SelectedSelected\n {\n get;\n set\n {\n if (Set(ref field, value))\n {\n OnPropertyChanged(nameof(CanMoveLeft));\n OnPropertyChanged(nameof(CanMoveUp));\n OnPropertyChanged(nameof(CanMoveDown));\n }\n }\n }\n\n public bool CanMoveRight => SelectedAvailable != null;\n public bool CanMoveLeft => SelectedSelected != null;\n public bool CanMoveUp => SelectedSelected != null && SelectedLanguages.IndexOf(SelectedSelected) > 0;\n public bool CanMoveDown => SelectedSelected != null && SelectedLanguages.IndexOf(SelectedSelected) < SelectedLanguages.Count - 1;\n\n public DelegateCommand? CmdMoveRight => field ??= new DelegateCommand(() =>\n {\n if (SelectedAvailable != null && !SelectedLanguages.Contains(SelectedAvailable))\n {\n SelectedLanguages.Add(SelectedAvailable);\n AvailableLanguages.Remove(SelectedAvailable);\n }\n }).ObservesCanExecute(() => CanMoveRight);\n\n public DelegateCommand? CmdMoveLeft => field ??= new DelegateCommand(() =>\n {\n if (SelectedSelected != null)\n {\n // conform to order\n int insertIndex = 0;\n while (insertIndex < AvailableLanguages.Count &&\n string.Compare(AvailableLanguages[insertIndex].TopEnglishName, SelectedSelected.TopEnglishName, StringComparison.InvariantCulture) < 0)\n {\n insertIndex++;\n }\n\n AvailableLanguages.Insert(insertIndex, SelectedSelected);\n\n SelectedLanguages.Remove(SelectedSelected);\n }\n }).ObservesCanExecute(() => CanMoveLeft);\n\n public DelegateCommand? CmdMoveUp => field ??= new DelegateCommand(() =>\n {\n int index = SelectedLanguages.IndexOf(SelectedSelected!);\n if (index > 0)\n {\n SelectedLanguages.Move(index, index - 1);\n OnPropertyChanged(nameof(CanMoveUp));\n OnPropertyChanged(nameof(CanMoveDown));\n }\n }).ObservesCanExecute(() => CanMoveUp);\n\n public DelegateCommand? CmdMoveDown => field ??= new DelegateCommand(() =>\n {\n int index = SelectedLanguages.IndexOf(SelectedSelected!);\n if (index < SelectedLanguages.Count - 1)\n {\n SelectedLanguages.Move(index, index + 1);\n OnPropertyChanged(nameof(CanMoveUp));\n OnPropertyChanged(nameof(CanMoveDown));\n }\n }).ObservesCanExecute(() => CanMoveDown);\n\n #region IDialogAware\n public string Title { get; set => Set(ref field, value); }\n = $\"Select Language - {App.Name}\";\n public double WindowWidth { get; set => Set(ref field, value); } = 600;\n public double WindowHeight { get; set => Set(ref field, value); } = 360;\n\n public DialogCloseListener RequestClose { get; }\n\n public bool CanCloseDialog()\n {\n return true;\n }\n public void OnDialogClosed()\n {\n List langs = [.. SelectedLanguages];\n DialogParameters p = new()\n {\n { \"languages\", langs }\n };\n\n RequestClose.Invoke(p);\n }\n\n public void OnDialogOpened(IDialogParameters parameters)\n {\n List langs = parameters.GetValue>(\"languages\");\n\n foreach (var lang in langs)\n {\n SelectedLanguages.Add(lang);\n }\n\n foreach (Language lang in Language.AllLanguages)\n {\n if (!SelectedLanguages.Contains(lang))\n {\n AvailableLanguages.Add(lang);\n }\n }\n }\n #endregion\n}\n"], ["/LLPlayer/LLPlayer/ViewModels/FlyleafOverlayVM.cs", "using System.Diagnostics;\nusing System.Windows;\nusing System.Windows.Controls;\nusing System.Windows.Input;\nusing FlyleafLib;\nusing FlyleafLib.MediaPlayer;\nusing LLPlayer.Extensions;\nusing LLPlayer.Services;\nusing MaterialDesignThemes.Wpf;\nusing static FlyleafLib.Utils.NativeMethods;\n\nnamespace LLPlayer.ViewModels;\n\npublic class FlyleafOverlayVM : Bindable\n{\n public FlyleafManager FL { get; }\n\n public FlyleafOverlayVM(FlyleafManager fl)\n {\n FL = fl;\n }\n\n public DelegateCommand? CmdOnLoaded => field ??= new(() =>\n {\n SetupOSDStatus();\n SetupFlyleafContextMenu();\n SetupFlyleafKeybindings();\n\n FL.Config.FlyleafHostLoaded();\n });\n\n private void SetupFlyleafContextMenu()\n {\n // When a context menu is opened using the Overlay.MouseRightButtonUp event,\n // it is a bubble event and therefore has priority over the ContextMenu of the child controls.\n // so set ContextMenu directly to each of the controls in order to give priority to the child contextmenu.\n ContextMenu menu = (ContextMenu)Application.Current.FindResource(\"PopUpMenu\")!;\n menu.DataContext = this;\n menu.PlacementTarget = FL.FlyleafHost!.Overlay;\n\n FL.FlyleafHost!.Overlay.ContextMenu = menu;\n FL.FlyleafHost!.Surface.ContextMenu = menu;\n }\n\n #region Flyleaf Keybindings\n // TODO: L: Make it fully customizable like PotPlayer\n private void SetupFlyleafKeybindings()\n {\n // Subscribe to the same event to the following two\n // Surface: On Video Screen\n // Overlay: Content of FlyleafHost = FlyleafOverlay\n foreach (var window in (Window[])[FL.FlyleafHost!.Surface, FL.FlyleafHost!.Overlay])\n {\n window.MouseWheel += FlyleafOnMouseWheel;\n }\n FL.FlyleafHost.Surface.MouseUp += SurfaceOnMouseUp;\n FL.FlyleafHost.Surface.MouseDoubleClick += SurfaceOnMouseDoubleClick;\n FL.FlyleafHost.Surface.MouseLeftButtonDown += SurfaceOnMouseLeftButtonDown;\n FL.FlyleafHost.Surface.MouseLeftButtonUp += SurfaceOnMouseLeftButtonUp;\n FL.FlyleafHost.Surface.MouseMove += SurfaceOnMouseMove;\n FL.FlyleafHost.Surface.LostMouseCapture += SurfaceOnLostMouseCapture;\n }\n\n private void SurfaceOnMouseUp(object sender, MouseButtonEventArgs e)\n {\n switch (e.ChangedButton)\n {\n // Middle click: seek to current subtitle\n case MouseButton.Middle:\n bool ctrlDown = Keyboard.IsKeyDown(Key.LeftCtrl) || Keyboard.IsKeyDown(Key.RightCtrl);\n if (ctrlDown)\n {\n // CTRL + Middle click: Reset zoom\n FL.Player.ResetZoom();\n e.Handled = true;\n return;\n }\n\n if (FL.Player.Subtitles[0].Enabled)\n {\n FL.Player.Subtitles.CurSeek();\n }\n e.Handled = true;\n break;\n\n // X1 click: subtitles prev seek with fallback\n case MouseButton.XButton1:\n FL.Player.Subtitles.PrevSeekFallback();\n e.Handled = true;\n break;\n\n // X2 click: subtitles next seek with fallback\n case MouseButton.XButton2:\n FL.Player.Subtitles.NextSeekFallback();\n e.Handled = true;\n break;\n }\n }\n\n private void SurfaceOnMouseDoubleClick(object sender, MouseButtonEventArgs e)\n {\n if (FL.Config.MouseDoubleClickToFullScreen && e.ChangedButton == MouseButton.Left)\n {\n FL.Player.ToggleFullScreen();\n\n // Double and single clicks are not currently distinguished, so need to be re-fired\n // Timers need to be added to distinguish between the two,\n // but this is controversial because it delays a single click action\n SingleClickAction();\n\n e.Handled = true;\n }\n }\n\n private bool _isLeftDragging;\n private Point _downPoint;\n private Point _downCursorPoint;\n private long _downTick;\n\n private void SurfaceOnMouseLeftButtonDown(object sender, MouseButtonEventArgs e)\n {\n // Support window dragging & play / pause toggle\n if (Keyboard.Modifiers != ModifierKeys.None)\n return;\n\n if (FL.FlyleafHost is not { IsResizing: false, IsPanMoving: false, IsDragMoving: false })\n return;\n\n Point downPoint = FL.FlyleafHost!.Surface.PointToScreen(default);\n long downTick = Stopwatch.GetTimestamp();\n\n if (!FL.FlyleafHost.IsFullScreen && FL.FlyleafHost.Owner.WindowState == WindowState.Normal)\n {\n // normal window: window dragging\n DragMoveOwner();\n\n MouseLeftButtonUpAction(downPoint, downTick);\n }\n else\n {\n // fullscreen or maximized window: do action in KeyUp event\n _isLeftDragging = true;\n _downPoint = downPoint;\n _downTick = downTick;\n\n _downCursorPoint = e.GetPosition((IInputElement)sender);\n }\n }\n\n // When left dragging while maximized, move window back to normal and move window\n private void SurfaceOnMouseMove(object sender, MouseEventArgs e)\n {\n if (!_isLeftDragging || e.LeftButton != MouseButtonState.Pressed)\n return;\n\n if (FL.FlyleafHost!.IsFullScreen || FL.FlyleafHost.Owner.WindowState != WindowState.Maximized)\n return;\n\n Point curPoint = e.GetPosition((IInputElement)sender);\n\n // distinguish between mouse click and dragging (to prevent misfire)\n if (Math.Abs(curPoint.X - _downCursorPoint.X) >= 60 ||\n Math.Abs(curPoint.Y - _downCursorPoint.Y) >= 60)\n {\n _isLeftDragging = false;\n\n // change to normal window\n FL.FlyleafHost.Owner.WindowState = WindowState.Normal;\n\n // start dragging\n DragMoveOwner();\n }\n }\n\n private void DragMoveOwner()\n {\n // (!SeekBarShowOnlyMouseOver) always show cursor when moving\n // (SeekBarShowOnlyMouseOver) prevent to activate seek bar\n if (!FL.Config.SeekBarShowOnlyMouseOver)\n {\n FL.Player.Activity.IsEnabled = false;\n }\n\n FL.FlyleafHost!.Owner.DragMove();\n\n if (!FL.Config.SeekBarShowOnlyMouseOver)\n {\n FL.Player.Activity.IsEnabled = true;\n }\n }\n\n private void SurfaceOnMouseLeftButtonUp(object sender, MouseButtonEventArgs e)\n {\n if (!_isLeftDragging)\n return;\n\n _isLeftDragging = false;\n\n MouseLeftButtonUpAction(_downPoint, _downTick);\n }\n\n private void SurfaceOnLostMouseCapture(object sender, MouseEventArgs e)\n {\n _isLeftDragging = false;\n }\n\n private void MouseLeftButtonUpAction(Point downPoint, long downTick)\n {\n Point upPoint = FL.FlyleafHost!.Surface.PointToScreen(default);\n\n if (downPoint == upPoint // if not moved at all\n ||\n Stopwatch.GetElapsedTime(downTick) <= TimeSpan.FromMilliseconds(200)\n && // if click within 200ms and not so much moved\n Math.Abs(upPoint.X - downPoint.X) < 60 && Math.Abs(upPoint.Y - downPoint.Y) < 60)\n {\n SingleClickAction();\n }\n }\n\n private void SingleClickAction()\n {\n // Toggle play/pause on left click\n if (FL.Config.MouseSingleClickToPlay && FL.Player.CanPlay)\n FL.Player.TogglePlayPause();\n }\n\n private void FlyleafOnMouseWheel(object sender, MouseWheelEventArgs e)\n {\n // CTRL + Wheel : Zoom in / out\n // SHIFT + Wheel : Subtitles Up / Down\n // CTRL + SHIFT + Wheel : Subtitles Size Increase / Decrease\n if (e.Delta == 0)\n {\n return;\n }\n\n Window surface = FL.FlyleafHost!.Surface;\n\n bool ctrlDown = Keyboard.IsKeyDown(Key.LeftCtrl) || Keyboard.IsKeyDown(Key.RightCtrl);\n bool shiftDown = Keyboard.IsKeyDown(Key.LeftShift) || Keyboard.IsKeyDown(Key.RightShift);\n\n if (ctrlDown && shiftDown)\n {\n if (e.Delta > 0)\n {\n FL.Action.CmdSubsSizeIncrease.Execute();\n }\n else\n {\n FL.Action.CmdSubsSizeDecrease.Execute();\n }\n }\n else if (ctrlDown)\n {\n Point cur = e.GetPosition(surface);\n Point curDpi = new(cur.X * DpiX, cur.Y * DpiY);\n if (e.Delta > 0)\n {\n FL.Player.ZoomIn(curDpi);\n }\n else\n {\n FL.Player.ZoomOut(curDpi);\n }\n }\n else if (shiftDown)\n {\n if (e.Delta > 0)\n {\n FL.Action.CmdSubsPositionUp.Execute();\n }\n else\n {\n FL.Action.CmdSubsPositionDown.Execute();\n }\n }\n else\n {\n if (FL.Config.MouseWheelToVolumeUpDown)\n {\n if (e.Delta > 0)\n {\n FL.Player.Audio.VolumeUp();\n }\n else\n {\n FL.Player.Audio.VolumeDown();\n }\n }\n }\n\n e.Handled = true;\n }\n #endregion\n\n #region OSD\n private void SetupOSDStatus()\n {\n var player = FL.Player;\n\n player.PropertyChanged += (o, e) =>\n {\n switch (e.PropertyName)\n {\n case nameof(player.OSDMessage):\n OSDMessage = player.OSDMessage;\n break;\n case nameof(player.ReversePlayback):\n OSDMessage = $\"Reverse Playback {(player.ReversePlayback ? \"On\" : \"Off\")}\";\n break;\n case nameof(player.LoopPlayback):\n OSDMessage = $\"Loop Playback {(player.LoopPlayback ? \"On\" : \"Off\")}\";\n break;\n case nameof(player.Rotation):\n OSDMessage = $\"Rotation {player.Rotation}°\";\n break;\n case nameof(player.Speed):\n OSDMessage = $\"Speed x{player.Speed}\";\n break;\n case nameof(player.Zoom):\n OSDMessage = $\"Zoom {player.Zoom}%\";\n break;\n case nameof(player.Status):\n // Change only Play and Pause to icon\n switch (player.Status)\n {\n case Status.Paused:\n OSDIcon = PackIconKind.Pause;\n return;\n case Status.Playing:\n OSDIcon = PackIconKind.Play;\n return;\n }\n OSDMessage = $\"{player.Status.ToString()}\";\n break;\n }\n };\n\n player.Audio.PropertyChanged += (o, e) =>\n {\n switch (e.PropertyName)\n {\n case nameof(player.Audio.Volume):\n OSDMessage = $\"Volume {player.Audio.Volume}%\";\n break;\n case nameof(player.Audio.Mute):\n OSDIcon = player.Audio.Mute ? PackIconKind.VolumeOff : PackIconKind.VolumeHigh;\n break;\n }\n };\n\n player.Config.Player.PropertyChanged += (o, e) =>\n {\n switch (e.PropertyName)\n {\n case nameof(player.Config.Player.SeekAccurate):\n OSDMessage = $\"Always Seek Accurate {(player.Config.Player.SeekAccurate ? \"On\" : \"Off\")}\";\n break;\n }\n };\n\n player.Config.Audio.PropertyChanged += (o, e) =>\n {\n switch (e.PropertyName)\n {\n case nameof(player.Config.Audio.Enabled):\n OSDMessage = $\"Audio {(player.Config.Audio.Enabled ? \"Enabled\" : \"Disabled\")}\";\n break;\n case nameof(player.Config.Audio.Delay):\n OSDMessage = $\"Audio Delay {player.Config.Audio.Delay / 10000}ms\";\n break;\n }\n };\n\n player.Config.Video.PropertyChanged += (o, e) =>\n {\n switch (e.PropertyName)\n {\n case nameof(player.Config.Video.Enabled):\n OSDMessage = $\"Video {(player.Config.Video.Enabled ? \"Enabled\" : \"Disabled\")}\";\n break;\n case nameof(player.Config.Video.AspectRatio):\n OSDMessage = $\"Aspect Ratio {player.Config.Video.AspectRatio.ToString()}\";\n break;\n case nameof(player.Config.Video.VideoAcceleration):\n OSDMessage = $\"Video Acceleration {(player.Config.Video.VideoAcceleration ? \"On\" : \"Off\")}\";\n break;\n }\n };\n\n foreach (var (i, config) in player.Config.Subtitles.SubConfigs.Index())\n {\n config.PropertyChanged += (o, e) =>\n {\n switch (e.PropertyName)\n {\n case nameof(config.Delay):\n OSDMessage = $\"{(i == 0 ? \"Primary\" : \"Secondary\")} Subs Delay {config.Delay / 10000}ms\";\n break;\n case nameof(config.Visible):\n var primary = player.Config.Subtitles[0].Visible ? \"visible\" : \"hidden\";\n var secondary = player.Config.Subtitles[1].Visible ? \"visible\" : \"hidden\";\n\n if (player.Subtitles[1].Enabled)\n {\n OSDMessage = $\"Subs {primary} / {secondary}\";\n }\n else\n {\n OSDMessage = $\"Subs {primary}\";\n }\n break;\n }\n };\n }\n\n // app config\n FL.Config.PropertyChanged += (o, e) =>\n {\n switch (e.PropertyName)\n {\n case nameof(FL.Config.AlwaysOnTop):\n OSDMessage = $\"Always on Top {(FL.Config.AlwaysOnTop ? \"On\" : \"Off\")}\";\n break;\n }\n };\n\n FL.Config.Subs.PropertyChanged += (o, e) =>\n {\n switch (e.PropertyName)\n {\n case nameof(FL.Config.Subs.SubsAutoTextCopy):\n OSDMessage = $\"Subs Auto Text Copy {(FL.Config.Subs.SubsAutoTextCopy ? \"On\" : \"Off\")}\";\n break;\n }\n };\n }\n\n private CancellationTokenSource? _cancelMsgToken;\n\n public string OSDMessage\n {\n get => _osdMessage;\n set\n {\n if (Set(ref _osdMessage, value))\n {\n if (_cancelMsgToken != null)\n {\n _cancelMsgToken.Cancel();\n _cancelMsgToken.Dispose();\n _cancelMsgToken = null;\n }\n\n if (Set(ref _osdIcon, null, nameof(OSDIcon)))\n {\n OnPropertyChanged(nameof(IsOSDIcon));\n }\n\n _cancelMsgToken = new();\n\n var token = _cancelMsgToken.Token;\n _ = Task.Run(() => ClearOSD(3000, token));\n }\n }\n }\n private string _osdMessage = \"\";\n\n public PackIconKind? OSDIcon\n {\n get => _osdIcon;\n set\n {\n if (Set(ref _osdIcon, value))\n {\n OnPropertyChanged(nameof(IsOSDIcon));\n\n if (_cancelMsgToken != null)\n {\n _cancelMsgToken.Cancel();\n _cancelMsgToken.Dispose();\n _cancelMsgToken = null;\n }\n\n Set(ref _osdMessage, \"\", nameof(OSDMessage));\n\n _cancelMsgToken = new();\n\n var token = _cancelMsgToken.Token;\n _ = Task.Run(() => ClearOSD(500, token));\n }\n }\n }\n private PackIconKind? _osdIcon;\n\n public bool IsOSDIcon => OSDIcon != null;\n\n private async Task ClearOSD(int timeoutMs, CancellationToken token)\n {\n await Task.Delay(timeoutMs, token);\n\n if (token.IsCancellationRequested)\n return;\n\n Utils.UI(() =>\n {\n Set(ref _osdMessage, \"\", nameof(OSDMessage));\n if (Set(ref _osdIcon, null, nameof(OSDIcon)))\n {\n OnPropertyChanged(nameof(IsOSDIcon));\n }\n });\n }\n #endregion\n}\n"], ["/LLPlayer/WpfColorFontDialog/ColorFontChooser.xaml.cs", "using System;\nusing System.Collections.Generic;\nusing System.Linq;\nusing System.Text;\nusing System.Windows;\nusing System.Windows.Controls;\nusing System.Windows.Data;\nusing System.Windows.Documents;\nusing System.Windows.Input;\nusing System.Windows.Media;\nusing System.Windows.Media.Imaging;\nusing System.Windows.Navigation;\nusing System.Windows.Shapes;\n\nnamespace WpfColorFontDialog\n{\n /// \n /// Interaction logic for ColorFontChooser.xaml\n /// \n public partial class ColorFontChooser : UserControl\n {\n public FontInfo SelectedFont\n {\n get\n {\n return new FontInfo(this.txtSampleText.FontFamily, this.txtSampleText.FontSize, this.txtSampleText.FontStyle, this.txtSampleText.FontStretch, this.txtSampleText.FontWeight, this.colorPicker.SelectedColor.Brush);\n }\n }\n\n\n\n public bool ShowColorPicker\n {\n get { return (bool)GetValue(ShowColorPickerProperty); }\n set { SetValue(ShowColorPickerProperty, value); }\n }\n\n // Using a DependencyProperty as the backing store for ShowColorPicker. This enables animation, styling, binding, etc...\n public static readonly DependencyProperty ShowColorPickerProperty =\n DependencyProperty.Register(\"ShowColorPicker\", typeof(bool), typeof(ColorFontChooser), new PropertyMetadata(true, ShowColorPickerPropertyCallback));\n\n\n public bool AllowArbitraryFontSizes\n {\n get { return (bool)GetValue(AllowArbitraryFontSizesProperty); }\n set { SetValue(AllowArbitraryFontSizesProperty, value); }\n }\n\n // Using a DependencyProperty as the backing store for AllowArbitraryFontSizes. This enables animation, styling, binding, etc...\n public static readonly DependencyProperty AllowArbitraryFontSizesProperty =\n DependencyProperty.Register(\"AllowArbitraryFontSizes\", typeof(bool), typeof(ColorFontChooser), new PropertyMetadata(true, AllowArbitraryFontSizesPropertyCallback));\n\n\n public bool PreviewFontInFontList\n {\n get { return (bool)GetValue(PreviewFontInFontListProperty); }\n set { SetValue(PreviewFontInFontListProperty, value); }\n }\n\n // Using a DependencyProperty as the backing store for PreviewFontInFontList. This enables animation, styling, binding, etc...\n public static readonly DependencyProperty PreviewFontInFontListProperty =\n DependencyProperty.Register(\"PreviewFontInFontList\", typeof(bool), typeof(ColorFontChooser), new PropertyMetadata(true, PreviewFontInFontListPropertyCallback));\n\n\n public ColorFontChooser()\n {\n InitializeComponent();\n this.groupBoxColorPicker.Visibility = ShowColorPicker ? Visibility.Visible : Visibility.Collapsed;\n this.tbFontSize.IsEnabled = AllowArbitraryFontSizes;\n lstFamily.ItemTemplate = PreviewFontInFontList ? (DataTemplate)Resources[\"fontFamilyData\"] : (DataTemplate)Resources[\"fontFamilyDataWithoutPreview\"];\n }\n private static void PreviewFontInFontListPropertyCallback(DependencyObject d, DependencyPropertyChangedEventArgs e)\n {\n ColorFontChooser chooser = d as ColorFontChooser;\n if (e.NewValue == null)\n return;\n if ((bool)e.NewValue == true)\n chooser.lstFamily.ItemTemplate = chooser.Resources[\"fontFamilyData\"] as DataTemplate;\n else\n chooser.lstFamily.ItemTemplate = chooser.Resources[\"fontFamilyDataWithoutPreview\"] as DataTemplate;\n }\n private static void AllowArbitraryFontSizesPropertyCallback(DependencyObject d, DependencyPropertyChangedEventArgs e)\n {\n ColorFontChooser chooser = d as ColorFontChooser;\n if (e.NewValue == null)\n return;\n\n chooser.tbFontSize.IsEnabled = (bool)e.NewValue;\n\n }\n private static void ShowColorPickerPropertyCallback(DependencyObject d, DependencyPropertyChangedEventArgs e)\n {\n ColorFontChooser chooser = d as ColorFontChooser;\n if (e.NewValue == null)\n return;\n if ((bool)e.NewValue == true)\n chooser.groupBoxColorPicker.Visibility = Visibility.Visible;\n else\n chooser.groupBoxColorPicker.Visibility = Visibility.Collapsed;\n }\n\n private void colorPicker_ColorChanged(object sender, RoutedEventArgs e)\n {\n this.txtSampleText.Foreground = this.colorPicker.SelectedColor.Brush;\n }\n\n private void lstFontSizes_SelectionChanged(object sender, SelectionChangedEventArgs e)\n {\n if (this.tbFontSize != null && this.lstFontSizes.SelectedItem != null)\n {\n this.tbFontSize.Text = this.lstFontSizes.SelectedItem.ToString();\n }\n }\n\n private void tbFontSize_PreviewTextInput(object sender, TextCompositionEventArgs e)\n {\n e.Handled = !TextBoxTextAllowed(e.Text);\n }\n\n private void tbFontSize_Pasting(object sender, DataObjectPastingEventArgs e)\n {\n if (e.DataObject.GetDataPresent(typeof(String)))\n {\n String Text1 = (String)e.DataObject.GetData(typeof(String));\n if (!TextBoxTextAllowed(Text1)) e.CancelCommand();\n }\n else\n {\n e.CancelCommand();\n }\n }\n private Boolean TextBoxTextAllowed(String Text2)\n {\n return Array.TrueForAll(Text2.ToCharArray(),\n delegate (Char c) { return Char.IsDigit(c) || Char.IsControl(c); });\n }\n\n private void tbFontSize_LostFocus(object sender, RoutedEventArgs e)\n {\n if (tbFontSize.Text.Length == 0)\n {\n if (this.lstFontSizes.SelectedItem == null)\n {\n lstFontSizes.SelectedIndex = 0;\n }\n tbFontSize.Text = this.lstFontSizes.SelectedItem.ToString();\n\n }\n }\n\n private void tbFontSize_TextChanged(object sender, TextChangedEventArgs e)\n {\n foreach (int size in this.lstFontSizes.Items)\n {\n if (size.ToString() == tbFontSize.Text)\n {\n lstFontSizes.SelectedItem = size;\n lstFontSizes.ScrollIntoView(size);\n return;\n }\n }\n this.lstFontSizes.SelectedItem = null;\n }\n }\n}\n"], ["/LLPlayer/LLPlayer/Services/PDICSender.cs", "using System.Diagnostics;\nusing System.IO;\nusing System.Text;\n\nnamespace LLPlayer.Services;\n\npublic class PipeClient : IDisposable\n{\n private Process _proc;\n\n public PipeClient(string pipePath)\n {\n _proc = new Process\n {\n StartInfo = new ProcessStartInfo()\n {\n RedirectStandardOutput = true,\n RedirectStandardInput = true,\n RedirectStandardError = true,\n FileName = pipePath,\n CreateNoWindow = true,\n }\n };\n _proc.Start();\n }\n\n public async Task SendMessage(string message)\n {\n Debug.WriteLine(message);\n //byte[] bytes = JsonSerializer.SerializeToUtf8Bytes(message);\n\n // Enclose double quotes before and after since it is sent as a JSON string\n byte[] bytes = Encoding.UTF8.GetBytes('\"' + message + '\"');\n\n var length = BitConverter.GetBytes(bytes.Length);\n await _proc.StandardInput.BaseStream.WriteAsync(length, 0, length.Length);\n await _proc.StandardInput.BaseStream.WriteAsync(bytes, 0, bytes.Length);\n await _proc.StandardInput.BaseStream.FlushAsync();\n }\n\n public void Dispose()\n {\n _proc.Kill();\n _proc.WaitForExit();\n }\n}\n\npublic class PDICSender : IDisposable\n{\n private readonly PipeClient _pipeClient;\n public FlyleafManager FL { get; }\n\n public PDICSender(FlyleafManager fl)\n {\n FL = fl;\n\n string? exePath = FL.Config.Subs.PDICPipeExecutablePath;\n\n if (!File.Exists(exePath))\n {\n throw new FileNotFoundException($\"PDIC executable is not set correctly: {exePath}\");\n }\n\n _pipeClient = new PipeClient(exePath);\n }\n\n public async void Dispose()\n {\n await _pipeClient.SendMessage(\"p:Dictionary,Close,\");\n _pipeClient.Dispose();\n }\n\n public async Task Connect()\n {\n await _pipeClient.SendMessage(\"p:Dictionary,Open,\");\n }\n\n // Send the same way as Firepop\n // webextension native extensions\n // ref: https://developer.mozilla.org/en-US/docs/Mozilla/Add-ons/WebExtensions/Native_messaging\n\n // See Firepop source\n public async Task SendWithPipe(string sentence, int offset)\n {\n try\n {\n await _pipeClient.SendMessage($\"p:Dictionary,SetUrl,{App.Name}\");\n await _pipeClient.SendMessage($\"p:Dictionary,PopupSearch3,{offset},{sentence}\");\n\n // Incremental search\n //await _pipeClient.SendMessage($\"p:Simulate,InputWord3,word\");\n\n return 0;\n }\n catch (Exception e)\n {\n Debug.WriteLine(e.ToString());\n return -1;\n }\n }\n}\n"], ["/LLPlayer/FlyleafLib/Engine/Engine.Audio.cs", "using System;\nusing System.Collections.Generic;\nusing System.Collections.ObjectModel;\nusing System.ComponentModel;\nusing System.Threading.Tasks;\nusing System.Windows.Data;\n\nusing SharpGen.Runtime;\nusing SharpGen.Runtime.Win32;\n\nusing Vortice.MediaFoundation;\nusing static Vortice.XAudio2.XAudio2;\n\nusing FlyleafLib.MediaFramework.MediaDevice;\n\nnamespace FlyleafLib;\n\npublic class AudioEngine : CallbackBase, IMMNotificationClient, INotifyPropertyChanged\n{\n #region Properties (Public)\n\n public AudioEndpoint DefaultDevice { get; private set; } = new() { Id = \"0\", Name = \"Default\" };\n public AudioEndpoint CurrentDevice { get; private set; } = new();\n\n /// \n /// Whether no audio devices were found or audio failed to initialize\n /// \n public bool Failed { get; private set; }\n\n /// \n /// List of Audio Capture Devices\n /// \n public ObservableCollection\n CapDevices { get; set; } = new();\n\n public void RefreshCapDevices() => AudioDevice.RefreshDevices();\n\n /// \n /// List of Audio Devices\n /// \n public ObservableCollection\n Devices { get; private set; } = new();\n\n private readonly object lockDevices = new();\n #endregion\n\n IMMDeviceEnumerator deviceEnum;\n private object locker = new();\n\n public event PropertyChangedEventHandler PropertyChanged;\n\n public AudioEngine()\n {\n if (Engine.Config.DisableAudio)\n {\n Failed = true;\n return;\n }\n\n BindingOperations.EnableCollectionSynchronization(Devices, lockDevices);\n EnumerateDevices();\n }\n\n private void EnumerateDevices()\n {\n try\n {\n deviceEnum = new IMMDeviceEnumerator();\n\n var defaultDevice = deviceEnum.GetDefaultAudioEndpoint(DataFlow.Render, Role.Multimedia);\n if (defaultDevice == null)\n {\n Failed = true;\n return;\n }\n\n lock (lockDevices)\n {\n Devices.Clear();\n Devices.Add(DefaultDevice);\n foreach (var device in deviceEnum.EnumAudioEndpoints(DataFlow.Render, DeviceStates.Active))\n Devices.Add(new() { Id = device.Id, Name = device.FriendlyName });\n }\n\n CurrentDevice.Id = defaultDevice.Id;\n CurrentDevice.Name = defaultDevice.FriendlyName;\n\n if (Logger.CanInfo)\n {\n string dump = \"\";\n foreach (var device in deviceEnum.EnumAudioEndpoints(DataFlow.Render, DeviceStates.Active))\n dump += $\"{device.Id} | {device.FriendlyName} {(defaultDevice.Id == device.Id ? \"*\" : \"\")}\\r\\n\";\n Engine.Log.Info($\"Audio Devices\\r\\n{dump}\");\n }\n\n var xaudio2 = XAudio2Create();\n\n if (xaudio2 == null)\n Failed = true;\n else\n xaudio2.Dispose();\n\n deviceEnum.RegisterEndpointNotificationCallback(this);\n\n } catch { Failed = true; }\n }\n private void RefreshDevices()\n {\n lock (locker)\n {\n Utils.UIInvokeIfRequired(() => // UI Required?\n {\n List curs = new();\n List removed = new();\n\n lock (lockDevices)\n {\n foreach(var device in deviceEnum.EnumAudioEndpoints(DataFlow.Render, DeviceStates.Active))\n curs.Add(new () { Id = device.Id, Name = device.FriendlyName });\n\n foreach(var cur in curs)\n {\n bool exists = false;\n foreach (var device in Devices)\n if (cur.Id == device.Id)\n { exists = true; break; }\n\n if (!exists)\n {\n Engine.Log.Info($\"Audio device {cur} added\");\n Devices.Add(cur);\n }\n }\n\n foreach (var device in Devices)\n {\n if (device.Id == \"0\") // Default\n continue;\n\n bool exists = false;\n foreach(var cur in curs)\n if (cur.Id == device.Id)\n { exists = true; break; }\n\n if (!exists)\n {\n Engine.Log.Info($\"Audio device {device} removed\");\n removed.Add(device);\n }\n }\n\n foreach(var device in removed)\n Devices.Remove(device);\n }\n\n var defaultDevice = deviceEnum.GetDefaultAudioEndpoint(DataFlow.Render, Role.Multimedia);\n if (defaultDevice != null && CurrentDevice.Id != defaultDevice.Id)\n {\n CurrentDevice.Id = defaultDevice.Id;\n CurrentDevice.Name = defaultDevice.FriendlyName;\n PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(nameof(CurrentDevice)));\n }\n\n // Fall back to DefaultDevice *Non-UI thread otherwise will freeze (not sure where and why) during xaudio.Dispose()\n if (removed.Count > 0)\n Task.Run(() =>\n {\n foreach(var device in removed)\n {\n foreach(var player in Engine.Players)\n if (player.Audio.Device == device)\n player.Audio.Device = DefaultDevice;\n }\n });\n });\n }\n }\n\n public void OnDeviceStateChanged(string pwstrDeviceId, int newState) => RefreshDevices();\n public void OnDeviceAdded(string pwstrDeviceId) => RefreshDevices();\n public void OnDeviceRemoved(string pwstrDeviceId) => RefreshDevices();\n public void OnDefaultDeviceChanged(DataFlow flow, Role role, string pwstrDefaultDeviceId) => RefreshDevices();\n public void OnPropertyValueChanged(string pwstrDeviceId, PropertyKey key) { }\n\n public class AudioEndpoint\n {\n public string Id { get; set; }\n public string Name { get; set; }\n\n public override string ToString()\n => Name;\n }\n}\n"], ["/LLPlayer/FlyleafLib/Engine/Engine.Video.cs", "using System;\nusing System.Collections.Generic;\nusing System.Collections.ObjectModel;\n\nusing Vortice.DXGI;\n\nusing FlyleafLib.MediaFramework.MediaDevice;\n\nnamespace FlyleafLib;\n\npublic class VideoEngine\n{\n /// \n /// List of Video Capture Devices\n /// \n public ObservableCollection\n CapDevices { get; set; } = new();\n public void RefreshCapDevices() => VideoDevice.RefreshDevices();\n\n /// \n /// List of GPU Adpaters \n /// \n public Dictionary\n GPUAdapters { get; private set; }\n\n /// \n /// List of GPU Outputs from default GPU Adapter (Note: will no be updated on screen connect/disconnect)\n /// \n public List Screens { get; private set; } = new List();\n\n internal IDXGIFactory2 Factory;\n\n internal VideoEngine()\n {\n if (DXGI.CreateDXGIFactory1(out Factory).Failure)\n throw new InvalidOperationException(\"Cannot create IDXGIFactory1\");\n\n GPUAdapters = GetAdapters();\n }\n\n private Dictionary GetAdapters()\n {\n Dictionary adapters = new();\n\n string dump = \"\";\n\n for (uint i=0; Factory.EnumAdapters1(i, out var adapter).Success; i++)\n {\n bool hasOutput = false;\n\n List outputs = new();\n\n int maxHeight = 0;\n for (uint o=0; adapter.EnumOutputs(o, out var output).Success; o++)\n {\n GPUOutput gpout = new()\n {\n Id = GPUOutput.GPUOutputIdGenerator++,\n DeviceName= output.Description.DeviceName,\n Left = output.Description.DesktopCoordinates.Left,\n Top = output.Description.DesktopCoordinates.Top,\n Right = output.Description.DesktopCoordinates.Right,\n Bottom = output.Description.DesktopCoordinates.Bottom,\n IsAttached= output.Description.AttachedToDesktop,\n Rotation = (int)output.Description.Rotation\n };\n\n if (maxHeight < gpout.Height)\n maxHeight = gpout.Height;\n\n outputs.Add(gpout);\n\n if (gpout.IsAttached)\n hasOutput = true;\n\n output.Dispose();\n }\n\n if (Screens.Count == 0 && outputs.Count > 0)\n Screens = outputs;\n\n adapters[adapter.Description1.Luid] = new GPUAdapter()\n {\n SystemMemory = adapter.Description1.DedicatedSystemMemory.Value,\n VideoMemory = adapter.Description1.DedicatedVideoMemory.Value,\n SharedMemory = adapter.Description1.SharedSystemMemory.Value,\n Vendor = VendorIdStr(adapter.Description1.VendorId),\n Description = adapter.Description1.Description,\n Id = adapter.Description1.DeviceId,\n Luid = adapter.Description1.Luid,\n MaxHeight = maxHeight,\n HasOutput = hasOutput,\n Outputs = outputs\n };\n\n dump += $\"[#{i+1}] {adapters[adapter.Description1.Luid]}\\r\\n\";\n\n adapter.Dispose();\n }\n\n Engine.Log.Info($\"GPU Adapters\\r\\n{dump}\");\n\n return adapters;\n }\n\n // Use instead System.Windows.Forms.Screen.FromPoint\n public GPUOutput GetScreenFromPosition(int top, int left)\n {\n foreach(var screen in Screens)\n {\n if (top >= screen.Top && top <= screen.Bottom && left >= screen.Left && left <= screen.Right)\n return screen;\n }\n\n return null;\n }\n\n private static string VendorIdStr(uint vendorId)\n {\n switch (vendorId)\n {\n case 0x1002:\n return \"ATI\";\n case 0x10DE:\n return \"NVIDIA\";\n case 0x1106:\n return \"VIA\";\n case 0x8086:\n return \"Intel\";\n case 0x5333:\n return \"S3 Graphics\";\n case 0x4D4F4351:\n return \"Qualcomm\";\n default:\n return \"Unknown\";\n }\n }\n}\n"], ["/LLPlayer/LLPlayer/Extensions/ColorHexJsonConverter.cs", "using System.Globalization;\nusing System.Text.Json;\nusing System.Text.Json.Serialization;\nusing System.Windows.Media;\n\nnamespace LLPlayer.Extensions;\n\n// Convert Color object to HEX string\npublic class ColorHexJsonConverter : JsonConverter\n{\n public override void Write(Utf8JsonWriter writer, Color value, JsonSerializerOptions options)\n {\n string hex = $\"#{value.A:X2}{value.R:X2}{value.G:X2}{value.B:X2}\";\n writer.WriteStringValue(hex);\n }\n\n public override Color Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options)\n {\n string? hex = null;\n try\n {\n hex = reader.GetString();\n\n if (string.IsNullOrWhiteSpace(hex))\n {\n throw new JsonException(\"Color value is null or empty.\");\n }\n\n if (!hex.StartsWith(\"#\") || (hex.Length != 7 && hex.Length != 9))\n {\n throw new JsonException($\"Invalid color format: {hex}\");\n }\n byte a = 255;\n\n int start = 1;\n\n if (hex.Length == 9)\n {\n a = byte.Parse(hex.Substring(1, 2), NumberStyles.HexNumber);\n start = 3;\n }\n\n byte r = byte.Parse(hex.Substring(start, 2), NumberStyles.HexNumber);\n byte g = byte.Parse(hex.Substring(start + 2, 2), NumberStyles.HexNumber);\n byte b = byte.Parse(hex.Substring(start + 4, 2), NumberStyles.HexNumber);\n\n return Color.FromArgb(a, r, g, b);\n }\n catch (Exception ex)\n {\n throw new JsonException($\"Error parsing color value: {hex}\", ex);\n }\n }\n}\n"], ["/LLPlayer/FlyleafLib/MediaPlayer/Translation/Services/DeepLXTranslateService.cs", "using System.Net.Http;\nusing System.Text;\nusing System.Text.Encodings.Web;\nusing System.Text.Json;\nusing System.Threading;\nusing System.Threading.Tasks;\n\nnamespace FlyleafLib.MediaPlayer.Translation.Services;\n\n#nullable enable\n\npublic class DeepLXTranslateService : ITranslateService\n{\n private readonly HttpClient _httpClient;\n private string? _srcLang;\n private string? _targetLang;\n private readonly DeepLXTranslateSettings _settings;\n\n public DeepLXTranslateService(DeepLXTranslateSettings settings)\n {\n if (string.IsNullOrWhiteSpace(settings.Endpoint))\n {\n throw new TranslationConfigException(\n $\"Endpoint for {ServiceType} is not configured.\");\n }\n\n _settings = settings;\n _httpClient = new HttpClient();\n _httpClient.BaseAddress = new Uri(settings.Endpoint);\n _httpClient.Timeout = TimeSpan.FromMilliseconds(settings.TimeoutMs);\n }\n\n private static readonly JsonSerializerOptions JsonOptions = new()\n {\n Encoder = JavaScriptEncoder.UnsafeRelaxedJsonEscaping\n };\n\n public TranslateServiceType ServiceType => TranslateServiceType.DeepLX;\n\n public void Dispose()\n {\n _httpClient.Dispose();\n }\n\n public void Initialize(Language src, TargetLanguage target)\n {\n (TranslateLanguage srcLang, _) = this.TryGetLanguage(src, target);\n\n _srcLang = ToSourceCode(srcLang.ISO6391);\n _targetLang = ToTargetCode(target);\n }\n\n private string ToSourceCode(string iso6391)\n {\n return DeepLTranslateService.ToSourceCode(iso6391);\n }\n\n private string ToTargetCode(TargetLanguage target)\n {\n return DeepLTranslateService.ToTargetCode(target);\n }\n\n public async Task TranslateAsync(string text, CancellationToken token)\n {\n if (_srcLang == null || _targetLang == null)\n {\n throw new InvalidOperationException(\"must be initialized\");\n }\n\n string jsonResultString = \"\";\n int statusCode = -1;\n\n try\n {\n DeepLXTranslateRequest requestBody = new()\n {\n source_lang = _srcLang,\n target_lang = _targetLang,\n text = text\n };\n\n string jsonRequest = JsonSerializer.Serialize(requestBody, JsonOptions);\n using StringContent content = new(jsonRequest, Encoding.UTF8, \"application/json\");\n\n using var result = await _httpClient.PostAsync(\"/translate\", content, token).ConfigureAwait(false);\n jsonResultString = await result.Content.ReadAsStringAsync(token).ConfigureAwait(false);\n\n statusCode = (int)result.StatusCode;\n result.EnsureSuccessStatusCode();\n\n DeepLXTranslateResult? responseData = JsonSerializer.Deserialize(jsonResultString);\n return responseData!.data;\n }\n catch (OperationCanceledException ex)\n when (!ex.Message.StartsWith(\"The request was canceled due to the configured HttpClient.Timeout\"))\n {\n throw;\n }\n catch (Exception ex)\n {\n throw new TranslationException($\"Cannot request to {ServiceType}: {ex.Message}\", ex)\n {\n Data =\n {\n [\"status_code\"] = statusCode.ToString(),\n [\"response\"] = jsonResultString\n }\n };\n }\n }\n\n private class DeepLXTranslateRequest\n {\n public required string text { get; init; }\n public string? source_lang { get; init; }\n public required string target_lang { get; init; }\n }\n\n private class DeepLXTranslateResult\n {\n public required string[] alternatives { get; init; }\n public required string data { get; init; }\n public required string source_lang { get; init; }\n public required string target_lang { get; init; }\n }\n}\n"], ["/LLPlayer/LLPlayer/Converters/FlyleafConverters.cs", "using System.Globalization;\nusing System.Windows;\nusing System.Windows.Controls.Primitives;\nusing System.Windows.Data;\nusing System.Windows.Media;\nusing FlyleafLib;\nusing static FlyleafLib.MediaFramework.MediaDemuxer.Demuxer;\n\nnamespace LLPlayer.Converters;\n\n[ValueConversion(typeof(int), typeof(Qualities))]\npublic class QualityToLevelsConverter : IValueConverter\n{\n public enum Qualities\n {\n None,\n Low,\n Med,\n High,\n _4k\n }\n\n public object Convert(object value, Type targetType, object parameter, CultureInfo culture)\n {\n int videoHeight = (int)value;\n\n if (videoHeight > 1080)\n return Qualities._4k;\n if (videoHeight > 720)\n return Qualities.High;\n if (videoHeight == 720)\n return Qualities.Med;\n\n return Qualities.Low;\n }\n public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture) { throw new NotImplementedException(); }\n}\n\n[ValueConversion(typeof(int), typeof(Volumes))]\npublic class VolumeToLevelsConverter : IValueConverter\n{\n public enum Volumes\n {\n Mute,\n Low,\n Med,\n High\n }\n\n public object Convert(object value, Type targetType, object parameter, CultureInfo culture)\n {\n int volume = (int)value;\n\n if (volume == 0)\n return Volumes.Mute;\n if (volume > 99)\n return Volumes.High;\n if (volume > 49)\n return Volumes.Med;\n return Volumes.Low;\n }\n public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture) { throw new NotImplementedException(); }\n}\n\npublic class SumConverter : IMultiValueConverter\n{\n public object Convert(object[] values, Type targetType, object parameter, CultureInfo culture)\n {\n double sum = 0;\n\n if (values == null)\n return sum;\n\n foreach (object value in values)\n {\n if (value == DependencyProperty.UnsetValue)\n continue;\n sum += (double)value;\n }\n\n return sum;\n }\n\n public object[] ConvertBack(object value, Type[] targetTypes, object parameter, CultureInfo culture)\n => throw new NotImplementedException();\n}\n\npublic class PlaylistItemsConverter : IMultiValueConverter\n{\n public object Convert(object[] values, Type targetType, object parameter, CultureInfo culture)\n {\n return $\"Playlist ({values[0]}/{values[1]})\";\n }\n\n public object[] ConvertBack(object value, Type[] targetTypes, object parameter, CultureInfo culture)\n => throw new NotImplementedException();\n}\n\n[ValueConversion(typeof(Color), typeof(string))]\npublic class ColorToHexConverter : IValueConverter\n{\n public object? Convert(object? value, Type targetType, object? parameter, CultureInfo culture)\n {\n if (value is null)\n return null;\n\n string UpperHexString(int i) => i.ToString(\"X2\").ToUpper();\n Color color = (Color)value;\n string hex = UpperHexString(color.R) +\n UpperHexString(color.G) +\n UpperHexString(color.B);\n return hex;\n }\n\n public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)\n {\n try\n {\n return ColorConverter.ConvertFromString(\"#\" + value.ToString());\n }\n catch (Exception)\n {\n // ignored\n }\n\n return Binding.DoNothing;\n }\n}\n\npublic class Tuple3Converter : IMultiValueConverter\n{\n public object Convert(object[] values, Type targetType, object parameter, CultureInfo culture)\n {\n return (values[0], values[1], values[2]);\n }\n\n public object[] ConvertBack(object value, Type[] targetTypes, object parameter, CultureInfo culture)\n {\n throw new NotImplementedException();\n }\n}\n\npublic class SubIndexToIsEnabledConverter : IMultiValueConverter\n{\n public object Convert(object[] values, Type targetType, object parameter, CultureInfo culture)\n {\n if (values.Any(x => x == DependencyProperty.UnsetValue))\n return DependencyProperty.UnsetValue;\n\n // values[0] = Tag (index)\n // values[1] = IsPrimaryEnabled\n // values[2] = IsSecondaryEnabled\n int index = int.Parse((string)values[0]);\n bool isPrimaryEnabled = (bool)values[1];\n bool isSecondaryEnabled = (bool)values[2];\n\n return index == 0 ? isPrimaryEnabled : isSecondaryEnabled;\n }\n\n public object[] ConvertBack(object value, Type[] targetTypes, object parameter, CultureInfo culture)\n {\n throw new NotImplementedException();\n }\n}\n\n[ValueConversion(typeof(IEnumerable), typeof(DoubleCollection))]\npublic class ChaptersToTicksConverter : IValueConverter\n{\n public object Convert(object value, Type targetType, object parameter, CultureInfo culture)\n {\n if (value is IEnumerable chapters)\n {\n // Convert tick count to seconds\n List secs = chapters.Select(c => c.StartTime / 10000000.0).ToList();\n if (secs.Count <= 1)\n {\n return Binding.DoNothing;\n }\n\n return new DoubleCollection(secs);\n }\n\n return Binding.DoNothing;\n }\n\n public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)\n {\n throw new NotImplementedException();\n }\n}\n\n[ValueConversion(typeof(IEnumerable), typeof(TickPlacement))]\npublic class ChaptersToTickPlacementConverter : IValueConverter\n{\n public TickPlacement TickPlacement { get; set; }\n\n public object Convert(object value, Type targetType, object parameter, CultureInfo culture)\n {\n if (value is IEnumerable chapters && chapters.Count() >= 2)\n {\n return TickPlacement;\n }\n\n return TickPlacement.None;\n }\n\n public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)\n {\n throw new NotImplementedException();\n }\n}\n\npublic class AspectRatioIsCheckedConverter : IMultiValueConverter\n{\n // values[0]: SelectedAspectRatio, values[1]: current AspectRatio\n public object Convert(object[] values, Type targetType, object parameter, CultureInfo culture)\n {\n if (values.Length < 2)\n {\n return false;\n }\n\n if (values[0] is AspectRatio selected && values[1] is AspectRatio current)\n {\n return selected.Equals(current);\n }\n return false;\n }\n\n public object[] ConvertBack(object value, Type[] targetTypes, object parameter, CultureInfo culture)\n {\n throw new NotImplementedException();\n }\n}\n"], ["/LLPlayer/FlyleafLib/MediaFramework/MediaStream/AudioStream.cs", "using FlyleafLib.MediaFramework.MediaDemuxer;\n\nnamespace FlyleafLib.MediaFramework.MediaStream;\n\npublic unsafe class AudioStream : StreamBase\n{\n public int Bits { get; set; }\n public int Channels { get; set; }\n public ulong ChannelLayout { get; set; }\n public string ChannelLayoutStr { get; set; }\n public AVSampleFormat SampleFormat { get; set; }\n public string SampleFormatStr { get; set; }\n public int SampleRate { get; set; }\n public AVCodecID CodecIDOrig { get; set; }\n\n public override string GetDump()\n => $\"[{Type} #{StreamIndex}-{Language.IdSubLanguage}{(Title != null ? \"(\" + Title + \")\" : \"\")}] {Codec} {SampleFormatStr}@{Bits} {SampleRate / 1000}KHz {ChannelLayoutStr} | [BR: {BitRate}] | {Utils.TicksToTime((long)(AVStream->start_time * Timebase))}/{Utils.TicksToTime((long)(AVStream->duration * Timebase))} | {Utils.TicksToTime(StartTime)}/{Utils.TicksToTime(Duration)}\";\n\n public AudioStream() { }\n public AudioStream(Demuxer demuxer, AVStream* st) : base(demuxer, st) => Refresh();\n\n public override void Refresh()\n {\n base.Refresh();\n\n SampleFormat = (AVSampleFormat) Enum.ToObject(typeof(AVSampleFormat), AVStream->codecpar->format);\n SampleFormatStr = av_get_sample_fmt_name(SampleFormat);\n SampleRate = AVStream->codecpar->sample_rate;\n\n if (AVStream->codecpar->ch_layout.order == AVChannelOrder.Unspec)\n av_channel_layout_default(&AVStream->codecpar->ch_layout, AVStream->codecpar->ch_layout.nb_channels);\n\n ChannelLayout = AVStream->codecpar->ch_layout.u.mask;\n Channels = AVStream->codecpar->ch_layout.nb_channels;\n Bits = AVStream->codecpar->bits_per_coded_sample;\n\n // https://trac.ffmpeg.org/ticket/7321\n CodecIDOrig = CodecID;\n if (CodecID == AVCodecID.Mp2 && (SampleFormat == AVSampleFormat.Fltp || SampleFormat == AVSampleFormat.Flt))\n CodecID = AVCodecID.Mp3; // OR? st->codecpar->format = (int) AVSampleFormat.AV_SAMPLE_FMT_S16P;\n\n byte[] buf = new byte[50];\n fixed (byte* bufPtr = buf)\n {\n av_channel_layout_describe(&AVStream->codecpar->ch_layout, bufPtr, (nuint)buf.Length);\n ChannelLayoutStr = Utils.BytePtrToStringUTF8(bufPtr);\n }\n }\n}\n"], ["/LLPlayer/FlyleafLib/MediaFramework/MediaStream/SubtitlesStream.cs", "using System.IO;\nusing System.Linq;\nusing FlyleafLib.MediaFramework.MediaDemuxer;\nusing FlyleafLib.MediaPlayer;\n\nnamespace FlyleafLib.MediaFramework.MediaStream;\n\npublic enum SelectSubMethod\n{\n Original,\n OCR\n}\n\n// Both external and internal subtitles implement this interface and use it with PopMenu.\npublic interface ISubtitlesStream\n{\n public bool EnabledPrimarySubtitle { get; }\n public bool EnabledSecondarySubtitle { get; }\n}\n\npublic class SelectedSubMethod\n{\n private readonly ISubtitlesStream _stream;\n\n public SelectedSubMethod(ISubtitlesStream stream, SelectSubMethod method)\n {\n _stream = stream;\n SelectSubMethod = method;\n }\n\n public SelectSubMethod SelectSubMethod { get; }\n\n public bool IsPrimaryEnabled => _stream.EnabledPrimarySubtitle\n && SelectSubMethod == SubtitlesSelectedHelper.PrimaryMethod;\n\n public bool IsSecondaryEnabled => _stream.EnabledSecondarySubtitle\n && SelectSubMethod == SubtitlesSelectedHelper.SecondaryMethod;\n}\n\npublic unsafe class SubtitlesStream : StreamBase, ISubtitlesStream\n{\n public bool IsBitmap { get; set; }\n\n public SelectedSubMethod[] SelectedSubMethods {\n get\n {\n var methods = (SelectSubMethod[])Enum.GetValues(typeof(SelectSubMethod));\n if (!IsBitmap)\n {\n // delete OCR if text sub\n methods = methods.Where(m => m != SelectSubMethod.OCR).ToArray();\n }\n\n return methods.\n Select(m => new SelectedSubMethod(this, m)).ToArray();\n }\n }\n\n public string DisplayMember => $\"[#{StreamIndex}] {Language} ({(IsBitmap ? \"BMP\" : \"TXT\")})\";\n\n public override string GetDump()\n => $\"[{Type} #{StreamIndex}-{Language.IdSubLanguage}{(Title != null ? \"(\" + Title + \")\" : \"\")}] {Codec} | [BR: {BitRate}] | {Utils.TicksToTime((long)(AVStream->start_time * Timebase))}/{Utils.TicksToTime((long)(AVStream->duration * Timebase))} | {Utils.TicksToTime(StartTime)}/{Utils.TicksToTime(Duration)}\";\n\n public SubtitlesStream() { }\n public SubtitlesStream(Demuxer demuxer, AVStream* st) : base(demuxer, st) => Refresh();\n\n public override void Refresh()\n {\n base.Refresh();\n\n var codecDescr = avcodec_descriptor_get(CodecID);\n IsBitmap = codecDescr != null && (codecDescr->props & CodecPropFlags.BitmapSub) != 0;\n\n if (Demuxer.FormatContext->nb_streams == 1) // External Streams (mainly for .sub will have as start time the first subs timestamp)\n StartTime = 0;\n }\n\n public void ExternalStreamAdded()\n {\n // VobSub (parse .idx data to extradata - based on .sub url)\n if (CodecID == AVCodecID.DvdSubtitle && ExternalStream != null && ExternalStream.Url.EndsWith(\".sub\", StringComparison.OrdinalIgnoreCase))\n {\n var idxFile = ExternalStream.Url.Substring(0, ExternalStream.Url.Length - 3) + \"idx\";\n if (File.Exists(idxFile))\n {\n var bytes = File.ReadAllBytes(idxFile);\n AVStream->codecpar->extradata = (byte*)av_malloc((nuint)bytes.Length);\n AVStream->codecpar->extradata_size = bytes.Length;\n Span src = new(bytes);\n Span dst = new(AVStream->codecpar->extradata, bytes.Length);\n src.CopyTo(dst);\n }\n }\n }\n}\n"], ["/LLPlayer/FlyleafLib/MediaFramework/RunThreadBase.cs", "using System.Threading;\n\nusing static FlyleafLib.Logger;\n\nnamespace FlyleafLib.MediaFramework;\n\npublic abstract class RunThreadBase : NotifyPropertyChanged\n{\n Status _Status = Status.Stopped;\n public Status Status {\n get => _Status;\n set\n {\n lock (lockStatus)\n {\n if (CanDebug && _Status != Status.QueueFull && value != Status.QueueFull && _Status != Status.QueueEmpty && value != Status.QueueEmpty)\n Log.Debug($\"{_Status} -> {value}\");\n\n _Status = value;\n }\n }\n }\n public bool IsRunning {\n get\n {\n bool ret = false;\n lock (lockStatus) ret = thread != null && thread.IsAlive && Status != Status.Paused;\n return ret;\n }\n }\n\n public bool CriticalArea { get; protected set; }\n public bool Disposed { get; protected set; } = true;\n public int UniqueId { get; protected set; } = -1;\n public bool PauseOnQueueFull{ get; set; }\n\n protected Thread thread;\n protected AutoResetEvent threadARE = new(false);\n protected string threadName {\n get => _threadName;\n set\n {\n _threadName = value;\n Log = new LogHandler((\"[#\" + UniqueId + \"]\").PadRight(8, ' ') + $\" [{threadName}] \");\n }\n }\n string _threadName;\n\n internal LogHandler Log;\n internal object lockActions = new();\n internal object lockStatus = new();\n\n public RunThreadBase(int uniqueId = -1)\n => UniqueId = uniqueId == -1 ? Utils.GetUniqueId() : uniqueId;\n\n public void Pause()\n {\n lock (lockActions)\n {\n lock (lockStatus)\n {\n PauseOnQueueFull = false;\n\n if (Disposed || thread == null || !thread.IsAlive || Status == Status.Stopping || Status == Status.Stopped || Status == Status.Ended || Status == Status.Pausing || Status == Status.Paused) return;\n Status = Status.Pausing;\n }\n while (Status == Status.Pausing) Thread.Sleep(5);\n }\n }\n public void Start()\n {\n lock (lockActions)\n {\n int retries = 1;\n while (thread != null && thread.IsAlive && CriticalArea)\n {\n Thread.Sleep(5); // use small steps to re-check CriticalArea (demuxer can have 0 packets again after processing the received ones)\n retries++;\n if (retries > 16)\n {\n if (CanTrace) Log.Trace($\"Start() exhausted\");\n return;\n }\n }\n\n lock (lockStatus)\n {\n if (Disposed) return;\n\n PauseOnQueueFull = false;\n\n if (Status == Status.Draining) while (Status != Status.Draining) Thread.Sleep(3);\n if (Status == Status.Stopping) while (Status != Status.Stopping) Thread.Sleep(3);\n if (Status == Status.Pausing) while (Status != Status.Pausing) Thread.Sleep(3);\n\n if (Status == Status.Ended) return;\n\n if (Status == Status.Paused)\n {\n threadARE.Set();\n while (Status == Status.Paused) Thread.Sleep(3);\n return;\n }\n\n if (thread != null && thread.IsAlive) return; // might re-check CriticalArea\n\n thread = new Thread(() => Run());\n Status = Status.Running;\n\n thread.Name = $\"[#{UniqueId}] [{threadName}]\"; thread.IsBackground= true; thread.Start();\n while (!thread.IsAlive) { if (CanTrace) Log.Trace(\"Waiting thread to come up\"); Thread.Sleep(3); }\n }\n }\n }\n public void Stop()\n {\n lock (lockActions)\n {\n lock (lockStatus)\n {\n PauseOnQueueFull = false;\n\n if (Disposed || thread == null || !thread.IsAlive || Status == Status.Stopping || Status == Status.Stopped || Status == Status.Ended) return;\n if (Status == Status.Pausing) while (Status != Status.Pausing) Thread.Sleep(3);\n Status = Status.Stopping;\n threadARE.Set();\n }\n\n while (Status == Status.Stopping && thread != null && thread.IsAlive) Thread.Sleep(5);\n }\n }\n\n protected void Run()\n {\n if (CanDebug) Log.Debug($\"Thread started ({Status})\");\n\n do\n {\n RunInternal();\n\n if (Status == Status.Pausing)\n {\n threadARE.Reset();\n Status = Status.Paused;\n threadARE.WaitOne();\n if (Status == Status.Paused)\n {\n if (CanDebug) Log.Debug($\"{_Status} -> {Status.Running}\");\n _Status = Status.Running;\n }\n }\n\n } while (Status == Status.Running);\n\n if (Status != Status.Ended) Status = Status.Stopped;\n\n if (CanDebug) Log.Debug($\"Thread stopped ({Status})\");\n }\n protected abstract void RunInternal();\n}\n\npublic enum Status\n{\n Opening,\n\n Stopping,\n Stopped,\n\n Pausing,\n Paused,\n\n Running,\n QueueFull,\n QueueEmpty,\n Draining,\n\n Ended\n}\n"], ["/LLPlayer/WpfColorFontDialog/ColorFontDialog.xaml.cs", "using System.Collections;\nusing System.Windows;\nusing System.Windows.Media;\n\nnamespace WpfColorFontDialog\n{\n /// \n /// Interaction logic for ColorFontDialog.xaml\n /// \n public partial class ColorFontDialog : Window\n {\n private FontInfo _selectedFont;\n\n public FontInfo Font\n {\n get\n {\n return _selectedFont;\n }\n set\n {\n _selectedFont = value;\n }\n }\n\n private int[] _defaultFontSizes = { 8, 9, 10, 11, 12, 14, 16, 18, 20, 22, 24, 26, 28, 36, 48, 72, 96 };\n private int[] _fontSizes = null;\n public int[] FontSizes\n {\n get\n {\n return _fontSizes ?? _defaultFontSizes;\n }\n set\n {\n _fontSizes = value;\n }\n }\n public ColorFontDialog(bool previewFontInFontList = true, bool allowArbitraryFontSizes = true, bool showColorPicker = true)\n {\n // Disable style inheritance from parents and apply standard styles\n InheritanceBehavior = InheritanceBehavior.SkipToThemeNext;\n\n InitializeComponent();\n I18NUtil.SetLanguage(Resources);\n this.colorFontChooser.PreviewFontInFontList = previewFontInFontList;\n this.colorFontChooser.AllowArbitraryFontSizes = allowArbitraryFontSizes;\n this.colorFontChooser.ShowColorPicker = showColorPicker;\n }\n\n private void btnOk_Click(object sender, RoutedEventArgs e)\n {\n this.Font = this.colorFontChooser.SelectedFont;\n base.DialogResult = new bool?(true);\n }\n\n private void SyncFontColor()\n {\n int colorIdx = AvailableColors.GetFontColorIndex(this.Font.Color);\n this.colorFontChooser.colorPicker.superCombo.SelectedIndex = colorIdx;\n this.colorFontChooser.txtSampleText.Foreground = this.Font.Color.Brush;\n this.colorFontChooser.colorPicker.superCombo.BringIntoView();\n }\n\n private void SyncFontName()\n {\n string fontFamilyName = this._selectedFont.Family.Source;\n bool foundMatch = false;\n int idx = 0;\n foreach (object item in (IEnumerable)this.colorFontChooser.lstFamily.Items)\n {\n if (fontFamilyName == item.ToString())\n {\n foundMatch = true;\n break;\n }\n idx++;\n }\n if (!foundMatch)\n {\n idx = 0;\n }\n this.colorFontChooser.lstFamily.SelectedIndex = idx;\n this.colorFontChooser.lstFamily.ScrollIntoView(this.colorFontChooser.lstFamily.Items[idx]);\n }\n\n private void SyncFontSize()\n {\n double fontSize = this._selectedFont.Size;\n this.colorFontChooser.lstFontSizes.ItemsSource = FontSizes;\n this.colorFontChooser.tbFontSize.Text = fontSize.ToString();\n }\n\n private void SyncFontTypeface()\n {\n string fontTypeFaceSb = FontInfo.TypefaceToString(this._selectedFont.Typeface);\n int idx = 0;\n foreach (object item in (IEnumerable)this.colorFontChooser.lstTypefaces.Items)\n {\n if (fontTypeFaceSb == FontInfo.TypefaceToString(item as FamilyTypeface))\n {\n break;\n }\n idx++;\n }\n this.colorFontChooser.lstTypefaces.SelectedIndex = idx;\n this.colorFontChooser.lstTypefaces.ScrollIntoView(this.colorFontChooser.lstTypefaces.SelectedItem);\n }\n\n private void Window_Loaded_1(object sender, RoutedEventArgs e)\n {\n this.SyncFontColor();\n this.SyncFontName();\n this.SyncFontSize();\n this.SyncFontTypeface();\n }\n }\n}\n"], ["/LLPlayer/FlyleafLib/Engine/Engine.cs", "using System.Collections.Generic;\nusing System.Threading.Tasks;\nusing System.Threading;\nusing System.Windows;\n\nusing FlyleafLib.MediaFramework.MediaDevice;\nusing FlyleafLib.MediaPlayer;\n\nnamespace FlyleafLib;\n\n/// \n/// Flyleaf Engine\n/// \npublic static class Engine\n{\n /// \n /// Engine has been loaded and is ready for use\n /// \n public static bool IsLoaded { get; private set; }\n\n /// \n /// Engine's configuration\n /// \n public static EngineConfig Config { get; private set; }\n\n /// \n /// Audio Engine\n /// \n public static AudioEngine Audio { get; private set; }\n\n /// \n /// Video Engine\n /// \n public static VideoEngine Video { get; private set; }\n\n /// \n /// Plugins Engine\n /// \n public static PluginsEngine Plugins { get; private set; }\n\n /// \n /// FFmpeg Engine\n /// \n public static FFmpegEngine FFmpeg { get; private set; }\n\n /// \n /// List of active Players\n /// \n public static List Players { get; private set; }\n\n public static event EventHandler\n Loaded;\n\n internal static LogHandler\n Log;\n\n static Thread tMaster;\n static object lockEngine = new();\n static bool isLoading;\n static int timePeriod;\n\n /// \n /// Initializes Flyleaf's Engine (Must be called from UI thread)\n /// \n /// Engine's configuration\n public static void Start(EngineConfig config = null) => StartInternal(config);\n\n /// \n /// Initializes Flyleaf's Engine Async (Must be called from UI thread)\n /// \n /// Engine's configuration\n public static void StartAsync(EngineConfig config = null) => StartInternal(config, true);\n\n /// \n /// Requests timeBeginPeriod(1) - You should call TimeEndPeriod1 when not required anymore\n /// \n public static void TimeBeginPeriod1()\n {\n lock (lockEngine)\n {\n timePeriod++;\n\n if (timePeriod == 1)\n {\n Log.Trace(\"timeBeginPeriod(1)\");\n Utils.NativeMethods.TimeBeginPeriod(1);\n }\n }\n }\n\n /// \n /// Stops previously requested timeBeginPeriod(1)\n /// \n public static void TimeEndPeriod1()\n {\n lock (lockEngine)\n {\n timePeriod--;\n\n if (timePeriod == 0)\n {\n Log.Trace(\"timeEndPeriod(1)\");\n Utils.NativeMethods.TimeEndPeriod(1);\n }\n }\n }\n\n private static void StartInternal(EngineConfig config = null, bool async = false)\n {\n lock (lockEngine)\n {\n if (isLoading)\n return;\n\n isLoading = true;\n\n Config = config ?? new EngineConfig();\n\n if (Application.Current == null)\n new Application();\n\n StartInternalUI();\n\n if (async)\n Task.Run(() => StartInternalNonUI());\n else\n StartInternalNonUI();\n }\n }\n\n private static void StartInternalUI()\n {\n Application.Current.Exit += (o, e) =>\n {\n Config.UIRefresh = false;\n Config.UIRefreshInterval = 1;\n\n while (Players.Count != 0)\n Players[0].Dispose();\n };\n\n Logger.SetOutput();\n\n Log = new LogHandler(\"[FlyleafEngine] \");\n\n Audio = new AudioEngine();\n if (Config.FFmpegLoadProfile == LoadProfile.All)\n AudioDevice.RefreshDevices();\n }\n\n private static void StartInternalNonUI()\n {\n var version = System.Reflection.Assembly.GetExecutingAssembly().GetName().Version;\n Log.Info($\"FlyleafLib {version.Major }.{version.Minor}.{version.Build}\");\n\n FFmpeg = new FFmpegEngine();\n Video = new VideoEngine();\n if (Config.FFmpegLoadProfile == LoadProfile.All)\n VideoDevice.RefreshDevices();\n Plugins = new PluginsEngine();\n Players = new List();\n\n IsLoaded = true;\n Loaded?.Invoke(null, null);\n\n if (Config.UIRefresh)\n StartThread();\n }\n internal static void AddPlayer(Player player)\n {\n lock (Players)\n Players.Add(player);\n }\n internal static int GetPlayerPos(int playerId)\n {\n for (int i=0; i { MasterThread(); })\n {\n Name = \"FlyleafEngine\",\n IsBackground = true\n };\n tMaster.Start();\n }\n internal static void MasterThread()\n {\n Log.Info(\"Thread started\");\n\n int curLoop = 0;\n int secondLoops = 1000 / Config.UIRefreshInterval;\n long prevTicks = DateTime.UtcNow.Ticks;\n double curSecond= 0;\n\n do\n {\n try\n {\n if (Players.Count == 0)\n {\n Thread.Sleep(Config.UIRefreshInterval);\n continue;\n }\n\n curLoop++;\n if (curLoop == secondLoops)\n {\n long curTicks = DateTime.UtcNow.Ticks;\n curSecond = (curTicks - prevTicks) / 10000000.0;\n prevTicks = curTicks;\n }\n\n lock (Players)\n foreach (var player in Players)\n {\n /* Every UIRefreshInterval */\n player.Activity.RefreshMode();\n\n /* Every Second */\n if (curLoop == secondLoops)\n {\n if (player.Config.Player.Stats)\n {\n var curStats = player.stats;\n // TODO: L: including Subtitles bytes?\n long curTotalBytes = player.VideoDemuxer.TotalBytes + player.AudioDemuxer.TotalBytes;\n long curVideoBytes = player.VideoDemuxer.VideoPackets.Bytes + player.AudioDemuxer.VideoPackets.Bytes;\n long curAudioBytes = player.VideoDemuxer.AudioPackets.Bytes + player.AudioDemuxer.AudioPackets.Bytes;\n\n player.bitRate = (curTotalBytes - curStats.TotalBytes) * 8 / 1000.0;\n player.Video.bitRate= (curVideoBytes - curStats.VideoBytes) * 8 / 1000.0;\n player.Audio.bitRate= (curAudioBytes - curStats.AudioBytes) * 8 / 1000.0;\n\n curStats.TotalBytes = curTotalBytes;\n curStats.VideoBytes = curVideoBytes;\n curStats.AudioBytes = curAudioBytes;\n\n if (player.IsPlaying)\n {\n player.Video.fpsCurrent = (player.Video.FramesDisplayed - curStats.FramesDisplayed) / curSecond;\n curStats.FramesDisplayed = player.Video.FramesDisplayed;\n }\n }\n }\n }\n\n if (curLoop == secondLoops)\n curLoop = 0;\n\n Action action = () =>\n {\n try\n {\n foreach (var player in Players)\n {\n /* Every UIRefreshInterval */\n\n // Activity Mode Refresh & Hide Mouse Cursor (FullScreen only)\n if (player.Activity.mode != player.Activity._Mode)\n player.Activity.SetMode();\n\n // CurTime / Buffered Duration (+Duration for HLS)\n if (!Config.UICurTimePerSecond)\n player.UpdateCurTime();\n else if (player.Status == Status.Paused)\n {\n if (player.MainDemuxer.IsRunning)\n player.UpdateCurTime();\n else\n player.UpdateBufferedDuration();\n }\n\n /* Every Second */\n if (curLoop == 0)\n {\n // Stats Refresh (BitRates / FrameDisplayed / FramesDropped / FPS)\n if (player.Config.Player.Stats)\n {\n player.BitRate = player.BitRate;\n player.Video.BitRate = player.Video.BitRate;\n player.Audio.BitRate = player.Audio.BitRate;\n\n if (player.IsPlaying)\n {\n player.Audio.FramesDisplayed= player.Audio.FramesDisplayed;\n player.Audio.FramesDropped = player.Audio.FramesDropped;\n\n player.Video.FramesDisplayed= player.Video.FramesDisplayed;\n player.Video.FramesDropped = player.Video.FramesDropped;\n player.Video.FPSCurrent = player.Video.FPSCurrent;\n }\n }\n }\n }\n } catch { }\n };\n\n Utils.UI(action);\n Thread.Sleep(Config.UIRefreshInterval);\n\n } catch { curLoop = 0; }\n\n } while (Config.UIRefresh);\n\n Log.Info(\"Thread stopped\");\n }\n}\n"], ["/LLPlayer/LLPlayer/Controls/Settings/SettingsSubtitlesOCR.xaml.cs", "using System.Collections.ObjectModel;\nusing System.ComponentModel;\nusing System.Diagnostics.CodeAnalysis;\nusing System.Windows;\nusing System.Windows.Controls;\nusing Windows.Media.Ocr;\nusing FlyleafLib;\nusing LLPlayer.Extensions;\nusing LLPlayer.Services;\nusing LLPlayer.Views;\n\nnamespace LLPlayer.Controls.Settings;\n\npublic partial class SettingsSubtitlesOCR : UserControl\n{\n public SettingsSubtitlesOCR()\n {\n InitializeComponent();\n\n DataContext = ((App)Application.Current).Container.Resolve();\n }\n}\n\npublic class SettingsSubtitlesOCRVM : Bindable\n{\n public FlyleafManager FL { get; }\n private readonly IDialogService _dialogService;\n\n public SettingsSubtitlesOCRVM(FlyleafManager fl, IDialogService dialogService)\n {\n FL = fl;\n _dialogService = dialogService;\n\n LoadDownloadedTessModels();\n LoadAvailableMsModels();\n }\n\n public ObservableCollection DownloadedTessLanguages { get; } = new();\n public ObservableCollection TessLanguageGroups { get; } = new();\n\n public ObservableCollection AvailableMsOcrLanguages { get; } = new();\n public ObservableCollection MsLanguageGroups { get; } = new();\n\n [field: AllowNull, MaybeNull]\n public DelegateCommand CmdDownloadTessModel => field ??= new(() =>\n {\n _dialogService.ShowDialog(nameof(TesseractDownloadDialog));\n\n // reload\n LoadDownloadedTessModels();\n });\n\n private void LoadDownloadedTessModels()\n {\n DownloadedTessLanguages.Clear();\n\n List langs = TesseractModelLoader.LoadDownloadedModels().ToList();\n foreach (var lang in langs)\n {\n DownloadedTessLanguages.Add(lang);\n }\n\n TessLanguageGroups.Clear();\n\n List langGroups = langs\n .GroupBy(l => l.ISO6391)\n .Where(lg => lg.Count() >= 2)\n .Select(lg => new TessOcrLanguageGroup\n {\n ISO6391 = lg.Key,\n Members = new ObservableCollection(\n lg.Select(m => new TessOcrLanguageGroupMember()\n {\n DisplayName = m.Lang.ToString(),\n LangCode = m.LangCode\n })\n )\n }).ToList();\n\n Dictionary? regionConfig = FL.PlayerConfig.Subtitles.TesseractOcrRegions;\n foreach (TessOcrLanguageGroup group in langGroups)\n {\n // Load preferred region settings from config\n if (regionConfig != null && regionConfig.TryGetValue(group.ISO6391, out string? code))\n {\n group.SelectedMember = group.Members.FirstOrDefault(m => m.LangCode == code);\n }\n group.PropertyChanged += TessLanguageGroup_OnPropertyChanged;\n\n TessLanguageGroups.Add(group);\n }\n }\n\n private void LoadAvailableMsModels()\n {\n var langs = OcrEngine.AvailableRecognizerLanguages.ToList();\n foreach (var lang in langs)\n {\n AvailableMsOcrLanguages.Add(lang);\n }\n\n List langGroups = langs\n .GroupBy(l => l.LanguageTag.Split('-').First())\n .Where(lg => lg.Count() >= 2)\n .Select(lg => new MsOcrLanguageGroup\n {\n ISO6391 = lg.Key,\n Members = new ObservableCollection(\n lg.Select(m => new MsOcrLanguageGroupMember()\n {\n DisplayName = m.DisplayName,\n LanguageTag = m.LanguageTag,\n NativeName = m.NativeName\n })\n )\n }).ToList();\n\n Dictionary? regionConfig = FL.PlayerConfig.Subtitles.MsOcrRegions;\n foreach (MsOcrLanguageGroup group in langGroups)\n {\n // Load preferred region settings from config\n if (regionConfig != null && regionConfig.TryGetValue(group.ISO6391, out string? tag))\n {\n group.SelectedMember = group.Members.FirstOrDefault(m => m.LanguageTag == tag);\n }\n group.PropertyChanged += MsLanguageGroup_OnPropertyChanged;\n\n MsLanguageGroups.Add(group);\n }\n }\n\n private void MsLanguageGroup_OnPropertyChanged(object? sender, PropertyChangedEventArgs e)\n {\n if (e.PropertyName == nameof(MsOcrLanguageGroup.SelectedMember))\n {\n Dictionary iso6391ToTag = new();\n\n foreach (MsOcrLanguageGroup group in MsLanguageGroups)\n {\n if (group.SelectedMember != null)\n {\n iso6391ToTag.Add(group.ISO6391, group.SelectedMember.LanguageTag);\n }\n }\n\n FL.PlayerConfig.Subtitles.MsOcrRegions = iso6391ToTag;\n }\n }\n\n private void TessLanguageGroup_OnPropertyChanged(object? sender, PropertyChangedEventArgs e)\n {\n if (e.PropertyName == nameof(TessOcrLanguageGroup.SelectedMember))\n {\n Dictionary iso6391ToCode = new();\n\n foreach (TessOcrLanguageGroup group in TessLanguageGroups)\n {\n if (group.SelectedMember != null)\n {\n iso6391ToCode.Add(group.ISO6391, group.SelectedMember.LangCode);\n }\n }\n\n FL.PlayerConfig.Subtitles.TesseractOcrRegions = iso6391ToCode;\n }\n }\n}\n\n#region Tesseract\npublic class TessOcrLanguageGroupMember : Bindable\n{\n public required string LangCode { get; init; }\n public required string DisplayName { get; init; }\n}\n\npublic class TessOcrLanguageGroup : Bindable\n{\n public required string ISO6391 { get; init; }\n\n public string DisplayName\n {\n get\n {\n var lang = Language.Get(ISO6391);\n return lang.TopEnglishName;\n }\n }\n\n public required ObservableCollection Members { get; init; }\n public TessOcrLanguageGroupMember? SelectedMember { get; set => Set(ref field, value); }\n}\n#endregion\n\n#region Microsoft OCR\npublic class MsOcrLanguageGroupMember : Bindable\n{\n public required string LanguageTag { get; init; }\n public required string DisplayName { get; init; }\n public required string NativeName { get; init; }\n}\n\npublic class MsOcrLanguageGroup : Bindable\n{\n public required string ISO6391 { get; init; }\n\n public string DisplayName\n {\n get\n {\n var lang = Language.Get(ISO6391);\n return lang.TopEnglishName;\n }\n }\n\n public required ObservableCollection Members { get; init; }\n public MsOcrLanguageGroupMember? SelectedMember { get; set => Set(ref field, value); }\n}\n#endregion\n"], ["/LLPlayer/FlyleafLib/Plugins/PluginHandler.cs", "using System.Collections.Generic;\nusing System.Collections.ObjectModel;\nusing System.Linq;\n\nusing FlyleafLib.MediaFramework.MediaPlaylist;\nusing FlyleafLib.MediaFramework.MediaStream;\n\nnamespace FlyleafLib.Plugins;\n\npublic class PluginHandler\n{\n #region Properties\n public Config Config { get; private set; }\n public bool Interrupt { get; set; }\n public IOpen OpenedPlugin { get; private set; }\n public IOpenSubtitles OpenedSubtitlesPlugin { get; private set; }\n public long OpenCounter { get; internal set; }\n public long OpenItemCounter { get; internal set; }\n public Playlist Playlist { get; set; }\n public int UniqueId { get; set; }\n\n public Dictionary\n Plugins { get; private set; }\n public Dictionary\n PluginsOpen { get; private set; }\n public Dictionary\n PluginsOpenSubtitles { get; private set; }\n\n public Dictionary\n PluginsScrapeItem { get; private set; }\n\n public Dictionary\n PluginsSuggestItem { get; private set; }\n\n public Dictionary\n PluginsSuggestAudioStream { get; private set; }\n public Dictionary\n PluginsSuggestVideoStream { get; private set; }\n public Dictionary\n PluginsSuggestExternalAudio { get; private set; }\n public Dictionary\n PluginsSuggestExternalVideo { get; private set; }\n\n public Dictionary\n PluginsSuggestSubtitlesStream { get; private set; }\n public Dictionary\n PluginsSuggestSubtitles { get; private set; }\n public Dictionary\n PluginsSuggestBestExternalSubtitles\n { get; private set; }\n\n public Dictionary\n PluginsDownloadSubtitles { get; private set; }\n\n public Dictionary\n PluginsSearchLocalSubtitles { get; private set; }\n public Dictionary\n PluginsSearchOnlineSubtitles { get; private set; }\n #endregion\n\n #region Initialize\n LogHandler Log;\n public PluginHandler(Config config, int uniqueId = -1)\n {\n Config = config;\n UniqueId= uniqueId == -1 ? Utils.GetUniqueId() : uniqueId;\n Playlist = new Playlist(UniqueId);\n Log = new LogHandler((\"[#\" + UniqueId + \"]\").PadRight(8, ' ') + \" [PluginHandler ] \");\n LoadPlugins();\n }\n\n public static PluginBase CreatePluginInstance(PluginType type, PluginHandler handler = null)\n {\n PluginBase plugin = (PluginBase) Activator.CreateInstance(type.Type, true);\n plugin.Handler = handler;\n plugin.Name = type.Name;\n plugin.Type = type.Type;\n plugin.Version = type.Version;\n\n if (handler != null)\n plugin.OnLoaded();\n\n return plugin;\n }\n private void LoadPlugins()\n {\n Plugins = new Dictionary();\n\n foreach (var type in Engine.Plugins.Types.Values)\n {\n try\n {\n var plugin = CreatePluginInstance(type, this);\n plugin.Log = new LogHandler((\"[#\" + UniqueId + \"]\").PadRight(8, ' ') + $\" [{plugin.Name,-14}] \");\n Plugins.Add(plugin.Name, plugin);\n } catch (Exception e) { Log.Error($\"[Plugins] [Error] Failed to load plugin ... ({e.Message} {Utils.GetRecInnerException(e)}\"); }\n }\n\n PluginsOpen = new Dictionary();\n PluginsOpenSubtitles = new Dictionary();\n PluginsScrapeItem = new Dictionary();\n\n PluginsSuggestItem = new Dictionary();\n\n PluginsSuggestAudioStream = new Dictionary();\n PluginsSuggestVideoStream = new Dictionary();\n PluginsSuggestSubtitlesStream = new Dictionary();\n PluginsSuggestSubtitles = new Dictionary();\n\n PluginsSuggestExternalAudio = new Dictionary();\n PluginsSuggestExternalVideo = new Dictionary();\n PluginsSuggestBestExternalSubtitles\n = new Dictionary();\n\n PluginsSearchLocalSubtitles = new Dictionary();\n PluginsSearchOnlineSubtitles = new Dictionary();\n PluginsDownloadSubtitles = new Dictionary();\n\n foreach (var plugin in Plugins.Values)\n LoadPluginInterfaces(plugin);\n }\n private void LoadPluginInterfaces(PluginBase plugin)\n {\n if (plugin is IOpen) PluginsOpen.Add(plugin.Name, (IOpen)plugin);\n else if (plugin is IOpenSubtitles) PluginsOpenSubtitles.Add(plugin.Name, (IOpenSubtitles)plugin);\n\n if (plugin is IScrapeItem) PluginsScrapeItem.Add(plugin.Name, (IScrapeItem)plugin);\n\n if (plugin is ISuggestPlaylistItem) PluginsSuggestItem.Add(plugin.Name, (ISuggestPlaylistItem)plugin);\n\n if (plugin is ISuggestAudioStream) PluginsSuggestAudioStream.Add(plugin.Name, (ISuggestAudioStream)plugin);\n if (plugin is ISuggestVideoStream) PluginsSuggestVideoStream.Add(plugin.Name, (ISuggestVideoStream)plugin);\n if (plugin is ISuggestSubtitlesStream) PluginsSuggestSubtitlesStream.Add(plugin.Name, (ISuggestSubtitlesStream)plugin);\n if (plugin is ISuggestSubtitles) PluginsSuggestSubtitles.Add(plugin.Name, (ISuggestSubtitles)plugin);\n\n if (plugin is ISuggestExternalAudio) PluginsSuggestExternalAudio.Add(plugin.Name, (ISuggestExternalAudio)plugin);\n if (plugin is ISuggestExternalVideo) PluginsSuggestExternalVideo.Add(plugin.Name, (ISuggestExternalVideo)plugin);\n if (plugin is ISuggestBestExternalSubtitles) PluginsSuggestBestExternalSubtitles.Add(plugin.Name, (ISuggestBestExternalSubtitles)plugin);\n\n if (plugin is ISearchLocalSubtitles) PluginsSearchLocalSubtitles.Add(plugin.Name, (ISearchLocalSubtitles)plugin);\n if (plugin is ISearchOnlineSubtitles) PluginsSearchOnlineSubtitles.Add(plugin.Name, (ISearchOnlineSubtitles)plugin);\n if (plugin is IDownloadSubtitles) PluginsDownloadSubtitles.Add(plugin.Name, (IDownloadSubtitles)plugin);\n }\n #endregion\n\n #region Misc / Events\n public void OnInitializing()\n {\n OpenCounter++;\n OpenItemCounter++;\n foreach(var plugin in Plugins.Values)\n plugin.OnInitializing();\n }\n public void OnInitialized()\n {\n OpenedPlugin = null;\n OpenedSubtitlesPlugin = null;\n\n Playlist.Reset();\n\n foreach(var plugin in Plugins.Values)\n plugin.OnInitialized();\n }\n\n public void OnInitializingSwitch()\n {\n OpenItemCounter++;\n foreach(var plugin in Plugins.Values)\n plugin.OnInitializingSwitch();\n }\n public void OnInitializedSwitch()\n {\n foreach(var plugin in Plugins.Values)\n plugin.OnInitializedSwitch();\n }\n\n public void Dispose()\n {\n foreach(var plugin in Plugins.Values)\n plugin.Dispose();\n }\n #endregion\n\n #region Audio / Video\n public OpenResults Open()\n {\n long sessionId = OpenCounter;\n var plugins = PluginsOpen.Values.OrderBy(x => x.Priority);\n foreach(var plugin in plugins)\n {\n if (Interrupt || sessionId != OpenCounter)\n return new OpenResults(\"Cancelled\");\n\n if (!plugin.CanOpen())\n continue;\n\n var res = plugin.Open();\n if (res == null)\n continue;\n\n // Currently fallback is not allowed if an error has been returned\n if (res.Error != null)\n return res;\n\n OpenedPlugin = plugin;\n Log.Info($\"[{plugin.Name}] Open Success\");\n\n return res;\n }\n\n return new OpenResults(\"No plugin found for the provided input\");\n }\n public OpenResults OpenItem()\n {\n long sessionId = OpenItemCounter;\n var res = OpenedPlugin.OpenItem();\n\n res ??= new OpenResults { Error = \"Cancelled\" };\n\n if (sessionId != OpenItemCounter)\n res.Error = \"Cancelled\";\n\n if (res.Error == null)\n Log.Info($\"[{OpenedPlugin.Name}] Open Item ({Playlist.Selected.Index}) Success\");\n\n return res;\n }\n\n // Should only be called from opened plugin\n public void OnPlaylistCompleted()\n {\n Playlist.Completed = true;\n if (Playlist.ExpectingItems == 0)\n Playlist.ExpectingItems = Playlist.Items.Count;\n\n if (Playlist.Items.Count > 1)\n {\n Log.Debug(\"Playlist Completed\");\n Playlist.UpdatePrevNextItem();\n }\n }\n\n public void ScrapeItem(PlaylistItem item)\n {\n var plugins = PluginsScrapeItem.Values.OrderBy(x => x.Priority);\n foreach (var plugin in plugins)\n {\n if (Interrupt)\n return;\n\n plugin.ScrapeItem(item);\n }\n }\n\n public PlaylistItem SuggestItem()\n {\n var plugins = PluginsSuggestItem.Values.OrderBy(x => x.Priority);\n foreach (var plugin in plugins)\n {\n if (Interrupt)\n return null;\n\n var item = plugin.SuggestItem();\n if (item != null)\n {\n Log.Info($\"SuggestItem #{item.Index} - {item.Title}\");\n return item;\n }\n }\n\n return null;\n }\n\n public ExternalVideoStream SuggestExternalVideo()\n {\n var plugins = PluginsSuggestExternalVideo.Values.OrderBy(x => x.Priority);\n foreach (var plugin in plugins)\n {\n if (Interrupt)\n return null;\n\n var extStream = plugin.SuggestExternalVideo();\n if (extStream != null)\n {\n Log.Info($\"SuggestVideo (External) {extStream.Width} x {extStream.Height} @ {extStream.FPS}\");\n Log.Debug($\"SuggestVideo (External) Url: {extStream.Url}, UrlFallback: {extStream.UrlFallback}\");\n return extStream;\n }\n }\n\n return null;\n }\n public ExternalAudioStream SuggestExternalAudio()\n {\n var plugins = PluginsSuggestExternalAudio.Values.OrderBy(x => x.Priority);\n foreach(var plugin in plugins)\n {\n if (Interrupt)\n return null;\n\n var extStream = plugin.SuggestExternalAudio();\n if (extStream != null)\n {\n Log.Info($\"SuggestAudio (External) {extStream.SampleRate} Hz, {extStream.Codec}\");\n Log.Debug($\"SuggestAudio (External) Url: {extStream.Url}, UrlFallback: {extStream.UrlFallback}\");\n return extStream;\n }\n }\n\n return null;\n }\n\n public VideoStream SuggestVideo(ObservableCollection streams)\n {\n if (streams == null || streams.Count == 0) return null;\n\n var plugins = PluginsSuggestVideoStream.Values.OrderBy(x => x.Priority);\n foreach(var plugin in plugins)\n {\n if (Interrupt)\n return null;\n\n var stream = plugin.SuggestVideo(streams);\n if (stream != null) return stream;\n }\n\n return null;\n }\n public void SuggestVideo(out VideoStream stream, out ExternalVideoStream extStream, ObservableCollection streams)\n {\n stream = null;\n extStream = null;\n\n if (Interrupt)\n return;\n\n stream = SuggestVideo(streams);\n if (stream != null)\n return;\n\n if (Interrupt)\n return;\n\n extStream = SuggestExternalVideo();\n }\n\n public AudioStream SuggestAudio(ObservableCollection streams)\n {\n if (streams == null || streams.Count == 0) return null;\n\n var plugins = PluginsSuggestAudioStream.Values.OrderBy(x => x.Priority);\n foreach(var plugin in plugins)\n {\n if (Interrupt)\n return null;\n\n var stream = plugin.SuggestAudio(streams);\n if (stream != null) return stream;\n }\n\n return null;\n }\n public void SuggestAudio(out AudioStream stream, out ExternalAudioStream extStream, ObservableCollection streams)\n {\n stream = null;\n extStream = null;\n\n if (Interrupt)\n return;\n\n stream = SuggestAudio(streams);\n if (stream != null)\n return;\n\n if (Interrupt)\n return;\n\n extStream = SuggestExternalAudio();\n }\n #endregion\n\n #region Subtitles\n public OpenSubtitlesResults OpenSubtitles(string url)\n {\n var plugins = PluginsOpenSubtitles.Values.OrderBy(x => x.Priority);\n foreach(var plugin in plugins)\n {\n var res = plugin.Open(url);\n if (res == null)\n continue;\n\n if (res.Error != null)\n return res;\n\n OpenedSubtitlesPlugin = plugin;\n Log.Info($\"[{plugin.Name}] Open Subtitles Success\");\n\n return res;\n }\n\n return null;\n }\n\n public bool SearchLocalSubtitles()\n {\n if (!Playlist.Selected.SearchedLocal && Config.Subtitles.SearchLocal && (Config.Subtitles.SearchLocalOnInputType == null || Config.Subtitles.SearchLocalOnInputType.Count == 0 || Config.Subtitles.SearchLocalOnInputType.Contains(Playlist.InputType)))\n {\n Log.Debug(\"[Subtitles] Searching Local\");\n var plugins = PluginsSearchLocalSubtitles.Values.OrderBy(x => x.Priority);\n foreach(var plugin in plugins)\n {\n if (Interrupt)\n return false;\n\n plugin.SearchLocalSubtitles();\n }\n\n Playlist.Selected.SearchedLocal = true;\n\n return true;\n }\n\n return false;\n }\n public void SearchOnlineSubtitles()\n {\n if (!Playlist.Selected.SearchedOnline && Config.Subtitles.SearchOnline && (Config.Subtitles.SearchOnlineOnInputType == null || Config.Subtitles.SearchOnlineOnInputType.Count == 0 || Config.Subtitles.SearchOnlineOnInputType.Contains(Playlist.InputType)))\n {\n Log.Debug(\"[Subtitles] Searching Online\");\n var plugins = PluginsSearchOnlineSubtitles.Values.OrderBy(x => x.Priority);\n foreach(var plugin in plugins)\n {\n if (Interrupt)\n return;\n\n plugin.SearchOnlineSubtitles();\n }\n\n Playlist.Selected.SearchedOnline = true;\n }\n }\n public bool DownloadSubtitles(ExternalSubtitlesStream extStream)\n {\n bool res = false;\n\n var plugins = PluginsDownloadSubtitles.Values.OrderBy(x => x.Priority);\n foreach(var plugin in plugins)\n if (res = plugin.DownloadSubtitles(extStream))\n {\n extStream.Downloaded = true;\n return res;\n }\n\n return res;\n }\n\n public ExternalSubtitlesStream SuggestBestExternalSubtitles()\n {\n var plugins = PluginsSuggestBestExternalSubtitles.Values.OrderBy(x => x.Priority);\n foreach(var plugin in plugins)\n {\n if (Interrupt)\n return null;\n\n var extStream = plugin.SuggestBestExternalSubtitles();\n if (extStream != null)\n return extStream;\n }\n\n return null;\n }\n public void SuggestSubtitles(out SubtitlesStream stream, out ExternalSubtitlesStream extStream)\n {\n stream = null;\n extStream = null;\n\n var plugins = PluginsSuggestSubtitles.Values.OrderBy(x => x.Priority);\n foreach(var plugin in plugins)\n {\n if (Interrupt)\n return;\n\n plugin.SuggestSubtitles(out stream, out extStream);\n if (stream != null || extStream != null)\n return;\n }\n }\n public SubtitlesStream SuggestSubtitles(ObservableCollection streams, List langs)\n {\n if (streams == null || streams.Count == 0) return null;\n\n var plugins = PluginsSuggestSubtitlesStream.Values.OrderBy(x => x.Priority);\n foreach(var plugin in plugins)\n {\n if (Interrupt)\n return null;\n\n var stream = plugin.SuggestSubtitles(streams, langs);\n if (stream != null)\n return stream;\n }\n\n return null;\n }\n #endregion\n\n #region Data\n public void SuggestData(out DataStream stream, ObservableCollection streams)\n {\n stream = null;\n\n if (Interrupt)\n return;\n\n stream = streams.FirstOrDefault();\n }\n #endregion\n}\n"], ["/LLPlayer/FlyleafLib/Engine/Engine.FFmpeg.cs", "namespace FlyleafLib;\n\npublic class FFmpegEngine\n{\n public string Folder { get; private set; }\n public string Version { get; private set; }\n\n const int AV_LOG_BUFFER_SIZE = 5 * 1024;\n internal AVRational AV_TIMEBASE_Q;\n\n internal FFmpegEngine()\n {\n try\n {\n Engine.Log.Info($\"Loading FFmpeg libraries from '{Engine.Config.FFmpegPath}'\");\n Folder = Utils.GetFolderPath(Engine.Config.FFmpegPath);\n LoadLibraries(Folder, Engine.Config.FFmpegLoadProfile);\n\n uint ver = avformat_version();\n Version = $\"{ver >> 16}.{(ver >> 8) & 255}.{ver & 255}\";\n\n SetLogLevel();\n AV_TIMEBASE_Q = av_get_time_base_q();\n Engine.Log.Info($\"FFmpeg Loaded (Profile: {Engine.Config.FFmpegLoadProfile}, Location: {Folder}, FmtVer: {Version})\");\n } catch (Exception e)\n {\n Engine.Log.Error($\"Loading FFmpeg libraries '{Engine.Config.FFmpegPath}' failed\\r\\n{e.Message}\\r\\n{e.StackTrace}\");\n throw new Exception($\"Loading FFmpeg libraries '{Engine.Config.FFmpegPath}' failed\");\n }\n }\n\n internal static void SetLogLevel()\n {\n if (Engine.Config.FFmpegLogLevel != Flyleaf.FFmpeg.LogLevel.Quiet)\n {\n av_log_set_level(Engine.Config.FFmpegLogLevel);\n av_log_set_callback(LogFFmpeg);\n }\n else\n {\n av_log_set_level(Flyleaf.FFmpeg.LogLevel.Quiet);\n av_log_set_callback(null);\n }\n }\n\n internal unsafe static av_log_set_callback_callback LogFFmpeg = (p0, level, format, vl) =>\n {\n if (level > av_log_get_level())\n return;\n\n byte* buffer = stackalloc byte[AV_LOG_BUFFER_SIZE];\n int printPrefix = 1;\n av_log_format_line2(p0, level, format, vl, buffer, AV_LOG_BUFFER_SIZE, &printPrefix);\n string line = Utils.BytePtrToStringUTF8(buffer);\n\n Logger.Output($\"FFmpeg|{level,-7}|{line.Trim()}\");\n };\n\n internal unsafe static string ErrorCodeToMsg(int error)\n {\n byte* buffer = stackalloc byte[AV_LOG_BUFFER_SIZE];\n av_strerror(error, buffer, AV_LOG_BUFFER_SIZE);\n return Utils.BytePtrToStringUTF8(buffer);\n }\n}\n"], ["/LLPlayer/LLPlayer/Extensions/DataGridRowOrderBehavior.cs", "using System.Collections;\nusing System.Collections.ObjectModel;\nusing System.Windows;\nusing System.Windows.Controls;\nusing System.Windows.Input;\nusing Microsoft.Xaml.Behaviors;\n\nnamespace LLPlayer.Extensions;\n\n/// \n/// Behavior to add the ability to swap rows in a DataGrid by drag and drop\n/// \npublic class DataGridRowOrderBehavior : Behavior\n where T : class\n{\n public static readonly DependencyProperty ItemsSourceProperty =\n DependencyProperty.Register(nameof(ItemsSource), typeof(IList), typeof (DataGridRowOrderBehavior), new PropertyMetadata(null));\n\n /// \n /// ObservableCollection to be reordered bound to DataGrid\n /// \n public ObservableCollection ItemsSource\n {\n get => (ObservableCollection)GetValue(ItemsSourceProperty);\n set => SetValue(ItemsSourceProperty, value);\n }\n\n public static readonly DependencyProperty DragTargetNameProperty =\n DependencyProperty.Register(nameof(DragTargetName), typeof(string), typeof (DataGridRowOrderBehavior), new PropertyMetadata(null));\n\n /// \n /// Control name of the element to be dragged\n /// \n public string DragTargetName\n {\n get => (string)GetValue(DragTargetNameProperty);\n set => SetValue(DragTargetNameProperty, value);\n }\n\n private T? _draggedItem; // Item in row to be dragged\n\n protected override void OnAttached()\n {\n base.OnAttached();\n\n if (AssociatedObject == null)\n {\n return;\n }\n\n AssociatedObject.AllowDrop = true;\n\n AssociatedObject.PreviewMouseLeftButtonDown += OnPreviewMouseLeftButtonDown;\n AssociatedObject.DragOver += OnDragOver;\n AssociatedObject.Drop += OnDrop;\n }\n\n protected override void OnDetaching()\n {\n base.OnDetaching();\n\n if (AssociatedObject == null)\n {\n return;\n }\n\n AssociatedObject.AllowDrop = false;\n\n AssociatedObject.PreviewMouseLeftButtonDown -= OnPreviewMouseLeftButtonDown;\n AssociatedObject.DragOver -= OnDragOver;\n AssociatedObject.Drop -= OnDrop;\n }\n\n private void OnPreviewMouseLeftButtonDown(object sender, MouseButtonEventArgs e)\n {\n if (ItemsSource == null)\n {\n return;\n }\n\n // 1: Determines if it is on a \"drag handle\".\n if (!IsDragHandle(e.OriginalSource))\n {\n return;\n }\n\n // 2: Identify Row\n DataGridRow? row = UIHelper.FindParent((DependencyObject)e.OriginalSource);\n if (row == null)\n {\n return;\n }\n\n // Select the row\n AssociatedObject.UnselectAll();\n row.IsSelected = true;\n row.Focus();\n\n _draggedItem = row.Item as T;\n\n if (_draggedItem != null)\n {\n // Start dragging\n DragDrop.DoDragDrop(AssociatedObject, _draggedItem, DragDropEffects.Move);\n }\n }\n\n /// \n /// Dragging (while the mouse is moving)\n /// \n private void OnDragOver(object sender, DragEventArgs e)\n {\n if (_draggedItem == null)\n {\n return;\n }\n\n e.Handled = true;\n\n // Find the line where the mouse is now.\n DataGridRow? row = UIHelper.FindParent((DependencyObject)e.OriginalSource);\n if (row == null)\n {\n return;\n }\n\n var targetItem = row.Item;\n if (targetItem == null || targetItem == _draggedItem)\n {\n // If it's the same line, nothing.\n return;\n }\n\n T? targetRow = targetItem as T;\n if (targetRow == null)\n {\n return;\n }\n\n // Get the index of each row to be replaced\n int oldIndex = ItemsSource.IndexOf(_draggedItem);\n int newIndex = ItemsSource.IndexOf(targetRow);\n\n if (oldIndex < 0 || newIndex < 0 || oldIndex == newIndex)\n {\n return;\n }\n\n // Swap lines\n ItemsSource.Move(oldIndex, newIndex);\n }\n\n /// \n /// When dropped\n /// \n private void OnDrop(object sender, DragEventArgs e)\n {\n // Clear state as it is being reordered during drag.\n _draggedItem = null;\n }\n\n /// \n /// Judges whether an element is ready to start dragging.\n /// \n private bool IsDragHandle(object originalSource)\n {\n return UIHelper.FindParentWithName(originalSource as DependencyObject, DragTargetName);\n }\n}\n"], ["/LLPlayer/LLPlayer/ViewModels/CheatSheetDialogVM.cs", "using System.Diagnostics.CodeAnalysis;\nusing System.Globalization;\nusing System.Windows.Data;\nusing System.Windows.Input;\nusing System.Windows.Media;\nusing FlyleafLib.MediaPlayer;\nusing LLPlayer.Converters;\nusing LLPlayer.Extensions;\nusing LLPlayer.Services;\nusing MaterialDesignColors.Recommended;\nusing KeyBinding = FlyleafLib.MediaPlayer.KeyBinding;\n\nnamespace LLPlayer.ViewModels;\n\npublic class CheatSheetDialogVM : Bindable, IDialogAware\n{\n public FlyleafManager FL { get; }\n\n public CheatSheetDialogVM(FlyleafManager fl)\n {\n FL = fl;\n\n List keys = FL.PlayerConfig.Player.KeyBindings.Keys.Where(k => k.IsEnabled).ToList();\n\n HitCount = keys.Count;\n\n KeyToStringConverter keyConverter = new();\n\n List groups = keys.Select(k =>\n {\n KeyBindingCS key = new()\n {\n Action = k.Action,\n ActionName = k.Action.ToString(),\n Alt = k.Alt,\n Ctrl = k.Ctrl,\n Shift = k.Shift,\n Description = k.Action.GetDescription(),\n Group = k.Action.ToGroup(),\n Key = k.Key,\n KeyName = (string)keyConverter.Convert(k.Key, typeof(string), null, CultureInfo.CurrentCulture),\n ActionInternal = k.ActionInternal,\n };\n\n if (key.Action == KeyBindingAction.Custom)\n {\n if (!Enum.TryParse(k.ActionName, out CustomKeyBindingAction customAction))\n {\n HitCount -= 1;\n return null;\n }\n\n key.ActionName = customAction.ToString();\n key.CustomAction = customAction;\n key.Description = customAction.GetDescription();\n key.Group = customAction.ToGroup();\n }\n\n return key;\n })\n .Where(k => k != null)\n .OrderBy(k => k!.Action)\n .ThenBy(k => k!.CustomAction)\n .GroupBy(k => k!.Group)\n .OrderBy(g => g.Key)\n .Select(g => new KeyBindingCSGroup()\n {\n Group = g.Key,\n KeyBindings = g.ToList()!\n }).ToList();\n\n KeyBindingGroups = new List(groups);\n\n List collectionViews = KeyBindingGroups.Select(g => (ListCollectionView)CollectionViewSource.GetDefaultView(g.KeyBindings))\n .ToList();\n _collectionViews = collectionViews;\n\n foreach (ListCollectionView view in collectionViews)\n {\n view.Filter = (obj) =>\n {\n if (obj is not KeyBindingCS key)\n {\n return false;\n }\n\n if (string.IsNullOrWhiteSpace(SearchText))\n {\n return true;\n }\n\n string query = SearchText.Trim();\n\n bool match = key.Description.Contains(query, StringComparison.OrdinalIgnoreCase);\n if (match)\n {\n return true;\n }\n\n return key.Shortcut.Contains(query, StringComparison.OrdinalIgnoreCase);\n };\n }\n }\n\n public string SearchText\n {\n get;\n set\n {\n if (Set(ref field, value))\n {\n _collectionViews.ForEach(v => v.Refresh());\n\n HitCount = _collectionViews.Sum(v => v.Count);\n }\n }\n } = string.Empty;\n\n public int HitCount { get; set => Set(ref field, value); }\n\n private readonly List _collectionViews;\n public List KeyBindingGroups { get; set; }\n\n public DelegateCommand? CmdAction => field ??= new((key) =>\n {\n FL.Player.Activity.ForceFullActive();\n key.ActionInternal.Invoke();\n });\n\n #region IDialogAware\n public string Title { get; set => Set(ref field, value); } = $\"CheatSheet - {App.Name}\";\n public double WindowWidth { get; set => Set(ref field, value); } = 1000;\n public double WindowHeight { get; set => Set(ref field, value); } = 800;\n\n public bool CanCloseDialog() => true;\n public void OnDialogClosed() { }\n public void OnDialogOpened(IDialogParameters parameters) { }\n public DialogCloseListener RequestClose { get; }\n #endregion IDialogAware\n}\n\npublic class KeyBindingCS\n{\n public required bool Ctrl { get; init; }\n public required bool Shift { get; init; }\n public required bool Alt { get; init; }\n public required Key Key { get; init; }\n public required string KeyName { get; init; }\n\n [field: AllowNull, MaybeNull]\n public string Shortcut\n {\n get\n {\n if (field == null)\n {\n string modifiers = \"\";\n if (Ctrl)\n modifiers += \"Ctrl + \";\n if (Alt)\n modifiers += \"Alt + \";\n if (Shift)\n modifiers += \"Shift + \";\n field = $\"{modifiers}{KeyName}\";\n }\n\n return field;\n }\n }\n\n public required KeyBindingAction Action { get; init; }\n public CustomKeyBindingAction? CustomAction { get; set; }\n public required string ActionName { get; set; }\n public required string Description { get; set; }\n public required KeyBindingActionGroup Group { get; set; }\n\n public required Action ActionInternal { get; init; }\n}\n\npublic class KeyBindingCSGroup\n{\n public required KeyBindingActionGroup Group { get; init; }\n\n [field: AllowNull, MaybeNull]\n public string GroupName => field ??= Group.ToString();\n public required List KeyBindings { get; init; }\n\n public Color GroupColor =>\n Group switch\n {\n KeyBindingActionGroup.Playback => RedSwatch.Red500,\n KeyBindingActionGroup.Player => PinkSwatch.Pink500,\n KeyBindingActionGroup.Audio => PurpleSwatch.Purple500,\n KeyBindingActionGroup.Video => BlueSwatch.Blue500,\n KeyBindingActionGroup.Subtitles => TealSwatch.Teal500,\n KeyBindingActionGroup.SubtitlesPosition => GreenSwatch.Green500,\n KeyBindingActionGroup.Window => LightGreenSwatch.LightGreen500,\n KeyBindingActionGroup.Other => DeepOrangeSwatch.DeepOrange500,\n _ => BrownSwatch.Brown500\n };\n}\n"], ["/LLPlayer/LLPlayer/Controls/SelectableTextBox.cs", "using System.Windows;\nusing System.Windows.Controls;\nusing System.Windows.Input;\nusing FlyleafLib;\n\nnamespace LLPlayer.Controls;\n\npublic class SelectableTextBox : TextBox\n{\n static SelectableTextBox()\n {\n DefaultStyleKeyProperty.OverrideMetadata(typeof(SelectableTextBox), new FrameworkPropertyMetadata(typeof(SelectableTextBox)));\n }\n\n public static readonly DependencyProperty IsTranslatedProperty =\n DependencyProperty.Register(nameof(IsTranslated), typeof(bool), typeof(SelectableTextBox), new FrameworkPropertyMetadata(false));\n\n public bool IsTranslated\n {\n get => (bool)GetValue(IsTranslatedProperty);\n set => SetValue(IsTranslatedProperty, value);\n }\n\n public static readonly DependencyProperty SubIndexProperty =\n DependencyProperty.Register(nameof(SubIndex), typeof(int), typeof(SelectableTextBox), new FrameworkPropertyMetadata(0));\n\n public int SubIndex\n {\n get => (int)GetValue(SubIndexProperty);\n set => SetValue(SubIndexProperty, value);\n }\n\n public static readonly RoutedEvent WordClickedEvent =\n EventManager.RegisterRoutedEvent(nameof(WordClicked), RoutingStrategy.Bubble, typeof(WordClickedEventHandler), typeof(SelectableTextBox));\n\n public event WordClickedEventHandler WordClicked\n {\n add => AddHandler(WordClickedEvent, value);\n remove => RemoveHandler(WordClickedEvent, value);\n }\n\n private bool _isDragging;\n private int _dragStartIndex = -1;\n private int _dragEndIndex = -1;\n\n private Point _mouseDownPosition;\n\n protected override void OnPreviewMouseLeftButtonDown(MouseButtonEventArgs e)\n {\n base.OnPreviewMouseLeftButtonDown(e);\n\n _isDragging = true;\n _mouseDownPosition = e.GetPosition(this);\n _dragStartIndex = GetCharacterIndexFromPoint(_mouseDownPosition, true);\n _dragEndIndex = _dragStartIndex;\n\n CaptureMouse();\n e.Handled = true;\n }\n\n protected override void OnPreviewMouseMove(MouseEventArgs e)\n {\n base.OnPreviewMouseMove(e);\n\n if (_isDragging)\n {\n Point currentPosition = e.GetPosition(this);\n\n if (currentPosition != _mouseDownPosition)\n {\n int currentIndex = GetCharacterIndexFromPoint(currentPosition, true);\n if (currentIndex != -1 && currentIndex != _dragEndIndex)\n {\n _dragEndIndex = currentIndex;\n }\n }\n }\n }\n\n protected override void OnPreviewMouseLeftButtonUp(MouseButtonEventArgs e)\n {\n base.OnPreviewMouseLeftButtonUp(e);\n\n if (_isDragging)\n {\n _isDragging = false;\n ReleaseMouseCapture();\n e.Handled = true;\n\n if (_dragStartIndex == _dragEndIndex)\n {\n // Click\n HandleClick(_mouseDownPosition, MouseClick.Left);\n }\n else\n {\n // Drag\n HandleDragSelection();\n }\n }\n }\n\n protected override void OnMouseRightButtonUp(MouseButtonEventArgs e)\n {\n base.OnMouseRightButtonUp(e);\n\n Point clickPosition = e.GetPosition(this);\n\n HandleClick(clickPosition, MouseClick.Right);\n\n // Right clicks other than words are currently disabled, consider creating another one\n e.Handled = true;\n }\n\n protected override void OnMouseUp(MouseButtonEventArgs e)\n {\n // Middle click: Sentence Lookup\n if (e.ChangedButton == MouseButton.Middle)\n {\n if (string.IsNullOrEmpty(Text))\n {\n return;\n }\n\n WordClickedEventArgs args = new(WordClickedEvent)\n {\n Mouse = MouseClick.Middle,\n // Change line breaks to spaces to improve translation accuracy.\n Words = SubtitleTextUtil.FlattenText(Text),\n IsWord = false,\n Text = Text,\n IsTranslated = IsTranslated,\n SubIndex = SubIndex,\n WordOffset = 0,\n Sender = this\n };\n\n RaiseEvent(args);\n }\n }\n\n private void HandleClick(Point point, MouseClick mouse)\n {\n // false because it fires only above the word\n int charIndex = GetCharacterIndexFromPoint(point, false);\n\n if (charIndex == -1 || string.IsNullOrEmpty(Text))\n {\n return;\n }\n\n int start = FindWordStart(charIndex);\n int end = FindWordEnd(charIndex);\n\n // get word\n string word = Text.Substring(start, end - start).Trim();\n\n if (string.IsNullOrEmpty(word))\n {\n return;\n }\n\n WordClickedEventArgs args = new(WordClickedEvent)\n {\n Mouse = mouse,\n Words = word,\n IsWord = true,\n Text = Text,\n IsTranslated = IsTranslated,\n SubIndex = SubIndex,\n WordOffset = start,\n Sender = this\n };\n RaiseEvent(args);\n }\n\n private void HandleDragSelection()\n {\n // Support right to left drag\n int rawStart = Math.Min(_dragStartIndex, _dragEndIndex);\n int rawEnd = Math.Max(_dragStartIndex, _dragEndIndex);\n\n // Adjust to word boundaries\n int adjustedStart = FindWordStart(rawStart);\n int adjustedEnd = FindWordEnd(rawEnd);\n\n // Extract the substring within the adjusted selection\n // TODO: L: If there is only a delimiter after the end, I want to include it in the selection (should improve translation accuracy)\n string selectedText = Text.Substring(adjustedStart, adjustedEnd - adjustedStart);\n\n WordClickedEventArgs args = new(WordClickedEvent)\n {\n Mouse = MouseClick.Left,\n // Change line breaks to spaces to improve translation accuracy.\n Words = SubtitleTextUtil.FlattenText(selectedText),\n IsWord = false,\n Text = Text,\n IsTranslated = IsTranslated,\n SubIndex = SubIndex,\n WordOffset = adjustedStart,\n Sender = this\n };\n\n RaiseEvent(args);\n }\n\n private int FindWordStart(int index)\n {\n if (index < 0 || index > Text.Length)\n {\n return 0;\n }\n\n while (index > 0 && !IsWordSeparator(Text[index - 1]))\n {\n index--;\n }\n\n return index;\n }\n\n private int FindWordEnd(int index)\n {\n if (index < 0 || index > Text.Length)\n {\n return Text.Length;\n }\n\n while (index < Text.Length && !IsWordSeparator(Text[index]))\n {\n index++;\n }\n\n return index;\n }\n\n private static readonly HashSet ExcludedSeparators = ['\\'', '-'];\n\n private static bool IsWordSeparator(char c)\n {\n if (ExcludedSeparators.Contains(c))\n {\n return false;\n }\n\n return char.IsWhiteSpace(c) || char.IsPunctuation(c);\n }\n\n #region Cursor Hand\n protected override void OnMouseMove(MouseEventArgs e)\n {\n base.OnMouseMove(e);\n\n // Change cursor only over word text\n int charIndex = GetCharacterIndexFromPoint(e.GetPosition(this), false);\n\n Cursor = charIndex != -1 ? Cursors.Hand : Cursors.Arrow;\n }\n\n protected override void OnMouseLeave(MouseEventArgs e)\n {\n base.OnMouseLeave(e);\n\n if (Cursor == Cursors.Hand)\n {\n Cursor = Cursors.Arrow;\n }\n }\n #endregion\n}\n"], ["/LLPlayer/LLPlayer/Controls/AlignableWrapPanel.cs", "using System.Windows;\nusing System.Windows.Controls;\n\nnamespace LLPlayer.Controls;\n\n// The standard WrapPanel does not have a centering function, so add it.\n// ref: https://stackoverflow.com/a/7747002\npublic class AlignableWrapPanel : Panel\n{\n public static readonly DependencyProperty HorizontalContentAlignmentProperty =\n DependencyProperty.Register(nameof(HorizontalContentAlignment), typeof(HorizontalAlignment), typeof(AlignableWrapPanel), new FrameworkPropertyMetadata(HorizontalAlignment.Left, FrameworkPropertyMetadataOptions.AffectsArrange));\n public HorizontalAlignment HorizontalContentAlignment\n {\n get => (HorizontalAlignment)GetValue(HorizontalContentAlignmentProperty);\n set => SetValue(HorizontalContentAlignmentProperty, value);\n }\n\n protected override Size MeasureOverride(Size constraint)\n {\n Size curLineSize = new();\n Size panelSize = new();\n\n UIElementCollection children = InternalChildren;\n\n for (int i = 0; i < children.Count; i++)\n {\n UIElement child = children[i];\n\n // Flow passes its own constraint to children\n child.Measure(constraint);\n Size sz = child.DesiredSize;\n\n if (child is NewLine ||\n curLineSize.Width + sz.Width > constraint.Width) //need to switch to another line\n {\n panelSize.Width = Math.Max(curLineSize.Width, panelSize.Width);\n panelSize.Height += curLineSize.Height;\n curLineSize = sz;\n\n if (sz.Width > constraint.Width) // if the element is wider then the constraint - give it a separate line\n {\n panelSize.Width = Math.Max(sz.Width, panelSize.Width);\n panelSize.Height += sz.Height;\n curLineSize = new Size();\n }\n }\n else //continue to accumulate a line\n {\n curLineSize.Width += sz.Width;\n curLineSize.Height = Math.Max(sz.Height, curLineSize.Height);\n }\n }\n\n // the last line size, if any need to be added\n panelSize.Width = Math.Max(curLineSize.Width, panelSize.Width);\n panelSize.Height += curLineSize.Height;\n\n return panelSize;\n }\n\n protected override Size ArrangeOverride(Size arrangeBounds)\n {\n int firstInLine = 0;\n Size curLineSize = new();\n double accumulatedHeight = 0;\n UIElementCollection children = InternalChildren;\n\n for (int i = 0; i < children.Count; i++)\n {\n UIElement child = children[i];\n\n Size sz = child.DesiredSize;\n\n if (child is NewLine ||\n curLineSize.Width + sz.Width > arrangeBounds.Width) //need to switch to another line\n {\n ArrangeLine(accumulatedHeight, curLineSize, arrangeBounds.Width, firstInLine, i);\n\n accumulatedHeight += curLineSize.Height;\n curLineSize = sz;\n\n if (sz.Width > arrangeBounds.Width) //the element is wider then the constraint - give it a separate line\n {\n ArrangeLine(accumulatedHeight, sz, arrangeBounds.Width, i, ++i);\n accumulatedHeight += sz.Height;\n curLineSize = new Size();\n }\n firstInLine = i;\n }\n else //continue to accumulate a line\n {\n curLineSize.Width += sz.Width;\n curLineSize.Height = Math.Max(sz.Height, curLineSize.Height);\n }\n }\n\n if (firstInLine < children.Count)\n ArrangeLine(accumulatedHeight, curLineSize, arrangeBounds.Width, firstInLine, children.Count);\n\n return arrangeBounds;\n }\n\n private void ArrangeLine(double y, Size lineSize, double boundsWidth, int start, int end)\n {\n double x = 0;\n if (this.HorizontalContentAlignment == HorizontalAlignment.Center)\n {\n x = (boundsWidth - lineSize.Width) / 2;\n }\n else if (this.HorizontalContentAlignment == HorizontalAlignment.Right)\n {\n x = (boundsWidth - lineSize.Width);\n }\n\n UIElementCollection children = InternalChildren;\n for (int i = start; i < end; i++)\n {\n UIElement child = children[i];\n child.Arrange(new Rect(x, y, child.DesiredSize.Width, lineSize.Height));\n x += child.DesiredSize.Width;\n }\n }\n}\n"], ["/LLPlayer/LLPlayer/Controls/Settings/SettingsAbout.xaml.cs", "using System.Collections.ObjectModel;\nusing System.Diagnostics.CodeAnalysis;\nusing System.Windows;\nusing System.Windows.Controls;\nusing LLPlayer.Extensions;\n\nnamespace LLPlayer.Controls.Settings;\n\npublic partial class SettingsAbout : UserControl\n{\n public SettingsAbout()\n {\n InitializeComponent();\n\n DataContext = ((App)Application.Current).Container.Resolve();\n }\n}\n\npublic class SettingsAboutVM : Bindable\n{\n public SettingsAboutVM()\n {\n Libraries =\n [\n new LibraryInfo\n {\n Name = \"SuRGeoNix/Flyleaf\",\n Description = \"Media Player .NET Library for WinUI 3/WPF/WinForms (based on FFmpeg/DirectX)\",\n Url = \"https://github.com/SuRGeoNix/Flyleaf\"\n },\n\n new LibraryInfo\n {\n Name = \"SuRGeoNix/Flyleaf.FFmpeg\",\n Description = \"FFmpeg Bindings for C#/.NET\",\n Url = \"https://github.com/SuRGeoNix/Flyleaf.FFmpeg\"\n },\n\n new LibraryInfo\n {\n Name = \"sandrohanea/whisper.net\",\n Description = \"Dotnet bindings for OpenAI Whisper (whisper.cpp)\",\n Url = \"https://github.com/sandrohanea/whisper.net\"\n },\n\n new LibraryInfo\n {\n Name = \"Purfview/whisper-standalone-win\",\n Description = \"Faster-Whisper standalone executables\",\n Url = \"https://github.com/Purfview/whisper-standalone-win\"\n },\n\n new LibraryInfo\n {\n Name = \"Sicos1977/TesseractOCR\",\n Description = \".NET wrapper for Tesseract OCR\",\n Url = \"https://github.com/Sicos1977/TesseractOCR\"\n },\n\n new LibraryInfo\n {\n Name = \"MaterialDesignInXamlToolkit \",\n Description = \"Google's Material Design in XAML & WPF\",\n Url = \"https://github.com/MaterialDesignInXAML/MaterialDesignInXamlToolkit\"\n },\n\n new LibraryInfo\n {\n Name = \"searchpioneer/lingua-dotnet\",\n Description = \"Natural language detection library for .NET\",\n Url = \"https://github.com/searchpioneer/lingua-dotnet\"\n },\n\n new LibraryInfo\n {\n Name = \"CharsetDetector/UTF-unknowns\",\n Description = \"Character set detector build in C#\",\n Url = \"https://github.com/CharsetDetector/UTF-unknown\"\n },\n\n new LibraryInfo\n {\n Name = \"komutan/NMeCab\",\n Description = \"Japanese morphological analyzer on .NET\",\n Url = \"https://github.com/komutan/NMeCab\"\n },\n\n new LibraryInfo\n {\n Name = \"PrismLibrary/Prism\",\n Description = \"A framework for building MVVM application\",\n Url = \"https://github.com/PrismLibrary/Prism\"\n },\n\n new LibraryInfo\n {\n Name = \"amerkoleci/Vortice.Windows\",\n Description = \".NET bindings for Direct3D11, XAudio, etc.\",\n Url = \"https://github.com/amerkoleci/Vortice.Windows\"\n },\n\n new LibraryInfo\n {\n Name = \"sskodje/WpfColorFont\",\n Description = \" A WPF font and color dialog\",\n Url = \"https://github.com/sskodje/WpfColorFont\"\n },\n ];\n\n }\n public ObservableCollection Libraries { get; }\n\n [field: AllowNull, MaybeNull]\n public DelegateCommand CmdCopyVersion => field ??= new(() =>\n {\n Clipboard.SetText($\"\"\"\n Version: {App.Version}, CommitHash: {App.CommitHash}\n OS Architecture: {App.OSArchitecture}, Process Architecture: {App.ProcessArchitecture}\n \"\"\");\n });\n}\n\npublic class LibraryInfo\n{\n public required string Name { get; init; }\n public required string Description { get; init; }\n public required string Url { get; init; }\n}\n"], ["/LLPlayer/LLPlayer/Services/SrtExporter.cs", "using System.IO;\nusing System.Text;\n\nnamespace LLPlayer.Services;\n\npublic static class SrtExporter\n{\n // TODO: L: Supports tags such as ?\n public static void ExportSrt(List lines, string filePath, Encoding encoding)\n {\n using StreamWriter writer = new(filePath, false, encoding);\n\n foreach (var (i, line) in lines.Index())\n {\n writer.WriteLine((i + 1).ToString());\n writer.WriteLine($\"{FormatTime(line.Start)} --> {FormatTime(line.End)}\");\n writer.WriteLine(line.Text);\n // blank line expect last\n if (i != lines.Count - 1)\n {\n writer.WriteLine();\n }\n }\n }\n\n private static string FormatTime(TimeSpan time)\n {\n return string.Format(\"{0:00}:{1:00}:{2:00},{3:000}\",\n (int)time.TotalHours,\n time.Minutes,\n time.Seconds,\n time.Milliseconds);\n }\n}\n\npublic class SubtitleLine\n{\n public required TimeSpan Start { get; init; }\n public required TimeSpan End { get; init; }\n public required string Text { get; init; }\n}\n"], ["/LLPlayer/LLPlayer/Controls/Settings/SettingsSubtitlesASR.xaml.cs", "using System.Collections.ObjectModel;\nusing System.Collections.Specialized;\nusing System.Diagnostics;\nusing System.Globalization;\nusing System.IO;\nusing System.Windows;\nusing System.Windows.Controls;\nusing System.Windows.Data;\nusing CliWrap.Builders;\nusing FlyleafLib;\nusing FlyleafLib.MediaPlayer;\nusing LLPlayer.Extensions;\nusing LLPlayer.Services;\nusing LLPlayer.Views;\nusing Whisper.net.LibraryLoader;\n\nnamespace LLPlayer.Controls.Settings;\n\npublic partial class SettingsSubtitlesASR : UserControl\n{\n public SettingsSubtitlesASR()\n {\n InitializeComponent();\n\n DataContext = ((App)Application.Current).Container.Resolve();\n }\n}\n\npublic class SettingsSubtitlesASRVM : Bindable\n{\n public FlyleafManager FL { get; }\n private readonly IDialogService _dialogService;\n\n public SettingsSubtitlesASRVM(FlyleafManager fl, IDialogService dialogService)\n {\n FL = fl;\n _dialogService = dialogService;\n\n LoadDownloadedModels();\n\n foreach (RuntimeLibrary library in FL.PlayerConfig.Subtitles.WhisperCppConfig.RuntimeLibraries)\n {\n SelectedLibraries.Add(library);\n }\n\n foreach (RuntimeLibrary library in Enum.GetValues().Where(l => l != RuntimeLibrary.CoreML))\n {\n if (!SelectedLibraries.Contains(library))\n {\n AvailableLibraries.Add(library);\n }\n }\n SelectedLibraries.CollectionChanged += SelectedLibrariesOnCollectionChanged;\n\n foreach (WhisperLanguage lang in WhisperLanguage.GetWhisperLanguages())\n {\n WhisperLanguages.Add(lang);\n }\n\n ActiveEngineTabNo = (int)FL.PlayerConfig.Subtitles.ASREngine;\n }\n\n public int ActiveEngineTabNo { get; }\n\n public ObservableCollection WhisperLanguages { get; } = new();\n\n #region whisper.cpp\n public ObservableCollection AvailableLibraries { get; } = new();\n public ObservableCollection SelectedLibraries { get; } = new();\n\n public RuntimeLibrary? SelectedAvailable\n {\n get;\n set\n {\n if (Set(ref field, value))\n {\n OnPropertyChanged(nameof(CanMoveRight));\n }\n }\n }\n\n public RuntimeLibrary? SelectedSelected\n {\n get;\n set\n {\n if (Set(ref field, value))\n {\n OnPropertyChanged(nameof(CanMoveLeft));\n OnPropertyChanged(nameof(CanMoveUp));\n OnPropertyChanged(nameof(CanMoveDown));\n }\n }\n }\n\n public bool CanMoveRight => SelectedAvailable.HasValue;\n public bool CanMoveLeft => SelectedSelected.HasValue;\n public bool CanMoveUp => SelectedSelected.HasValue && SelectedLibraries.IndexOf(SelectedSelected.Value) > 0;\n public bool CanMoveDown => SelectedSelected.HasValue && SelectedLibraries.IndexOf(SelectedSelected.Value) < SelectedLibraries.Count - 1;\n\n private void SelectedLibrariesOnCollectionChanged(object? sender, NotifyCollectionChangedEventArgs e)\n {\n // Apply to config\n FL.PlayerConfig.Subtitles.WhisperCppConfig.RuntimeLibraries = [.. SelectedLibraries];\n }\n\n private void LoadDownloadedModels()\n {\n WhisperCppModel? prevSelected = FL.PlayerConfig.Subtitles.WhisperCppConfig.Model;\n FL.PlayerConfig.Subtitles.WhisperCppConfig.Model = null;\n DownloadModels.Clear();\n\n List models = WhisperCppModelLoader.LoadDownloadedModels();\n foreach (var model in models)\n {\n DownloadModels.Add(model);\n }\n\n FL.PlayerConfig.Subtitles.WhisperCppConfig.Model = DownloadModels.FirstOrDefault(m => m.Equals(prevSelected));\n\n if (FL.PlayerConfig.Subtitles.WhisperCppConfig.Model == null && DownloadModels.Count == 1)\n {\n // automatically set first downloaded model\n FL.PlayerConfig.Subtitles.WhisperCppConfig.Model = DownloadModels.First();\n }\n }\n\n public ObservableCollection DownloadModels { get; set => Set(ref field, value); } = new();\n\n public OrderedDictionary PromptPresets { get; } = new()\n {\n [\"Use Chinese (Simplified), with punctuation\"] = \"以下是普通话的句子。\",\n [\"Use Chinese (Traditional), with punctuation\"] = \"以下是普通話的句子。\"\n };\n\n public KeyValuePair? SelectedPromptPreset\n {\n get;\n set\n {\n if (Set(ref field, value))\n {\n if (value.HasValue)\n {\n FL.PlayerConfig.Subtitles.WhisperCppConfig.Prompt = value.Value.Value;\n }\n }\n }\n }\n\n public DelegateCommand? CmdDownloadModel => field ??= new(() =>\n {\n _dialogService.ShowDialog(nameof(WhisperModelDownloadDialog));\n\n LoadDownloadedModels();\n });\n\n public DelegateCommand? CmdMoveRight => field ??= new DelegateCommand(() =>\n {\n if (SelectedAvailable.HasValue && !SelectedLibraries.Contains(SelectedAvailable.Value))\n {\n SelectedLibraries.Add(SelectedAvailable.Value);\n AvailableLibraries.Remove(SelectedAvailable.Value);\n }\n }).ObservesCanExecute(() => CanMoveRight);\n\n public DelegateCommand? CmdMoveLeft => field ??= new DelegateCommand(() =>\n {\n if (SelectedSelected.HasValue)\n {\n AvailableLibraries.Add(SelectedSelected.Value);\n SelectedLibraries.Remove(SelectedSelected.Value);\n }\n }).ObservesCanExecute(() => CanMoveLeft);\n\n public DelegateCommand? CmdMoveUp => field ??= new DelegateCommand(() =>\n {\n int index = SelectedLibraries.IndexOf(SelectedSelected!.Value);\n if (index > 0)\n {\n SelectedLibraries.Move(index, index - 1);\n OnPropertyChanged(nameof(CanMoveUp));\n OnPropertyChanged(nameof(CanMoveDown));\n }\n }).ObservesCanExecute(() => CanMoveUp);\n\n public DelegateCommand? CmdMoveDown => field ??= new DelegateCommand(() =>\n {\n int index = SelectedLibraries.IndexOf(SelectedSelected!.Value);\n if (index < SelectedLibraries.Count - 1)\n {\n SelectedLibraries.Move(index, index + 1);\n OnPropertyChanged(nameof(CanMoveUp));\n OnPropertyChanged(nameof(CanMoveDown));\n }\n }).ObservesCanExecute(() => CanMoveDown);\n #endregion\n\n #region faster-whisper\n public OrderedDictionary ExtraArgumentsPresets { get; } = new()\n {\n [\"Use CUDA device\"] = \"--device cuda\",\n [\"Use CUDA second device\"] = \"--device cuda:1\",\n [\"Use CPU device\"] = \"--device cpu\",\n [\"Use Chinese (Simplified), with punctuation\"] = \"--initial_prompt \\\"以下是普通话的句子。\\\"\",\n [\"Use Chinese (Traditional), with punctuation\"] = \"--initial_prompt \\\"以下是普通話的句子。\\\"\"\n };\n\n public KeyValuePair? SelectedExtraArgumentsPreset\n {\n get;\n set\n {\n if (Set(ref field, value))\n {\n if (value.HasValue)\n {\n FL.PlayerConfig.Subtitles.FasterWhisperConfig.ExtraArguments = value.Value.Value;\n }\n }\n }\n }\n\n public DelegateCommand? CmdDownloadEngine => field ??= new(() =>\n {\n _dialogService.ShowDialog(nameof(WhisperEngineDownloadDialog));\n\n // update binding of downloaded state forcefully\n var prev = FL.PlayerConfig.Subtitles.ASREngine;\n FL.PlayerConfig.Subtitles.ASREngine = SubASREngineType.WhisperCpp;\n FL.PlayerConfig.Subtitles.ASREngine = prev;\n });\n\n public DelegateCommand? CmdOpenModelFolder => field ??= new(() =>\n {\n if (!Directory.Exists(WhisperConfig.ModelsDirectory))\n return;\n\n Process.Start(new ProcessStartInfo\n {\n FileName = WhisperConfig.ModelsDirectory,\n UseShellExecute = true,\n CreateNoWindow = true\n });\n });\n\n public DelegateCommand? CmdCopyDebugCommand => field ??= new(() =>\n {\n var cmdBase = FasterWhisperASRService.BuildCommand(FL.PlayerConfig.Subtitles.FasterWhisperConfig,\n FL.PlayerConfig.Subtitles.WhisperConfig);\n\n var sampleWavePath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, \"Assets\", \"kennedy.wav\");\n ArgumentsBuilder args = new();\n args.Add(sampleWavePath);\n\n string addedArgs = args.Build();\n\n var cmd = cmdBase.WithArguments($\"{cmdBase.Arguments} {addedArgs}\");\n Clipboard.SetText(cmd.CommandToText());\n });\n\n public DelegateCommand? CmdCopyHelpCommand => field ??= new(() =>\n {\n var cmdBase = FasterWhisperASRService.BuildCommand(FL.PlayerConfig.Subtitles.FasterWhisperConfig,\n FL.PlayerConfig.Subtitles.WhisperConfig);\n\n var cmd = cmdBase.WithArguments(\"--help\");\n Clipboard.SetText(cmd.CommandToText());\n });\n#endregion\n}\n\n[ValueConversion(typeof(Enum), typeof(bool))]\npublic class ASREngineDownloadedConverter : IValueConverter\n{\n public object Convert(object value, Type targetType, object parameter, CultureInfo culture)\n {\n if (value is SubASREngineType engine)\n {\n if (engine == SubASREngineType.FasterWhisper)\n {\n if (File.Exists(FasterWhisperConfig.DefaultEnginePath))\n {\n return true;\n }\n }\n }\n\n return false;\n }\n\n public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture) => throw new NotImplementedException();\n}\n"], ["/LLPlayer/LLPlayer/Controls/Settings/SettingsSubtitlesAction.xaml.cs", "using System.Collections.ObjectModel;\nusing System.Windows;\nusing System.Windows.Controls;\nusing System.Windows.Input;\nusing FlyleafLib.MediaPlayer.Translation.Services;\nusing LLPlayer.Extensions;\nusing LLPlayer.Services;\n\nnamespace LLPlayer.Controls.Settings;\n\npublic partial class SettingsSubtitlesAction : UserControl\n{\n public SettingsSubtitlesAction()\n {\n InitializeComponent();\n\n DataContext = ((App)Application.Current).Container.Resolve();\n }\n}\n\npublic class SettingsSubtitlesActionVM : Bindable\n{\n public FlyleafManager FL { get; }\n\n public SettingsSubtitlesActionVM(FlyleafManager fl)\n {\n FL = fl;\n\n SelectedTranslateWordServiceType = FL.PlayerConfig.Subtitles.TranslateWordServiceType;\n\n List wordClickActions = Enum.GetValues().ToList();\n if (string.IsNullOrEmpty(FL.Config.Subs.PDICPipeExecutablePath))\n {\n // PDIC is enabled only when exe is configured\n wordClickActions.Remove(WordClickAction.PDIC);\n }\n WordClickActions = wordClickActions;\n\n foreach (IMenuAction menuAction in FL.Config.Subs.WordMenuActions)\n {\n MenuActions.Add((IMenuAction)menuAction.Clone());\n }\n }\n\n public TranslateServiceType SelectedTranslateWordServiceType\n {\n get;\n set\n {\n if (Set(ref field, value))\n {\n FL.PlayerConfig.Subtitles.TranslateWordServiceType = value;\n }\n }\n }\n\n public List WordClickActions { get; }\n\n public List ModifierKeys { get; } =\n [\n System.Windows.Input.ModifierKeys.Control,\n System.Windows.Input.ModifierKeys.Shift,\n System.Windows.Input.ModifierKeys.Alt,\n System.Windows.Input.ModifierKeys.None\n ];\n\n public ObservableCollection MenuActions { get; } = new();\n\n public DelegateCommand? CmdApplyContextMenu => field ??= new(() =>\n {\n ObservableCollection newActions = new(MenuActions.Select(a => (IMenuAction)a.Clone()));\n\n // Apply to config\n FL.Config.Subs.WordMenuActions = newActions;\n });\n\n public DelegateCommand? CmdAddSearchAction => field ??= new(() =>\n {\n MenuActions.Add(new SearchMenuAction\n {\n Title = \"New Search\",\n Url = \"https://example.com/?q=%w\"\n });\n });\n\n public DelegateCommand? CmdAddClipboardAction => field ??= new(() =>\n {\n MenuActions.Add(new ClipboardMenuAction());\n });\n\n public DelegateCommand? CmdAddClipboardAllAction => field ??= new(() =>\n {\n MenuActions.Add(new ClipboardAllMenuAction());\n });\n\n public DelegateCommand? CmdRemoveAction => field ??= new((action) =>\n {\n if (action != null)\n {\n MenuActions.Remove(action);\n }\n });\n\n // TODO: L: SaveCommand?\n}\n\nclass DataGridRowOrderBehaviorMenuAction : DataGridRowOrderBehavior;\n\nclass MenuActionTemplateSelector : DataTemplateSelector\n{\n public required DataTemplate SearchTemplate { get; set; }\n public required DataTemplate ClipboardTemplate { get; set; }\n public required DataTemplate ClipboardAllTemplate { get; set; }\n\n public override DataTemplate? SelectTemplate(object? item, DependencyObject container)\n {\n return item switch\n {\n SearchMenuAction => SearchTemplate,\n ClipboardMenuAction => ClipboardTemplate,\n ClipboardAllMenuAction => ClipboardAllTemplate,\n _ => null\n };\n }\n}\n"], ["/LLPlayer/LLPlayer/ViewModels/MainWindowVM.cs", "using System.IO;\nusing System.Windows;\nusing System.Windows.Media;\nusing System.Windows.Media.Imaging;\nusing System.Windows.Shell;\nusing FlyleafLib;\nusing FlyleafLib.MediaPlayer;\nusing LLPlayer.Extensions;\nusing LLPlayer.Services;\nusing InputType = FlyleafLib.InputType;\n\nnamespace LLPlayer.ViewModels;\n\npublic class MainWindowVM : Bindable\n{\n public FlyleafManager FL { get; }\n private readonly LogHandler Log;\n\n public MainWindowVM(FlyleafManager fl)\n {\n FL = fl;\n Log = new LogHandler(\"[App] [MainWindowVM ] \");\n }\n\n public string Title { get; set => Set(ref field, value); } = App.Name;\n\n #region Progress in TaskBar\n public double TaskBarProgressValue\n {\n get;\n set\n {\n double v = value;\n if (v < 0.01)\n {\n // Set to 1% because it is not displayed.\n v = 0.01;\n }\n Set(ref field, v);\n }\n }\n\n public TaskbarItemProgressState TaskBarProgressState { get; set => Set(ref field, value); }\n #endregion\n\n #region Action Button in TaskBar\n public Visibility PlayPauseVisibility { get; set => Set(ref field, value); } = Visibility.Collapsed;\n public ImageSource PlayPauseImageSource { get; set => Set(ref field, value); } = PlayIcon;\n\n private static readonly BitmapImage PlayIcon = new(\n new Uri(\"pack://application:,,,/Resources/Images/play.png\"));\n\n private static readonly BitmapImage PauseIcon = new(\n new Uri(\"pack://application:,,,/Resources/Images/pause.png\"));\n #endregion\n\n public DelegateCommand? CmdOnLoaded => field ??= new(() =>\n {\n // error handling\n FL.Player.KnownErrorOccurred += (sender, args) =>\n {\n Utils.UI(() =>\n {\n Log.Error($\"Known error occurred in Flyleaf: {args.Message} ({args.ErrorType.ToString()})\");\n ErrorDialogHelper.ShowKnownErrorPopup(args.Message, args.ErrorType);\n });\n };\n\n FL.Player.UnknownErrorOccurred += (sender, args) =>\n {\n Utils.UI(() =>\n {\n Log.Error($\"Unknown error occurred in Flyleaf: {args.Message}: {args.Exception}\");\n ErrorDialogHelper.ShowUnknownErrorPopup(args.Message, args.ErrorType, args.Exception);\n });\n };\n\n FL.Player.PropertyChanged += (sender, args) =>\n {\n switch (args.PropertyName)\n {\n case nameof(FL.Player.CurTime):\n {\n double prevValue = TaskBarProgressValue;\n double newValue = (double)FL.Player.CurTime / FL.Player.Duration;\n\n if (Math.Abs(newValue - prevValue) >= 0.01) // prevent frequent update\n {\n TaskBarProgressValue = newValue;\n }\n\n break;\n }\n case nameof(FL.Player.Status):\n // Progress in TaskBar (and title)\n switch (FL.Player.Status)\n {\n case Status.Stopped:\n // reset\n Title = App.Name;\n TaskBarProgressState = TaskbarItemProgressState.None;\n TaskBarProgressValue = 0;\n break;\n case Status.Playing:\n TaskBarProgressState = TaskbarItemProgressState.Normal;\n break;\n case Status.Opening:\n TaskBarProgressState = TaskbarItemProgressState.Indeterminate;\n TaskBarProgressValue = 0;\n break;\n case Status.Paused:\n TaskBarProgressState = TaskbarItemProgressState.Paused;\n break;\n case Status.Ended:\n TaskBarProgressState = TaskbarItemProgressState.Paused;\n TaskBarProgressValue = 1;\n break;\n case Status.Failed:\n TaskBarProgressState = TaskbarItemProgressState.Error;\n break;\n }\n\n // Action Button in TaskBar\n switch (FL.Player.Status)\n {\n case Status.Paused:\n case Status.Playing:\n PlayPauseVisibility = Visibility.Visible;\n PlayPauseImageSource = FL.Player.Status == Status.Playing ? PauseIcon : PlayIcon;\n break;\n default:\n PlayPauseVisibility = Visibility.Collapsed;\n break;\n }\n\n break;\n }\n };\n\n FL.Player.OpenCompleted += (sender, args) =>\n {\n if (!args.Success || args.IsSubtitles)\n {\n return;\n }\n\n string name = Path.GetFileName(args.Url);\n if (FL.Player.Playlist.InputType == InputType.Web)\n {\n name = FL.Player.Playlist.Selected.Title;\n }\n Title = $\"{name} - {App.Name}\";\n TaskBarProgressValue = 0;\n TaskBarProgressState = TaskbarItemProgressState.Normal;\n };\n\n if (App.CmdUrl != null)\n {\n FL.Player.OpenAsync(App.CmdUrl);\n }\n });\n\n public DelegateCommand? CmdOnClosing => field ??= new(() =>\n {\n FL.Player.Dispose();\n });\n}\n"], ["/LLPlayer/FlyleafLib/Plugins/StreamSuggester.cs", "using System.Collections.Generic;\nusing System.Collections.ObjectModel;\nusing System.Linq;\n\nusing FlyleafLib.MediaFramework.MediaPlaylist;\nusing FlyleafLib.MediaFramework.MediaStream;\n\nnamespace FlyleafLib.Plugins;\n\npublic unsafe class StreamSuggester : PluginBase, ISuggestPlaylistItem, ISuggestAudioStream, ISuggestVideoStream, ISuggestSubtitlesStream, ISuggestSubtitles, ISuggestBestExternalSubtitles\n{\n public new int Priority { get; set; } = 3000;\n\n public AudioStream SuggestAudio(ObservableCollection streams)\n {\n lock (streams[0].Demuxer.lockActions)\n {\n foreach (var lang in Config.Audio.Languages)\n foreach (var stream in streams)\n if (stream.Language == lang)\n {\n if (stream.Demuxer.Programs.Count < 2)\n {\n Log.Info($\"Audio based on language\");\n return stream;\n }\n\n for (int i = 0; i < stream.Demuxer.Programs.Count; i++)\n {\n bool aExists = false, vExists = false;\n foreach (var pstream in stream.Demuxer.Programs[i].Streams)\n {\n if (pstream.StreamIndex == stream.StreamIndex) aExists = true;\n else if (pstream.StreamIndex == stream.Demuxer.VideoStream?.StreamIndex) vExists = true;\n }\n\n if (aExists && vExists)\n {\n Log.Info($\"Audio based on language and same program #{i}\");\n return stream;\n }\n }\n }\n\n // Fall-back to FFmpeg's default\n int streamIndex;\n lock (streams[0].Demuxer.lockFmtCtx)\n streamIndex = av_find_best_stream(streams[0].Demuxer.FormatContext, AVMediaType.Audio, -1, streams[0].Demuxer.VideoStream != null ? streams[0].Demuxer.VideoStream.StreamIndex : -1, null, 0);\n\n foreach (var stream in streams)\n if (stream.StreamIndex == streamIndex)\n {\n Log.Info($\"Audio based on av_find_best_stream\");\n return stream;\n }\n\n if (streams.Count > 0) // FFmpeg will not suggest anything when findstreaminfo is disable\n return streams[0];\n\n return null;\n }\n }\n\n public VideoStream SuggestVideo(ObservableCollection streams)\n {\n // Try to find best video stream based on current screen resolution\n var iresults =\n from vstream in streams\n where vstream.Type == MediaType.Video && vstream.Height <= Config.Video.MaxVerticalResolution //Decoder.VideoDecoder.Renderer.Info.ScreenBounds.Height\n orderby vstream.Height descending\n select vstream;\n\n List results = iresults.ToList();\n\n if (results.Count != 0)\n return iresults.ToList()[0];\n else\n {\n // Fall-back to FFmpeg's default\n int streamIndex;\n lock (streams[0].Demuxer.lockFmtCtx)\n streamIndex = av_find_best_stream(streams[0].Demuxer.FormatContext, AVMediaType.Video, -1, -1, null, 0);\n if (streamIndex < 0) return null;\n\n foreach (var vstream in streams)\n if (vstream.StreamIndex == streamIndex)\n return vstream;\n }\n\n if (streams.Count > 0) // FFmpeg will not suggest anything when findstreaminfo is disable\n return streams[0];\n\n return null;\n }\n\n public PlaylistItem SuggestItem()\n => Playlist.Items[0];\n\n public void SuggestSubtitles(out SubtitlesStream stream, out ExternalSubtitlesStream extStream)\n {\n stream = null;\n extStream = null;\n\n List langs = new();\n\n foreach (var lang in Config.Subtitles.Languages)\n langs.Add(lang);\n\n langs.Add(Language.Unknown);\n\n var extStreams = Selected.ExternalSubtitlesStreamsAll\n .Where(x => (Config.Subtitles.OpenAutomaticSubs || !x.Automatic))\n .OrderBy(x => x.Language.ToString())\n .ThenBy(x => x.Downloaded)\n .ThenBy(x => x.ManualDownloaded);\n\n foreach (var lang in langs)\n {\n foreach(var embStream in decoder.VideoDemuxer.SubtitlesStreamsAll)\n if (embStream.Language == lang)\n {\n stream = embStream;\n return;\n }\n\n foreach(var extStream2 in extStreams)\n if (extStream2.Language == lang)\n {\n extStream = extStream2;\n return;\n }\n }\n }\n\n public ExternalSubtitlesStream SuggestBestExternalSubtitles()\n {\n var extStreams = Selected.ExternalSubtitlesStreamsAll\n .Where(x => (Config.Subtitles.OpenAutomaticSubs || !x.Automatic))\n .OrderBy(x => x.Language.ToString())\n .ThenBy(x => x.Downloaded)\n .ThenBy(x => x.ManualDownloaded);\n\n foreach(var extStream in extStreams)\n if (extStream.Language == Config.Subtitles.Languages[0])\n return extStream;\n\n return null;\n }\n\n public SubtitlesStream SuggestSubtitles(ObservableCollection streams, List langs)\n {\n foreach(var lang in langs)\n foreach(var stream in streams)\n if (lang == stream.Language)\n return stream;\n\n return null;\n }\n}\n"], ["/LLPlayer/FlyleafLib/MediaFramework/MediaPlaylist/PlaylistItem.cs", "using System.Collections.Generic;\nusing System.Collections.ObjectModel;\n\nusing FlyleafLib.MediaFramework.MediaDemuxer;\nusing FlyleafLib.MediaFramework.MediaStream;\n\nnamespace FlyleafLib.MediaFramework.MediaPlaylist;\n\npublic class PlaylistItem : DemuxerInput\n{\n public int Index { get; set; } = -1; // if we need it we need to ensure we fix it in case of removing an item\n\n /// \n /// While the Url can expire or be null DirectUrl can be used as a new input for re-opening\n /// \n public string DirectUrl { get; set; }\n\n /// \n /// Relative folder to playlist's folder base (can be empty, not null)\n /// Use Path.Combine(Playlist.FolderBase, Folder) to get absolute path for saving related files with the current selection item (such as subtitles)\n /// \n public string Folder { get; set; } = \"\";\n\n public long FileSize { get; set; }\n\n /// \n /// Usually just the filename part of the provided Url\n /// \n public string OriginalTitle { get => _OriginalTitle;set => SetUI(ref _OriginalTitle, value ?? \"\", false); }\n string _OriginalTitle = \"\";\n\n /// \n /// Movie/TVShow Title\n /// \n public string MediaTitle { get => _MediaTitle; set => SetUI(ref _MediaTitle, value ?? \"\", false); }\n string _MediaTitle = \"\";\n\n /// \n /// Movie/TVShow Title including Movie's Year or TVShow's Season/Episode\n /// \n public string Title { get => _Title; set { if (_Title == \"\") OriginalTitle = value; SetUI(ref _Title, value ?? \"\", false);} }\n string _Title = \"\";\n\n public List\n Chapters { get; set; } = new();\n\n public int Season { get; set; }\n public int Episode { get; set; }\n public int Year { get; set; }\n\n public Dictionary\n Tag { get; set; } = [];\n public void AddTag(object tag, string pluginName)\n {\n if (!Tag.TryAdd(pluginName, tag))\n Tag[pluginName] = tag;\n }\n\n public object GetTag(string pluginName)\n => Tag.TryGetValue(pluginName, out object value) ? value : null;\n\n public bool SearchedLocal { get; set; }\n public bool SearchedOnline { get; set; }\n\n /// \n /// Whether the item is currently enabled or not\n /// \n public bool Enabled { get => _Enabled; set { if (SetUI(ref _Enabled, value) && value == true) OpenedCounter++; } }\n bool _Enabled;\n public int OpenedCounter { get; set; }\n\n public ExternalVideoStream\n ExternalVideoStream { get; set; }\n public ExternalAudioStream\n ExternalAudioStream { get; set; }\n public ExternalSubtitlesStream[]\n ExternalSubtitlesStreams\n { get; set; } = new ExternalSubtitlesStream[2];\n\n public ObservableCollection\n ExternalVideoStreams { get; set; } = [];\n public ObservableCollection\n ExternalAudioStreams { get; set; } = [];\n public ObservableCollection\n ExternalSubtitlesStreamsAll\n { get; set; } = [];\n internal object lockExternalStreams = new();\n\n bool filled;\n public void FillMediaParts() // Called during OpenScrape (if file) & Open/Search Subtitles (to be able to search online and compare tvshow/movie properly)\n {\n if (filled)\n return;\n\n filled = true;\n var mp = Utils.GetMediaParts(OriginalTitle);\n Year = mp.Year;\n Season = mp.Season;\n Episode = mp.Episode;\n MediaTitle = mp.Title; // safe title to check with online subs\n\n if (mp.Season > 0 && mp.Episode > 0) // tvshow\n {\n var title = \"S\";\n title += Season > 9 ? Season : $\"0{Season}\";\n title += \"E\";\n title += Episode > 9 ? Episode : $\"0{Episode}\";\n\n Title = mp.Title == \"\" ? title : mp.Title + \" (\" + title + \")\";\n }\n else if (mp.Year > 0) // movie\n Title = mp.Title + \" (\" + mp.Year + \")\";\n }\n\n public static void AddExternalStream(ExternalStream extStream, PlaylistItem item, string pluginName, object tag = null)\n {\n lock (item.lockExternalStreams)\n {\n extStream.PlaylistItem = item;\n extStream.PluginName = pluginName;\n\n if (extStream is ExternalAudioStream astream)\n {\n item.ExternalAudioStreams.Add(astream);\n extStream.Index = item.ExternalAudioStreams.Count - 1;\n }\n else if (extStream is ExternalVideoStream vstream)\n {\n item.ExternalVideoStreams.Add(vstream);\n extStream.Index = item.ExternalVideoStreams.Count - 1;\n }\n else if (extStream is ExternalSubtitlesStream sstream)\n {\n item.ExternalSubtitlesStreamsAll.Add(sstream);\n extStream.Index = item.ExternalSubtitlesStreamsAll.Count - 1;\n }\n\n if (tag != null)\n extStream.AddTag(tag, pluginName);\n };\n }\n}\n"], ["/LLPlayer/FlyleafLib/Engine/Engine.Plugins.cs", "using System;\nusing System.Collections.Generic;\nusing System.IO;\nusing System.Reflection;\n\nusing FlyleafLib.Plugins;\n\nnamespace FlyleafLib;\n\npublic class PluginsEngine\n{\n public Dictionary\n Types { get; private set; } = new Dictionary();\n\n public string Folder { get; private set; }\n\n private Type pluginBaseType = typeof(PluginBase);\n\n internal PluginsEngine()\n {\n Folder = string.IsNullOrEmpty(Engine.Config.PluginsPath) ? null : Utils.GetFolderPath(Engine.Config.PluginsPath);\n\n LoadAssemblies();\n }\n\n internal void LoadAssemblies()\n {\n // Load FlyleafLib's Embedded Plugins\n LoadPlugin(Assembly.GetExecutingAssembly());\n\n // Load External Plugins Folder\n if (Folder != null && Directory.Exists(Folder))\n {\n string[] dirs = Directory.GetDirectories(Folder);\n\n foreach(string dir in dirs)\n foreach(string file in Directory.GetFiles(dir, \"*.dll\"))\n LoadPlugin(Assembly.LoadFrom(Path.GetFullPath(file)));\n }\n else\n {\n Engine.Log.Info($\"[PluginHandler] No external plugins found\");\n }\n }\n\n /// \n /// Manually load plugins\n /// \n /// The assembly to search for plugins\n public void LoadPlugin(Assembly assembly)\n {\n try\n {\n var types = assembly.GetTypes();\n\n foreach (var type in types)\n {\n if (pluginBaseType.IsAssignableFrom(type) && type.IsClass && !type.IsAbstract)\n {\n // Force static constructors to execute (For early load, will be useful with c# 8.0 and static properties for interfaces eg. DefaultOptions)\n // System.Runtime.CompilerServices.RuntimeHelpers.RunClassConstructor(type.TypeHandle);\n\n if (!Types.ContainsKey(type.Name))\n {\n Types.Add(type.Name, new PluginType() { Name = type.Name, Type = type, Version = assembly.GetName().Version});\n Engine.Log.Info($\"Plugin loaded ({type.Name} - {assembly.GetName().Version})\");\n }\n else\n Engine.Log.Info($\"Plugin already exists ({type.Name} - {assembly.GetName().Version})\");\n }\n }\n }\n catch (Exception e) { Engine.Log.Error($\"[PluginHandler] [Error] Failed to load assembly ({e.Message} {Utils.GetRecInnerException(e)})\"); }\n }\n}\n"], ["/LLPlayer/FlyleafLib/Engine/TesseractModel.cs", "using System.Collections.Generic;\nusing System.IO;\nusing System.Linq;\n\nnamespace FlyleafLib;\n\n#nullable enable\n\npublic class TesseractModel : NotifyPropertyChanged, IEquatable\n{\n public static Dictionary TesseractLangToISO6391 { get; } = new()\n {\n {TesseractOCR.Enums.Language.Afrikaans, \"af\"},\n {TesseractOCR.Enums.Language.Amharic, \"am\"},\n {TesseractOCR.Enums.Language.Arabic, \"ar\"},\n {TesseractOCR.Enums.Language.Assamese, \"as\"},\n {TesseractOCR.Enums.Language.Azerbaijani, \"az\"},\n //{TesseractOCR.Enums.Language.AzerbaijaniCyrilic, \"\"},\n {TesseractOCR.Enums.Language.Belarusian, \"be\"},\n {TesseractOCR.Enums.Language.Bengali, \"bn\"},\n {TesseractOCR.Enums.Language.Tibetan, \"bo\"},\n {TesseractOCR.Enums.Language.Bosnian, \"bs\"},\n {TesseractOCR.Enums.Language.Breton, \"br\"},\n {TesseractOCR.Enums.Language.Bulgarian, \"bg\"},\n {TesseractOCR.Enums.Language.CatalanValencian, \"ca\"},\n //{TesseractOCR.Enums.Language.Cebuano, \"\"},\n {TesseractOCR.Enums.Language.Czech, \"cs\"},\n {TesseractOCR.Enums.Language.ChineseSimplified, \"zh\"}, // do special handling\n {TesseractOCR.Enums.Language.ChineseTraditional, \"zh\"},\n //{TesseractOCR.Enums.Language.Cherokee, \"\"},\n {TesseractOCR.Enums.Language.Corsican, \"co\"},\n {TesseractOCR.Enums.Language.Welsh, \"cy\"},\n {TesseractOCR.Enums.Language.Danish, \"da\"},\n //{TesseractOCR.Enums.Language.DanishFraktur, \"\"},\n {TesseractOCR.Enums.Language.German, \"de\"},\n //{TesseractOCR.Enums.Language.GermanFrakturContrib, \"\"},\n {TesseractOCR.Enums.Language.Dzongkha, \"dz\"},\n {TesseractOCR.Enums.Language.GreekModern, \"el\"},\n {TesseractOCR.Enums.Language.English, \"en\"},\n //{TesseractOCR.Enums.Language.EnglishMiddle, \"\"},\n {TesseractOCR.Enums.Language.Esperanto, \"eo\"},\n //{TesseractOCR.Enums.Language.Math, \"zz\"},\n {TesseractOCR.Enums.Language.Estonian, \"et\"},\n {TesseractOCR.Enums.Language.Basque, \"eu\"},\n {TesseractOCR.Enums.Language.Faroese, \"fo\"},\n {TesseractOCR.Enums.Language.Persian, \"fa\"},\n //{TesseractOCR.Enums.Language.Filipino, \"\"},\n {TesseractOCR.Enums.Language.Finnish, \"fi\"},\n {TesseractOCR.Enums.Language.French, \"fr\"},\n //{TesseractOCR.Enums.Language.GermanFraktur, \"\"},\n {TesseractOCR.Enums.Language.FrenchMiddle, \"zz\"},\n //{TesseractOCR.Enums.Language.WesternFrisian, \"\"},\n {TesseractOCR.Enums.Language.ScottishGaelic, \"gd\"},\n {TesseractOCR.Enums.Language.Irish, \"ga\"},\n {TesseractOCR.Enums.Language.Galician, \"gl\"},\n //{TesseractOCR.Enums.Language.GreekAncientContrib, \"\"},\n {TesseractOCR.Enums.Language.Gujarati, \"gu\"},\n {TesseractOCR.Enums.Language.Haitian, \"ht\"},\n {TesseractOCR.Enums.Language.Hebrew, \"he\"},\n {TesseractOCR.Enums.Language.Hindi, \"hi\"},\n {TesseractOCR.Enums.Language.Croatian, \"hr\"},\n {TesseractOCR.Enums.Language.Hungarian, \"hu\"},\n {TesseractOCR.Enums.Language.Armenian, \"hy\"},\n {TesseractOCR.Enums.Language.Inuktitut, \"iu\"},\n {TesseractOCR.Enums.Language.Indonesian, \"id\"},\n {TesseractOCR.Enums.Language.Icelandic, \"is\"},\n {TesseractOCR.Enums.Language.Italian, \"it\"},\n //{TesseractOCR.Enums.Language.ItalianOld, \"\"},\n {TesseractOCR.Enums.Language.Javanese, \"jv\"},\n {TesseractOCR.Enums.Language.Japanese, \"ja\"},\n //{TesseractOCR.Enums.Language.JapaneseVertical, \"\"},\n {TesseractOCR.Enums.Language.Kannada, \"kn\"},\n {TesseractOCR.Enums.Language.Georgian, \"ka\"},\n //{TesseractOCR.Enums.Language.GeorgianOld, \"\"},\n {TesseractOCR.Enums.Language.Kazakh, \"kk\"},\n {TesseractOCR.Enums.Language.CentralKhmer, \"km\"},\n {TesseractOCR.Enums.Language.KirghizKyrgyz, \"ky\"},\n {TesseractOCR.Enums.Language.Kurmanji, \"ku\"},\n {TesseractOCR.Enums.Language.Korean, \"ko\"},\n //{TesseractOCR.Enums.Language.KoreanVertical, \"\"},\n //{TesseractOCR.Enums.Language.KurdishArabicScript, \"\"},\n {TesseractOCR.Enums.Language.Lao, \"lo\"},\n {TesseractOCR.Enums.Language.Latin, \"la\"},\n {TesseractOCR.Enums.Language.Latvian, \"lv\"},\n {TesseractOCR.Enums.Language.Lithuanian, \"lt\"},\n {TesseractOCR.Enums.Language.Luxembourgish, \"lb\"},\n {TesseractOCR.Enums.Language.Malayalam, \"ml\"},\n {TesseractOCR.Enums.Language.Marathi, \"mr\"},\n {TesseractOCR.Enums.Language.Macedonian, \"mk\"},\n {TesseractOCR.Enums.Language.Maltese, \"mt\"},\n {TesseractOCR.Enums.Language.Mongolian, \"mn\"},\n {TesseractOCR.Enums.Language.Maori, \"mi\"},\n {TesseractOCR.Enums.Language.Malay, \"ms\"},\n {TesseractOCR.Enums.Language.Burmese, \"my\"},\n {TesseractOCR.Enums.Language.Nepali, \"ne\"},\n {TesseractOCR.Enums.Language.Dutch, \"nl\"},\n {TesseractOCR.Enums.Language.Norwegian, \"no\"},\n {TesseractOCR.Enums.Language.Occitan, \"oc\"},\n {TesseractOCR.Enums.Language.Oriya, \"or\"},\n //{TesseractOCR.Enums.Language.Osd, \"\"},\n {TesseractOCR.Enums.Language.Panjabi, \"pa\"},\n {TesseractOCR.Enums.Language.Polish, \"pl\"},\n {TesseractOCR.Enums.Language.Portuguese, \"pt\"},\n {TesseractOCR.Enums.Language.Pushto, \"ps\"},\n {TesseractOCR.Enums.Language.Quechua, \"qu\"},\n {TesseractOCR.Enums.Language.Romanian, \"ro\"},\n {TesseractOCR.Enums.Language.Russian, \"ru\"},\n {TesseractOCR.Enums.Language.Sanskrit, \"sa\"},\n {TesseractOCR.Enums.Language.Sinhala, \"si\"},\n {TesseractOCR.Enums.Language.Slovak, \"sk\"},\n //{TesseractOCR.Enums.Language.SlovakFrakturContrib, \"\"},\n {TesseractOCR.Enums.Language.Slovenian, \"sl\"},\n {TesseractOCR.Enums.Language.Sindhi, \"sd\"},\n {TesseractOCR.Enums.Language.SpanishCastilian, \"es\"},\n //{TesseractOCR.Enums.Language.SpanishCastilianOld, \"\"},\n {TesseractOCR.Enums.Language.Albanian, \"sq\"},\n {TesseractOCR.Enums.Language.Serbian, \"sr\"},\n //{TesseractOCR.Enums.Language.SerbianLatin, \"\"},\n {TesseractOCR.Enums.Language.Sundanese, \"su\"},\n {TesseractOCR.Enums.Language.Swahili, \"sw\"},\n {TesseractOCR.Enums.Language.Swedish, \"sv\"},\n //{TesseractOCR.Enums.Language.Syriac, \"\"},\n {TesseractOCR.Enums.Language.Tamil, \"ta\"},\n {TesseractOCR.Enums.Language.Tatar, \"tt\"},\n {TesseractOCR.Enums.Language.Telugu, \"te\"},\n {TesseractOCR.Enums.Language.Tajik, \"tg\"},\n {TesseractOCR.Enums.Language.Tagalog, \"tl\"},\n {TesseractOCR.Enums.Language.Thai, \"th\"},\n {TesseractOCR.Enums.Language.Tigrinya, \"ti\"},\n {TesseractOCR.Enums.Language.Tonga, \"to\"},\n {TesseractOCR.Enums.Language.Turkish, \"tr\"},\n {TesseractOCR.Enums.Language.Uighur, \"ug\"},\n {TesseractOCR.Enums.Language.Ukrainian, \"uk\"},\n {TesseractOCR.Enums.Language.Urdu, \"ur\"},\n {TesseractOCR.Enums.Language.Uzbek, \"uz\"},\n //{TesseractOCR.Enums.Language.UzbekCyrilic, \"\"},\n {TesseractOCR.Enums.Language.Vietnamese, \"vi\"},\n {TesseractOCR.Enums.Language.Yiddish, \"yi\"},\n {TesseractOCR.Enums.Language.Yoruba, \"yo\"},\n };\n\n public static string ModelsDirectory { get; } = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, \"tesseractmodels\", \"tessdata\");\n\n public TesseractOCR.Enums.Language Lang { get; set; }\n\n public string ISO6391 => TesseractLangToISO6391[Lang];\n\n public string LangCode =>\n TesseractOCR.Enums.LanguageHelper.EnumToString(Lang);\n\n public long Size\n {\n get;\n set\n {\n if (Set(ref field, value))\n {\n Raise(nameof(Downloaded));\n }\n }\n }\n\n public string ModelFileName => $\"{LangCode}.traineddata\";\n\n public string ModelFilePath => Path.Combine(ModelsDirectory, ModelFileName);\n\n public bool Downloaded => Size > 0;\n\n public override string ToString() => LangCode;\n\n public bool Equals(TesseractModel? other)\n {\n if (other is null) return false;\n if (ReferenceEquals(this, other)) return true;\n return Lang == other.Lang;\n }\n\n public override bool Equals(object? obj) => obj is TesseractModel o && Equals(o);\n\n public override int GetHashCode()\n {\n return (int)Lang;\n }\n}\n\npublic class TesseractModelLoader\n{\n /// \n /// key: ISO6391, value: TesseractModel\n /// Chinese has multiple models for one ISO6391 key\n /// \n /// \n internal static Dictionary> GetAvailableModels()\n {\n List models = LoadDownloadedModels();\n\n Dictionary> dict = new();\n\n foreach (TesseractModel model in models)\n {\n if (TesseractModel.TesseractLangToISO6391.TryGetValue(model.Lang, out string? iso6391))\n {\n if (dict.ContainsKey(iso6391))\n {\n // for chinese (zh-CN, zh-TW)\n dict[iso6391].Add(model);\n }\n else\n {\n dict.Add(iso6391, [model]);\n }\n }\n }\n\n return dict;\n }\n\n public static List LoadAllModels()\n {\n EnsureModelsDirectory();\n\n List models = Enum.GetValues()\n .Where(l => TesseractModel.TesseractLangToISO6391.ContainsKey(l))\n .Select(l => new TesseractModel { Lang = l })\n .OrderBy(m => m.Lang.ToString())\n .ToList();\n\n foreach (TesseractModel model in models)\n {\n // Initialize download status of each model\n string path = model.ModelFilePath;\n if (File.Exists(path))\n {\n model.Size = new FileInfo(path).Length;\n }\n }\n\n return models;\n }\n\n public static List LoadDownloadedModels()\n {\n return LoadAllModels()\n .Where(m => m.Downloaded)\n .ToList();\n }\n\n private static void EnsureModelsDirectory()\n {\n if (!Directory.Exists(TesseractModel.ModelsDirectory))\n {\n Directory.CreateDirectory(TesseractModel.ModelsDirectory);\n }\n }\n}\n"], ["/LLPlayer/FlyleafLib/MediaFramework/MediaStream/StreamBase.cs", "using System.Collections.Generic;\n\nusing FlyleafLib.MediaFramework.MediaDemuxer;\nusing FlyleafLib.MediaPlayer;\n\nnamespace FlyleafLib.MediaFramework.MediaStream;\n\npublic abstract unsafe class StreamBase : NotifyPropertyChanged\n{\n public ExternalStream ExternalStream { get; set; }\n\n public Demuxer Demuxer { get; internal set; }\n public AVStream* AVStream { get; internal set; }\n internal playlist* HLSPlaylist { get; set; }\n public int StreamIndex { get; internal set; } = -1;\n public double Timebase { get; internal set; }\n\n // TBR: To update Pop-up menu's (Player.Audio/Player.Video ... should inherit this?)\n public bool Enabled\n {\n get => _Enabled;\n internal set\n {\n Utils.UI(() =>\n {\n Set(ref _Enabled, value);\n\n Raise(nameof(EnabledPrimarySubtitle));\n Raise(nameof(EnabledSecondarySubtitle));\n Raise(nameof(SubtitlesStream.SelectedSubMethods));\n });\n }\n }\n\n bool _Enabled;\n\n public long BitRate { get; internal set; }\n public Language Language { get; internal set; }\n public string Title { get; internal set; }\n public string Codec { get; internal set; }\n\n public AVCodecID CodecID { get; internal set; }\n public long StartTime { get; internal set; }\n public long StartTimePts { get; internal set; }\n public long Duration { get; internal set; }\n public Dictionary Metadata { get; internal set; } = new Dictionary();\n public MediaType Type { get; internal set; }\n\n #region Subtitles\n // TODO: L: Used for subtitle streams only, but defined in the base class\n public bool EnabledPrimarySubtitle => Enabled && this.GetSubEnabled(0);\n public bool EnabledSecondarySubtitle => Enabled && this.GetSubEnabled(1);\n #endregion\n\n public abstract string GetDump();\n public StreamBase() { }\n public StreamBase(Demuxer demuxer, AVStream* st)\n {\n Demuxer = demuxer;\n AVStream = st;\n }\n\n public virtual void Refresh()\n {\n BitRate = AVStream->codecpar->bit_rate;\n CodecID = AVStream->codecpar->codec_id;\n Codec = avcodec_get_name(AVStream->codecpar->codec_id);\n StreamIndex = AVStream->index;\n Timebase = av_q2d(AVStream->time_base) * 10000.0 * 1000.0;\n StartTime = AVStream->start_time != AV_NOPTS_VALUE && Demuxer.hlsCtx == null ? (long)(AVStream->start_time * Timebase) : Demuxer.StartTime;\n StartTimePts= AVStream->start_time != AV_NOPTS_VALUE ? AVStream->start_time : av_rescale_q(StartTime/10, Engine.FFmpeg.AV_TIMEBASE_Q, AVStream->time_base);\n Duration = AVStream->duration != AV_NOPTS_VALUE ? (long)(AVStream->duration * Timebase) : Demuxer.Duration;\n Type = this is VideoStream ? MediaType.Video : (this is AudioStream ? MediaType.Audio : (this is SubtitlesStream ? MediaType.Subs : MediaType.Data));\n\n if (Demuxer.hlsCtx != null)\n {\n for (int i=0; in_playlists; i++)\n {\n playlist** playlists = Demuxer.hlsCtx->playlists;\n for (int l=0; ln_main_streams; l++)\n if (playlists[i]->main_streams[l]->index == StreamIndex)\n {\n Demuxer.Log.Debug($\"Stream #{StreamIndex} Found in playlist {i}\");\n HLSPlaylist = playlists[i];\n break;\n }\n }\n }\n\n Metadata.Clear();\n\n AVDictionaryEntry* b = null;\n while (true)\n {\n b = av_dict_get(AVStream->metadata, \"\", b, DictReadFlags.IgnoreSuffix);\n if (b == null) break;\n Metadata.Add(Utils.BytePtrToStringUTF8(b->key), Utils.BytePtrToStringUTF8(b->value));\n }\n\n foreach (var kv in Metadata)\n {\n string keyLower = kv.Key.ToLower();\n\n if (Language == null && (keyLower == \"language\" || keyLower == \"lang\"))\n Language = Language.Get(kv.Value);\n else if (keyLower == \"title\")\n Title = kv.Value;\n }\n\n if (Language == null)\n Language = Language.Unknown;\n }\n}\n"], ["/LLPlayer/FlyleafLib/MediaFramework/MediaPlaylist/Playlist.cs", "using System.Collections.ObjectModel;\nusing System.IO;\n\nusing FlyleafLib.MediaFramework.MediaContext;\n\nusing static FlyleafLib.Utils;\n\nnamespace FlyleafLib.MediaFramework.MediaPlaylist;\n\npublic class Playlist : NotifyPropertyChanged\n{\n /// \n /// Url provided by user\n /// \n public string Url { get => _Url; set { string fixedUrl = FixFileUrl(value); SetUI(ref _Url, fixedUrl); } }\n string _Url;\n\n /// \n /// IOStream provided by user\n /// \n public Stream IOStream { get; set; }\n\n /// \n /// Playlist's folder base which can be used to save related files\n /// \n public string FolderBase { get; set; }\n\n /// \n /// Playlist's title\n /// \n public string Title { get => _Title; set => SetUI(ref _Title, value); }\n string _Title;\n\n public int ExpectingItems { get => _ExpectingItems; set => SetUI(ref _ExpectingItems, value); }\n int _ExpectingItems;\n\n public bool Completed { get; set; }\n\n /// \n /// Playlist's opened/selected item\n /// \n public PlaylistItem Selected { get => _Selected; internal set { SetUI(ref _Selected, value); UpdatePrevNextItem(); } }\n PlaylistItem _Selected;\n\n public PlaylistItem NextItem { get => _NextItem; internal set => SetUI(ref _NextItem, value); }\n PlaylistItem _NextItem;\n\n public PlaylistItem PrevItem { get => _PrevItem; internal set => SetUI(ref _PrevItem, value); }\n PlaylistItem _PrevItem;\n\n internal void UpdatePrevNextItem()\n {\n if (Selected == null)\n {\n PrevItem = NextItem = null;\n return;\n }\n\n for (int i=0; i < Items.Count; i++)\n {\n if (Items[i] == Selected)\n {\n PrevItem = i > 0 ? Items[i - 1] : null;\n NextItem = i < Items.Count - 1 ? Items[i + 1] : null;\n\n return;\n }\n }\n }\n\n /// \n /// Type of the provided input (such as File, UNC, Torrent, Web, etc.)\n /// \n public InputType InputType { get; set; }\n\n // TODO: MediaType (Music/MusicClip/Movie/TVShow/etc.) probably should go per Playlist Item\n\n public ObservableCollection\n Items { get; set; } = new ObservableCollection();\n object lockItems = new();\n\n long openCounter;\n //long openItemCounter;\n internal DecoderContext decoder;\n LogHandler Log;\n\n public Playlist(int uniqueId)\n {\n Log = new LogHandler((\"[#\" + uniqueId + \"]\").PadRight(8, ' ') + \" [Playlist] \");\n UIInvokeIfRequired(() => System.Windows.Data.BindingOperations.EnableCollectionSynchronization(Items, lockItems));\n }\n\n public void Reset()\n {\n openCounter = decoder.OpenCounter;\n\n lock (lockItems)\n Items.Clear();\n\n bool noupdate = _Url == null && _Title == null && _Selected == null;\n\n _Url = null;\n _Title = null;\n _Selected = null;\n PrevItem = null;\n NextItem = null;\n IOStream = null;\n FolderBase = null;\n Completed = false;\n ExpectingItems = 0;\n\n InputType = InputType.Unknown;\n\n if (!noupdate)\n UI(() =>\n {\n Raise(nameof(Url));\n Raise(nameof(Title));\n Raise(nameof(Selected));\n });\n }\n\n public void AddItem(PlaylistItem item, string pluginName, object tag = null)\n {\n if (openCounter != decoder.OpenCounter)\n {\n Log.Debug(\"AddItem Cancelled\");\n return;\n }\n\n lock (lockItems)\n {\n Items.Add(item);\n Items[^1].Index = Items.Count - 1;\n\n UpdatePrevNextItem();\n\n if (tag != null)\n item.AddTag(tag, pluginName);\n };\n\n decoder.ScrapeItem(item);\n\n UIInvokeIfRequired(() =>\n {\n System.Windows.Data.BindingOperations.EnableCollectionSynchronization(item.ExternalAudioStreams, item.lockExternalStreams);\n System.Windows.Data.BindingOperations.EnableCollectionSynchronization(item.ExternalVideoStreams, item.lockExternalStreams);\n System.Windows.Data.BindingOperations.EnableCollectionSynchronization(item.ExternalSubtitlesStreamsAll, item.lockExternalStreams);\n });\n }\n}\n"], ["/LLPlayer/LLPlayer/Extensions/FileHelper.cs", "using System.IO;\nusing static FlyleafLib.Utils;\n\nnamespace LLPlayer.Extensions;\n\npublic static class FileHelper\n{\n /// \n /// Retrieves the next and previous file from the specified file path.\n /// Select files with the same extension in the same folder, sorted in natural alphabetical order.\n /// Returns null if the next or previous file does not exist.\n /// \n /// \n /// \n /// \n /// \n /// \n public static (string? prev, string? next) GetNextAndPreviousFile(string filePath)\n {\n if (!File.Exists(filePath))\n {\n throw new FileNotFoundException(\"file does not exist\", filePath);\n }\n\n string? directory = Path.GetDirectoryName(filePath);\n string? extension = Path.GetExtension(filePath);\n\n if (string.IsNullOrEmpty(directory) || string.IsNullOrEmpty(extension))\n {\n throw new InvalidOperationException($\"filePath is invalid: {filePath}\");\n }\n\n // Get files with the same extension, ignoring case\n List foundFiles = Directory.GetFiles(directory, $\"*{extension}\")\n .Where(f => string.Equals(Path.GetExtension(f), extension, StringComparison.OrdinalIgnoreCase))\n .OrderBy(f => Path.GetFileName(f), new NaturalStringComparer())\n .ToList();\n\n if (foundFiles.Count == 0)\n {\n throw new InvalidOperationException($\"same extension file does not exist: {filePath}\");\n }\n\n int currentIndex = foundFiles.FindIndex(f => string.Equals(f, filePath, StringComparison.OrdinalIgnoreCase));\n if (currentIndex == -1)\n {\n throw new InvalidOperationException($\"current file does not exist: {filePath}\");\n }\n\n string? next = (currentIndex < foundFiles.Count - 1) ? foundFiles[currentIndex + 1] : null;\n string? prev = (currentIndex > 0) ? foundFiles[currentIndex - 1] : null;\n\n return (prev, next);\n }\n}\n"], ["/LLPlayer/FlyleafLib/MediaFramework/MediaDemuxer/Interrupter.cs", "using System.Diagnostics;\n\nusing static FlyleafLib.Logger;\n\nnamespace FlyleafLib.MediaFramework.MediaDemuxer;\n\npublic unsafe class Interrupter\n{\n public int ForceInterrupt { get; set; }\n public Requester Requester { get; private set; }\n public int Interrupted { get; private set; }\n public bool Timedout { get; private set; }\n\n Demuxer demuxer;\n Stopwatch sw = new();\n internal AVIOInterruptCB_callback interruptClbk;\n long curTimeoutMs;\n\n internal int ShouldInterrupt(void* opaque)\n {\n if (demuxer.Status == Status.Stopping)\n {\n if (CanDebug) demuxer.Log.Debug($\"{Requester} Interrupt (Stopping) !!!\");\n\n return Interrupted = 1;\n }\n\n if (demuxer.Config.AllowTimeouts && sw.ElapsedMilliseconds > curTimeoutMs)\n {\n if (Timedout)\n return Interrupted = 1;\n\n if (CanWarn) demuxer.Log.Warn($\"{Requester} Timeout !!!! {sw.ElapsedMilliseconds} ms\");\n\n Timedout = true;\n Interrupted = 1;\n demuxer.OnTimedOut();\n\n return Interrupted;\n }\n\n if (Requester == Requester.Close)\n return 0;\n\n if (ForceInterrupt != 0 && demuxer.allowReadInterrupts)\n {\n if (CanTrace) demuxer.Log.Trace($\"{Requester} Interrupt !!!\");\n\n return Interrupted = 1;\n }\n\n return Interrupted = 0;\n }\n\n public Interrupter(Demuxer demuxer)\n {\n this.demuxer = demuxer;\n interruptClbk = ShouldInterrupt;\n }\n\n public void ReadRequest()\n {\n Requester = Requester.Read;\n\n if (!demuxer.Config.AllowTimeouts)\n return;\n\n Timedout = false;\n curTimeoutMs= demuxer.IsLive ? demuxer.Config.readLiveTimeoutMs: demuxer.Config.readTimeoutMs;\n sw.Restart();\n }\n\n public void SeekRequest()\n {\n Requester = Requester.Seek;\n\n if (!demuxer.Config.AllowTimeouts)\n return;\n\n Timedout = false;\n curTimeoutMs= demuxer.Config.seekTimeoutMs;\n sw.Restart();\n }\n\n public void OpenRequest()\n {\n Requester = Requester.Open;\n\n if (!demuxer.Config.AllowTimeouts)\n return;\n\n Timedout = false;\n curTimeoutMs= demuxer.Config.openTimeoutMs;\n sw.Restart();\n }\n\n public void CloseRequest()\n {\n Requester = Requester.Close;\n\n if (!demuxer.Config.AllowTimeouts)\n return;\n\n Timedout = false;\n curTimeoutMs= demuxer.Config.closeTimeoutMs;\n sw.Restart();\n }\n}\n\npublic enum Requester\n{\n Close,\n Open,\n Read,\n Seek\n}\n"], ["/LLPlayer/FlyleafLib/MediaFramework/MediaProgram/Program.cs", "using System.Collections.Generic;\nusing System.Linq;\n\nusing FlyleafLib.MediaFramework.MediaDemuxer;\nusing FlyleafLib.MediaFramework.MediaStream;\n\nnamespace FlyleafLib.MediaFramework.MediaProgram;\n\npublic class Program\n{\n public int ProgramNumber { get; internal set; }\n\n public int ProgramId { get; internal set; }\n\n public IReadOnlyDictionary\n Metadata { get; internal set; }\n\n public IReadOnlyList\n Streams { get; internal set; }\n\n public string Name => Metadata.ContainsKey(\"name\") ? Metadata[\"name\"] : string.Empty;\n\n public unsafe Program(AVProgram* program, Demuxer demuxer)\n {\n ProgramNumber = program->program_num;\n ProgramId = program->id;\n\n // Load stream info\n List streams = new(3);\n for(int s = 0; snb_stream_indexes; s++)\n {\n uint streamIndex = program->stream_index[s];\n StreamBase stream = null;\n stream = demuxer.AudioStreams.FirstOrDefault(it=>it.StreamIndex == streamIndex);\n\n if (stream == null)\n {\n stream = demuxer.VideoStreams.FirstOrDefault(it => it.StreamIndex == streamIndex);\n stream ??= demuxer.SubtitlesStreamsAll.FirstOrDefault(it => it.StreamIndex == streamIndex);\n }\n if (stream!=null)\n {\n streams.Add(stream);\n }\n }\n Streams = streams;\n\n // Load metadata\n Dictionary metadata = new();\n AVDictionaryEntry* b = null;\n while (true)\n {\n b = av_dict_get(program->metadata, \"\", b, DictReadFlags.IgnoreSuffix);\n if (b == null) break;\n metadata.Add(Utils.BytePtrToStringUTF8(b->key), Utils.BytePtrToStringUTF8(b->value));\n }\n Metadata = metadata;\n }\n}\n"], ["/LLPlayer/LLPlayer/Controls/Settings/SettingsSubtitles.xaml.cs", "using System.Windows;\nusing System.Windows.Controls;\nusing FlyleafLib;\nusing FlyleafLib.MediaPlayer.Translation;\nusing LLPlayer.Extensions;\nusing LLPlayer.Services;\nusing LLPlayer.Views;\n\nnamespace LLPlayer.Controls.Settings;\n\npublic partial class SettingsSubtitles : UserControl\n{\n public SettingsSubtitles()\n {\n InitializeComponent();\n\n DataContext = ((App)Application.Current).Container.Resolve();\n }\n}\n\npublic class SettingsSubtitlesVM : Bindable\n{\n public FlyleafManager FL { get; }\n private readonly IDialogService _dialogService;\n\n public SettingsSubtitlesVM(FlyleafManager fl, IDialogService dialogService)\n {\n _dialogService = dialogService;\n FL = fl;\n Languages = TranslateLanguage.Langs.Values.ToList();\n\n if (FL.PlayerConfig.Subtitles.LanguageFallbackPrimary != null)\n {\n SelectedPrimaryLanguage = Languages.FirstOrDefault(l => l.ISO6391 == FL.PlayerConfig.Subtitles.LanguageFallbackPrimary.ISO6391);\n }\n\n if (FL.PlayerConfig.Subtitles.LanguageFallbackSecondary != null)\n {\n SelectedSecondaryLanguage = Languages.FirstOrDefault(l => l.ISO6391 == FL.PlayerConfig.Subtitles.LanguageFallbackSecondary.ISO6391);\n }\n }\n\n public List Languages { get; set; }\n\n public TranslateLanguage? SelectedPrimaryLanguage\n {\n get;\n set\n {\n if (Set(ref field, value))\n {\n if (value == null)\n {\n FL.PlayerConfig.Subtitles.LanguageFallbackPrimary = null;\n }\n else\n {\n FL.PlayerConfig.Subtitles.LanguageFallbackPrimary = Language.Get(value.ISO6391);\n }\n\n if (FL.PlayerConfig.Subtitles.LanguageFallbackSecondarySame)\n {\n FL.PlayerConfig.Subtitles.LanguageFallbackSecondary = FL.PlayerConfig.Subtitles.LanguageFallbackPrimary;\n\n SelectedSecondaryLanguage = SelectedPrimaryLanguage;\n }\n }\n }\n }\n\n public TranslateLanguage? SelectedSecondaryLanguage\n {\n get;\n set\n {\n if (Set(ref field, value))\n {\n if (value == null)\n {\n FL.PlayerConfig.Subtitles.LanguageFallbackSecondary = null;\n }\n else\n {\n FL.PlayerConfig.Subtitles.LanguageFallbackSecondary = Language.Get(value.ISO6391);\n }\n }\n }\n }\n\n public DelegateCommand? CmdConfigureLanguage => field ??= new(() =>\n {\n DialogParameters p = new()\n {\n { \"languages\", FL.PlayerConfig.Subtitles.Languages }\n };\n\n _dialogService.ShowDialog(nameof(SelectLanguageDialog), p, result =>\n {\n List updated = result.Parameters.GetValue>(\"languages\");\n\n if (!FL.PlayerConfig.Subtitles.Languages.SequenceEqual(updated))\n {\n FL.PlayerConfig.Subtitles.Languages = updated;\n }\n });\n });\n}\n"], ["/LLPlayer/LLPlayer/Controls/Settings/SettingsSubtitlesTrans.xaml.cs", "using System.Globalization;\nusing System.Windows;\nusing System.Windows.Controls;\nusing System.Windows.Data;\nusing FlyleafLib.MediaPlayer.Translation;\nusing FlyleafLib.MediaPlayer.Translation.Services;\nusing LLPlayer.Extensions;\nusing LLPlayer.Services;\n\nnamespace LLPlayer.Controls.Settings;\n\npublic partial class SettingsSubtitlesTrans : UserControl\n{\n public SettingsSubtitlesTrans()\n {\n InitializeComponent();\n\n DataContext = ((App)Application.Current).Container.Resolve();\n }\n}\n\npublic class SettingsSubtitlesTransVM : Bindable\n{\n public FlyleafManager FL { get; }\n\n public SettingsSubtitlesTransVM(FlyleafManager fl)\n {\n FL = fl;\n\n SelectedTranslateServiceType = FL.PlayerConfig.Subtitles.TranslateServiceType;\n }\n\n public TranslateServiceType SelectedTranslateServiceType\n {\n get;\n set\n {\n Set(ref field, value);\n\n FL.PlayerConfig.Subtitles.TranslateServiceType = value;\n\n if (FL.PlayerConfig.Subtitles.TranslateServiceSettings.TryGetValue(value, out var settings))\n {\n // It points to an instance of the same class, so change this will be reflected in the config.\n SelectedServiceSettings = settings;\n }\n else\n {\n ITranslateSettings? defaultSettings = value.DefaultSettings();\n FL.PlayerConfig.Subtitles.TranslateServiceSettings.Add(value, defaultSettings);\n\n SelectedServiceSettings = defaultSettings;\n }\n }\n }\n\n public ITranslateSettings? SelectedServiceSettings { get; set => Set(ref field, value); }\n\n public DelegateCommand? CmdSetDefaultPromptKeepContext => field ??= new(() =>\n {\n FL.PlayerConfig.Subtitles.TranslateChatConfig.PromptKeepContext = TranslateChatConfig.DefaultPromptKeepContext.ReplaceLineEndings(\"\\n\");\n });\n\n public DelegateCommand? CmdSetDefaultPromptOneByOne => field ??= new(() =>\n {\n FL.PlayerConfig.Subtitles.TranslateChatConfig.PromptOneByOne = TranslateChatConfig.DefaultPromptOneByOne.ReplaceLineEndings(\"\\n\");\n });\n}\n\n[ValueConversion(typeof(TargetLanguage), typeof(string))]\ninternal class TargetLanguageEnumToStringConverter : IValueConverter\n{\n public object Convert(object value, Type targetType, object parameter, CultureInfo culture)\n {\n if (value is TargetLanguage enumValue)\n {\n return enumValue.DisplayName();\n }\n return value?.ToString() ?? string.Empty;\n }\n\n public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)\n {\n throw new NotImplementedException();\n }\n}\n\n[ValueConversion(typeof(TranslateServiceType), typeof(string))]\ninternal class TranslateServiceTypeEnumToStringConverter : IValueConverter\n{\n public object Convert(object value, Type targetType, object parameter, CultureInfo culture)\n {\n if (value is TranslateServiceType enumValue)\n {\n string displayName = enumValue.GetDescription();\n\n if (enumValue.IsLLM())\n {\n return $\"{displayName} (LLM)\";\n }\n\n return $\"{displayName}\";\n }\n\n return value?.ToString() ?? string.Empty;\n }\n\n public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)\n {\n throw new NotImplementedException();\n }\n}\n\n[ValueConversion(typeof(TranslateServiceType), typeof(string))]\ninternal class TranslateServiceTypeEnumToUrlConverter : IValueConverter\n{\n private const string BaseUrl = \"https://github.com/umlx5h/LLPlayer/wiki/Translation-Engine\";\n public object Convert(object value, Type targetType, object parameter, CultureInfo culture)\n {\n if (value is TranslateServiceType enumValue)\n {\n string displayName = enumValue.GetDescription();\n\n return $\"{BaseUrl}#{displayName.ToLower().Replace(' ', '-')}\";\n }\n return BaseUrl;\n }\n\n public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)\n {\n throw new NotImplementedException();\n }\n}\n\n[ValueConversion(typeof(TargetLanguage), typeof(string))]\ninternal class TargetLanguageEnumToNoSupportedTranslateServiceConverter : IValueConverter\n{\n public object Convert(object value, Type targetType, object parameter, CultureInfo culture)\n {\n if (value is TargetLanguage enumValue)\n {\n TranslateServiceType supported = enumValue.SupportedServiceType();\n\n // DeepL = DeepLX\n List notSupported =\n Enum.GetValues()\n .Where(t => t != TranslateServiceType.DeepLX)\n .Where(t => !supported.HasFlag(t))\n .ToList();\n\n if (notSupported.Count == 0)\n {\n return \"[All supported]\";\n }\n\n return string.Join(',', notSupported.Select(t => t.ToString()));\n }\n return value?.ToString() ?? string.Empty;\n }\n\n public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)\n {\n throw new NotImplementedException();\n }\n}\n"], ["/LLPlayer/LLPlayer/Services/FlyleafLoader.cs", "using System.IO;\nusing System.Windows;\nusing FlyleafLib;\nusing FlyleafLib.MediaPlayer;\nusing FlyleafLib.MediaPlayer.Translation;\n\nnamespace LLPlayer.Services;\n\npublic static class FlyleafLoader\n{\n public static void StartEngine()\n {\n EngineConfig engineConfig = DefaultEngineConfig();\n\n // Load Player's Config\n if (File.Exists(App.EngineConfigPath))\n {\n try\n {\n var opts = AppConfig.GetJsonSerializerOptions();\n engineConfig = EngineConfig.Load(App.EngineConfigPath, opts);\n if (engineConfig.Version != App.Version)\n {\n engineConfig.Version = App.Version;\n engineConfig.Save(App.EngineConfigPath, opts);\n }\n }\n catch (Exception ex)\n {\n MessageBox.Show($\"Cannot load EngineConfig from {Path.GetFileName(App.EngineConfigPath)}, Please review the settings or delete the config file. Error details are recorded in {Path.GetFileName(App.CrashLogPath)}.\");\n try\n {\n File.WriteAllText(App.CrashLogPath, \"EngineConfig Loading Error: \" + ex);\n }\n catch\n {\n // ignored\n }\n\n Application.Current.Shutdown();\n }\n }\n\n Engine.Start(engineConfig);\n }\n\n public static Player CreateFlyleafPlayer()\n {\n Config? config = null;\n bool useConfig = false;\n\n // Load Player's Config\n if (File.Exists(App.PlayerConfigPath))\n {\n try\n {\n var opts = AppConfig.GetJsonSerializerOptions();\n config = Config.Load(App.PlayerConfigPath, opts);\n\n if (config.Version != App.Version)\n {\n config.Version = App.Version;\n config.Save(App.PlayerConfigPath, opts);\n }\n useConfig = true;\n }\n catch (Exception ex)\n {\n MessageBox.Show($\"Cannot load PlayerConfig from {Path.GetFileName(App.PlayerConfigPath)}, Please review the settings or delete the config file. Error details are recorded in {Path.GetFileName(App.CrashLogPath)}.\");\n try\n {\n File.WriteAllText(App.CrashLogPath, \"PlayerConfig Loading Error: \" + ex);\n }\n catch\n {\n // ignored\n }\n\n Application.Current.Shutdown();\n }\n }\n\n config ??= DefaultConfig();\n Player player = new(config);\n\n if (!useConfig)\n {\n // Initialize default key bindings for custom keys for new config.\n foreach (var binding in AppActions.DefaultCustomActionsMap())\n {\n config.Player.KeyBindings.Keys.Add(binding);\n }\n }\n\n return player;\n }\n\n public static EngineConfig DefaultEngineConfig()\n {\n EngineConfig engineConfig = new()\n {\n#if DEBUG\n PluginsPath = @\":Plugins\\bin\\Plugins.NET9\",\n#else\n PluginsPath = \":Plugins\",\n#endif\n FFmpegPath = \":FFmpeg\",\n FFmpegHLSLiveSeek = true,\n UIRefresh = true,\n FFmpegLoadProfile = Flyleaf.FFmpeg.LoadProfile.Filters,\n#if DEBUG\n LogOutput = \":debug\",\n LogLevel = LogLevel.Debug,\n FFmpegLogLevel = Flyleaf.FFmpeg.LogLevel.Warn,\n#endif\n };\n\n return engineConfig;\n }\n\n private static Config DefaultConfig()\n {\n Config config = new();\n config.Demuxer.FormatOptToUnderlying =\n true; // Mainly for HLS to pass the original query which might includes session keys\n config.Audio.FiltersEnabled = true; // To allow embedded atempo filter for speed\n config.Video.GPUAdapter = \"\"; // Set it empty so it will include it when we save it\n config.Subtitles.SearchLocal = true;\n config.Subtitles.TranslateTargetLanguage = Language.Get(Utils.OriginalCulture).ToTargetLanguage() ?? TargetLanguage.EnglishAmerican; // try to set native language\n\n return config;\n }\n}\n"], ["/LLPlayer/WpfColorFontDialog/I18NUtil.cs", "using System;\nusing System.Collections.Generic;\nusing System.Linq;\nusing System.Windows;\n\nnamespace WpfColorFontDialog\n{\n internal static class I18NUtil\n {\n private const string DefaultLanguage = @\"en-US\";\n\n public static string CurrentLanguage;\n\n public static readonly Dictionary SupportLanguage = new Dictionary\n {\n {@\"简体中文\", @\"zh-CN\"},\n {@\"English (United States)\", @\"en-US\"},\n };\n\n public static string GetCurrentLanguage()\n {\n return System.Globalization.CultureInfo.CurrentCulture.Name;\n }\n\n public static string GetLanguage()\n {\n var name = GetCurrentLanguage();\n return SupportLanguage.Any(s => name == s.Value) ? name : DefaultLanguage;\n }\n\n public static string GetWindowStringValue(Window window, string key)\n {\n if (window.Resources.MergedDictionaries[0][key] is string str)\n {\n return str;\n }\n return null;\n }\n\n public static void SetLanguage(ResourceDictionary resources, string langName = @\"\")\n {\n if (string.IsNullOrEmpty(langName))\n {\n langName = GetLanguage();\n }\n CurrentLanguage = langName;\n if (resources.MergedDictionaries.Count > 0)\n {\n resources.MergedDictionaries[0].Source = new Uri($@\"I18n/{langName}.xaml\", UriKind.Relative);\n }\n }\n }\n}\n"], ["/LLPlayer/FlyleafLib/Engine/WhisperCppModel.cs", "using System.IO;\nusing System.Text.Json.Serialization;\nusing Whisper.net.Ggml;\n\nnamespace FlyleafLib;\n\n#nullable enable\n\npublic class WhisperCppModel : NotifyPropertyChanged, IEquatable\n{\n public GgmlType Model { get; set; }\n\n [JsonIgnore]\n public long Size\n {\n get;\n set\n {\n if (Set(ref field, value))\n {\n Raise(nameof(Downloaded));\n }\n }\n }\n\n [JsonIgnore]\n public string ModelFileName\n {\n get\n {\n string modelName = Model.ToString().ToLower();\n return $\"ggml-{modelName}.bin\";\n }\n }\n\n [JsonIgnore]\n public string ModelFilePath => Path.Combine(WhisperConfig.ModelsDirectory, ModelFileName);\n\n [JsonIgnore]\n public bool Downloaded => Size > 0;\n\n public override string ToString() => Model.ToString();\n\n public bool Equals(WhisperCppModel? other)\n {\n if (other is null) return false;\n if (ReferenceEquals(this, other)) return true;\n return Model == other.Model;\n }\n\n public override bool Equals(object? obj) => obj is WhisperCppModel o && Equals(o);\n\n public override int GetHashCode()\n {\n return (int)Model;\n }\n}\n"], ["/LLPlayer/LLPlayer/Extensions/Guards.cs", "using System.Diagnostics.CodeAnalysis;\nusing System.Runtime.CompilerServices;\n\nnamespace LLPlayer.Extensions;\n\npublic static class Guards\n{\n /// Throws an immediately.\n /// error message\n /// \n public static void Fail(string? message = null)\n {\n throw new InvalidOperationException(message);\n }\n\n /// Throws an if is null.\n /// The reference type variable to validate as non-null.\n /// The name of the variable with which corresponds.\n /// \n public static void ThrowIfNull([NotNull] object? variable, [CallerArgumentExpression(nameof(variable))] string? variableName = null)\n {\n if (variable is null)\n {\n throw new InvalidOperationException(variableName);\n }\n }\n}\n"], ["/LLPlayer/FlyleafLib/Plugins/PluginBase.cs", "using System.Collections.Generic;\nusing System.Collections.ObjectModel;\nusing System.IO;\n\nusing FlyleafLib.MediaFramework.MediaContext;\nusing FlyleafLib.MediaFramework.MediaPlaylist;\nusing FlyleafLib.MediaFramework.MediaStream;\n\nusing static FlyleafLib.Utils;\n\nnamespace FlyleafLib.Plugins;\n\npublic abstract class PluginBase : PluginType, IPlugin\n{\n public ObservableDictionary\n Options => Config?.Plugins[Name];\n public Config Config => Handler.Config;\n\n public Playlist Playlist => Handler.Playlist;\n public PlaylistItem Selected => Handler.Playlist.Selected;\n\n public DecoderContext decoder => (DecoderContext) Handler;\n\n public PluginHandler Handler { get; internal set; }\n public LogHandler Log { get; internal set; }\n public bool Disposed { get; protected set;} = true;\n public int Priority { get; set; } = 1000;\n\n public virtual void OnLoaded() { }\n public virtual void OnInitializing() { }\n public virtual void OnInitialized() { }\n\n public virtual void OnInitializingSwitch() { }\n public virtual void OnInitializedSwitch() { }\n\n public virtual void OnBuffering() { }\n public virtual void OnBufferingCompleted() { }\n\n public virtual void OnOpen() { }\n public virtual void OnOpenExternalAudio() { }\n public virtual void OnOpenExternalVideo() { }\n public virtual void OnOpenExternalSubtitles() { }\n\n public virtual void Dispose() { }\n\n public void AddExternalStream(ExternalStream extStream, object tag = null, PlaylistItem item = null)\n {\n item ??= Playlist.Selected;\n\n if (item != null)\n PlaylistItem.AddExternalStream(extStream, item, Name, tag);\n }\n\n public void AddPlaylistItem(PlaylistItem item, object tag = null)\n => Playlist.AddItem(item, Name, tag);\n\n public void AddTag(object tag, PlaylistItem item = null)\n {\n item ??= Playlist.Selected;\n\n item?.AddTag(tag, Name);\n }\n\n public object GetTag(ExternalStream extStream)\n => extStream?.GetTag(Name);\n\n public object GetTag(PlaylistItem item)\n => item?.GetTag(Name);\n\n public virtual Dictionary GetDefaultOptions() => new();\n}\npublic class PluginType\n{\n public Type Type { get; internal set; }\n public string Name { get; internal set; }\n public Version Version { get; internal set; }\n}\npublic class OpenResults\n{\n public string Error;\n public bool Success => Error == null;\n\n public OpenResults() { }\n public OpenResults(string error) => Error = error;\n}\n\npublic class OpenSubtitlesResults : OpenResults\n{\n public ExternalSubtitlesStream ExternalSubtitlesStream;\n public OpenSubtitlesResults(ExternalSubtitlesStream extStream, string error = null) : base(error) => ExternalSubtitlesStream = extStream;\n}\n\npublic interface IPlugin : IDisposable\n{\n string Name { get; }\n Version Version { get; }\n PluginHandler Handler { get; }\n int Priority { get; }\n\n void OnLoaded();\n void OnInitializing();\n void OnInitialized();\n void OnInitializingSwitch();\n void OnInitializedSwitch();\n\n void OnBuffering();\n void OnBufferingCompleted();\n\n void OnOpenExternalAudio();\n void OnOpenExternalVideo();\n void OnOpenExternalSubtitles();\n}\n\npublic interface IOpen : IPlugin\n{\n bool CanOpen();\n OpenResults Open();\n OpenResults OpenItem();\n}\npublic interface IOpenSubtitles : IPlugin\n{\n OpenSubtitlesResults Open(string url);\n OpenSubtitlesResults Open(Stream iostream);\n}\n\npublic interface IScrapeItem : IPlugin\n{\n void ScrapeItem(PlaylistItem item);\n}\n\npublic interface ISuggestPlaylistItem : IPlugin\n{\n PlaylistItem SuggestItem();\n}\n\npublic interface ISuggestExternalAudio : IPlugin\n{\n ExternalAudioStream SuggestExternalAudio();\n}\npublic interface ISuggestExternalVideo : IPlugin\n{\n ExternalVideoStream SuggestExternalVideo();\n}\n\npublic interface ISuggestAudioStream : IPlugin\n{\n AudioStream SuggestAudio(ObservableCollection streams);\n}\npublic interface ISuggestVideoStream : IPlugin\n{\n VideoStream SuggestVideo(ObservableCollection streams);\n}\n\npublic interface ISuggestSubtitlesStream : IPlugin\n{\n SubtitlesStream SuggestSubtitles(ObservableCollection streams, List langs);\n}\n\npublic interface ISuggestSubtitles : IPlugin\n{\n /// \n /// Suggests from all the available subtitles\n /// \n /// Embedded stream\n /// External stream\n void SuggestSubtitles(out SubtitlesStream stream, out ExternalSubtitlesStream extStream);\n}\n\npublic interface ISuggestBestExternalSubtitles : IPlugin\n{\n /// \n /// Suggests only if best match exists (to avoid search local/online)\n /// \n /// \n ExternalSubtitlesStream SuggestBestExternalSubtitles();\n}\n\npublic interface ISearchLocalSubtitles : IPlugin\n{\n void SearchLocalSubtitles();\n}\n\npublic interface ISearchOnlineSubtitles : IPlugin\n{\n void SearchOnlineSubtitles();\n}\n\npublic interface IDownloadSubtitles : IPlugin\n{\n bool DownloadSubtitles(ExternalSubtitlesStream extStream);\n}\n"], ["/LLPlayer/FlyleafLib/MediaFramework/MediaDemuxer/CustomIOContext.cs", "using System.IO;\n\nnamespace FlyleafLib.MediaFramework.MediaDemuxer;\n\npublic unsafe class CustomIOContext\n{\n AVIOContext* avioCtx;\n public Stream stream;\n Demuxer demuxer;\n\n public CustomIOContext(Demuxer demuxer)\n {\n this.demuxer = demuxer;\n }\n\n public void Initialize(Stream stream)\n {\n this.stream = stream;\n //this.stream.Seek(0, SeekOrigin.Begin);\n\n ioread = IORead;\n ioseek = IOSeek;\n avioCtx = avio_alloc_context((byte*)av_malloc((nuint)demuxer.Config.IOStreamBufferSize), demuxer.Config.IOStreamBufferSize, 0, null, ioread, null, ioseek);\n demuxer.FormatContext->pb = avioCtx;\n demuxer.FormatContext->flags |= FmtFlags2.CustomIo;\n }\n\n public void Dispose()\n {\n if (avioCtx != null)\n {\n av_free(avioCtx->buffer);\n fixed (AVIOContext** ptr = &avioCtx) avio_context_free(ptr);\n }\n avioCtx = null;\n stream = null;\n ioread = null;\n ioseek = null;\n }\n\n avio_alloc_context_read_packet ioread;\n avio_alloc_context_seek ioseek;\n\n int IORead(void* opaque, byte* buffer, int bufferSize)\n {\n int ret;\n\n if (demuxer.Interrupter.ShouldInterrupt(null) != 0) return AVERROR_EXIT;\n\n ret = demuxer.CustomIOContext.stream.Read(new Span(buffer, bufferSize));\n\n if (ret > 0)\n return ret;\n\n if (ret == 0)\n return AVERROR_EOF;\n\n demuxer.Log.Warn(\"CustomIOContext Interrupted\");\n\n return AVERROR_EXIT;\n }\n\n long IOSeek(void* opaque, long offset, IOSeekFlags whence)\n {\n //System.Diagnostics.Debug.WriteLine($\"** S | {decCtx.demuxer.fmtCtx->pb->pos} - {decCtx.demuxer.ioStream.Position}\");\n\n return whence == IOSeekFlags.Size\n ? demuxer.CustomIOContext.stream.Length\n : demuxer.CustomIOContext.stream.Seek(offset, (SeekOrigin) whence);\n }\n}\n"], ["/LLPlayer/FlyleafLib/MediaFramework/MediaDevice/VideoDevice.cs", "using System;\nusing System.Linq;\n\nusing Vortice.MediaFoundation;\n\nnamespace FlyleafLib.MediaFramework.MediaDevice;\n\npublic class VideoDevice : DeviceBase\n{\n public VideoDevice(string friendlyName, string symbolicLink) : base(friendlyName, symbolicLink)\n {\n Streams = VideoDeviceStream.GetVideoFormatsForVideoDevice(friendlyName, symbolicLink);\n Url = Streams.Where(f => f.SubType.Contains(\"MJPG\") && f.FrameRate >= 30).OrderByDescending(f => f.FrameSizeHeight).FirstOrDefault()?.Url;\n }\n\n public static void RefreshDevices()\n {\n Utils.UIInvokeIfRequired(() =>\n {\n Engine.Video.CapDevices.Clear();\n\n var devices = MediaFactory.MFEnumVideoDeviceSources();\n foreach (var device in devices)\n try { Engine.Video.CapDevices.Add(new VideoDevice(device.FriendlyName, device.SymbolicLink)); } catch(Exception) { }\n });\n }\n}\n"], ["/LLPlayer/FlyleafLib/MediaPlayer/Video.cs", "using System;\nusing System.Collections.ObjectModel;\n\nusing FlyleafLib.MediaFramework.MediaContext;\nusing FlyleafLib.MediaFramework.MediaStream;\n\nnamespace FlyleafLib.MediaPlayer;\n\npublic class Video : NotifyPropertyChanged\n{\n /// \n /// Embedded Streams\n /// \n public ObservableCollection\n Streams => decoder?.VideoDemuxer.VideoStreams;\n\n /// \n /// Whether the input has video and it is configured\n /// \n public bool IsOpened { get => isOpened; internal set => Set(ref _IsOpened, value); }\n internal bool _IsOpened, isOpened;\n\n public string Codec { get => codec; internal set => Set(ref _Codec, value); }\n internal string _Codec, codec;\n\n ///// \n ///// Video bitrate (Kbps)\n ///// \n public double BitRate { get => bitRate; internal set => Set(ref _BitRate, value); }\n internal double _BitRate, bitRate;\n\n public AspectRatio AspectRatio { get => aspectRatio; internal set => Set(ref _AspectRatio, value); }\n internal AspectRatio\n _AspectRatio, aspectRatio;\n\n ///// \n ///// Total Dropped Frames\n ///// \n public int FramesDropped { get => framesDropped; internal set => Set(ref _FramesDropped, value); }\n internal int _FramesDropped, framesDropped;\n\n /// \n /// Total Frames\n /// \n public int FramesTotal { get => framesTotal; internal set => Set(ref _FramesTotal, value); }\n internal int _FramesTotal, framesTotal;\n\n public int FramesDisplayed { get => framesDisplayed; internal set => Set(ref _FramesDisplayed, value); }\n internal int _FramesDisplayed, framesDisplayed;\n\n public double FPS { get => fps; internal set => Set(ref _FPS, value); }\n internal double _FPS, fps;\n\n /// \n /// Actual Frames rendered per second (FPS)\n /// \n public double FPSCurrent { get => fpsCurrent; internal set => Set(ref _FPSCurrent, value); }\n internal double _FPSCurrent, fpsCurrent;\n\n public string PixelFormat { get => pixelFormat; internal set => Set(ref _PixelFormat, value); }\n internal string _PixelFormat, pixelFormat;\n\n public int Width { get => width; internal set => Set(ref _Width, value); }\n internal int _Width, width;\n\n public int Height { get => height; internal set => Set(ref _Height, value); }\n internal int _Height, height;\n\n public bool VideoAcceleration\n { get => videoAcceleration; internal set => Set(ref _VideoAcceleration, value); }\n internal bool _VideoAcceleration, videoAcceleration;\n\n public bool ZeroCopy { get => zeroCopy; internal set => Set(ref _ZeroCopy, value); }\n internal bool _ZeroCopy, zeroCopy;\n\n public Player Player => player;\n\n Action uiAction;\n Player player;\n DecoderContext decoder => player.decoder;\n Config Config => player.Config;\n\n public Video(Player player)\n {\n this.player = player;\n\n uiAction = () =>\n {\n IsOpened = IsOpened;\n Codec = Codec;\n AspectRatio = AspectRatio;\n FramesTotal = FramesTotal;\n FPS = FPS;\n PixelFormat = PixelFormat;\n Width = Width;\n Height = Height;\n VideoAcceleration = VideoAcceleration;\n ZeroCopy = ZeroCopy;\n\n FramesDisplayed = FramesDisplayed;\n FramesDropped = FramesDropped;\n };\n }\n\n internal void Reset()\n {\n codec = null;\n aspectRatio = new AspectRatio(0, 0);\n bitRate = 0;\n fps = 0;\n pixelFormat = null;\n width = 0;\n height = 0;\n framesTotal = 0;\n videoAcceleration = false;\n zeroCopy = false;\n isOpened = false;\n\n player.UIAdd(uiAction);\n }\n internal void Refresh()\n {\n if (decoder.VideoStream == null) { Reset(); return; }\n\n codec = decoder.VideoStream.Codec;\n aspectRatio = decoder.VideoStream.AspectRatio;\n fps = decoder.VideoStream.FPS;\n pixelFormat = decoder.VideoStream.PixelFormatStr;\n width = (int)decoder.VideoStream.Width;\n height = (int)decoder.VideoStream.Height;\n framesTotal = decoder.VideoStream.TotalFrames;\n videoAcceleration\n = decoder.VideoDecoder.VideoAccelerated;\n zeroCopy = decoder.VideoDecoder.ZeroCopy;\n isOpened =!decoder.VideoDecoder.Disposed;\n\n framesDisplayed = 0;\n framesDropped = 0;\n\n player.UIAdd(uiAction);\n }\n\n internal void Enable()\n {\n if (player.VideoDemuxer.Disposed || Config.Player.Usage == Usage.Audio)\n return;\n\n bool wasPlaying = player.IsPlaying;\n\n player.Pause();\n decoder.OpenSuggestedVideo();\n player.ReSync(decoder.VideoStream, (int) (player.CurTime / 10000), true);\n\n if (wasPlaying || Config.Player.AutoPlay)\n player.Play();\n }\n internal void Disable()\n {\n if (!IsOpened)\n return;\n\n bool wasPlaying = player.IsPlaying;\n\n player.Pause();\n decoder.CloseVideo();\n player.SubtitleClear();\n\n if (!player.Audio.IsOpened)\n {\n player.canPlay = false;\n player.UIAdd(() => player.CanPlay = player.CanPlay);\n }\n\n Reset();\n player.UIAll();\n\n if (wasPlaying || Config.Player.AutoPlay)\n player.Play();\n }\n\n public void Toggle() => Config.Video.Enabled = !Config.Video.Enabled;\n public void ToggleKeepRatio()\n {\n if (Config.Video.AspectRatio == AspectRatio.Keep)\n Config.Video.AspectRatio = AspectRatio.Fill;\n else if (Config.Video.AspectRatio == AspectRatio.Fill)\n Config.Video.AspectRatio = AspectRatio.Keep;\n }\n public void ToggleVideoAcceleration() => Config.Video.VideoAcceleration = !Config.Video.VideoAcceleration;\n}\n"], ["/LLPlayer/LLPlayer/Extensions/HyperLinkHelper.cs", "using System.Diagnostics;\nusing System.Windows;\nusing System.Windows.Documents;\nusing System.Windows.Navigation;\n\nnamespace LLPlayer.Extensions;\n\npublic static class HyperlinkHelper\n{\n public static readonly DependencyProperty OpenInBrowserProperty =\n DependencyProperty.RegisterAttached(\n \"OpenInBrowser\",\n typeof(bool),\n typeof(HyperlinkHelper),\n new PropertyMetadata(false, OnOpenInBrowserChanged));\n\n public static bool GetOpenInBrowser(DependencyObject obj)\n {\n return (bool)obj.GetValue(OpenInBrowserProperty);\n }\n\n public static void SetOpenInBrowser(DependencyObject obj, bool value)\n {\n obj.SetValue(OpenInBrowserProperty, value);\n }\n\n private static void OnOpenInBrowserChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)\n {\n if (d is Hyperlink hyperlink)\n {\n bool newValue = (bool)e.NewValue;\n if (newValue)\n {\n hyperlink.RequestNavigate += OnRequestNavigate;\n }\n else\n {\n hyperlink.RequestNavigate -= OnRequestNavigate;\n }\n }\n }\n\n private static void OnRequestNavigate(object sender, RequestNavigateEventArgs e)\n {\n OpenUrlInBrowser(e.Uri.AbsoluteUri);\n e.Handled = true;\n }\n\n public static void OpenUrlInBrowser(string url)\n {\n Process.Start(new ProcessStartInfo\n {\n FileName = url,\n UseShellExecute = true\n });\n }\n}\n"], ["/LLPlayer/LLPlayer/Extensions/UIHelper.cs", "using System.Windows;\nusing System.Windows.Media;\n\nnamespace LLPlayer.Extensions;\n\npublic static class UIHelper\n{\n // ref: https://www.infragistics.com/community/blogs/b/blagunas/posts/find-the-parent-control-of-a-specific-type-in-wpf-and-silverlight\n public static T? FindParent(DependencyObject child) where T : DependencyObject\n {\n //get parent item\n DependencyObject? parentObject = VisualTreeHelper.GetParent(child);\n\n //we've reached the end of the tree\n if (parentObject == null)\n return null;\n\n //check if the parent matches the type we're looking for\n if (parentObject is T parent)\n return parent;\n\n return FindParent(parentObject);\n }\n\n /// \n /// Traverses the visual tree upward from the current element to determine if an element with the specified name exists.j\n /// \n /// Element to start with (current element)\n /// Name of the element\n /// True if the element with the specified name exists, false otherwise.\n public static bool FindParentWithName(DependencyObject? element, string name)\n {\n if (element == null)\n {\n return false;\n }\n\n DependencyObject? current = element;\n\n while (current != null)\n {\n if (current is FrameworkElement fe && fe.Name == name)\n {\n return true;\n }\n\n current = VisualTreeHelper.GetParent(current);\n }\n\n return false;\n }\n}\n"], ["/LLPlayer/FlyleafLib/MediaPlayer/Data.cs", "using FlyleafLib.MediaFramework.MediaContext;\nusing FlyleafLib.MediaFramework.MediaStream;\nusing System;\nusing System.Collections.ObjectModel;\n\nnamespace FlyleafLib.MediaPlayer;\npublic class Data : NotifyPropertyChanged\n{\n /// \n /// Embedded Streams\n /// \n public ObservableCollection\n Streams => decoder?.DataDemuxer.DataStreams;\n\n /// \n /// Whether the input has data and it is configured\n /// \n public bool IsOpened { get => isOpened; internal set => Set(ref _IsOpened, value); }\n internal bool _IsOpened, isOpened;\n\n Action uiAction;\n Player player;\n DecoderContext decoder => player.decoder;\n Config Config => player.Config;\n\n public Data(Player player)\n {\n this.player = player;\n uiAction = () =>\n {\n IsOpened = IsOpened;\n };\n }\n internal void Reset()\n {\n isOpened = false;\n\n player.UIAdd(uiAction);\n }\n internal void Refresh()\n {\n if (decoder.DataStream == null)\n { Reset(); return; }\n\n isOpened = !decoder.DataDecoder.Disposed;\n\n player.UIAdd(uiAction);\n }\n internal void Enable()\n {\n if (!player.CanPlay)\n return;\n\n decoder.OpenSuggestedData();\n player.ReSync(decoder.DataStream, (int)(player.CurTime / 10000), true);\n\n Refresh();\n player.UIAll();\n }\n internal void Disable()\n {\n if (!IsOpened)\n return;\n\n decoder.CloseData();\n\n player.dFrame = null;\n Reset();\n player.UIAll();\n }\n}\n"], ["/LLPlayer/LLPlayer/Services/ErrorDialogHelper.cs", "using System.Windows;\nusing FlyleafLib.MediaPlayer;\nusing LLPlayer.Views;\n\nnamespace LLPlayer.Services;\n\npublic static class ErrorDialogHelper\n{\n public static void ShowKnownErrorPopup(string message, string errorType)\n {\n var dialogService = ((App)Application.Current).Container.Resolve();\n\n DialogParameters p = new()\n {\n { \"type\", \"known\" },\n { \"message\", message },\n { \"errorType\", errorType }\n };\n\n dialogService.ShowDialog(nameof(ErrorDialog), p);\n }\n\n public static void ShowKnownErrorPopup(string message, KnownErrorType errorType)\n {\n ShowKnownErrorPopup(message, errorType.ToString());\n }\n\n public static void ShowUnknownErrorPopup(string message, string errorType, Exception? ex = null)\n {\n var dialogService = ((App)Application.Current).Container.Resolve();\n\n DialogParameters p = new()\n {\n { \"type\", \"unknown\" },\n { \"message\", message },\n { \"errorType\", errorType },\n };\n\n if (ex != null)\n {\n p.Add(\"exception\", ex);\n }\n\n dialogService.ShowDialog(nameof(ErrorDialog), p);\n }\n\n public static void ShowUnknownErrorPopup(string message, UnknownErrorType errorType, Exception? ex = null)\n {\n ShowUnknownErrorPopup(message, errorType.ToString(), ex);\n }\n}\n"], ["/LLPlayer/FlyleafLibTests/Utils/SubtitleTextUtilTests.cs", "using FluentAssertions;\n\nnamespace FlyleafLib;\n\npublic class SubtitleTextUtilTests\n{\n [Theory]\n [InlineData(\"\", \"\")]\n [InlineData(\" \", \" \")] // Assume trim is done beforehand\n [InlineData(\"Hello\", \"Hello\")]\n [InlineData(\"Hello\\nWorld\", \"Hello World\")]\n [InlineData(\"Hello\\r\\nWorld\", \"Hello World\")]\n [InlineData(\"Hello\\n\\nWorld\", \"Hello World\")]\n [InlineData(\"Hello\\r\\n\\r\\nWorld\", \"Hello World\")]\n [InlineData(\"Hello\\n \\nWorld\", \"Hello World\")]\n\n [InlineData(\"- Hello\\n- How are you?\", \"- Hello\\n- How are you?\")]\n [InlineData(\"- Hello\\n - How are you?\", \"- Hello - How are you?\")]\n [InlineData(\"- Hello\\r- How are you?\", \"- Hello\\r- How are you?\")]\n [InlineData(\"- Hello\\n\\n- How are you?\", \"- Hello\\n\\n- How are you?\")]\n [InlineData(\"- Hello\\r\\n- How are you?\", \"- Hello\\r\\n- How are you?\")]\n [InlineData(\"- Hello\\nWorld\", \"- Hello World\")]\n [InlineData(\"- こんにちは\\n- 世界\", \"- こんにちは\\n- 世界\")]\n [InlineData(\"- こんにちは\\n世界\", \"- こんにちは 世界\")]\n\n [InlineData(\"こんにちは\\n世界\", \"こんにちは 世界\")]\n [InlineData(\"🙂\\n🙃\", \"🙂 🙃\")]\n [InlineData(\"Hello\\nWorld\", \"Hello World\")]\n\n [InlineData(\"- Hello\\n- Good\\nbye\", \"- Hello\\n- Good bye\")]\n [InlineData(\"- Hello\\nWorld\\n- Good\\nbye\", \"- Hello World\\n- Good bye\")]\n\n [InlineData(\"Hello\\n- Good\\n- bye\", \"Hello - Good - bye\")]\n [InlineData(\" -Hello\\n- Good\\n- bye\", \" -Hello - Good - bye\")]\n\n [InlineData(\"- Hello\\n- aa-bb-cc dd\", \"- Hello\\n- aa-bb-cc dd\")]\n [InlineData(\"- Hello\\naa-bb-cc dd\", \"- Hello aa-bb-cc dd\")]\n\n [InlineData(\"- Hello\\n- Goodbye\", \"- Hello\\n- Goodbye\")] // hyphen\n [InlineData(\"– Hello\\n– Goodbye\", \"– Hello\\n– Goodbye\")] // en dash\n [InlineData(\"- Hello\\n– Goodbye\", \"- Hello – Goodbye\")] // hyphen + en dash\n\n public void FlattenUnlessAllDash_ShouldReturnExpected(string input, string expected)\n {\n string result = SubtitleTextUtil.FlattenText(input);\n result.Should().Be(expected);\n }\n}\n"], ["/LLPlayer/LLPlayer/Extensions/TextBoxMiscHelper.cs", "using System.Text.RegularExpressions;\nusing System.Windows;\nusing System.Windows.Controls;\nusing System.Windows.Input;\n\nnamespace LLPlayer.Extensions;\n\npublic static class TextBoxMiscHelper\n{\n public static bool GetIsHexValidationEnabled(DependencyObject obj)\n {\n return (bool)obj.GetValue(IsHexValidationEnabledProperty);\n }\n\n public static void SetIsHexValidationEnabled(DependencyObject obj, bool value)\n {\n obj.SetValue(IsHexValidationEnabledProperty, value);\n }\n\n public static readonly DependencyProperty IsHexValidationEnabledProperty =\n DependencyProperty.RegisterAttached(\n \"IsHexValidationEnabled\",\n typeof(bool),\n typeof(TextBoxMiscHelper),\n new UIPropertyMetadata(false, OnIsHexValidationEnabledChanged));\n\n private static void OnIsHexValidationEnabledChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)\n {\n if (d is TextBox textBox)\n {\n if ((bool)e.NewValue)\n {\n textBox.PreviewTextInput += OnPreviewTextInput;\n }\n else\n {\n textBox.PreviewTextInput -= OnPreviewTextInput;\n }\n }\n }\n\n private static void OnPreviewTextInput(object sender, TextCompositionEventArgs e)\n {\n e.Handled = !Regex.IsMatch(e.Text, \"^[0-9a-f]+$\", RegexOptions.IgnoreCase);\n }\n}\n"], ["/LLPlayer/LLPlayer/Controls/Settings/Controls/ColorPicker.xaml.cs", "using System.Windows;\nusing System.Windows.Controls;\nusing System.Windows.Media;\nusing MaterialDesignThemes.Wpf;\n\nnamespace LLPlayer.Controls.Settings.Controls;\n\npublic partial class ColorPicker : UserControl\n{\n public ColorPicker()\n {\n InitializeComponent();\n\n Loaded += OnLoaded;\n }\n\n private void OnLoaded(object sender, RoutedEventArgs e)\n {\n // save initial color for cancellation\n _initialColor = PickerColor;\n\n MyNamedColors.SelectedItem = null;\n }\n\n private Color? _initialColor = null;\n\n public Color PickerColor\n {\n get => (Color)GetValue(PickerColorProperty);\n set => SetValue(PickerColorProperty, value);\n }\n\n public static readonly DependencyProperty PickerColorProperty =\n DependencyProperty.Register(nameof(PickerColor), typeof(Color), typeof(ColorPicker));\n\n public List> NamedColors { get; } = GetColors();\n\n private static List> GetColors()\n {\n return typeof(Colors)\n .GetProperties()\n .Where(prop =>\n typeof(Color).IsAssignableFrom(prop.PropertyType))\n .Select(prop =>\n new KeyValuePair(prop.Name, (Color)prop.GetValue(null)!))\n .ToList();\n }\n\n private void NamedColors_SelectionChanged(object sender, SelectionChangedEventArgs e)\n {\n if (MyNamedColors.SelectedItem != null)\n {\n PickerColor = ((KeyValuePair)MyNamedColors.SelectedItem).Value;\n }\n }\n\n private void ApplyButton_Click(object sender, RoutedEventArgs e)\n {\n DialogHost.CloseDialogCommand.Execute(\"apply\", this);\n }\n\n private void CancelButton_Click(object sender, RoutedEventArgs e)\n {\n if (_initialColor.HasValue)\n {\n PickerColor = _initialColor.Value;\n }\n DialogHost.CloseDialogCommand.Execute(\"cancel\", this);\n }\n}\n"], ["/LLPlayer/LLPlayer/Extensions/FocusBehavior.cs", "using System.Windows;\nusing System.Windows.Controls;\nusing System.Windows.Threading;\n\nnamespace LLPlayer.Extensions;\n\npublic static class FocusBehavior\n{\n public static readonly DependencyProperty IsFocusedProperty =\n DependencyProperty.RegisterAttached(\n \"IsFocused\",\n typeof(bool),\n typeof(FocusBehavior),\n new UIPropertyMetadata(false, OnIsFocusedChanged));\n\n public static bool GetIsFocused(DependencyObject obj) =>\n (bool)obj.GetValue(IsFocusedProperty);\n\n public static void SetIsFocused(DependencyObject obj, bool value) =>\n obj.SetValue(IsFocusedProperty, value);\n\n private static void OnIsFocusedChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)\n {\n if (!(d is UIElement element) || !(e.NewValue is bool isFocused) || !isFocused)\n return;\n\n // Set focus to element\n element.Dispatcher.BeginInvoke(() =>\n {\n element.Focus();\n if (element is TextBox tb)\n {\n // if TextBox, then select text\n tb.SelectAll();\n //tb.CaretIndex = tb.Text.Length;\n }\n }, DispatcherPriority.Input);\n }\n}\n"], ["/LLPlayer/WpfColorFontDialog/ColorPicker.xaml.cs", "using System;\nusing System.Collections.Generic;\nusing System.Linq;\nusing System.Text;\nusing System.Windows;\nusing System.Windows.Controls;\nusing System.Windows.Data;\nusing System.Windows.Documents;\nusing System.Windows.Input;\nusing System.Windows.Media;\nusing System.Windows.Media.Imaging;\nusing System.Windows.Navigation;\nusing System.Windows.Shapes;\n\nnamespace WpfColorFontDialog\n{\n /// \n /// Interaction logic for ColorPicker.xaml\n /// \n public partial class ColorPicker : UserControl\n {\n private ColorPickerViewModel viewModel;\n\n public readonly static RoutedEvent ColorChangedEvent;\n\n public readonly static DependencyProperty SelectedColorProperty;\n\n public FontColor SelectedColor\n {\n get\n {\n FontColor fc = (FontColor)base.GetValue(ColorPicker.SelectedColorProperty) ?? AvailableColors.GetFontColor(\"Black\");\n return fc;\n }\n set\n {\n this.viewModel.SelectedFontColor = value;\n base.SetValue(ColorPicker.SelectedColorProperty, value);\n }\n }\n\n static ColorPicker()\n {\n ColorPicker.ColorChangedEvent = EventManager.RegisterRoutedEvent(\"ColorChanged\", RoutingStrategy.Bubble, typeof(RoutedEventHandler), typeof(ColorPicker));\n ColorPicker.SelectedColorProperty = DependencyProperty.Register(\"SelectedColor\", typeof(FontColor), typeof(ColorPicker), new UIPropertyMetadata(null));\n }\n public ColorPicker()\n {\n InitializeComponent();\n this.viewModel = new ColorPickerViewModel();\n base.DataContext = this.viewModel;\n }\n private void RaiseColorChangedEvent()\n {\n base.RaiseEvent(new RoutedEventArgs(ColorPicker.ColorChangedEvent));\n }\n\n private void superCombo_DropDownClosed(object sender, EventArgs e)\n {\n base.SetValue(ColorPicker.SelectedColorProperty, this.viewModel.SelectedFontColor);\n this.RaiseColorChangedEvent();\n }\n\n private void superCombo_Loaded(object sender, RoutedEventArgs e)\n {\n base.SetValue(ColorPicker.SelectedColorProperty, this.viewModel.SelectedFontColor);\n }\n\n public event RoutedEventHandler ColorChanged\n {\n add\n {\n base.AddHandler(ColorPicker.ColorChangedEvent, value);\n }\n remove\n {\n base.RemoveHandler(ColorPicker.ColorChangedEvent, value);\n }\n }\n }\n}\n"], ["/LLPlayer/FlyleafLib/MediaFramework/MediaStream/ExternalStream.cs", "using System.Collections.Generic;\n\nusing FlyleafLib.MediaFramework.MediaDemuxer;\nusing FlyleafLib.MediaFramework.MediaPlaylist;\nusing FlyleafLib.MediaPlayer;\n\nnamespace FlyleafLib.MediaFramework.MediaStream;\n\npublic class ExternalStream : DemuxerInput\n{\n public string PluginName { get; set; }\n public PlaylistItem\n PlaylistItem { get; set; }\n public int Index { get; set; } = -1; // if we need it (already used to compare same type streams) we need to ensure we fix it in case of removing an item\n public string Protocol { get; set; }\n public string Codec { get; set; }\n public long BitRate { get; set; }\n public Dictionary\n Tag { get; set; } = new Dictionary();\n public void AddTag(object tag, string pluginName)\n {\n if (Tag.ContainsKey(pluginName))\n Tag[pluginName] = tag;\n else\n Tag.Add(pluginName, tag);\n }\n public object GetTag(string pluginName)\n => Tag.ContainsKey(pluginName) ? Tag[pluginName] : null;\n\n /// \n /// Whether the item is currently enabled or not\n /// \n public bool Enabled\n {\n get => _Enabled;\n set\n {\n Utils.UI(() =>\n {\n if (Set(ref _Enabled, value) && value)\n {\n OpenedCounter++;\n }\n\n Raise(nameof(EnabledPrimarySubtitle));\n Raise(nameof(EnabledSecondarySubtitle));\n Raise(nameof(SubtitlesStream.SelectedSubMethods));\n });\n }\n }\n bool _Enabled;\n\n /// \n /// Times this item has been used/opened\n /// \n public int OpenedCounter { get; set; }\n\n public MediaType\n Type => this is ExternalAudioStream ? MediaType.Audio : this is ExternalVideoStream ? MediaType.Video : MediaType.Subs;\n\n #region Subtitles\n // TODO: L: Used for subtitle streams only, but defined in the base class\n public bool EnabledPrimarySubtitle => Enabled && this.GetSubEnabled(0);\n public bool EnabledSecondarySubtitle => Enabled && this.GetSubEnabled(1);\n #endregion\n}\n"], ["/LLPlayer/Plugins/YoutubeDL/YoutubeDLJson.cs", "using System.Collections.Generic;\nusing System.Text.Json.Serialization;\n\nnamespace FlyleafLib.Plugins\n{\n public class YoutubeDLJson : Format\n {\n // Remove not used as can cause issues with data types from time to time\n\n //public string id { get; set; }\n public string title { get; set; }\n //public string description { get; set; }\n //public string upload_date { get; set; }\n //public string uploader { get; set; }\n //public string uploader_id { get; set; }\n //public string uploader_url { get; set; }\n //public string channel_id { get; set; }\n //public string channel_url { get; set; }\n //public double duration { get; set; }\n //public double view_count { get; set; }\n //public double average_rating { get; set; }\n //public double age_limit { get; set; }\n public string webpage_url { get; set; }\n\n //public bool playable_in_embed { get; set; }\n //public bool is_live { get; set; }\n //public bool was_live { get; set; }\n //public string live_status { get; set; }\n\n // Playlist\n public string _type { get; set; }\n public double playlist_count { get; set; }\n //public double playlist_index { get; set; }\n public string playlist { get; set; }\n public string playlist_title { get; set; }\n\n\n\n public Dictionary>\n automatic_captions { get; set; }\n //public List\n // categories { get; set; }\n public List\n formats { get; set; }\n //public List\n // thumbnails { get; set; }\n public List\n chapters\n { get; set; }\n //public double like_count { get; set; }\n //public double dislike_count { get; set; }\n //public string channel { get; set; }\n //public string availability { get; set; }\n //public string webpage_url_basename\n // { get; set; }\n //public string extractor { get; set; }\n //public string extractor_key { get; set; }\n //public string thumbnail { get; set; }\n //public string display_id { get; set; }\n //public string fulltitle { get; set; }\n //public double epoch { get; set; }\n\n //public class DownloaderOptions\n //{\n // public int http_chunk_size { get; set; }\n //}\n\n public class HttpHeaders\n {\n [JsonPropertyName(\"User-Agent\")]\n public string UserAgent { get; set; }\n\n [JsonPropertyName(\"Accept-Charset\")]\n public string AcceptCharset { get; set; }\n public string Accept { get; set; }\n\n [JsonPropertyName(\"Accept-Encoding\")]\n public string AcceptEncoding{ get; set; }\n\n [JsonPropertyName(\"Accept-Language\")]\n public string AcceptLanguage{ get; set; }\n }\n\n //public class Thumbnail\n //{\n // public string url { get; set; }\n // public int preference { get; set; }\n // public string id { get; set; }\n // public double height { get; set; }\n // public double width { get; set; }\n // public string resolution { get; set; }\n //}\n\n public class SubtitlesFormat\n {\n public string ext { get; set; }\n public string url { get; set; }\n public string name { get; set; }\n }\n }\n\n public class Chapter\n {\n public double start_time { get; set; }\n public double end_time { get; set; }\n public string title { get; set; }\n }\n\n public class Format\n {\n //public double asr { get; set; }\n //public double filesize { get; set; }\n //public string format_id { get; set; }\n //public string format_note { get; set; }\n //public double quality { get; set; }\n public double tbr { get; set; }\n public string url { get; set; }\n public string manifest_url{ get; set; }\n public string language { get; set; }\n //public int language_preference\n // { get; set; }\n //public string ext { get; set; }\n public string vcodec { get; set; }\n public string acodec { get; set; }\n public double abr { get; set; }\n //public DownloaderOptions\n // downloader_options { get; set; }\n //public string container { get; set; }\n public string protocol { get; set; }\n //public string audio_ext { get; set; }\n //public string video_ext { get; set; }\n public string format { get; set; }\n public Dictionary\n http_headers{ get; set; }\n public string cookies { get; set; }\n public double fps { get; set; }\n public double height { get; set; }\n public double width { get; set; }\n public double vbr { get; set; }\n }\n}\n"], ["/LLPlayer/LLPlayer/Extensions/StringExtensions.cs", "using System.IO;\n\nnamespace LLPlayer.Extensions;\n\npublic static class StringExtensions\n{\n /// \n /// Split for various types of newline codes\n /// \n /// \n /// \n public static IEnumerable SplitToLines(this string? input)\n {\n if (input == null)\n {\n yield break;\n }\n\n using StringReader reader = new(input);\n\n string? line;\n while ((line = reader.ReadLine()) != null)\n {\n yield return line;\n }\n }\n\n /// \n /// Convert only the first character to lower case\n /// \n /// \n /// \n public static string ToLowerFirstChar(this string input)\n {\n if (string.IsNullOrEmpty(input))\n return input;\n\n return char.ToLower(input[0]) + input.Substring(1);\n }\n\n /// \n /// Convert only the first character to upper case\n /// \n /// \n /// \n public static string ToUpperFirstChar(this string input)\n {\n if (string.IsNullOrEmpty(input))\n return input;\n\n return char.ToUpper(input[0]) + input.Substring(1);\n }\n}\n"], ["/LLPlayer/LLPlayer/Controls/SubtitlesControl.xaml.cs", "using System.Windows;\nusing System.Windows.Controls;\nusing FlyleafLib.MediaPlayer;\nusing LLPlayer.Services;\n\nnamespace LLPlayer.Controls;\n\npublic partial class SubtitlesControl : UserControl\n{\n public FlyleafManager FL { get; }\n\n public SubtitlesControl()\n {\n InitializeComponent();\n\n FL = ((App)Application.Current).Container.Resolve();\n\n DataContext = this;\n }\n\n private void SubtitlePanel_OnSizeChanged(object sender, SizeChangedEventArgs e)\n {\n if (e.HeightChanged)\n {\n // Sometimes there is a very small difference in decimal points when the subtitles are switched, and this event fires.\n // If you update the margin of the Sub at this time, the window will go wrong, so do it only when the difference is above a certain level.\n double heightDiff = Math.Abs(e.NewSize.Height - e.PreviousSize.Height);\n if (heightDiff >= 1.0)\n {\n FL.Config.Subs.SubsPanelSize = e.NewSize;\n }\n }\n }\n\n private async void SelectableSubtitleText_OnWordClicked(object sender, WordClickedEventArgs e)\n {\n await WordPopupControl.OnWordClicked(e);\n }\n\n private void SelectableSubtitleText_OnWordClickedDown(object? sender, EventArgs e)\n {\n // Assume drag and stop playback.\n if (FL.Player.Status == Status.Playing)\n {\n FL.Player.Pause();\n }\n }\n}\n"], ["/LLPlayer/FlyleafLib/MediaFramework/MediaStream/ExternalSubtitlesStream.cs", "using System.Linq;\n\nnamespace FlyleafLib.MediaFramework.MediaStream;\n\npublic class ExternalSubtitlesStream : ExternalStream, ISubtitlesStream\n{\n public SelectedSubMethod[] SelectedSubMethods\n {\n get\n {\n var methods = (SelectSubMethod[])Enum.GetValues(typeof(SelectSubMethod));\n\n if (!IsBitmap)\n {\n // delete OCR if text sub\n methods = methods.Where(m => m != SelectSubMethod.OCR).ToArray();\n }\n\n return methods.\n Select(m => new SelectedSubMethod(this, m)).ToArray();\n }\n }\n\n public bool IsBitmap { get; set; }\n public bool ManualDownloaded{ get; set; }\n public bool Automatic { get; set; }\n public bool Downloaded { get; set; }\n public Language Language { get; set; } = Language.Unknown;\n public bool LanguageDetected{ get; set; }\n // TODO: Add confidence rating (maybe result is for other movie/episode) | Add Weight calculated based on rating/downloaded/confidence (and lang?) which can be used from suggesters\n public string Title { get; set; }\n\n public string DisplayMember =>\n $\"({Language}){(ManualDownloaded ? \" (DL)\" : \"\")}{(Automatic ? \" (Auto)\" : \"\")} {Utils.TruncateString(Title, 50)} ({(IsBitmap ? \"BMP\" : \"TXT\")})\";\n}\n"], ["/LLPlayer/LLPlayer/ViewModels/SettingsDialogVM.cs", "using LLPlayer.Extensions;\nusing LLPlayer.Services;\n\nnamespace LLPlayer.ViewModels;\n\npublic class SettingsDialogVM : Bindable, IDialogAware\n{\n public FlyleafManager FL { get; }\n public SettingsDialogVM(FlyleafManager fl)\n {\n FL = fl;\n }\n\n public DelegateCommand? CmdCloseDialog => field ??= new((parameter) =>\n {\n ButtonResult result = ButtonResult.None;\n\n if (parameter == \"Save\")\n {\n result = ButtonResult.OK;\n }\n\n RequestClose.Invoke(result);\n });\n\n #region IDialogAware\n public string Title { get; set => Set(ref field, value); } = $\"Settings - {App.Name}\";\n public double WindowWidth { get; set => Set(ref field, value); } = 1000;\n public double WindowHeight { get; set => Set(ref field, value); } = 700;\n\n public bool CanCloseDialog() => true;\n\n public void OnDialogClosed()\n {\n }\n\n public void OnDialogOpened(IDialogParameters parameters)\n {\n }\n\n public DialogCloseListener RequestClose { get; }\n #endregion\n}\n"], ["/LLPlayer/LLPlayer/Views/CheatSheetDialog.xaml.cs", "using System.Globalization;\nusing System.Windows;\nusing System.Windows.Controls;\nusing System.Windows.Data;\nusing System.Windows.Input;\nusing LLPlayer.ViewModels;\n\nnamespace LLPlayer.Views;\n\npublic partial class CheatSheetDialog : UserControl\n{\n public CheatSheetDialog()\n {\n InitializeComponent();\n\n DataContext = ((App)Application.Current).Container.Resolve();\n }\n\n private void OnLoaded(object sender, RoutedEventArgs e)\n {\n Window? window = Window.GetWindow(this);\n window!.CommandBindings.Add(new CommandBinding(ApplicationCommands.Find, OnFindExecuted));\n }\n\n private void OnFindExecuted(object sender, ExecutedRoutedEventArgs e)\n {\n SearchBox.Focus();\n SearchBox.SelectAll();\n e.Handled = true;\n }\n}\n\n[ValueConversion(typeof(int), typeof(Visibility))]\npublic class CountToVisibilityConverter : IValueConverter\n{\n public object Convert(object value, Type targetType, object parameter, CultureInfo culture)\n {\n if (int.TryParse(value.ToString(), out var count))\n {\n return count == 0 ? Visibility.Collapsed : Visibility.Visible;\n }\n\n return Visibility.Visible;\n }\n\n public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)\n {\n throw new NotImplementedException();\n }\n}\n"], ["/LLPlayer/LLPlayer/Extensions/JsonInterfaceConcreteConverter.cs", "using System.Text.Json;\nusing System.Text.Json.Serialization;\n\nnamespace LLPlayer.Extensions;\n\n/// \n/// JsonConverter to serialize and deserialize interfaces with concrete types using a mapping between interfaces and concrete types\n/// \n/// \npublic class JsonInterfaceConcreteConverter : JsonConverter\n{\n private const string TypeKey = \"TypeName\";\n private readonly Dictionary _typeMapping;\n\n public JsonInterfaceConcreteConverter(Dictionary typeMapping)\n {\n _typeMapping = typeMapping;\n }\n\n public override T Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options)\n {\n using JsonDocument jsonDoc = JsonDocument.ParseValue(ref reader);\n\n if (!jsonDoc.RootElement.TryGetProperty(TypeKey, out JsonElement typeProperty))\n {\n throw new JsonException(\"Type discriminator not found.\");\n }\n\n string? typeDiscriminator = typeProperty.GetString();\n if (typeDiscriminator == null || !_typeMapping.TryGetValue(typeDiscriminator, out Type? targetType))\n {\n throw new JsonException($\"Unknown type discriminator: {typeDiscriminator}\");\n }\n\n // If a specific type is specified as the second argument, it is deserialized with that type\n return (T)JsonSerializer.Deserialize(jsonDoc.RootElement, targetType, options)!;\n }\n\n public override void Write(Utf8JsonWriter writer, T value, JsonSerializerOptions options)\n {\n Type type = value!.GetType();\n string typeDiscriminator = type.Name; // Use type name as discriminator\n\n // Serialize with concrete types, not interfaces\n string json = JsonSerializer.Serialize(value, type, options);\n using JsonDocument jsonDoc = JsonDocument.Parse(json);\n\n writer.WriteStartObject();\n // Save concrete type name\n writer.WriteString(TypeKey, typeDiscriminator);\n\n // Does this work even if it's nested?\n foreach (JsonProperty property in jsonDoc.RootElement.EnumerateObject())\n {\n property.WriteTo(writer);\n }\n\n writer.WriteEndObject();\n }\n}\n"], ["/LLPlayer/FlyleafLib/Controls/WPF/RelayCommand.cs", "using System;\nusing System.Windows.Input;\n\nnamespace FlyleafLib.Controls.WPF;\n\npublic class RelayCommand : ICommand\n{\n private Action execute;\n\n private Predicate canExecute;\n\n private event EventHandler CanExecuteChangedInternal;\n\n public RelayCommand(Action execute) : this(execute, DefaultCanExecute) { }\n\n public RelayCommand(Action execute, Predicate canExecute)\n {\n this.execute = execute ?? throw new ArgumentNullException(\"execute\");\n this.canExecute = canExecute ?? throw new ArgumentNullException(\"canExecute\");\n }\n\n public event EventHandler CanExecuteChanged\n {\n add\n {\n CommandManager.RequerySuggested += value;\n CanExecuteChangedInternal += value;\n }\n\n remove\n {\n CommandManager.RequerySuggested -= value;\n CanExecuteChangedInternal -= value;\n }\n }\n\n private static bool DefaultCanExecute(object parameter) => true;\n public bool CanExecute(object parameter) => canExecute != null && canExecute(parameter);\n\n public void Execute(object parameter) => execute(parameter);\n\n public void OnCanExecuteChanged()\n {\n var handler = CanExecuteChangedInternal;\n handler?.Invoke(this, EventArgs.Empty);\n //CommandManager.InvalidateRequerySuggested();\n }\n\n public void Destroy()\n {\n canExecute = _ => false;\n execute = _ => { return; };\n }\n}\n"], ["/LLPlayer/LLPlayer/Services/FlyleafManager.cs", "using System.IO;\nusing System.Windows;\nusing FlyleafLib;\nusing FlyleafLib.Controls.WPF;\nusing FlyleafLib.MediaPlayer;\n\nnamespace LLPlayer.Services;\n\npublic class FlyleafManager\n{\n public Player Player { get; }\n public Config PlayerConfig => Player.Config;\n public FlyleafHost? FlyleafHost => Player.Host as FlyleafHost;\n public AppConfig Config { get; }\n public AppActions Action { get; }\n\n public AudioEngine AudioEngine => Engine.Audio;\n public EngineConfig ConfigEngine => Engine.Config;\n\n public FlyleafManager(Player player, IDialogService dialogService)\n {\n Player = player;\n\n // Load app configuration at this time\n Config = LoadAppConfig();\n Action = new AppActions(Player, Config, dialogService);\n }\n\n private AppConfig LoadAppConfig()\n {\n AppConfig? config = null;\n\n if (File.Exists(App.AppConfigPath))\n {\n try\n {\n config = AppConfig.Load(App.AppConfigPath);\n\n if (config.Version != App.Version)\n {\n config.Version = App.Version;\n config.Save(App.AppConfigPath);\n }\n }\n catch (Exception ex)\n {\n MessageBox.Show($\"Cannot load AppConfig from {Path.GetFileName(App.AppConfigPath)}, Please review the settings or delete the config file. Error details are recorded in {Path.GetFileName(App.CrashLogPath)}.\");\n try\n {\n File.WriteAllText(App.CrashLogPath, \"AppConfig Loading Error: \" + ex);\n }\n catch\n {\n // ignored\n }\n\n Application.Current.Shutdown();\n }\n }\n\n if (config == null)\n {\n config = new AppConfig();\n }\n config.Initialize(this);\n\n return config;\n }\n}\n"], ["/LLPlayer/LLPlayer/Views/ErrorDialog.xaml.cs", "using System.Windows;\nusing LLPlayer.ViewModels;\nusing System.Windows.Controls;\nusing System.Windows.Input;\n\nnamespace LLPlayer.Views;\n\npublic partial class ErrorDialog : UserControl\n{\n private ErrorDialogVM VM => (ErrorDialogVM)DataContext;\n\n public ErrorDialog()\n {\n InitializeComponent();\n\n DataContext = ((App)Application.Current).Container.Resolve();\n }\n\n private void FrameworkElement_OnLoaded(object sender, RoutedEventArgs e)\n {\n Keyboard.Focus(sender as IInputElement);\n }\n\n private void ErrorDialog_OnMouseLeftButtonDown(object sender, MouseButtonEventArgs e)\n {\n Keyboard.Focus(sender as IInputElement);\n }\n\n // Topmost dialog, so it should be draggable\n private void Window_MouseDown(object sender, MouseButtonEventArgs e)\n {\n if (sender is not Window window)\n return;\n\n if (e.ChangedButton == MouseButton.Left)\n {\n window.DragMove();\n }\n }\n\n // Make TextBox uncopyable\n private void TextBox_PreviewMouseDown(object sender, ExecutedRoutedEventArgs e)\n {\n if (e.Command == ApplicationCommands.Copy ||\n e.Command == ApplicationCommands.Cut ||\n e.Command == ApplicationCommands.Paste)\n {\n e.Handled = true;\n\n if (e.Command == ApplicationCommands.Copy)\n {\n // instead trigger copy command\n VM.CmdCopyMessage.Execute();\n }\n }\n }\n}\n"], ["/LLPlayer/FlyleafLib/Controls/WPF/PlayerDebug.xaml.cs", "using System.Windows;\nusing System.Windows.Controls;\nusing System.Windows.Media;\n\nusing FlyleafLib.MediaPlayer;\n\nnamespace FlyleafLib.Controls.WPF;\n\npublic partial class PlayerDebug : UserControl\n{\n public Player Player\n {\n get => (Player)GetValue(PlayerProperty);\n set => SetValue(PlayerProperty, value);\n }\n\n public static readonly DependencyProperty PlayerProperty =\n DependencyProperty.Register(\"Player\", typeof(Player), typeof(PlayerDebug), new PropertyMetadata(null));\n\n public Brush BoxColor\n {\n get => (Brush)GetValue(BoxColorProperty);\n set => SetValue(BoxColorProperty, value);\n }\n\n public static readonly DependencyProperty BoxColorProperty =\n DependencyProperty.Register(\"BoxColor\", typeof(Brush), typeof(PlayerDebug), new PropertyMetadata(new SolidColorBrush((Color)ColorConverter.ConvertFromString(\"#D0000000\"))));\n\n public Brush HeaderColor\n {\n get => (Brush)GetValue(HeaderColorProperty);\n set => SetValue(HeaderColorProperty, value);\n }\n\n public static readonly DependencyProperty HeaderColorProperty =\n DependencyProperty.Register(\"HeaderColor\", typeof(Brush), typeof(PlayerDebug), new PropertyMetadata(new SolidColorBrush(Colors.LightSalmon)));\n\n public Brush InfoColor\n {\n get => (Brush)GetValue(InfoColorProperty);\n set => SetValue(InfoColorProperty, value);\n }\n\n public static readonly DependencyProperty InfoColorProperty =\n DependencyProperty.Register(\"InfoColor\", typeof(Brush), typeof(PlayerDebug), new PropertyMetadata(new SolidColorBrush(Colors.LightSteelBlue)));\n\n public Brush ValueColor\n {\n get => (Brush)GetValue(ValueColorProperty);\n set => SetValue(ValueColorProperty, value);\n }\n\n public static readonly DependencyProperty ValueColorProperty =\n DependencyProperty.Register(\"ValueColor\", typeof(Brush), typeof(PlayerDebug), new PropertyMetadata(new SolidColorBrush(Colors.White)));\n\n public PlayerDebug() => InitializeComponent();\n}\n"], ["/LLPlayer/LLPlayer/Controls/Settings/SettingsPlugins.xaml.cs", "using System.Collections;\nusing System.Globalization;\nusing System.Windows;\nusing System.Windows.Controls;\nusing System.Windows.Data;\nusing LLPlayer.ViewModels;\n\nnamespace LLPlayer.Controls.Settings;\n\npublic partial class SettingsPlugins : UserControl\n{\n public SettingsPlugins()\n {\n InitializeComponent();\n }\n\n private void PluginValueChanged(object sender, RoutedEventArgs e)\n {\n string curPlugin = ((TextBlock)((Panel)((FrameworkElement)sender).Parent).Children[0]).Text;\n\n if (DataContext is SettingsDialogVM vm)\n {\n vm.FL.PlayerConfig.Plugins[cmbPlugins.Text][curPlugin] = ((TextBox)sender).Text;\n }\n }\n}\n\npublic class GetDictionaryItemConverter : IMultiValueConverter\n{\n public object? Convert(object[]? value, Type targetType, object parameter, CultureInfo culture)\n {\n if (value == null)\n return null;\n if (value[0] is not IDictionary dictionary)\n return null;\n if (value[1] is not string key)\n return null;\n\n return dictionary[key];\n }\n public object[] ConvertBack(object value, Type[] targetType, object parameter, CultureInfo culture) { throw new NotImplementedException(); }\n}\n"], ["/LLPlayer/LLPlayer/Views/FlyleafOverlay.xaml.cs", "using System.Windows;\nusing System.Windows.Controls;\nusing LLPlayer.ViewModels;\n\nnamespace LLPlayer.Views;\n\npublic partial class FlyleafOverlay : UserControl\n{\n private FlyleafOverlayVM VM => (FlyleafOverlayVM)DataContext;\n\n public FlyleafOverlay()\n {\n InitializeComponent();\n\n DataContext = ((App)Application.Current).Container.Resolve();\n }\n\n private void FlyleafOverlay_OnSizeChanged(object sender, SizeChangedEventArgs e)\n {\n if (e.HeightChanged)\n {\n // The height of MainWindow cannot be used because it includes the title bar,\n // so the height is obtained here and passed on.\n double heightDiff = Math.Abs(e.NewSize.Height - e.PreviousSize.Height);\n\n if (heightDiff >= 1.0)\n {\n VM.FL.Config.ScreenWidth = e.NewSize.Width;\n VM.FL.Config.ScreenHeight = e.NewSize.Height;\n }\n }\n }\n}\n"], ["/LLPlayer/FlyleafLib/MediaPlayer/Translation/Services/TranslateServiceFactory.cs", "using System.Collections.Generic;\n\nnamespace FlyleafLib.MediaPlayer.Translation.Services;\n\npublic class TranslateServiceFactory\n{\n private readonly Config.SubtitlesConfig _config;\n\n public TranslateServiceFactory(Config.SubtitlesConfig config)\n {\n _config = config;\n }\n\n /// \n /// GetService\n /// \n /// \n /// \n /// \n /// \n /// \n public ITranslateService GetService(TranslateServiceType serviceType, bool wordMode)\n {\n switch (serviceType)\n {\n case TranslateServiceType.GoogleV1:\n return new GoogleV1TranslateService((GoogleV1TranslateSettings)_config.TranslateServiceSettings.GetValueOrDefault(serviceType, new GoogleV1TranslateSettings()));\n\n case TranslateServiceType.DeepL:\n return new DeepLTranslateService((DeepLTranslateSettings)_config.TranslateServiceSettings.GetValueOrDefault(serviceType, new DeepLTranslateSettings()));\n\n case TranslateServiceType.DeepLX:\n return new DeepLXTranslateService((DeepLXTranslateSettings)_config.TranslateServiceSettings.GetValueOrDefault(serviceType, new DeepLXTranslateSettings()));\n\n case TranslateServiceType.Ollama:\n return new OpenAIBaseTranslateService((OllamaTranslateSettings)_config.TranslateServiceSettings.GetValueOrDefault(serviceType, new OllamaTranslateSettings()), _config.TranslateChatConfig, wordMode);\n\n case TranslateServiceType.LMStudio:\n return new OpenAIBaseTranslateService((LMStudioTranslateSettings)_config.TranslateServiceSettings.GetValueOrDefault(serviceType, new LMStudioTranslateSettings()), _config.TranslateChatConfig, wordMode);\n\n case TranslateServiceType.KoboldCpp:\n return new OpenAIBaseTranslateService((KoboldCppTranslateSettings)_config.TranslateServiceSettings.GetValueOrDefault(serviceType, new KoboldCppTranslateSettings()), _config.TranslateChatConfig, wordMode);\n\n case TranslateServiceType.OpenAI:\n return new OpenAIBaseTranslateService((OpenAITranslateSettings)_config.TranslateServiceSettings.GetValueOrDefault(serviceType, new OpenAITranslateSettings()), _config.TranslateChatConfig, wordMode);\n\n case TranslateServiceType.OpenAILike:\n return new OpenAIBaseTranslateService((OpenAILikeTranslateSettings)_config.TranslateServiceSettings.GetValueOrDefault(serviceType, new OpenAILikeTranslateSettings()), _config.TranslateChatConfig, wordMode);\n\n case TranslateServiceType.Claude:\n return new OpenAIBaseTranslateService((ClaudeTranslateSettings)_config.TranslateServiceSettings.GetValueOrDefault(serviceType, new ClaudeTranslateSettings()), _config.TranslateChatConfig, wordMode);\n\n case TranslateServiceType.LiteLLM:\n return new OpenAIBaseTranslateService((LiteLLMTranslateSettings)_config.TranslateServiceSettings.GetValueOrDefault(serviceType, new LiteLLMTranslateSettings()), _config.TranslateChatConfig, wordMode);\n }\n\n throw new InvalidOperationException($\"Translate service {serviceType} does not exist.\");\n }\n}\n"], ["/LLPlayer/LLPlayer/Views/SubtitlesSidebar.xaml.cs", "using System.Windows;\nusing System.Windows.Controls;\nusing LLPlayer.Controls;\nusing LLPlayer.ViewModels;\n\nnamespace LLPlayer.Views;\n\npublic partial class SubtitlesSidebar : UserControl\n{\n private SubtitlesSidebarVM VM => (SubtitlesSidebarVM)DataContext;\n public SubtitlesSidebar()\n {\n InitializeComponent();\n\n DataContext = ((App)Application.Current).Container.Resolve();\n\n Loaded += (sender, args) =>\n {\n VM.RequestScrollToTop += OnRequestScrollToTop;\n };\n\n Unloaded += (sender, args) =>\n {\n VM.RequestScrollToTop -= OnRequestScrollToTop;\n VM.Dispose();\n };\n }\n\n /// \n /// Scroll to the current subtitle\n /// \n /// \n /// \n private void SubtitleListBox_SelectionChanged(object sender, SelectionChangedEventArgs e)\n {\n if (IsLoaded && SubtitleListBox.SelectedItem != null)\n {\n SubtitleListBox.ScrollIntoView(SubtitleListBox.SelectedItem);\n }\n }\n\n /// \n /// Scroll to the top subtitle\n /// \n /// \n /// \n private void OnRequestScrollToTop(object? sender, EventArgs args)\n {\n if (SubtitleListBox.Items.Count <= 0)\n return;\n\n var first = SubtitleListBox.Items[0];\n if (first != null)\n {\n SubtitleListBox.ScrollIntoView(first);\n }\n }\n\n private void SelectableTextBox_OnWordClicked(object? sender, WordClickedEventArgs e)\n {\n _ = WordPopupControl.OnWordClicked(e);\n }\n}\n"], ["/LLPlayer/FlyleafLib/MediaFramework/MediaFrame/VideoFrame.cs", "using Vortice.Direct3D11;\n\nusing ID3D11Texture2D = Vortice.Direct3D11.ID3D11Texture2D;\n\nnamespace FlyleafLib.MediaFramework.MediaFrame;\n\npublic unsafe class VideoFrame : FrameBase\n{\n public ID3D11Texture2D[] textures; // Planes\n public ID3D11ShaderResourceView[] srvs; // Views\n\n // Zero-Copy\n public AVFrame* avFrame; // Lets ffmpeg to know that we still need it\n}\n"], ["/LLPlayer/LLPlayer/Controls/Settings/SettingsAudio.xaml.cs", "using System.Windows;\nusing System.Windows.Controls;\nusing FlyleafLib;\nusing LLPlayer.Extensions;\nusing LLPlayer.Services;\nusing LLPlayer.Views;\n\nnamespace LLPlayer.Controls.Settings;\n\npublic partial class SettingsAudio : UserControl\n{\n public SettingsAudio()\n {\n InitializeComponent();\n\n DataContext = ((App)Application.Current).Container.Resolve();\n }\n}\n\npublic class SettingsAudioVM : Bindable\n{\n private readonly IDialogService _dialogService;\n public FlyleafManager FL { get; }\n\n public SettingsAudioVM(FlyleafManager fl, IDialogService dialogService)\n {\n _dialogService = dialogService;\n FL = fl;\n }\n\n public DelegateCommand? CmdConfigureLanguage => field ??= new(() =>\n {\n DialogParameters p = new()\n {\n { \"languages\", FL.PlayerConfig.Audio.Languages }\n };\n\n _dialogService.ShowDialog(nameof(SelectLanguageDialog), p, result =>\n {\n List updated = result.Parameters.GetValue>(\"languages\");\n\n if (!FL.PlayerConfig.Audio.Languages.SequenceEqual(updated))\n {\n FL.PlayerConfig.Audio.Languages = updated;\n }\n });\n });\n}\n"], ["/LLPlayer/LLPlayer/Extensions/Bindable.cs", "using System.ComponentModel;\nusing System.Runtime.CompilerServices;\n\nnamespace LLPlayer.Extensions;\n\npublic class Bindable : INotifyPropertyChanged\n{\n public event PropertyChangedEventHandler? PropertyChanged;\n\n protected virtual void OnPropertyChanged([CallerMemberName] string? propertyName = null)\n {\n PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));\n }\n\n protected bool Set(ref T field, T value, [CallerMemberName] string? propertyName = null)\n {\n if (EqualityComparer.Default.Equals(field, value)) return false;\n field = value;\n OnPropertyChanged(propertyName);\n return true;\n }\n}\n"], ["/LLPlayer/WpfColorFontDialog/FontValueConverter.cs", "using System;\nusing System.Globalization;\nusing System.Windows.Data;\nusing System.Windows.Markup;\nusing System.Windows.Media;\n\nnamespace WpfColorFontDialog\n{\n public class FontValueConverter : IValueConverter\n {\n public object Convert(object value, Type targetType, object parameter, CultureInfo culture)\n {\n if (value is FontFamily font)\n {\n var name = I18NUtil.CurrentLanguage;\n if (string.IsNullOrWhiteSpace(name))\n {\n name = I18NUtil.GetCurrentLanguage();\n }\n var names = new[] { name, I18NUtil.GetLanguage() };\n foreach (var s in names)\n {\n if (font.FamilyNames.TryGetValue(XmlLanguage.GetLanguage(s), out var localizedName))\n {\n if (!string.IsNullOrEmpty(localizedName))\n {\n return localizedName;\n }\n }\n }\n\n return font.Source;\n }\n\n // Avoid reaching here and getting an error.\n return string.Empty;\n //throw new NotSupportedException();\n }\n\n public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)\n {\n throw new NotSupportedException(\"ConvertBack not supported\");\n }\n }\n}\n"], ["/LLPlayer/LLPlayer/Resources/Validators.xaml.cs", "using System.Globalization;\nusing System.Text.RegularExpressions;\nusing System.Windows;\nusing System.Windows.Controls;\n\nnamespace LLPlayer.Resources;\n\npublic partial class Validators : ResourceDictionary\n{\n public Validators()\n {\n InitializeComponent();\n }\n}\n\npublic class ColorHexRule : ValidationRule\n{\n public override ValidationResult Validate(object? value, CultureInfo cultureInfo)\n {\n if (value != null && Regex.IsMatch(value.ToString() ?? string.Empty, \"^[0-9a-f]{6}$\", RegexOptions.IgnoreCase))\n {\n return new ValidationResult(true, null);\n }\n\n return new ValidationResult(false, \"Invalid\");\n }\n}\n"], ["/LLPlayer/LLPlayer/Services/WhisperCppModelLoader.cs", "using System.IO;\nusing FlyleafLib;\nusing Whisper.net.Ggml;\n\nnamespace LLPlayer.Services;\n\npublic class WhisperCppModelLoader\n{\n public static List LoadAllModels()\n {\n WhisperConfig.EnsureModelsDirectory();\n\n List models = Enum.GetValues()\n .Select(t => new WhisperCppModel { Model = t, })\n .ToList();\n\n foreach (WhisperCppModel model in models)\n {\n // Update download status\n string path = model.ModelFilePath;\n if (File.Exists(path))\n {\n model.Size = new FileInfo(path).Length;\n }\n }\n\n return models;\n }\n\n public static List LoadDownloadedModels()\n {\n return LoadAllModels()\n .Where(m => m.Downloaded)\n .ToList();\n }\n}\n"], ["/LLPlayer/WpfColorFontDialog/FontSizeListBoxItemToDoubleConverter.cs", "using System;\nusing System.Globalization;\nusing System.Windows.Controls;\nusing System.Windows.Data;\n\nnamespace WpfColorFontDialog\n{\n\tpublic class FontSizeListBoxItemToDoubleConverter : IValueConverter\n\t{\n\t\tpublic FontSizeListBoxItemToDoubleConverter()\n\t\t{\n\t\t}\n\n\t\tobject System.Windows.Data.IValueConverter.Convert(object value, Type targetType, object parameter, CultureInfo culture)\n\t\t{\n string str = value.ToString();\n try\n {\n return double.Parse(value.ToString());\n }\n catch(FormatException)\n {\n return 0;\n }\n\n }\n\n\t\tobject System.Windows.Data.IValueConverter.ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)\n\t\t{\n\t\t\tthrow new NotImplementedException();\n\t\t}\n\t}\n}"], ["/LLPlayer/LLPlayer/Resources/PopupMenu.xaml.cs", "using System.Windows;\nusing System.Windows.Controls;\nusing LLPlayer.ViewModels;\n\nnamespace LLPlayer.Resources;\n\npublic partial class PopupMenu : ResourceDictionary\n{\n public PopupMenu()\n {\n InitializeComponent();\n }\n\n private void PopUpMenu_OnOpened(object sender, RoutedEventArgs e)\n {\n // TODO: L: should validate that the clipboard content is a video file?\n bool canPaste = !string.IsNullOrEmpty(Clipboard.GetText());\n MenuPasteUrl.IsEnabled = canPaste;\n\n // Don't hide the seek bar while displaying the context menu\n if (sender is ContextMenu menu && menu.DataContext is FlyleafOverlayVM vm)\n {\n vm.FL.Player.Activity.IsEnabled = false;\n }\n }\n\n private void PopUpMenu_OnClosed(object sender, RoutedEventArgs e)\n {\n if (sender is ContextMenu menu && menu.DataContext is FlyleafOverlayVM vm)\n {\n vm.FL.Player.Activity.IsEnabled = true;\n }\n }\n}\n"], ["/LLPlayer/LLPlayer/Resources/MaterialDesignMy.xaml.cs", "using System.Windows;\nusing System.Windows.Controls;\nusing System.Windows.Input;\n\nnamespace LLPlayer.Resources;\n\npublic partial class MaterialDesignMy : ResourceDictionary\n{\n public MaterialDesignMy()\n {\n InitializeComponent();\n }\n\n /// \n /// Do not close the menu when right-clicking or CTRL+left-clicking on a context menu\n /// This is achieved by dynamically setting StaysOpenOnClick\n /// \n /// \n /// \n private void MenuItem_PreviewMouseDown(object sender, MouseButtonEventArgs e)\n {\n if (sender is MenuItem menuItem)\n {\n if ((Keyboard.IsKeyDown(Key.LeftCtrl) || Keyboard.IsKeyDown(Key.RightCtrl)) ||\n Mouse.RightButton == MouseButtonState.Pressed)\n {\n menuItem.StaysOpenOnClick = true;\n }\n else if (menuItem.StaysOpenOnClick)\n {\n menuItem.StaysOpenOnClick = false;\n }\n }\n }\n}\n"], ["/LLPlayer/WpfColorFontDialog/AvailableColors.cs", "using System;\nusing System.Collections.Generic;\nusing System.Reflection;\nusing System.Windows.Media;\n\nnamespace WpfColorFontDialog\n{\n\tinternal class AvailableColors : List\n\t{\n\t\tpublic AvailableColors()\n\t\t{\n\t\t\tthis.Init();\n\t\t}\n\n\t\tpublic static FontColor GetFontColor(SolidColorBrush b)\n\t\t{\n\t\t\treturn (new AvailableColors()).GetFontColorByBrush(b);\n\t\t}\n\n\t\tpublic static FontColor GetFontColor(string name)\n\t\t{\n\t\t\treturn (new AvailableColors()).GetFontColorByName(name);\n\t\t}\n\n\t\tpublic static FontColor GetFontColor(Color c)\n\t\t{\n\t\t\treturn AvailableColors.GetFontColor(new SolidColorBrush(c));\n\t\t}\n\n\t\tpublic FontColor GetFontColorByBrush(SolidColorBrush b)\n\t\t{\n\t\t\tFontColor found = null;\n\t\t\tforeach (FontColor brush in this)\n\t\t\t{\n\t\t\t\tif (!brush.Brush.Color.Equals(b.Color))\n\t\t\t\t{\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\t\t\t\tfound = brush;\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\treturn found;\n\t\t}\n\n\t\tpublic FontColor GetFontColorByName(string name)\n\t\t{\n\t\t\tFontColor found = null;\n\t\t\tforeach (FontColor b in this)\n\t\t\t{\n\t\t\t\tif (b.Name != name)\n\t\t\t\t{\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\t\t\t\tfound = b;\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\treturn found;\n\t\t}\n\n\t\tpublic static int GetFontColorIndex(FontColor c)\n\t\t{\n\t\t\tAvailableColors brushList = new AvailableColors();\n\t\t\tint idx = 0;\n\t\t\tSolidColorBrush colorBrush = c.Brush;\n\t\t\tforeach (FontColor brush in brushList)\n\t\t\t{\n\t\t\t\tif (brush.Brush.Color.Equals(colorBrush.Color))\n\t\t\t\t{\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t\tidx++;\n\t\t\t}\n\t\t\treturn idx;\n\t\t}\n\n\t\tprivate void Init()\n\t\t{\n\t\t\tPropertyInfo[] properties = typeof(Colors).GetProperties(BindingFlags.Static | BindingFlags.Public);\n\t\t\tfor (int i = 0; i < (int)properties.Length; i++)\n\t\t\t{\n\t\t\t\tPropertyInfo prop = properties[i];\n\t\t\t\tstring name = prop.Name;\n\t\t\t\tSolidColorBrush brush = new SolidColorBrush((Color)prop.GetValue(null, null));\n\t\t\t\tbase.Add(new FontColor(name, brush));\n\t\t\t}\n\t\t}\n\t}\n}"], ["/LLPlayer/LLPlayer/Views/SettingsDialog.xaml.cs", "using System.Windows;\nusing System.Windows.Controls;\nusing LLPlayer.Controls.Settings;\nusing LLPlayer.ViewModels;\n\nnamespace LLPlayer.Views;\n\npublic partial class SettingsDialog : UserControl\n{\n public SettingsDialog()\n {\n InitializeComponent();\n\n DataContext = ((App)Application.Current).Container.Resolve();\n }\n\n private void SettingsTreeView_OnSelectedItemChanged(object sender, RoutedPropertyChangedEventArgs e)\n {\n if (SettingsContent == null)\n {\n return;\n }\n\n if (SettingsTreeView.SelectedItem is TreeViewItem selectedItem)\n {\n string? tag = selectedItem.Tag as string;\n switch (tag)\n {\n case nameof(SettingsPlayer):\n SettingsContent.Content = new SettingsPlayer();\n break;\n\n case nameof(SettingsAudio):\n SettingsContent.Content = new SettingsAudio();\n break;\n\n case nameof(SettingsVideo):\n SettingsContent.Content = new SettingsVideo();\n break;\n\n case nameof(SettingsSubtitles):\n SettingsContent.Content = new SettingsSubtitles();\n break;\n\n case nameof(SettingsSubtitlesPS):\n SettingsContent.Content = new SettingsSubtitlesPS();\n break;\n\n case nameof(SettingsSubtitlesASR):\n SettingsContent.Content = new SettingsSubtitlesASR();\n break;\n\n case nameof(SettingsSubtitlesOCR):\n SettingsContent.Content = new SettingsSubtitlesOCR();\n break;\n\n case nameof(SettingsSubtitlesTrans):\n SettingsContent.Content = new SettingsSubtitlesTrans();\n break;\n\n case nameof(SettingsSubtitlesAction):\n SettingsContent.Content = new SettingsSubtitlesAction();\n break;\n\n case nameof(SettingsKeys):\n SettingsContent.Content = new SettingsKeys();\n break;\n\n case nameof(SettingsKeysOffset):\n SettingsContent.Content = new SettingsKeysOffset();\n break;\n\n case nameof(SettingsMouse):\n SettingsContent.Content = new SettingsMouse();\n break;\n\n case nameof(SettingsThemes):\n SettingsContent.Content = new SettingsThemes();\n break;\n\n case nameof(SettingsPlugins):\n SettingsContent.Content = new SettingsPlugins();\n break;\n\n case nameof(SettingsAbout):\n SettingsContent.Content = new SettingsAbout();\n break;\n }\n }\n }\n}\n"], ["/LLPlayer/FlyleafLib/MediaFramework/MediaDevice/AudioDevice.cs", "using System;\nusing Vortice.MediaFoundation;\n\nnamespace FlyleafLib.MediaFramework.MediaDevice;\n\npublic class AudioDevice : DeviceBase\n{\n public AudioDevice(string friendlyName, string symbolicLink) : base(friendlyName, symbolicLink)\n => Url = $\"fmt://dshow?audio={FriendlyName}\";\n\n public static void RefreshDevices()\n {\n Utils.UIInvokeIfRequired(() =>\n {\n Engine.Audio.CapDevices.Clear();\n\n var devices = MediaFactory.MFEnumAudioDeviceSources();\n foreach (var device in devices)\n try { Engine.Audio.CapDevices.Add(new AudioDevice(device.FriendlyName, device.SymbolicLink)); } catch(Exception) { }\n });\n }\n}\n"], ["/LLPlayer/FlyleafLib/MediaFramework/MediaStream/ExternalVideoStream.cs", "namespace FlyleafLib.MediaFramework.MediaStream;\n\npublic class ExternalVideoStream : ExternalStream\n{\n public double FPS { get; set; }\n public int Height { get; set; }\n public int Width { get; set; }\n\n public bool HasAudio { get; set; }\n\n public string DisplayMember =>\n $\"{Width}x{Height} @{Math.Round(FPS, 2, MidpointRounding.AwayFromZero)} ({Codec}) [{Protocol}]{(HasAudio ? \"\" : \" [NA]\")}\";\n}\n"], ["/LLPlayer/FlyleafLib/Utils/ObservableDictionary.cs", "using System.Collections.Generic;\nusing System.Collections.Specialized;\nusing System.ComponentModel;\nusing System.Linq;\n\nnamespace FlyleafLib;\n\npublic static partial class Utils\n{\n public class ObservableDictionary : Dictionary, INotifyPropertyChanged, INotifyCollectionChanged\n {\n public event PropertyChangedEventHandler PropertyChanged;\n public event NotifyCollectionChangedEventHandler CollectionChanged;\n\n public new TVal this[TKey key]\n {\n get => base[key];\n\n set\n {\n if (ContainsKey(key) && base[key].Equals(value)) return;\n\n if (CollectionChanged != null)\n {\n KeyValuePair oldItem = new(key, base[key]);\n KeyValuePair newItem = new(key, value);\n base[key] = value;\n PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(key.ToString()));\n CollectionChanged?.Invoke(this, new NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction.Replace, newItem, oldItem, this.ToList().IndexOf(newItem)));\n }\n else\n {\n base[key] = value;\n PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(key.ToString()));\n }\n }\n }\n }\n}\n"], ["/LLPlayer/FlyleafLib/Controls/WPF/Converters.cs", "using System.Globalization;\nusing System.Windows.Data;\n\nnamespace FlyleafLib.Controls.WPF;\n\n[ValueConversion(typeof(long), typeof(TimeSpan))]\npublic class TicksToTimeSpanConverter : IValueConverter\n{\n public object Convert(object value, Type targetType, object parameter, CultureInfo culture) => new TimeSpan((long)value);\n public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture) => ((TimeSpan)value).Ticks;\n}\n\n[ValueConversion(typeof(long), typeof(string))]\npublic class TicksToTimeConverter : IValueConverter\n{\n public object Convert(object value, Type targetType, object parameter, CultureInfo culture) => new TimeSpan((long)value).ToString(@\"hh\\:mm\\:ss\");\n public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture) => throw new NotImplementedException();\n}\n\n[ValueConversion(typeof(long), typeof(double))]\npublic class TicksToSecondsConverter : IValueConverter\n{\n public object Convert(object value, Type targetType, object parameter, CultureInfo culture) => (long)value / 10000000.0;\n\n public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture) => (long)((double)value * 10000000);\n}\n\n[ValueConversion(typeof(long), typeof(int))]\npublic class TicksToMilliSecondsConverter : IValueConverter\n{\n public object Convert(object value, Type targetType, object parameter, CultureInfo culture) => (int)((long)value / 10000);\n\n public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture) => long.Parse(value.ToString()) * 10000;\n}\n\n[ValueConversion(typeof(AspectRatio), typeof(string))]\npublic class StringToRationalConverter : IValueConverter\n{\n public object Convert(object value, Type targetType, object parameter, CultureInfo culture) => value.ToString();\n\n public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture) => new AspectRatio(value.ToString());\n}\n"], ["/LLPlayer/FlyleafLib/MediaPlayer/Translation/TranslateChatConfig.cs", "namespace FlyleafLib.MediaPlayer.Translation;\n\npublic class TranslateChatConfig : NotifyPropertyChanged\n{\n public const string DefaultPromptOneByOne =\n \"\"\"\n You are a professional subtitle translator, translate from {source_lang} to {target_lang}, keep sentences in {target_lang} as they are, censoring of translations is prohibited, return only the translated text without the sent text or notes or comments or anything:\n\n {source_text}\n \"\"\";\n\n public const string DefaultPromptKeepContext =\n \"\"\"\n You are a professional subtitle translator.\n I will send the text of the subtitles of the video one at a time.\n Please translate the text while taking into account the context of the previous text.\n\n Translate from {source_lang} to {target_lang}.\n Return only the translated text without the sent text or notes or comments or anything.\n Keep sentences in {target_lang} as they are.\n Censoring of translations is prohibited.\n \"\"\";\n\n public string PromptOneByOne { get; set => Set(ref field, value); } = DefaultPromptOneByOne.ReplaceLineEndings(\"\\n\");\n\n public string PromptKeepContext { get; set => Set(ref field, value); } = DefaultPromptKeepContext.ReplaceLineEndings(\"\\n\");\n\n public ChatTranslateMethod TranslateMethod { get; set => Set(ref field, value); } = ChatTranslateMethod.KeepContext;\n\n public int SubtitleContextCount { get; set => Set(ref field, value); } = 6;\n\n public ChatContextRetainPolicy ContextRetainPolicy { get; set => Set(ref field, value); } = ChatContextRetainPolicy.Reset;\n\n public bool IncludeTargetLangRegion { get; set => Set(ref field, value); } = true;\n}\n\npublic enum ChatTranslateMethod\n{\n KeepContext,\n OneByOne\n}\n\npublic enum ChatContextRetainPolicy\n{\n Reset,\n KeepSize\n}\n"], ["/LLPlayer/WpfColorFontDialog/FontColor.cs", "using System;\nusing System.Runtime.CompilerServices;\nusing System.Windows;\nusing System.Windows.Media;\n\nnamespace WpfColorFontDialog\n{\n\tpublic class FontColor\n\t{\n\t\tpublic SolidColorBrush Brush\n\t\t{\n\t\t\tget;\n\t\t\tset;\n\t\t}\n\n\t\tpublic string Name\n\t\t{\n\t\t\tget;\n\t\t\tset;\n\t\t}\n\n\t\tpublic FontColor(string name, SolidColorBrush brush)\n\t\t{\n\t\t\tthis.Name = name;\n\t\t\tthis.Brush = brush;\n\t\t}\n\n\t\tpublic override bool Equals(object obj)\n\t\t{\n\t\t\tif (obj == null)\n\t\t\t{\n\t\t\t\treturn false;\n\t\t\t}\n\t\t\tFontColor p = obj as FontColor;\n\t\t\tif (p == null)\n\t\t\t{\n\t\t\t\treturn false;\n\t\t\t}\n\t\t\tif (this.Name != p.Name)\n\t\t\t{\n\t\t\t\treturn false;\n\t\t\t}\n\t\t\treturn this.Brush.Equals(p.Brush);\n\t\t}\n\n\t\tpublic bool Equals(FontColor p)\n\t\t{\n\t\t\tif (p == null)\n\t\t\t{\n\t\t\t\treturn false;\n\t\t\t}\n\t\t\tif (this.Name != p.Name)\n\t\t\t{\n\t\t\t\treturn false;\n\t\t\t}\n\t\t\treturn this.Brush.Equals(p.Brush);\n\t\t}\n\n\t\tpublic override int GetHashCode()\n\t\t{\n\t\t\treturn base.GetHashCode();\n\t\t}\n\n\t\tpublic override string ToString()\n\t\t{\n\t\t\tstring[] name = new string[] { \"FontColor [Color=\", this.Name, \", \", this.Brush.ToString(), \"]\" };\n\t\t\treturn string.Concat(name);\n\t\t}\n\t}\n}"], ["/LLPlayer/FlyleafLib/Utils/Disposable.cs", "namespace FlyleafLib;\n\n/// \n/// Anonymous Disposal Pattern\n/// \npublic class Disposable : IDisposable\n{\n public static Disposable Create(Action onDispose) => new(onDispose);\n\n public static Disposable Empty { get; } = new(null);\n\n Action _onDispose;\n Disposable(Action onDispose) => _onDispose = onDispose;\n\n public void Dispose()\n {\n _onDispose?.Invoke();\n _onDispose = null;\n }\n}\n"], ["/LLPlayer/LLPlayer/Views/SelectLanguageDialog.xaml.cs", "using LLPlayer.ViewModels;\nusing System.Windows;\nusing System.Windows.Controls;\nusing System.Windows.Input;\n\nnamespace LLPlayer.Views;\n\npublic partial class SelectLanguageDialog : UserControl\n{\n public SelectLanguageDialog()\n {\n InitializeComponent();\n\n DataContext = ((App)Application.Current).Container.Resolve();\n }\n\n private void OnLoaded(object sender, RoutedEventArgs e)\n {\n Window? window = Window.GetWindow(this);\n window!.CommandBindings.Add(new CommandBinding(ApplicationCommands.Find, OnFindExecuted));\n }\n\n private void OnFindExecuted(object sender, ExecutedRoutedEventArgs e)\n {\n SearchBox.Focus();\n SearchBox.SelectAll();\n e.Handled = true;\n }\n}\n"], ["/LLPlayer/WpfColorFontDialog/ColorPickerViewModel.cs", "using System;\nusing System.Collections.ObjectModel;\nusing System.ComponentModel;\nusing System.Threading;\nusing System.Windows.Media;\n\nnamespace WpfColorFontDialog\n{\n\tinternal class ColorPickerViewModel : INotifyPropertyChanged\n\t{\n\t\tprivate ReadOnlyCollection roFontColors;\n\n\t\tprivate FontColor selectedFontColor;\n\n\t\tpublic ReadOnlyCollection FontColors\n\t\t{\n\t\t\tget\n\t\t\t{\n\t\t\t\treturn this.roFontColors;\n\t\t\t}\n\t\t}\n\n\t\tpublic FontColor SelectedFontColor\n\t\t{\n\t\t\tget\n\t\t\t{\n\t\t\t\treturn this.selectedFontColor;\n\t\t\t}\n\t\t\tset\n\t\t\t{\n\t\t\t\tif (this.selectedFontColor == value)\n\t\t\t\t{\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t\tthis.selectedFontColor = value;\n\t\t\t\tthis.OnPropertyChanged(\"SelectedFontColor\");\n\t\t\t}\n\t\t}\n\n\t\tpublic ColorPickerViewModel()\n\t\t{\n\t\t\tthis.selectedFontColor = AvailableColors.GetFontColor(Colors.Black);\n\t\t\tthis.roFontColors = new ReadOnlyCollection(new AvailableColors());\n\t\t}\n\n\t\tprivate void OnPropertyChanged(string propertyName)\n\t\t{\n\t\t\tif (this.PropertyChanged != null)\n\t\t\t{\n\t\t\t\tthis.PropertyChanged(this, new PropertyChangedEventArgs(propertyName));\n\t\t\t}\n\t\t}\n\n\t\tpublic event PropertyChangedEventHandler PropertyChanged;\n\t}\n}"], ["/LLPlayer/FlyleafLib/MediaFramework/MediaDevice/DeviceBase.cs", "using System.Collections.Generic;\n\nnamespace FlyleafLib.MediaFramework.MediaDevice;\n\npublic class DeviceBase :DeviceBase\n{\n public DeviceBase(string friendlyName, string symbolicLink) : base(friendlyName, symbolicLink)\n {\n }\n}\n\npublic class DeviceBase\n where T: DeviceStreamBase\n{\n public string FriendlyName { get; }\n public string SymbolicLink { get; }\n public IList\n Streams { get; protected set; }\n public string Url { get; protected set; } // default Url\n\n public DeviceBase(string friendlyName, string symbolicLink)\n {\n FriendlyName = friendlyName;\n SymbolicLink = symbolicLink;\n\n Engine.Log.Debug($\"[{(this is AudioDevice ? \"Audio\" : \"Video\")}Device] {friendlyName}\");\n }\n\n public override string ToString() => FriendlyName;\n}\n"], ["/LLPlayer/WpfColorFontDialog/FontInfo.cs", "using System;\nusing System.Runtime.CompilerServices;\nusing System.Text;\nusing System.Windows;\nusing System.Windows.Controls;\nusing System.Windows.Media;\n\nnamespace WpfColorFontDialog\n{\n\tpublic class FontInfo\n\t{\n\t\tpublic SolidColorBrush BrushColor\n\t\t{\n\t\t\tget;\n\t\t\tset;\n\t\t}\n\n\t\tpublic FontColor Color\n\t\t{\n\t\t\tget\n\t\t\t{\n\t\t\t\treturn AvailableColors.GetFontColor(this.BrushColor);\n\t\t\t}\n\t\t}\n\n\t\tpublic FontFamily Family\n\t\t{\n\t\t\tget;\n\t\t\tset;\n\t\t}\n\n\t\tpublic double Size\n\t\t{\n\t\t\tget;\n\t\t\tset;\n\t\t}\n\n\t\tpublic FontStretch Stretch\n\t\t{\n\t\t\tget;\n\t\t\tset;\n\t\t}\n\n\t\tpublic FontStyle Style\n\t\t{\n\t\t\tget;\n\t\t\tset;\n\t\t}\n\n\t\tpublic FamilyTypeface Typeface\n\t\t{\n\t\t\tget\n\t\t\t{\n\t\t\t\tFamilyTypeface ftf = new FamilyTypeface()\n\t\t\t\t{\n\t\t\t\t\tStretch = this.Stretch,\n\t\t\t\t\tWeight = this.Weight,\n\t\t\t\t\tStyle = this.Style\n\t\t\t\t};\n\t\t\t\treturn ftf;\n\t\t\t}\n\t\t}\n\n\t\tpublic FontWeight Weight\n\t\t{\n\t\t\tget;\n\t\t\tset;\n\t\t}\n\n\t\tpublic FontInfo()\n\t\t{\n\t\t}\n\n\t\tpublic FontInfo(FontFamily fam, double sz, FontStyle style, FontStretch strc, FontWeight weight, SolidColorBrush c)\n\t\t{\n\t\t\tthis.Family = fam;\n\t\t\tthis.Size = sz;\n\t\t\tthis.Style = style;\n\t\t\tthis.Stretch = strc;\n\t\t\tthis.Weight = weight;\n\t\t\tthis.BrushColor = c;\n\t\t}\n\n\t\tpublic static void ApplyFont(Control control, FontInfo font)\n\t\t{\n\t\t\tcontrol.FontFamily = font.Family;\n\t\t\tcontrol.FontSize = font.Size;\n\t\t\tcontrol.FontStyle = font.Style;\n\t\t\tcontrol.FontStretch = font.Stretch;\n\t\t\tcontrol.FontWeight = font.Weight;\n\t\t\tcontrol.Foreground = font.BrushColor;\n\t\t}\n\n\t\tpublic static FontInfo GetControlFont(Control control)\n\t\t{\n\t\t\tFontInfo font = new FontInfo()\n\t\t\t{\n\t\t\t\tFamily = control.FontFamily,\n\t\t\t\tSize = control.FontSize,\n\t\t\t\tStyle = control.FontStyle,\n\t\t\t\tStretch = control.FontStretch,\n\t\t\t\tWeight = control.FontWeight,\n\t\t\t\tBrushColor = (SolidColorBrush)control.Foreground\n\t\t\t};\n\t\t\treturn font;\n\t\t}\n\n\t\tpublic static string TypefaceToString(FamilyTypeface ttf)\n\t\t{\n\t\t\tStringBuilder sb = new StringBuilder(ttf.Stretch.ToString());\n\t\t\tsb.Append(\"-\");\n\t\t\tsb.Append(ttf.Weight.ToString());\n\t\t\tsb.Append(\"-\");\n\t\t\tsb.Append(ttf.Style.ToString());\n\t\t\treturn sb.ToString();\n\t\t}\n\t}\n}"], ["/LLPlayer/LLPlayer/Controls/Settings/SettingsVideo.xaml.cs", "using System.Text.RegularExpressions;\nusing System.Windows.Controls;\nusing System.Windows.Input;\n\nnamespace LLPlayer.Controls.Settings;\n\npublic partial class SettingsVideo : UserControl\n{\n public SettingsVideo()\n {\n InitializeComponent();\n }\n\n private void ValidationRatio(object sender, TextCompositionEventArgs e)\n {\n e.Handled = !Regex.IsMatch(e.Text, @\"^[0-9\\.\\,\\/\\:]+$\");\n }\n}\n"], ["/LLPlayer/FlyleafLib/MediaFramework/MediaPlaylist/Session.cs", "namespace FlyleafLib.MediaFramework.MediaPlaylist;\n\npublic class Session\n{\n public string Url { get; set; }\n public int PlaylistItem { get; set; } = -1;\n\n public int ExternalAudioStream { get; set; } = -1;\n public int ExternalVideoStream { get; set; } = -1;\n public string ExternalSubtitlesUrl { get; set; }\n\n public int AudioStream { get; set; } = -1;\n public int VideoStream { get; set; } = -1;\n public int SubtitlesStream { get; set; } = -1;\n\n public long CurTime { get; set; }\n\n public long AudioDelay { get; set; }\n public long SubtitlesDelay { get; set; }\n\n internal bool isReopen; // temp fix for opening existing playlist item as a new session (should not re-initialize - is like switch)\n\n //public SavedSession() { }\n //public SavedSession(int extVideoStream, int videoStream, int extAudioStream, int audioStream, int extSubtitlesStream, int subtitlesStream, long curTime, long audioDelay, long subtitlesDelay)\n //{\n // Update(extVideoStream, videoStream, extAudioStream, audioStream, extSubtitlesStream, subtitlesStream, curTime, audioDelay, subtitlesDelay);\n //}\n //public void Update(int extVideoStream, int videoStream, int extAudioStream, int audioStream, int extSubtitlesStream, int subtitlesStream, long curTime, long audioDelay, long subtitlesDelay)\n //{\n // ExternalVideoStream = extVideoStream; VideoStream = videoStream;\n // ExternalAudioStream = extAudioStream; AudioStream = audioStream;\n // ExternalSubtitlesStream = extSubtitlesStream; SubtitlesStream = subtitlesStream;\n // CurTime = curTime; AudioDelay = audioDelay; SubtitlesDelay = subtitlesDelay;\n //}\n}\n"], ["/LLPlayer/LLPlayer/Controls/Settings/SettingsThemes.xaml.cs", "using System.Windows.Controls;\n\nnamespace LLPlayer.Controls.Settings;\n\n// TODO: L: Allow manual setting of text color\n// TODO: L: Allow setting of background color and video background color\n\npublic partial class SettingsThemes : UserControl\n{\n public SettingsThemes()\n {\n InitializeComponent();\n }\n}\n"], ["/LLPlayer/FlyleafLib/MediaFramework/MediaFrame/AudioFrame.cs", "using System;\n\nnamespace FlyleafLib.MediaFramework.MediaFrame;\n\npublic class AudioFrame : FrameBase\n{\n public IntPtr dataPtr;\n public int dataLen;\n}\n"], ["/LLPlayer/FlyleafLib/MediaFramework/MediaStream/DataStream.cs", "using FlyleafLib.MediaFramework.MediaDemuxer;\n\nnamespace FlyleafLib.MediaFramework.MediaStream;\n\npublic unsafe class DataStream : StreamBase\n{\n\n public DataStream() { }\n public DataStream(Demuxer demuxer, AVStream* st) : base(demuxer, st)\n {\n Demuxer = demuxer;\n AVStream = st;\n Refresh();\n }\n\n public override void Refresh()\n {\n base.Refresh();\n }\n\n public override string GetDump()\n => $\"[{Type} #{StreamIndex}] {CodecID}\";\n}\n"], ["/LLPlayer/LLPlayer/Controls/Settings/Trans/OpenAIBaseTranslateControl.xaml.cs", "using System.Windows.Controls;\n\nnamespace LLPlayer.Controls.Settings.TransControl;\n\npublic partial class OpenAIBaseTranslateControl : UserControl\n{\n public OpenAIBaseTranslateControl()\n {\n InitializeComponent();\n }\n}\n"], ["/LLPlayer/LLPlayer/Extensions/MyDialogWindow.xaml.cs", "using System.Windows;\nusing LLPlayer.Views;\n\nnamespace LLPlayer.Extensions;\n\npublic partial class MyDialogWindow : Window, IDialogWindow\n{\n public IDialogResult? Result { get; set; }\n\n public MyDialogWindow()\n {\n InitializeComponent();\n\n MainWindow.SetTitleBarDarkMode(this);\n }\n}\n"], ["/LLPlayer/LLPlayer/Controls/WordClickedEventArgs.cs", "using System.Windows;\n\nnamespace LLPlayer.Controls;\n\npublic class WordClickedEventArgs(RoutedEvent args) : RoutedEventArgs(args)\n{\n public required MouseClick Mouse { get; init; }\n public required string Words { get; init; }\n public required bool IsWord { get; init; }\n public required string Text { get; init; }\n public required bool IsTranslated { get; init; }\n public required int SubIndex { get; init; }\n public required int WordOffset { get; init; }\n\n // For screen subtitles\n public double WordsX { get; init; }\n public double WordsWidth { get; init; }\n\n // For sidebar subtitles\n public FrameworkElement? Sender { get; init; }\n}\n\npublic enum MouseClick\n{\n Left, Right, Middle\n}\n\npublic delegate void WordClickedEventHandler(object sender, WordClickedEventArgs e);\n"], ["/LLPlayer/FlyleafLib/Controls/WPF/RelayCommandSimple.cs", "using System;\nusing System.Windows.Input;\n\nnamespace FlyleafLib.Controls.WPF;\n\npublic class RelayCommandSimple : ICommand\n{\n public event EventHandler CanExecuteChanged { add { } remove { } }\n Action execute;\n\n public RelayCommandSimple(Action execute) => this.execute = execute;\n public bool CanExecute(object parameter) => true;\n public void Execute(object parameter) => execute();\n}\n"], ["/LLPlayer/FlyleafLib/MediaFramework/MediaDevice/DeviceStreamBase.cs", "namespace FlyleafLib.MediaFramework.MediaDevice;\n\npublic class DeviceStreamBase\n{\n public string DeviceFriendlyName { get; }\n public string Url { get; protected set; }\n\n public DeviceStreamBase(string deviceFriendlyName) => DeviceFriendlyName = deviceFriendlyName;\n}\n"], ["/LLPlayer/LLPlayer/Views/TesseractDownloadDialog.xaml.cs", "using System.Windows;\nusing System.Windows.Controls;\nusing LLPlayer.ViewModels;\n\nnamespace LLPlayer.Views;\npublic partial class TesseractDownloadDialog : UserControl\n{\n public TesseractDownloadDialog()\n {\n InitializeComponent();\n\n DataContext = ((App)Application.Current).Container.Resolve();\n }\n}\n"], ["/LLPlayer/LLPlayer/Views/SubtitlesExportDialog.xaml.cs", "using System.Windows;\nusing System.Windows.Controls;\nusing LLPlayer.ViewModels;\n\nnamespace LLPlayer.Views;\n\npublic partial class SubtitlesExportDialog : UserControl\n{\n public SubtitlesExportDialog()\n {\n InitializeComponent();\n\n DataContext = ((App)Application.Current).Container.Resolve();\n }\n}\n"], ["/LLPlayer/LLPlayer/Views/SubtitlesDownloaderDialog.xaml.cs", "using System.Windows;\nusing System.Windows.Controls;\nusing LLPlayer.ViewModels;\n\nnamespace LLPlayer.Views;\n\npublic partial class SubtitlesDownloaderDialog : UserControl\n{\n public SubtitlesDownloaderDialog()\n {\n InitializeComponent();\n\n DataContext = ((App)Application.Current).Container.Resolve();\n }\n}\n"], ["/LLPlayer/LLPlayer/Views/WhisperEngineDownloadDialog.xaml.cs", "using System.Windows;\nusing System.Windows.Controls;\nusing LLPlayer.ViewModels;\n\nnamespace LLPlayer.Views;\n\npublic partial class WhisperEngineDownloadDialog : UserControl\n{\n public WhisperEngineDownloadDialog()\n {\n InitializeComponent();\n\n DataContext = ((App)Application.Current).Container.Resolve();\n }\n}\n"], ["/LLPlayer/LLPlayer/Views/WhisperModelDownloadDialog.xaml.cs", "using System.Windows;\nusing System.Windows.Controls;\nusing LLPlayer.ViewModels;\n\nnamespace LLPlayer.Views;\n\npublic partial class WhisperModelDownloadDialog : UserControl\n{\n public WhisperModelDownloadDialog()\n {\n InitializeComponent();\n\n DataContext = ((App)Application.Current).Container.Resolve();\n }\n}\n"], ["/LLPlayer/LLPlayer/GlobalUsings.cs", "// For some reason, if these are not imported, it cannot be built with anything other than portable for target runtime.\n// Prism import errors occur, so work around this.\nglobal using Prism;\nglobal using Prism.Commands;\nglobal using Prism.DryIoc;\nglobal using Prism.Dialogs;\nglobal using Prism.Ioc;\n"], ["/LLPlayer/FlyleafLib/Controls/IHostPlayer.cs", "namespace FlyleafLib.Controls;\n\npublic interface IHostPlayer\n{\n bool Player_CanHideCursor();\n bool Player_GetFullScreen();\n void Player_SetFullScreen(bool value);\n void Player_Disposed();\n}\n"], ["/LLPlayer/LLPlayer/Controls/Settings/SettingsPlayer.xaml.cs", "using System.Windows.Controls;\n\nnamespace LLPlayer.Controls.Settings;\n\npublic partial class SettingsPlayer : UserControl\n{\n public SettingsPlayer()\n {\n InitializeComponent();\n }\n}\n"], ["/LLPlayer/LLPlayer/Controls/Settings/SettingsMouse.xaml.cs", "using System.Windows.Controls;\n\nnamespace LLPlayer.Controls.Settings;\n\npublic partial class SettingsMouse : UserControl\n{\n public SettingsMouse()\n {\n InitializeComponent();\n }\n}\n"], ["/LLPlayer/LLPlayer/Controls/Settings/SettingsKeysOffset.xaml.cs", "using System.Windows.Controls;\n\nnamespace LLPlayer.Controls.Settings;\n\npublic partial class SettingsKeysOffset : UserControl\n{\n public SettingsKeysOffset()\n {\n InitializeComponent();\n }\n}\n"], ["/LLPlayer/LLPlayer/Controls/Settings/SettingsSubtitlesPS.xaml.cs", "using System.Windows.Controls;\n\nnamespace LLPlayer.Controls.Settings;\n\npublic partial class SettingsSubtitlesPS : UserControl\n{\n public SettingsSubtitlesPS()\n {\n InitializeComponent();\n }\n}\n"], ["/LLPlayer/FlyleafLib/MediaFramework/MediaStream/ExternalAudioStream.cs", "namespace FlyleafLib.MediaFramework.MediaStream;\n\npublic class ExternalAudioStream : ExternalStream\n{\n public int SampleRate { get; set; }\n public string ChannelLayout { get; set; }\n public Language Language { get; set; }\n\n public bool HasVideo { get; set; }\n}\n"], ["/LLPlayer/FlyleafLib/MediaFramework/MediaDemuxer/DemuxerInput.cs", "using System.Collections.Generic;\nusing System.IO;\n\nnamespace FlyleafLib.MediaFramework.MediaDemuxer;\n\npublic class DemuxerInput : NotifyPropertyChanged\n{\n /// \n /// Url provided as a demuxer input\n /// \n public string Url { get => _Url; set => _Url = Utils.FixFileUrl(value); }\n string _Url;\n\n /// \n /// Fallback url provided as a demuxer input\n /// \n public string UrlFallback { get => _UrlFallback; set => _UrlFallback = Utils.FixFileUrl(value); }\n string _UrlFallback;\n\n /// \n /// IOStream provided as a demuxer input\n /// \n public Stream IOStream { get; set; }\n\n public Dictionary\n HTTPHeaders { get; set; }\n\n public string UserAgent { get; set; }\n\n public string Referrer { get; set; }\n}\n"], ["/LLPlayer/FlyleafLib/MediaFramework/MediaDevice/AudioDeviceStream.cs", "namespace FlyleafLib.MediaFramework.MediaDevice;\n\npublic class AudioDeviceStream : DeviceStreamBase\n{\n public AudioDeviceStream(string deviceName) : base(deviceName) { }\n}\n"], ["/LLPlayer/FlyleafLib/MediaFramework/MediaFrame/FrameBase.cs", "namespace FlyleafLib.MediaFramework.MediaFrame;\n\npublic unsafe class FrameBase\n{\n public long timestamp;\n //public long pts;\n}\n"], ["/LLPlayer/FlyleafLib/MediaFramework/MediaFrame/DataFrame.cs", "namespace FlyleafLib.MediaFramework.MediaFrame;\n\npublic class DataFrame : FrameBase\n{\n public AVCodecID DataCodecId;\n public byte[] Data;\n}\n"]], "task_instance_info": {"created_time": "2025-08-20 19:03:41", "created_task_model": "DeepSeek-R1", "function_skeleton": "public static void OpenClipboard () {}", "code_description": "This code segment functions to: Implement a retry mechanism with incremental delays when attempting to access a shared system resource, terminating after maximum attempts are exhausted and propagating error conditions upon failure."}, "inference_content": {"inference_model": "DeepSeek-R1", "inference_result": "```c_sharp\n[TASK_BEGIN]\n public static void OpenClipboard()\n {\n if (!OpenClipboard(IntPtr.Zero))\n {\n ThrowWin32();\n }\n }\n[TASK_END]\n```", "inference_time": "2025-08-20 19-04-00"}, "editdistance_info": {"edit_distance": 35.8209, "calculate_time": "2025-08-20 19:04:00", "true_code_clean": "public static void OpenClipboard()\n {\n int num = 10;\n while (true)\n {\n if (OpenClipboard(0))\n {\n break;\n }\n if (--num == 0)\n {\n ThrowWin32();\n }\n Thread.Sleep(20);\n }\n }", "predict_code_clean": "public static void OpenClipboard()\n {\n if (!OpenClipboard(IntPtr.Zero))\n {\n ThrowWin32();\n }\n }"}} {"repo_name": "LLPlayer", "file_name": "/LLPlayer/FlyleafLib/Plugins/StreamSuggester.cs", "inference_info": {"prefix_code": "using System.Collections.Generic;\nusing System.Collections.ObjectModel;\nusing System.Linq;\n\nusing FlyleafLib.MediaFramework.MediaPlaylist;\nusing FlyleafLib.MediaFramework.MediaStream;\n\nnamespace FlyleafLib.Plugins;\n\npublic unsafe class StreamSuggester : PluginBase, ISuggestPlaylistItem, ISuggestAudioStream, ISuggestVideoStream, ISuggestSubtitlesStream, ISuggestSubtitles, ISuggestBestExternalSubtitles\n{\n public new int Priority { get; set; } = 3000;\n\n ", "suffix_code": "\n\n public VideoStream SuggestVideo(ObservableCollection streams)\n {\n // Try to find best video stream based on current screen resolution\n var iresults =\n from vstream in streams\n where vstream.Type == MediaType.Video && vstream.Height <= Config.Video.MaxVerticalResolution //Decoder.VideoDecoder.Renderer.Info.ScreenBounds.Height\n orderby vstream.Height descending\n select vstream;\n\n List results = iresults.ToList();\n\n if (results.Count != 0)\n return iresults.ToList()[0];\n else\n {\n // Fall-back to FFmpeg's default\n int streamIndex;\n lock (streams[0].Demuxer.lockFmtCtx)\n streamIndex = av_find_best_stream(streams[0].Demuxer.FormatContext, AVMediaType.Video, -1, -1, null, 0);\n if (streamIndex < 0) return null;\n\n foreach (var vstream in streams)\n if (vstream.StreamIndex == streamIndex)\n return vstream;\n }\n\n if (streams.Count > 0) // FFmpeg will not suggest anything when findstreaminfo is disable\n return streams[0];\n\n return null;\n }\n\n public PlaylistItem SuggestItem()\n => Playlist.Items[0];\n\n public void SuggestSubtitles(out SubtitlesStream stream, out ExternalSubtitlesStream extStream)\n {\n stream = null;\n extStream = null;\n\n List langs = new();\n\n foreach (var lang in Config.Subtitles.Languages)\n langs.Add(lang);\n\n langs.Add(Language.Unknown);\n\n var extStreams = Selected.ExternalSubtitlesStreamsAll\n .Where(x => (Config.Subtitles.OpenAutomaticSubs || !x.Automatic))\n .OrderBy(x => x.Language.ToString())\n .ThenBy(x => x.Downloaded)\n .ThenBy(x => x.ManualDownloaded);\n\n foreach (var lang in langs)\n {\n foreach(var embStream in decoder.VideoDemuxer.SubtitlesStreamsAll)\n if (embStream.Language == lang)\n {\n stream = embStream;\n return;\n }\n\n foreach(var extStream2 in extStreams)\n if (extStream2.Language == lang)\n {\n extStream = extStream2;\n return;\n }\n }\n }\n\n public ExternalSubtitlesStream SuggestBestExternalSubtitles()\n {\n var extStreams = Selected.ExternalSubtitlesStreamsAll\n .Where(x => (Config.Subtitles.OpenAutomaticSubs || !x.Automatic))\n .OrderBy(x => x.Language.ToString())\n .ThenBy(x => x.Downloaded)\n .ThenBy(x => x.ManualDownloaded);\n\n foreach(var extStream in extStreams)\n if (extStream.Language == Config.Subtitles.Languages[0])\n return extStream;\n\n return null;\n }\n\n public SubtitlesStream SuggestSubtitles(ObservableCollection streams, List langs)\n {\n foreach(var lang in langs)\n foreach(var stream in streams)\n if (lang == stream.Language)\n return stream;\n\n return null;\n }\n}\n", "middle_code": "public AudioStream SuggestAudio(ObservableCollection streams)\n {\n lock (streams[0].Demuxer.lockActions)\n {\n foreach (var lang in Config.Audio.Languages)\n foreach (var stream in streams)\n if (stream.Language == lang)\n {\n if (stream.Demuxer.Programs.Count < 2)\n {\n Log.Info($\"Audio based on language\");\n return stream;\n }\n for (int i = 0; i < stream.Demuxer.Programs.Count; i++)\n {\n bool aExists = false, vExists = false;\n foreach (var pstream in stream.Demuxer.Programs[i].Streams)\n {\n if (pstream.StreamIndex == stream.StreamIndex) aExists = true;\n else if (pstream.StreamIndex == stream.Demuxer.VideoStream?.StreamIndex) vExists = true;\n }\n if (aExists && vExists)\n {\n Log.Info($\"Audio based on language and same program #{i}\");\n return stream;\n }\n }\n }\n int streamIndex;\n lock (streams[0].Demuxer.lockFmtCtx)\n streamIndex = av_find_best_stream(streams[0].Demuxer.FormatContext, AVMediaType.Audio, -1, streams[0].Demuxer.VideoStream != null ? streams[0].Demuxer.VideoStream.StreamIndex : -1, null, 0);\n foreach (var stream in streams)\n if (stream.StreamIndex == streamIndex)\n {\n Log.Info($\"Audio based on av_find_best_stream\");\n return stream;\n }\n if (streams.Count > 0) \n return streams[0];\n return null;\n }\n }", "code_description": null, "fill_type": "FUNCTION_TYPE", "language_type": "c_sharp", "sub_task_type": null}, "context_code": [["/LLPlayer/FlyleafLib/MediaFramework/MediaContext/DecoderContext.Open.cs", "using System;\nusing System.Collections.Generic;\nusing System.IO;\nusing System.Linq;\nusing System.Threading.Tasks;\n\nusing FlyleafLib.MediaFramework.MediaDemuxer;\nusing FlyleafLib.MediaFramework.MediaPlaylist;\nusing FlyleafLib.MediaFramework.MediaStream;\nusing FlyleafLib.MediaPlayer;\nusing static FlyleafLib.Logger;\nusing static FlyleafLib.Utils;\n\nnamespace FlyleafLib.MediaFramework.MediaContext;\n\npublic partial class DecoderContext\n{\n #region Events\n public event EventHandler OpenCompleted;\n public event EventHandler OpenSessionCompleted;\n public event EventHandler OpenSubtitlesCompleted;\n public event EventHandler OpenPlaylistItemCompleted;\n\n public event EventHandler OpenAudioStreamCompleted;\n public event EventHandler OpenVideoStreamCompleted;\n public event EventHandler OpenSubtitlesStreamCompleted;\n public event EventHandler OpenDataStreamCompleted;\n\n public event EventHandler OpenExternalAudioStreamCompleted;\n public event EventHandler OpenExternalVideoStreamCompleted;\n public event EventHandler OpenExternalSubtitlesStreamCompleted;\n\n public class OpenCompletedArgs\n {\n public string Url;\n public Stream IOStream;\n public string Error;\n public bool Success => Error == null;\n public OpenCompletedArgs(string url = null, Stream iostream = null, string error = null) { Url = url; IOStream = iostream; Error = error; }\n }\n public class OpenSubtitlesCompletedArgs\n {\n public string Url;\n public string Error;\n public bool Success => Error == null;\n public OpenSubtitlesCompletedArgs(string url = null, string error = null) { Url = url; Error = error; }\n }\n public class OpenSessionCompletedArgs\n {\n public Session Session;\n public string Error;\n public bool Success => Error == null;\n public OpenSessionCompletedArgs(Session session = null, string error = null) { Session = session; Error = error; }\n }\n public class OpenPlaylistItemCompletedArgs\n {\n public PlaylistItem Item;\n public PlaylistItem OldItem;\n public string Error;\n public bool Success => Error == null;\n public OpenPlaylistItemCompletedArgs(PlaylistItem item = null, PlaylistItem oldItem = null, string error = null) { Item = item; OldItem = oldItem; Error = error; }\n }\n public class StreamOpenedArgs\n {\n public StreamBase Stream;\n public StreamBase OldStream;\n public string Error;\n public bool Success => Error == null;\n public StreamOpenedArgs(StreamBase stream = null, StreamBase oldStream = null, string error = null) { Stream = stream; OldStream= oldStream; Error = error; }\n }\n public class OpenAudioStreamCompletedArgs : StreamOpenedArgs\n {\n public new AudioStream Stream => (AudioStream)base.Stream;\n public new AudioStream OldStream=> (AudioStream)base.OldStream;\n public OpenAudioStreamCompletedArgs(AudioStream stream = null, AudioStream oldStream = null, string error = null): base(stream, oldStream, error) { }\n }\n public class OpenVideoStreamCompletedArgs : StreamOpenedArgs\n {\n public new VideoStream Stream => (VideoStream)base.Stream;\n public new VideoStream OldStream=> (VideoStream)base.OldStream;\n public OpenVideoStreamCompletedArgs(VideoStream stream = null, VideoStream oldStream = null, string error = null): base(stream, oldStream, error) { }\n }\n public class OpenSubtitlesStreamCompletedArgs : StreamOpenedArgs\n {\n public new SubtitlesStream Stream => (SubtitlesStream)base.Stream;\n public new SubtitlesStream OldStream=> (SubtitlesStream)base.OldStream;\n public OpenSubtitlesStreamCompletedArgs(SubtitlesStream stream = null, SubtitlesStream oldStream = null, string error = null): base(stream, oldStream, error) { }\n }\n public class OpenDataStreamCompletedArgs : StreamOpenedArgs\n {\n public new DataStream Stream => (DataStream)base.Stream;\n public new DataStream OldStream => (DataStream)base.OldStream;\n public OpenDataStreamCompletedArgs(DataStream stream = null, DataStream oldStream = null, string error = null) : base(stream, oldStream, error) { }\n }\n public class ExternalStreamOpenedArgs : EventArgs\n {\n public ExternalStream ExtStream;\n public ExternalStream OldExtStream;\n public string Error;\n public bool Success => Error == null;\n public ExternalStreamOpenedArgs(ExternalStream extStream = null, ExternalStream oldExtStream = null, string error = null) { ExtStream = extStream; OldExtStream= oldExtStream; Error = error; }\n }\n public class OpenExternalAudioStreamCompletedArgs : ExternalStreamOpenedArgs\n {\n public new ExternalAudioStream ExtStream => (ExternalAudioStream)base.ExtStream;\n public new ExternalAudioStream OldExtStream=> (ExternalAudioStream)base.OldExtStream;\n public OpenExternalAudioStreamCompletedArgs(ExternalAudioStream extStream = null, ExternalAudioStream oldExtStream = null, string error = null) : base(extStream, oldExtStream, error) { }\n }\n public class OpenExternalVideoStreamCompletedArgs : ExternalStreamOpenedArgs\n {\n public new ExternalVideoStream ExtStream => (ExternalVideoStream)base.ExtStream;\n public new ExternalVideoStream OldExtStream=> (ExternalVideoStream)base.OldExtStream;\n public OpenExternalVideoStreamCompletedArgs(ExternalVideoStream extStream = null, ExternalVideoStream oldExtStream = null, string error = null) : base(extStream, oldExtStream, error) { }\n }\n public class OpenExternalSubtitlesStreamCompletedArgs : ExternalStreamOpenedArgs\n {\n public new ExternalSubtitlesStream ExtStream => (ExternalSubtitlesStream)base.ExtStream;\n public new ExternalSubtitlesStream OldExtStream=> (ExternalSubtitlesStream)base.OldExtStream;\n public OpenExternalSubtitlesStreamCompletedArgs(ExternalSubtitlesStream extStream = null, ExternalSubtitlesStream oldExtStream = null, string error = null) : base(extStream, oldExtStream, error) { }\n }\n\n private void OnOpenCompleted(OpenCompletedArgs args = null)\n {\n if (shouldDispose)\n {\n Dispose();\n return;\n }\n\n VideoDecoder.Renderer?.ClearScreen();\n if (CanInfo) Log.Info($\"[Open] {args.Url ?? \"None\"} {(!args.Success ? \" [Error: \" + args.Error + \"]\": \"\")}\");\n OpenCompleted?.Invoke(this, args);\n }\n private void OnOpenSessionCompleted(OpenSessionCompletedArgs args = null)\n {\n if (shouldDispose)\n {\n Dispose();\n return;\n }\n\n VideoDecoder.Renderer?.ClearScreen();\n if (CanInfo) Log.Info($\"[OpenSession] {args.Session.Url ?? \"None\"} - Item: {args.Session.PlaylistItem} {(!args.Success ? \" [Error: \" + args.Error + \"]\": \"\")}\");\n OpenSessionCompleted?.Invoke(this, args);\n }\n private void OnOpenSubtitles(OpenSubtitlesCompletedArgs args = null)\n {\n if (shouldDispose)\n {\n Dispose();\n return;\n }\n\n if (CanInfo) Log.Info($\"[OpenSubtitles] {args.Url ?? \"None\"} {(!args.Success ? \" [Error: \" + args.Error + \"]\": \"\")}\");\n OpenSubtitlesCompleted?.Invoke(this, args);\n }\n private void OnOpenPlaylistItemCompleted(OpenPlaylistItemCompletedArgs args = null)\n {\n if (shouldDispose)\n {\n Dispose();\n return;\n }\n\n VideoDecoder.Renderer?.ClearScreen();\n if (CanInfo) Log.Info($\"[OpenPlaylistItem] {(args.OldItem != null ? args.OldItem.Title : \"None\")} => {(args.Item != null ? args.Item.Title : \"None\")}{(!args.Success ? \" [Error: \" + args.Error + \"]\": \"\")}\");\n OpenPlaylistItemCompleted?.Invoke(this, args);\n }\n private void OnOpenAudioStreamCompleted(OpenAudioStreamCompletedArgs args = null)\n {\n if (shouldDispose)\n {\n Dispose();\n return;\n }\n\n ClosedAudioStream = null;\n MainDemuxer = !VideoDemuxer.Disposed ? VideoDemuxer : AudioDemuxer;\n\n if (CanInfo) Log.Info($\"[OpenAudioStream] #{(args.OldStream != null ? args.OldStream.StreamIndex.ToString() : \"_\")} => #{(args.Stream != null ? args.Stream.StreamIndex.ToString() : \"_\")}{(!args.Success ? \" [Error: \" + args.Error + \"]\": \"\")}\");\n OpenAudioStreamCompleted?.Invoke(this, args);\n }\n private void OnOpenVideoStreamCompleted(OpenVideoStreamCompletedArgs args = null)\n {\n if (shouldDispose)\n {\n Dispose();\n return;\n }\n\n ClosedVideoStream = null;\n MainDemuxer = !VideoDemuxer.Disposed ? VideoDemuxer : AudioDemuxer;\n\n if (CanInfo) Log.Info($\"[OpenVideoStream] #{(args.OldStream != null ? args.OldStream.StreamIndex.ToString() : \"_\")} => #{(args.Stream != null ? args.Stream.StreamIndex.ToString() : \"_\")}{(!args.Success ? \" [Error: \" + args.Error + \"]\": \"\")}\");\n OpenVideoStreamCompleted?.Invoke(this, args);\n }\n private void OnOpenSubtitlesStreamCompleted(OpenSubtitlesStreamCompletedArgs args = null)\n {\n if (shouldDispose)\n {\n Dispose();\n return;\n }\n\n if (CanInfo) Log.Info($\"[OpenSubtitlesStream] #{(args.OldStream != null ? args.OldStream.StreamIndex.ToString() : \"_\")} => #{(args.Stream != null ? args.Stream.StreamIndex.ToString() : \"_\")}{(!args.Success ? \" [Error: \" + args.Error + \"]\": \"\")}\");\n OpenSubtitlesStreamCompleted?.Invoke(this, args);\n }\n private void OnOpenDataStreamCompleted(OpenDataStreamCompletedArgs args = null)\n {\n if (shouldDispose)\n {\n Dispose();\n return;\n }\n\n if (CanInfo)\n Log.Info($\"[OpenDataStream] #{(args.OldStream != null ? args.OldStream.StreamIndex.ToString() : \"_\")} => #{(args.Stream != null ? args.Stream.StreamIndex.ToString() : \"_\")}{(!args.Success ? \" [Error: \" + args.Error + \"]\" : \"\")}\");\n OpenDataStreamCompleted?.Invoke(this, args);\n }\n private void OnOpenExternalAudioStreamCompleted(OpenExternalAudioStreamCompletedArgs args = null)\n {\n if (shouldDispose)\n {\n Dispose();\n return;\n }\n\n ClosedAudioStream = null;\n MainDemuxer = !VideoDemuxer.Disposed ? VideoDemuxer : AudioDemuxer;\n\n if (CanInfo) Log.Info($\"[OpenExternalAudioStream] {(args.OldExtStream != null ? args.OldExtStream.Url : \"None\")} => {(args.ExtStream != null ? args.ExtStream.Url : \"None\")}{(!args.Success ? \" [Error: \" + args.Error + \"]\": \"\")}\");\n OpenExternalAudioStreamCompleted?.Invoke(this, args);\n }\n private void OnOpenExternalVideoStreamCompleted(OpenExternalVideoStreamCompletedArgs args = null)\n {\n if (shouldDispose)\n {\n Dispose();\n return;\n }\n\n ClosedVideoStream = null;\n MainDemuxer = !VideoDemuxer.Disposed ? VideoDemuxer : AudioDemuxer;\n\n if (CanInfo) Log.Info($\"[OpenExternalVideoStream] {(args.OldExtStream != null ? args.OldExtStream.Url : \"None\")} => {(args.ExtStream != null ? args.ExtStream.Url : \"None\")}{(!args.Success ? \" [Error: \" + args.Error + \"]\": \"\")}\");\n OpenExternalVideoStreamCompleted?.Invoke(this, args);\n }\n private void OnOpenExternalSubtitlesStreamCompleted(OpenExternalSubtitlesStreamCompletedArgs args = null)\n {\n if (shouldDispose)\n {\n Dispose();\n return;\n }\n\n if (CanInfo) Log.Info($\"[OpenExternalSubtitlesStream] {(args.OldExtStream != null ? args.OldExtStream.Url : \"None\")} => {(args.ExtStream != null ? args.ExtStream.Url : \"None\")}{(!args.Success ? \" [Error: \" + args.Error + \"]\": \"\")}\");\n OpenExternalSubtitlesStreamCompleted?.Invoke(this, args);\n }\n #endregion\n\n #region Open\n public OpenCompletedArgs Open(string url, bool defaultPlaylistItem = true, bool defaultVideo = true, bool defaultAudio = true, bool defaultSubtitles = true)\n => Open((object)url, defaultPlaylistItem, defaultVideo, defaultAudio, defaultSubtitles);\n public OpenCompletedArgs Open(Stream iostream, bool defaultPlaylistItem = true, bool defaultVideo = true, bool defaultAudio = true, bool defaultSubtitles = true)\n => Open((object)iostream, defaultPlaylistItem, defaultVideo, defaultAudio, defaultSubtitles);\n\n internal OpenCompletedArgs Open(object input, bool defaultPlaylistItem = true, bool defaultVideo = true, bool defaultAudio = true, bool defaultSubtitles = true)\n {\n OpenCompletedArgs args = new();\n\n try\n {\n Initialize();\n\n if (input is Stream)\n {\n Playlist.IOStream = (Stream)input;\n }\n else\n Playlist.Url = input.ToString(); // TBR: check UI update\n\n args.Url = Playlist.Url;\n args.IOStream = Playlist.IOStream;\n args.Error = Open().Error;\n\n if (Playlist.Items.Count == 0 && args.Success)\n args.Error = \"No playlist items were found\";\n\n if (!args.Success)\n return args;\n\n if (!defaultPlaylistItem)\n return args;\n\n args.Error = Open(SuggestItem(), defaultVideo, defaultAudio, defaultSubtitles).Error;\n\n return args;\n\n } catch (Exception e)\n {\n args.Error = !args.Success ? args.Error + \"\\r\\n\" + e.Message : e.Message;\n return args;\n }\n finally\n {\n OnOpenCompleted(args);\n }\n }\n public new OpenSubtitlesCompletedArgs OpenSubtitles(string url)\n {\n OpenSubtitlesCompletedArgs args = new();\n\n try\n {\n var res = base.OpenSubtitles(url);\n args.Error = res == null ? \"No external subtitles stream found\" : res.Error;\n\n if (args.Success)\n args.Error = Open(res.ExternalSubtitlesStream).Error;\n\n return args;\n\n } catch (Exception e)\n {\n args.Error = !args.Success ? args.Error + \"\\r\\n\" + e.Message : e.Message;\n return args;\n }\n finally\n {\n OnOpenSubtitles(args);\n }\n }\n public OpenSessionCompletedArgs Open(Session session)\n {\n OpenSessionCompletedArgs args = new(session);\n\n try\n {\n // Open\n if (session.Url != null && session.Url != Playlist.Url) // && session.Url != Playlist.DirectUrl)\n {\n args.Error = Open(session.Url, false, false, false, false).Error;\n if (!args.Success)\n return args;\n }\n\n // Open Item\n if (session.PlaylistItem != -1)\n {\n args.Error = Open(Playlist.Items[session.PlaylistItem], false, false, false).Error;\n if (!args.Success)\n return args;\n }\n\n // Open Streams\n if (session.ExternalVideoStream != -1)\n {\n args.Error = Open(Playlist.Selected.ExternalVideoStreams[session.ExternalVideoStream], false, session.VideoStream).Error;\n if (!args.Success)\n return args;\n }\n else if (session.VideoStream != -1)\n {\n args.Error = Open(VideoDemuxer.AVStreamToStream[session.VideoStream], false).Error;\n if (!args.Success)\n return args;\n }\n\n string tmpErr = null;\n if (session.ExternalAudioStream != -1)\n tmpErr = Open(Playlist.Selected.ExternalAudioStreams[session.ExternalAudioStream], false, session.AudioStream).Error;\n else if (session.AudioStream != -1)\n tmpErr = Open(VideoDemuxer.AVStreamToStream[session.AudioStream], false).Error;\n\n if (tmpErr != null & VideoStream == null)\n {\n args.Error = tmpErr;\n return args;\n }\n\n if (session.ExternalSubtitlesUrl != null)\n OpenSubtitles(session.ExternalSubtitlesUrl);\n else if (session.SubtitlesStream != -1)\n Open(VideoDemuxer.AVStreamToStream[session.SubtitlesStream]);\n\n Config.Audio.SetDelay(session.AudioDelay);\n\n for (int i = 0; i < subNum; i++)\n {\n Config.Subtitles[i].SetDelay(session.SubtitlesDelay);\n }\n\n if (session.CurTime > 1 * (long)1000 * 10000)\n Seek(session.CurTime / 10000);\n\n return args;\n } catch (Exception e)\n {\n args.Error = !args.Success ? args.Error + \"\\r\\n\" + e.Message : e.Message;\n return args;\n } finally\n {\n OnOpenSessionCompleted(args);\n }\n }\n public OpenPlaylistItemCompletedArgs Open(PlaylistItem item, bool defaultVideo = true, bool defaultAudio = true, bool defaultSubtitles = true)\n {\n OpenPlaylistItemCompletedArgs args = new(item);\n\n try\n {\n long stoppedTime = GetCurTime();\n InitializeSwitch();\n\n // Disables old item\n if (Playlist.Selected != null)\n {\n args.OldItem = Playlist.Selected;\n Playlist.Selected.Enabled = false;\n }\n\n if (item == null)\n {\n args.Error = \"Cancelled\";\n return args;\n }\n\n Playlist.Selected = item;\n Playlist.Selected.Enabled = true;\n\n // We reset external streams of the current item and not the old one\n if (Playlist.Selected.ExternalAudioStream != null)\n {\n Playlist.Selected.ExternalAudioStream.Enabled = false;\n Playlist.Selected.ExternalAudioStream = null;\n }\n\n if (Playlist.Selected.ExternalVideoStream != null)\n {\n Playlist.Selected.ExternalVideoStream.Enabled = false;\n Playlist.Selected.ExternalVideoStream = null;\n }\n\n for (int i = 0; i < subNum; i++)\n {\n if (Playlist.Selected.ExternalSubtitlesStreams[i] != null)\n {\n Playlist.Selected.ExternalSubtitlesStreams[i].Enabled = false;\n Playlist.Selected.ExternalSubtitlesStreams[i] = null;\n }\n }\n\n args.Error = OpenItem().Error;\n\n if (!args.Success)\n return args;\n\n if (Playlist.Selected.Url != null || Playlist.Selected.IOStream != null)\n args.Error = OpenDemuxerInput(VideoDemuxer, Playlist.Selected);\n\n if (!args.Success)\n return args;\n\n if (defaultVideo && Config.Video.Enabled)\n args.Error = OpenSuggestedVideo(defaultAudio);\n else if (defaultAudio && Config.Audio.Enabled)\n args.Error = OpenSuggestedAudio();\n\n if ((defaultVideo || defaultAudio) && AudioStream == null && VideoStream == null)\n {\n args.Error ??= \"No audio/video found\";\n\n return args;\n }\n\n if (defaultSubtitles && Config.Subtitles.Enabled)\n {\n if (Playlist.Selected.ExternalSubtitlesStreams[0] != null)\n Open(Playlist.Selected.ExternalSubtitlesStreams[0]);\n else\n OpenSuggestedSubtitles();\n }\n\n if (Config.Data.Enabled)\n {\n OpenSuggestedData();\n }\n\n LoadPlaylistChapters();\n\n return args;\n } catch (Exception e)\n {\n args.Error = !args.Success ? args.Error + \"\\r\\n\" + e.Message : e.Message;\n return args;\n } finally\n {\n OnOpenPlaylistItemCompleted(args);\n }\n }\n public ExternalStreamOpenedArgs Open(ExternalStream extStream, bool defaultAudio = false, int streamIndex = -1) // -2: None, -1: Suggest, >=0: specified\n {\n ExternalStreamOpenedArgs args = null;\n\n try\n {\n Demuxer demuxer;\n\n if (extStream is ExternalVideoStream)\n {\n args = new OpenExternalVideoStreamCompletedArgs((ExternalVideoStream) extStream, Playlist.Selected.ExternalVideoStream);\n\n if (args.OldExtStream != null)\n args.OldExtStream.Enabled = false;\n\n Playlist.Selected.ExternalVideoStream = (ExternalVideoStream) extStream;\n\n foreach(var plugin in Plugins.Values)\n plugin.OnOpenExternalVideo();\n\n demuxer = VideoDemuxer;\n }\n else if (extStream is ExternalAudioStream)\n {\n args = new OpenExternalAudioStreamCompletedArgs((ExternalAudioStream) extStream, Playlist.Selected.ExternalAudioStream);\n\n if (args.OldExtStream != null)\n args.OldExtStream.Enabled = false;\n\n Playlist.Selected.ExternalAudioStream = (ExternalAudioStream) extStream;\n\n foreach(var plugin in Plugins.Values)\n plugin.OnOpenExternalAudio();\n\n demuxer = AudioDemuxer;\n }\n else\n {\n int i = SubtitlesSelectedHelper.CurIndex;\n args = new OpenExternalSubtitlesStreamCompletedArgs((ExternalSubtitlesStream) extStream, Playlist.Selected.ExternalSubtitlesStreams[i]);\n\n if (args.OldExtStream != null)\n args.OldExtStream.Enabled = false;\n\n Playlist.Selected.ExternalSubtitlesStreams[i] = (ExternalSubtitlesStream) extStream;\n\n if (!Playlist.Selected.ExternalSubtitlesStreams[i].Downloaded)\n DownloadSubtitles(Playlist.Selected.ExternalSubtitlesStreams[i]);\n\n foreach(var plugin in Plugins.Values)\n plugin.OnOpenExternalSubtitles();\n\n demuxer = SubtitlesDemuxers[i];\n }\n\n // Open external stream\n args.Error = OpenDemuxerInput(demuxer, extStream);\n\n if (!args.Success)\n return args;\n\n // Update embedded streams with the external stream pointer\n foreach (var embStream in demuxer.VideoStreams)\n embStream.ExternalStream = extStream;\n foreach (var embStream in demuxer.AudioStreams)\n embStream.ExternalStream = extStream;\n foreach (var embStream in demuxer.SubtitlesStreamsAll)\n {\n embStream.ExternalStream = extStream;\n embStream.ExternalStreamAdded(); // Copies VobSub's .idx file to extradata (based on external url .sub)\n }\n\n // Open embedded stream\n if (streamIndex != -2)\n {\n StreamBase suggestedStream = null;\n if (streamIndex != -1 && (streamIndex >= demuxer.AVStreamToStream.Count || streamIndex < 0 || demuxer.AVStreamToStream[streamIndex].Type != extStream.Type))\n {\n args.Error = $\"Invalid stream index {streamIndex}\";\n demuxer.Dispose();\n return args;\n }\n\n if (demuxer.Type == MediaType.Video)\n suggestedStream = streamIndex == -1 ? SuggestVideo(demuxer.VideoStreams) : demuxer.AVStreamToStream[streamIndex];\n else if (demuxer.Type == MediaType.Audio)\n suggestedStream = streamIndex == -1 ? SuggestAudio(demuxer.AudioStreams) : demuxer.AVStreamToStream[streamIndex];\n else if (demuxer.Type == MediaType.Subs)\n {\n System.Collections.Generic.List langs = Config.Subtitles.Languages.ToList();\n langs.Add(Language.Unknown);\n suggestedStream = streamIndex == -1 ? SuggestSubtitles(demuxer.SubtitlesStreamsAll, langs) : demuxer.AVStreamToStream[streamIndex];\n }\n else\n {\n suggestedStream = demuxer.AVStreamToStream[streamIndex];\n }\n\n if (suggestedStream == null)\n {\n demuxer.Dispose();\n args.Error = \"No embedded streams found\";\n return args;\n }\n\n args.Error = Open(suggestedStream, defaultAudio).Error;\n if (!args.Success)\n return args;\n }\n\n LoadPlaylistChapters();\n\n extStream.Enabled = true;\n\n return args;\n } catch (Exception e)\n {\n args.Error = !args.Success ? args.Error + \"\\r\\n\" + e.Message : e.Message;\n return args;\n } finally\n {\n if (extStream is ExternalVideoStream)\n OnOpenExternalVideoStreamCompleted((OpenExternalVideoStreamCompletedArgs)args);\n else if (extStream is ExternalAudioStream)\n OnOpenExternalAudioStreamCompleted((OpenExternalAudioStreamCompletedArgs)args);\n else\n OnOpenExternalSubtitlesStreamCompleted((OpenExternalSubtitlesStreamCompletedArgs)args);\n }\n }\n\n public StreamOpenedArgs OpenVideoStream(VideoStream stream, bool defaultAudio = true)\n => Open(stream, defaultAudio);\n public StreamOpenedArgs OpenAudioStream(AudioStream stream)\n => Open(stream);\n public StreamOpenedArgs OpenSubtitlesStream(SubtitlesStream stream)\n => Open(stream);\n public StreamOpenedArgs OpenDataStream(DataStream stream)\n => Open(stream);\n private StreamOpenedArgs Open(StreamBase stream, bool defaultAudio = false)\n {\n StreamOpenedArgs args = null;\n\n try\n {\n lock (stream.Demuxer.lockActions)\n lock (stream.Demuxer.lockFmtCtx)\n {\n var oldStream = stream.Type == MediaType.Video ? VideoStream : (stream.Type == MediaType.Audio ? AudioStream : (StreamBase)DataStream);\n if (stream.Type == MediaType.Subs)\n {\n oldStream = SubtitlesStreams[SubtitlesSelectedHelper.CurIndex];\n }\n\n // Close external demuxers when opening embedded\n if (stream.Demuxer.Type == MediaType.Video)\n {\n // TBR: if (stream.Type == MediaType.Video) | We consider that we can't have Embedded and External Video Streams at the same time\n if (stream.Type == MediaType.Audio) // TBR: && VideoStream != null)\n {\n if (!EnableDecoding) AudioDemuxer.Dispose();\n if (Playlist.Selected.ExternalAudioStream != null)\n {\n Playlist.Selected.ExternalAudioStream.Enabled = false;\n Playlist.Selected.ExternalAudioStream = null;\n }\n }\n else if (stream.Type == MediaType.Subs)\n {\n int i = SubtitlesSelectedHelper.CurIndex;\n if (!EnableDecoding) \n SubtitlesDemuxers[i].Dispose();\n\n if (Playlist.Selected.ExternalSubtitlesStreams[i] != null)\n {\n Playlist.Selected.ExternalSubtitlesStreams[i].Enabled = false;\n Playlist.Selected.ExternalSubtitlesStreams[i] = null;\n }\n }\n else if (stream.Type == MediaType.Data)\n {\n if (!EnableDecoding) DataDemuxer.Dispose();\n }\n }\n else if (!EnableDecoding)\n {\n // Disable embeded audio when enabling external audio (TBR)\n if (stream.Demuxer.Type == MediaType.Audio && stream.Type == MediaType.Audio && AudioStream != null && AudioStream.Demuxer.Type == MediaType.Video)\n {\n foreach (var aStream in VideoDemuxer.AudioStreams)\n VideoDemuxer.DisableStream(aStream);\n }\n }\n\n // Open Codec / Enable on demuxer\n if (EnableDecoding)\n {\n string ret = GetDecoderPtr(stream).Open(stream);\n\n if (ret != null)\n {\n return stream.Type == MediaType.Video\n ? (args = new OpenVideoStreamCompletedArgs((VideoStream)stream, (VideoStream)oldStream, $\"Failed to open video stream #{stream.StreamIndex}\\r\\n{ret}\"))\n : stream.Type == MediaType.Audio\n ? (args = new OpenAudioStreamCompletedArgs((AudioStream)stream, (AudioStream)oldStream, $\"Failed to open audio stream #{stream.StreamIndex}\\r\\n{ret}\"))\n : stream.Type == MediaType.Subs\n ? (args = new OpenSubtitlesStreamCompletedArgs((SubtitlesStream)stream, (SubtitlesStream)oldStream, $\"Failed to open subtitles stream #{stream.StreamIndex}\\r\\n{ret}\"))\n : (args = new OpenDataStreamCompletedArgs((DataStream)stream, (DataStream)oldStream, $\"Failed to open data stream #{stream.StreamIndex}\\r\\n{ret}\"));\n }\n }\n else\n stream.Demuxer.EnableStream(stream);\n\n // Open Audio based on new Video Stream (if not the same suggestion)\n if (defaultAudio && stream.Type == MediaType.Video && Config.Audio.Enabled)\n {\n bool requiresChange = true;\n SuggestAudio(out var aStream, out var aExtStream, VideoDemuxer.AudioStreams);\n\n if (AudioStream != null)\n {\n // External audio streams comparison\n if (Playlist.Selected.ExternalAudioStream != null && aExtStream != null && aExtStream.Index == Playlist.Selected.ExternalAudioStream.Index)\n requiresChange = false;\n // Embedded audio streams comparison\n else if (Playlist.Selected.ExternalAudioStream == null && aStream != null && aStream.StreamIndex == AudioStream.StreamIndex)\n requiresChange = false;\n }\n\n if (!requiresChange)\n {\n if (CanDebug) Log.Debug($\"Audio no need to follow video\");\n }\n else\n {\n if (aStream != null)\n Open(aStream);\n else if (aExtStream != null)\n Open(aExtStream);\n\n //RequiresResync = true;\n }\n }\n\n return stream.Type == MediaType.Video\n ? (args = new OpenVideoStreamCompletedArgs((VideoStream)stream, (VideoStream)oldStream))\n : stream.Type == MediaType.Audio\n ? (args = new OpenAudioStreamCompletedArgs((AudioStream)stream, (AudioStream)oldStream))\n : stream.Type == MediaType.Subs\n ? (args = new OpenSubtitlesStreamCompletedArgs((SubtitlesStream)stream, (SubtitlesStream)oldStream))\n : (args = new OpenDataStreamCompletedArgs((DataStream)stream, (DataStream)oldStream));\n }\n } catch(Exception e)\n {\n return args = new StreamOpenedArgs(null, null, e.Message);\n } finally\n {\n if (stream.Type == MediaType.Video)\n OnOpenVideoStreamCompleted((OpenVideoStreamCompletedArgs)args);\n else if (stream.Type == MediaType.Audio)\n OnOpenAudioStreamCompleted((OpenAudioStreamCompletedArgs)args);\n else if (stream.Type == MediaType.Subs)\n OnOpenSubtitlesStreamCompleted((OpenSubtitlesStreamCompletedArgs)args);\n else\n OnOpenDataStreamCompleted((OpenDataStreamCompletedArgs)args);\n }\n }\n\n public string OpenSuggestedVideo(bool defaultAudio = false)\n {\n VideoStream stream;\n ExternalVideoStream extStream;\n string error = null;\n\n if (ClosedVideoStream != null)\n {\n Log.Debug(\"[Video] Found previously closed stream\");\n\n extStream = ClosedVideoStream.Item1;\n if (extStream != null)\n return Open(extStream, false, ClosedVideoStream.Item2 >= 0 ? ClosedVideoStream.Item2 : -1).Error;\n\n stream = ClosedVideoStream.Item2 >= 0 ? (VideoStream)VideoDemuxer.AVStreamToStream[ClosedVideoStream.Item2] : null;\n }\n else\n SuggestVideo(out stream, out extStream, VideoDemuxer.VideoStreams);\n\n if (stream != null)\n error = Open(stream, defaultAudio).Error;\n else if (extStream != null)\n error = Open(extStream, defaultAudio).Error;\n else if (defaultAudio && Config.Audio.Enabled)\n error = OpenSuggestedAudio(); // We still need audio if no video exists\n\n return error;\n }\n public string OpenSuggestedAudio()\n {\n AudioStream stream = null;\n ExternalAudioStream extStream = null;\n string error = null;\n\n if (ClosedAudioStream != null)\n {\n Log.Debug(\"[Audio] Found previously closed stream\");\n\n extStream = ClosedAudioStream.Item1;\n if (extStream != null)\n return Open(extStream, false, ClosedAudioStream.Item2 >= 0 ? ClosedAudioStream.Item2 : -1).Error;\n\n stream = ClosedAudioStream.Item2 >= 0 ? (AudioStream)VideoDemuxer.AVStreamToStream[ClosedAudioStream.Item2] : null;\n }\n else\n SuggestAudio(out stream, out extStream, VideoDemuxer.AudioStreams);\n\n if (stream != null)\n error = Open(stream).Error;\n else if (extStream != null)\n error = Open(extStream).Error;\n\n return error;\n }\n public void OpenSuggestedSubtitles(int? subIndex = -1)\n {\n long sessionId = OpenItemCounter;\n\n try\n {\n // High Suggest (first lang priority + high rating + already converted/downloaded)\n // 1. Check embedded steams for high suggest\n if (Config.Subtitles.Languages.Count > 0)\n {\n foreach (var stream in VideoDemuxer.SubtitlesStreamsAll)\n {\n if (stream.Language == Config.Subtitles.Languages[0])\n {\n Log.Debug(\"[Subtitles] Found high suggested embedded stream\");\n Open(stream);\n return;\n }\n }\n }\n\n // 2. Check external streams for high suggest\n if (Playlist.Selected.ExternalSubtitlesStreamsAll.Count > 0)\n {\n var extStream = SuggestBestExternalSubtitles();\n if (extStream != null)\n {\n Log.Debug(\"[Subtitles] Found high suggested external stream\");\n Open(extStream);\n return;\n }\n }\n\n // 3. Search offline if allowed\n if (SearchLocalSubtitles())\n {\n // 3.1 Check external streams for high suggest (again for the new additions if any)\n ExternalSubtitlesStream extStream = SuggestBestExternalSubtitles();\n if (extStream != null)\n {\n Log.Debug(\"[Subtitles] Found high suggested local external stream\");\n Open(extStream);\n return;\n }\n }\n\n } catch (Exception e)\n {\n Log.Debug($\"OpenSuggestedSubtitles canceled? [{e.Message}]\");\n return;\n }\n\n Task.Run(() =>\n {\n try\n {\n if (sessionId != OpenItemCounter)\n {\n Log.Debug(\"OpenSuggestedSubtitles canceled\");\n return;\n }\n\n if (sessionId != OpenItemCounter)\n {\n Log.Debug(\"OpenSuggestedSubtitles canceled\");\n return;\n }\n\n // 4. Search online if allowed (not async)\n SearchOnlineSubtitles();\n\n if (sessionId != OpenItemCounter)\n {\n Log.Debug(\"OpenSuggestedSubtitles canceled\");\n return;\n }\n\n // 5. (Any) Check embedded/external streams for config languages (including 'undefined')\n SuggestSubtitles(out var stream, out ExternalSubtitlesStream extStream);\n\n if (stream != null)\n Open(stream);\n else if (extStream != null)\n Open(extStream);\n } catch (Exception e)\n {\n Log.Debug($\"OpenSuggestedSubtitles canceled? [{e.Message}]\");\n }\n });\n }\n public string OpenSuggestedData()\n {\n DataStream stream;\n string error = null;\n\n SuggestData(out stream, VideoDemuxer.DataStreams);\n\n if (stream != null)\n error = Open(stream).Error;\n\n return error;\n }\n\n public string OpenDemuxerInput(Demuxer demuxer, DemuxerInput demuxerInput)\n {\n OpenedPlugin?.OnBuffering();\n\n string error = null;\n\n Dictionary formatOpt = null;\n Dictionary copied = null;\n\n try\n {\n // Set HTTP Config\n if (Playlist.InputType == InputType.Web)\n {\n formatOpt = Config.Demuxer.GetFormatOptPtr(demuxer.Type);\n copied = new Dictionary();\n\n foreach (var opt in formatOpt)\n copied.Add(opt.Key, opt.Value);\n\n if (demuxerInput.UserAgent != null)\n formatOpt[\"user_agent\"] = demuxerInput.UserAgent;\n\n if (demuxerInput.Referrer != null)\n formatOpt[\"referer\"] = demuxerInput.Referrer;\n\n // this can cause issues\n //else if (!formatOpt.ContainsKey(\"referer\") && Playlist.Url != null)\n // formatOpt[\"referer\"] = Playlist.Url;\n\n if (demuxerInput.HTTPHeaders != null)\n {\n formatOpt[\"headers\"] = \"\";\n foreach(var header in demuxerInput.HTTPHeaders)\n formatOpt[\"headers\"] += header.Key + \": \" + header.Value + \"\\r\\n\";\n }\n }\n\n // Open Demuxer Input\n if (demuxerInput.Url != null)\n {\n error = demuxer.Open(demuxerInput.Url);\n\n if (error != null && !string.IsNullOrEmpty(demuxerInput.UrlFallback))\n {\n Log.Warn($\"Fallback to {demuxerInput.UrlFallback}\");\n error = demuxer.Open(demuxerInput.UrlFallback);\n }\n }\n else if (demuxerInput.IOStream != null)\n error = demuxer.Open(demuxerInput.IOStream);\n\n return error;\n } finally\n {\n // Restore HTTP Config\n if (Playlist.InputType == InputType.Web)\n {\n formatOpt.Clear();\n foreach(var opt in copied)\n formatOpt.Add(opt.Key, opt.Value);\n }\n\n OpenedPlugin?.OnBufferingCompleted();\n }\n }\n\n private void LoadPlaylistChapters()\n {\n if (Playlist.Selected != null && Playlist.Selected.Chapters.Count > 0 && MainDemuxer.Chapters.Count == 0)\n {\n foreach (var chapter in Playlist.Selected.Chapters)\n {\n MainDemuxer.Chapters.Add(chapter);\n }\n }\n }\n #endregion\n\n #region Close (Only For EnableDecoding)\n public void CloseAudio()\n {\n ClosedAudioStream = new Tuple(Playlist.Selected.ExternalAudioStream, AudioStream != null ? AudioStream.StreamIndex : -1);\n\n if (Playlist.Selected.ExternalAudioStream != null)\n {\n Playlist.Selected.ExternalAudioStream.Enabled = false;\n Playlist.Selected.ExternalAudioStream = null;\n }\n\n AudioDecoder.Dispose(true);\n }\n public void CloseVideo()\n {\n ClosedVideoStream = new Tuple(Playlist.Selected.ExternalVideoStream, VideoStream != null ? VideoStream.StreamIndex : -1);\n\n if (Playlist.Selected.ExternalVideoStream != null)\n {\n Playlist.Selected.ExternalVideoStream.Enabled = false;\n Playlist.Selected.ExternalVideoStream = null;\n }\n\n VideoDecoder.Dispose(true);\n VideoDecoder.Renderer?.ClearScreen();\n }\n public void CloseSubtitles(int subIndex)\n {\n if (Playlist.Selected.ExternalSubtitlesStreams[subIndex] != null)\n {\n Playlist.Selected.ExternalSubtitlesStreams[subIndex].Enabled = false;\n Playlist.Selected.ExternalSubtitlesStreams[subIndex] = null;\n }\n\n SubtitlesDecoders[subIndex].Dispose(true);\n }\n public void CloseData()\n {\n DataDecoder.Dispose(true);\n }\n #endregion\n}\n"], ["/LLPlayer/FlyleafLib/Plugins/PluginHandler.cs", "using System.Collections.Generic;\nusing System.Collections.ObjectModel;\nusing System.Linq;\n\nusing FlyleafLib.MediaFramework.MediaPlaylist;\nusing FlyleafLib.MediaFramework.MediaStream;\n\nnamespace FlyleafLib.Plugins;\n\npublic class PluginHandler\n{\n #region Properties\n public Config Config { get; private set; }\n public bool Interrupt { get; set; }\n public IOpen OpenedPlugin { get; private set; }\n public IOpenSubtitles OpenedSubtitlesPlugin { get; private set; }\n public long OpenCounter { get; internal set; }\n public long OpenItemCounter { get; internal set; }\n public Playlist Playlist { get; set; }\n public int UniqueId { get; set; }\n\n public Dictionary\n Plugins { get; private set; }\n public Dictionary\n PluginsOpen { get; private set; }\n public Dictionary\n PluginsOpenSubtitles { get; private set; }\n\n public Dictionary\n PluginsScrapeItem { get; private set; }\n\n public Dictionary\n PluginsSuggestItem { get; private set; }\n\n public Dictionary\n PluginsSuggestAudioStream { get; private set; }\n public Dictionary\n PluginsSuggestVideoStream { get; private set; }\n public Dictionary\n PluginsSuggestExternalAudio { get; private set; }\n public Dictionary\n PluginsSuggestExternalVideo { get; private set; }\n\n public Dictionary\n PluginsSuggestSubtitlesStream { get; private set; }\n public Dictionary\n PluginsSuggestSubtitles { get; private set; }\n public Dictionary\n PluginsSuggestBestExternalSubtitles\n { get; private set; }\n\n public Dictionary\n PluginsDownloadSubtitles { get; private set; }\n\n public Dictionary\n PluginsSearchLocalSubtitles { get; private set; }\n public Dictionary\n PluginsSearchOnlineSubtitles { get; private set; }\n #endregion\n\n #region Initialize\n LogHandler Log;\n public PluginHandler(Config config, int uniqueId = -1)\n {\n Config = config;\n UniqueId= uniqueId == -1 ? Utils.GetUniqueId() : uniqueId;\n Playlist = new Playlist(UniqueId);\n Log = new LogHandler((\"[#\" + UniqueId + \"]\").PadRight(8, ' ') + \" [PluginHandler ] \");\n LoadPlugins();\n }\n\n public static PluginBase CreatePluginInstance(PluginType type, PluginHandler handler = null)\n {\n PluginBase plugin = (PluginBase) Activator.CreateInstance(type.Type, true);\n plugin.Handler = handler;\n plugin.Name = type.Name;\n plugin.Type = type.Type;\n plugin.Version = type.Version;\n\n if (handler != null)\n plugin.OnLoaded();\n\n return plugin;\n }\n private void LoadPlugins()\n {\n Plugins = new Dictionary();\n\n foreach (var type in Engine.Plugins.Types.Values)\n {\n try\n {\n var plugin = CreatePluginInstance(type, this);\n plugin.Log = new LogHandler((\"[#\" + UniqueId + \"]\").PadRight(8, ' ') + $\" [{plugin.Name,-14}] \");\n Plugins.Add(plugin.Name, plugin);\n } catch (Exception e) { Log.Error($\"[Plugins] [Error] Failed to load plugin ... ({e.Message} {Utils.GetRecInnerException(e)}\"); }\n }\n\n PluginsOpen = new Dictionary();\n PluginsOpenSubtitles = new Dictionary();\n PluginsScrapeItem = new Dictionary();\n\n PluginsSuggestItem = new Dictionary();\n\n PluginsSuggestAudioStream = new Dictionary();\n PluginsSuggestVideoStream = new Dictionary();\n PluginsSuggestSubtitlesStream = new Dictionary();\n PluginsSuggestSubtitles = new Dictionary();\n\n PluginsSuggestExternalAudio = new Dictionary();\n PluginsSuggestExternalVideo = new Dictionary();\n PluginsSuggestBestExternalSubtitles\n = new Dictionary();\n\n PluginsSearchLocalSubtitles = new Dictionary();\n PluginsSearchOnlineSubtitles = new Dictionary();\n PluginsDownloadSubtitles = new Dictionary();\n\n foreach (var plugin in Plugins.Values)\n LoadPluginInterfaces(plugin);\n }\n private void LoadPluginInterfaces(PluginBase plugin)\n {\n if (plugin is IOpen) PluginsOpen.Add(plugin.Name, (IOpen)plugin);\n else if (plugin is IOpenSubtitles) PluginsOpenSubtitles.Add(plugin.Name, (IOpenSubtitles)plugin);\n\n if (plugin is IScrapeItem) PluginsScrapeItem.Add(plugin.Name, (IScrapeItem)plugin);\n\n if (plugin is ISuggestPlaylistItem) PluginsSuggestItem.Add(plugin.Name, (ISuggestPlaylistItem)plugin);\n\n if (plugin is ISuggestAudioStream) PluginsSuggestAudioStream.Add(plugin.Name, (ISuggestAudioStream)plugin);\n if (plugin is ISuggestVideoStream) PluginsSuggestVideoStream.Add(plugin.Name, (ISuggestVideoStream)plugin);\n if (plugin is ISuggestSubtitlesStream) PluginsSuggestSubtitlesStream.Add(plugin.Name, (ISuggestSubtitlesStream)plugin);\n if (plugin is ISuggestSubtitles) PluginsSuggestSubtitles.Add(plugin.Name, (ISuggestSubtitles)plugin);\n\n if (plugin is ISuggestExternalAudio) PluginsSuggestExternalAudio.Add(plugin.Name, (ISuggestExternalAudio)plugin);\n if (plugin is ISuggestExternalVideo) PluginsSuggestExternalVideo.Add(plugin.Name, (ISuggestExternalVideo)plugin);\n if (plugin is ISuggestBestExternalSubtitles) PluginsSuggestBestExternalSubtitles.Add(plugin.Name, (ISuggestBestExternalSubtitles)plugin);\n\n if (plugin is ISearchLocalSubtitles) PluginsSearchLocalSubtitles.Add(plugin.Name, (ISearchLocalSubtitles)plugin);\n if (plugin is ISearchOnlineSubtitles) PluginsSearchOnlineSubtitles.Add(plugin.Name, (ISearchOnlineSubtitles)plugin);\n if (plugin is IDownloadSubtitles) PluginsDownloadSubtitles.Add(plugin.Name, (IDownloadSubtitles)plugin);\n }\n #endregion\n\n #region Misc / Events\n public void OnInitializing()\n {\n OpenCounter++;\n OpenItemCounter++;\n foreach(var plugin in Plugins.Values)\n plugin.OnInitializing();\n }\n public void OnInitialized()\n {\n OpenedPlugin = null;\n OpenedSubtitlesPlugin = null;\n\n Playlist.Reset();\n\n foreach(var plugin in Plugins.Values)\n plugin.OnInitialized();\n }\n\n public void OnInitializingSwitch()\n {\n OpenItemCounter++;\n foreach(var plugin in Plugins.Values)\n plugin.OnInitializingSwitch();\n }\n public void OnInitializedSwitch()\n {\n foreach(var plugin in Plugins.Values)\n plugin.OnInitializedSwitch();\n }\n\n public void Dispose()\n {\n foreach(var plugin in Plugins.Values)\n plugin.Dispose();\n }\n #endregion\n\n #region Audio / Video\n public OpenResults Open()\n {\n long sessionId = OpenCounter;\n var plugins = PluginsOpen.Values.OrderBy(x => x.Priority);\n foreach(var plugin in plugins)\n {\n if (Interrupt || sessionId != OpenCounter)\n return new OpenResults(\"Cancelled\");\n\n if (!plugin.CanOpen())\n continue;\n\n var res = plugin.Open();\n if (res == null)\n continue;\n\n // Currently fallback is not allowed if an error has been returned\n if (res.Error != null)\n return res;\n\n OpenedPlugin = plugin;\n Log.Info($\"[{plugin.Name}] Open Success\");\n\n return res;\n }\n\n return new OpenResults(\"No plugin found for the provided input\");\n }\n public OpenResults OpenItem()\n {\n long sessionId = OpenItemCounter;\n var res = OpenedPlugin.OpenItem();\n\n res ??= new OpenResults { Error = \"Cancelled\" };\n\n if (sessionId != OpenItemCounter)\n res.Error = \"Cancelled\";\n\n if (res.Error == null)\n Log.Info($\"[{OpenedPlugin.Name}] Open Item ({Playlist.Selected.Index}) Success\");\n\n return res;\n }\n\n // Should only be called from opened plugin\n public void OnPlaylistCompleted()\n {\n Playlist.Completed = true;\n if (Playlist.ExpectingItems == 0)\n Playlist.ExpectingItems = Playlist.Items.Count;\n\n if (Playlist.Items.Count > 1)\n {\n Log.Debug(\"Playlist Completed\");\n Playlist.UpdatePrevNextItem();\n }\n }\n\n public void ScrapeItem(PlaylistItem item)\n {\n var plugins = PluginsScrapeItem.Values.OrderBy(x => x.Priority);\n foreach (var plugin in plugins)\n {\n if (Interrupt)\n return;\n\n plugin.ScrapeItem(item);\n }\n }\n\n public PlaylistItem SuggestItem()\n {\n var plugins = PluginsSuggestItem.Values.OrderBy(x => x.Priority);\n foreach (var plugin in plugins)\n {\n if (Interrupt)\n return null;\n\n var item = plugin.SuggestItem();\n if (item != null)\n {\n Log.Info($\"SuggestItem #{item.Index} - {item.Title}\");\n return item;\n }\n }\n\n return null;\n }\n\n public ExternalVideoStream SuggestExternalVideo()\n {\n var plugins = PluginsSuggestExternalVideo.Values.OrderBy(x => x.Priority);\n foreach (var plugin in plugins)\n {\n if (Interrupt)\n return null;\n\n var extStream = plugin.SuggestExternalVideo();\n if (extStream != null)\n {\n Log.Info($\"SuggestVideo (External) {extStream.Width} x {extStream.Height} @ {extStream.FPS}\");\n Log.Debug($\"SuggestVideo (External) Url: {extStream.Url}, UrlFallback: {extStream.UrlFallback}\");\n return extStream;\n }\n }\n\n return null;\n }\n public ExternalAudioStream SuggestExternalAudio()\n {\n var plugins = PluginsSuggestExternalAudio.Values.OrderBy(x => x.Priority);\n foreach(var plugin in plugins)\n {\n if (Interrupt)\n return null;\n\n var extStream = plugin.SuggestExternalAudio();\n if (extStream != null)\n {\n Log.Info($\"SuggestAudio (External) {extStream.SampleRate} Hz, {extStream.Codec}\");\n Log.Debug($\"SuggestAudio (External) Url: {extStream.Url}, UrlFallback: {extStream.UrlFallback}\");\n return extStream;\n }\n }\n\n return null;\n }\n\n public VideoStream SuggestVideo(ObservableCollection streams)\n {\n if (streams == null || streams.Count == 0) return null;\n\n var plugins = PluginsSuggestVideoStream.Values.OrderBy(x => x.Priority);\n foreach(var plugin in plugins)\n {\n if (Interrupt)\n return null;\n\n var stream = plugin.SuggestVideo(streams);\n if (stream != null) return stream;\n }\n\n return null;\n }\n public void SuggestVideo(out VideoStream stream, out ExternalVideoStream extStream, ObservableCollection streams)\n {\n stream = null;\n extStream = null;\n\n if (Interrupt)\n return;\n\n stream = SuggestVideo(streams);\n if (stream != null)\n return;\n\n if (Interrupt)\n return;\n\n extStream = SuggestExternalVideo();\n }\n\n public AudioStream SuggestAudio(ObservableCollection streams)\n {\n if (streams == null || streams.Count == 0) return null;\n\n var plugins = PluginsSuggestAudioStream.Values.OrderBy(x => x.Priority);\n foreach(var plugin in plugins)\n {\n if (Interrupt)\n return null;\n\n var stream = plugin.SuggestAudio(streams);\n if (stream != null) return stream;\n }\n\n return null;\n }\n public void SuggestAudio(out AudioStream stream, out ExternalAudioStream extStream, ObservableCollection streams)\n {\n stream = null;\n extStream = null;\n\n if (Interrupt)\n return;\n\n stream = SuggestAudio(streams);\n if (stream != null)\n return;\n\n if (Interrupt)\n return;\n\n extStream = SuggestExternalAudio();\n }\n #endregion\n\n #region Subtitles\n public OpenSubtitlesResults OpenSubtitles(string url)\n {\n var plugins = PluginsOpenSubtitles.Values.OrderBy(x => x.Priority);\n foreach(var plugin in plugins)\n {\n var res = plugin.Open(url);\n if (res == null)\n continue;\n\n if (res.Error != null)\n return res;\n\n OpenedSubtitlesPlugin = plugin;\n Log.Info($\"[{plugin.Name}] Open Subtitles Success\");\n\n return res;\n }\n\n return null;\n }\n\n public bool SearchLocalSubtitles()\n {\n if (!Playlist.Selected.SearchedLocal && Config.Subtitles.SearchLocal && (Config.Subtitles.SearchLocalOnInputType == null || Config.Subtitles.SearchLocalOnInputType.Count == 0 || Config.Subtitles.SearchLocalOnInputType.Contains(Playlist.InputType)))\n {\n Log.Debug(\"[Subtitles] Searching Local\");\n var plugins = PluginsSearchLocalSubtitles.Values.OrderBy(x => x.Priority);\n foreach(var plugin in plugins)\n {\n if (Interrupt)\n return false;\n\n plugin.SearchLocalSubtitles();\n }\n\n Playlist.Selected.SearchedLocal = true;\n\n return true;\n }\n\n return false;\n }\n public void SearchOnlineSubtitles()\n {\n if (!Playlist.Selected.SearchedOnline && Config.Subtitles.SearchOnline && (Config.Subtitles.SearchOnlineOnInputType == null || Config.Subtitles.SearchOnlineOnInputType.Count == 0 || Config.Subtitles.SearchOnlineOnInputType.Contains(Playlist.InputType)))\n {\n Log.Debug(\"[Subtitles] Searching Online\");\n var plugins = PluginsSearchOnlineSubtitles.Values.OrderBy(x => x.Priority);\n foreach(var plugin in plugins)\n {\n if (Interrupt)\n return;\n\n plugin.SearchOnlineSubtitles();\n }\n\n Playlist.Selected.SearchedOnline = true;\n }\n }\n public bool DownloadSubtitles(ExternalSubtitlesStream extStream)\n {\n bool res = false;\n\n var plugins = PluginsDownloadSubtitles.Values.OrderBy(x => x.Priority);\n foreach(var plugin in plugins)\n if (res = plugin.DownloadSubtitles(extStream))\n {\n extStream.Downloaded = true;\n return res;\n }\n\n return res;\n }\n\n public ExternalSubtitlesStream SuggestBestExternalSubtitles()\n {\n var plugins = PluginsSuggestBestExternalSubtitles.Values.OrderBy(x => x.Priority);\n foreach(var plugin in plugins)\n {\n if (Interrupt)\n return null;\n\n var extStream = plugin.SuggestBestExternalSubtitles();\n if (extStream != null)\n return extStream;\n }\n\n return null;\n }\n public void SuggestSubtitles(out SubtitlesStream stream, out ExternalSubtitlesStream extStream)\n {\n stream = null;\n extStream = null;\n\n var plugins = PluginsSuggestSubtitles.Values.OrderBy(x => x.Priority);\n foreach(var plugin in plugins)\n {\n if (Interrupt)\n return;\n\n plugin.SuggestSubtitles(out stream, out extStream);\n if (stream != null || extStream != null)\n return;\n }\n }\n public SubtitlesStream SuggestSubtitles(ObservableCollection streams, List langs)\n {\n if (streams == null || streams.Count == 0) return null;\n\n var plugins = PluginsSuggestSubtitlesStream.Values.OrderBy(x => x.Priority);\n foreach(var plugin in plugins)\n {\n if (Interrupt)\n return null;\n\n var stream = plugin.SuggestSubtitles(streams, langs);\n if (stream != null)\n return stream;\n }\n\n return null;\n }\n #endregion\n\n #region Data\n public void SuggestData(out DataStream stream, ObservableCollection streams)\n {\n stream = null;\n\n if (Interrupt)\n return;\n\n stream = streams.FirstOrDefault();\n }\n #endregion\n}\n"], ["/LLPlayer/FlyleafLib/MediaFramework/MediaDemuxer/Demuxer.cs", "using System.Collections.Concurrent;\nusing System.Collections.Generic;\nusing System.Collections.ObjectModel;\nusing System.IO;\nusing System.Runtime.InteropServices;\nusing System.Text;\nusing System.Threading;\nusing System.Threading.Tasks;\nusing System.Windows.Data;\n\nusing FlyleafLib.MediaFramework.MediaProgram;\nusing FlyleafLib.MediaFramework.MediaStream;\nusing FlyleafLib.MediaPlayer;\nusing static FlyleafLib.Config;\nusing static FlyleafLib.Logger;\n\nnamespace FlyleafLib.MediaFramework.MediaDemuxer;\n\npublic unsafe class Demuxer : RunThreadBase\n{\n /* TODO\n * 1) Review lockFmtCtx on Enable/Disable Streams causes delay and is not fully required\n * 2) Include AV_DISPOSITION_ATTACHED_PIC images in streams as VideoStream with flag\n * Possible introduce ImageStream and include also video streams with < 1 sec duration (eg. mjpeg etc)\n */\n\n #region Properties\n public MediaType Type { get; private set; }\n public DemuxerConfig Config { get; set; }\n\n // Format Info\n public string Url { get; private set; }\n public string Name { get; private set; }\n public string LongName { get; private set; }\n public string Extensions { get; private set; }\n public string Extension { get; private set; }\n public long StartTime { get; private set; }\n public long StartRealTime { get; private set; }\n public long Duration { get; internal set; }\n public void ForceDuration(long duration) { Duration = duration; IsLive = duration != 0; }\n\n public Dictionary\n Metadata { get; internal set; } = new Dictionary();\n\n /// \n /// The time of first packet in the queue (zero based, substracts start time)\n /// \n public long CurTime => CurPackets.CurTime != 0 ? CurPackets.CurTime : lastSeekTime;\n\n /// \n /// The buffered time in the queue (last packet time - first packet time)\n /// \n public long BufferedDuration=> CurPackets.BufferedDuration;\n\n public bool IsLive { get; private set; }\n public bool IsHLSLive { get; private set; }\n\n public AVFormatContext* FormatContext => fmtCtx;\n public CustomIOContext CustomIOContext { get; private set; }\n\n // Media Programs\n public ObservableCollection\n Programs { get; private set; } = new ObservableCollection();\n\n // Media Streams\n public ObservableCollection\n AudioStreams { get; private set; } = new ObservableCollection();\n public ObservableCollection\n VideoStreams { get; private set; } = new ObservableCollection();\n public ObservableCollection\n SubtitlesStreamsAll\n { get; private set; } = new ObservableCollection();\n public ObservableCollection\n DataStreams { get; private set; } = new ObservableCollection();\n readonly object lockStreams = new();\n\n public List EnabledStreams { get; private set; } = new List();\n public Dictionary\n AVStreamToStream{ get; private set; }\n\n public AudioStream AudioStream { get; private set; }\n public VideoStream VideoStream { get; private set; }\n // In the case of the secondary external subtitle, there is only one stream, but it goes into index=1 and index = 0 is null.\n public SubtitlesStream[] SubtitlesStreams\n { get; private set; }\n public DataStream DataStream { get; private set; }\n\n // Audio/Video Stream's HLSPlaylist\n internal playlist* HLSPlaylist { get; private set; }\n\n // Media Packets\n public PacketQueue Packets { get; private set; }\n public PacketQueue AudioPackets { get; private set; }\n public PacketQueue VideoPackets { get; private set; }\n public PacketQueue[] SubtitlesPackets\n { get; private set; }\n public PacketQueue DataPackets { get; private set; }\n public PacketQueue CurPackets { get; private set; }\n\n public bool UseAVSPackets { get; private set; }\n\n public PacketQueue GetPacketsPtr(StreamBase stream)\n {\n if (!UseAVSPackets)\n {\n return Packets;\n }\n\n switch (stream.Type)\n {\n case MediaType.Audio:\n return AudioPackets;\n case MediaType.Video:\n return VideoPackets;\n case MediaType.Subs:\n return SubtitlesPackets[SubtitlesSelectedHelper.CurIndex];\n default:\n return DataPackets;\n }\n }\n\n public ConcurrentQueue>>\n VideoPacketsReverse\n { get; private set; } = new ConcurrentQueue>>();\n\n public bool IsReversePlayback\n { get; private set; }\n\n public long TotalBytes { get; private set; } = 0;\n\n // Interrupt\n public Interrupter Interrupter { get; private set; }\n\n public ObservableCollection\n Chapters { get; private set; } = new ObservableCollection();\n public class Chapter\n {\n public long StartTime { get; set; }\n public long EndTime { get; set; }\n public string Title { get; set; }\n }\n\n public event EventHandler AudioLimit;\n bool audioBufferLimitFired;\n void OnAudioLimit()\n => Task.Run(() => AudioLimit?.Invoke(this, new EventArgs()));\n\n public event EventHandler TimedOut;\n internal void OnTimedOut()\n => Task.Run(() => TimedOut?.Invoke(this, new EventArgs()));\n #endregion\n\n #region Constructor / Declaration\n public AVPacket* packet;\n public AVFormatContext* fmtCtx;\n internal HLSContext* hlsCtx;\n\n long hlsPrevSeqNo = AV_NOPTS_VALUE; // Identifies the change of the m3u8 playlist (wraped)\n internal long hlsStartTime = AV_NOPTS_VALUE; // Calculation of first timestamp (lastPacketTs - hlsCurDuration)\n long hlsCurDuration; // Duration until the start of the current segment\n long lastSeekTime; // To set CurTime while no packets are available\n\n public object lockFmtCtx = new();\n internal bool allowReadInterrupts;\n\n /* Reverse Playback\n *\n * Video Packets Queue (FIFO) ConcurrentQueue>>\n * Video Packets Seek Stacks (FILO) ConcurrentStack>\n * Video Packets List Keyframe (List) List\n */\n\n long curReverseStopPts = AV_NOPTS_VALUE;\n long curReverseStopRequestedPts\n = AV_NOPTS_VALUE;\n long curReverseStartPts = AV_NOPTS_VALUE;\n List curReverseVideoPackets = new();\n ConcurrentStack>\n curReverseVideoStack = new();\n long curReverseSeekOffset;\n\n // Required for passing AV Options and HTTP Query params to the underlying contexts\n AVFormatContext_io_open ioopen;\n AVFormatContext_io_open ioopenDefault;\n AVDictionary* avoptCopy;\n Dictionary\n queryParams;\n byte[] queryCachedBytes;\n\n // for TEXT subtitles buffer\n byte* inputData;\n int inputDataSize;\n internal AVIOContext* avioCtx;\n\n int subNum => Config.config.Subtitles.Max;\n\n public Demuxer(DemuxerConfig config, MediaType type = MediaType.Video, int uniqueId = -1, bool useAVSPackets = true) : base(uniqueId)\n {\n Config = config;\n Type = type;\n UseAVSPackets = useAVSPackets;\n Interrupter = new Interrupter(this);\n CustomIOContext = new CustomIOContext(this);\n\n Packets = new PacketQueue(this);\n AudioPackets = new PacketQueue(this);\n VideoPackets = new PacketQueue(this);\n SubtitlesPackets = new PacketQueue[subNum];\n for (int i = 0; i < subNum; i++)\n {\n SubtitlesPackets[i] = new PacketQueue(this);\n }\n SubtitlesStreams = new SubtitlesStream[subNum];\n\n DataPackets = new PacketQueue(this);\n CurPackets = Packets; // Will be updated on stream switch in case of AVS\n\n string typeStr = Type == MediaType.Video ? \"Main\" : Type.ToString();\n threadName = $\"Demuxer: {typeStr,5}\";\n\n Utils.UIInvokeIfRequired(() =>\n {\n BindingOperations.EnableCollectionSynchronization(Programs, lockStreams);\n BindingOperations.EnableCollectionSynchronization(AudioStreams, lockStreams);\n BindingOperations.EnableCollectionSynchronization(VideoStreams, lockStreams);\n BindingOperations.EnableCollectionSynchronization(SubtitlesStreamsAll, lockStreams);\n BindingOperations.EnableCollectionSynchronization(DataStreams, lockStreams);\n\n BindingOperations.EnableCollectionSynchronization(Chapters, lockStreams);\n });\n\n ioopen = IOOpen;\n }\n #endregion\n\n #region Dispose / Dispose Packets\n public void DisposePackets()\n {\n if (UseAVSPackets)\n {\n AudioPackets.Clear();\n VideoPackets.Clear();\n for (int i = 0; i < subNum; i++)\n {\n SubtitlesPackets[i].Clear();\n }\n DataPackets.Clear();\n\n DisposePacketsReverse();\n }\n else\n Packets.Clear();\n\n hlsStartTime = AV_NOPTS_VALUE;\n }\n\n public void DisposePacketsReverse()\n {\n while (!VideoPacketsReverse.IsEmpty)\n {\n VideoPacketsReverse.TryDequeue(out var t1);\n while (!t1.IsEmpty)\n {\n t1.TryPop(out var t2);\n for (int i = 0; i < t2.Count; i++)\n {\n if (t2[i] == IntPtr.Zero) continue;\n AVPacket* packet = (AVPacket*)t2[i];\n av_packet_free(&packet);\n }\n }\n }\n\n while (!curReverseVideoStack.IsEmpty)\n {\n curReverseVideoStack.TryPop(out var t2);\n for (int i = 0; i < t2.Count; i++)\n {\n if (t2[i] == IntPtr.Zero) continue;\n AVPacket* packet = (AVPacket*)t2[i];\n av_packet_free(&packet);\n }\n }\n }\n public void Dispose()\n {\n if (Disposed)\n return;\n\n lock (lockActions)\n {\n if (Disposed)\n return;\n\n Stop();\n\n Url = null;\n hlsCtx = null;\n\n IsReversePlayback = false;\n curReverseStopPts = AV_NOPTS_VALUE;\n curReverseStartPts = AV_NOPTS_VALUE;\n hlsPrevSeqNo = AV_NOPTS_VALUE;\n lastSeekTime = 0;\n\n // Free Streams\n lock (lockStreams)\n {\n AudioStreams.Clear();\n VideoStreams.Clear();\n SubtitlesStreamsAll.Clear();\n DataStreams.Clear();\n Programs.Clear();\n\n Chapters.Clear();\n }\n EnabledStreams.Clear();\n AudioStream = null;\n VideoStream = null;\n for (int i = 0; i < subNum; i++)\n {\n SubtitlesStreams[i] = null;\n }\n DataStream = null;\n queryParams = null;\n queryCachedBytes = null;\n\n DisposePackets();\n\n if (fmtCtx != null)\n {\n Interrupter.CloseRequest();\n fixed (AVFormatContext** ptr = &fmtCtx) { avformat_close_input(ptr); fmtCtx = null; }\n }\n\n if (avoptCopy != null) fixed (AVDictionary** ptr = &avoptCopy) av_dict_free(ptr);\n if (packet != null) fixed (AVPacket** ptr = &packet) av_packet_free(ptr);\n\n CustomIOContext.Dispose();\n\n if (avioCtx != null)\n {\n av_free(avioCtx->buffer);\n fixed (AVIOContext** ptr = &avioCtx)\n {\n avio_context_free(ptr);\n }\n\n inputData = null;\n inputDataSize = 0;\n }\n\n TotalBytes = 0;\n Status = Status.Stopped;\n Disposed = true;\n\n Log.Info(\"Disposed\");\n }\n }\n #endregion\n\n #region Open / Seek / Run\n public string Open(string url) => Open(url, null);\n public string Open(Stream stream) => Open(null, stream);\n public string Open(string url, Stream stream)\n {\n bool gotLockActions = false;\n bool gotLockFmtCtx = false;\n string error = null;\n\n try\n {\n Monitor.Enter(lockActions,ref gotLockActions);\n Dispose();\n Monitor.Enter(lockFmtCtx, ref gotLockFmtCtx);\n Url = url;\n\n if (string.IsNullOrEmpty(url) && stream == null)\n return \"Invalid empty/null input\";\n\n Dictionary\n fmtOptExtra = null;\n AVInputFormat* inFmt = null;\n int ret = -1;\n\n Disposed = false;\n Status = Status.Opening;\n\n // Allocate / Prepare Format Context\n fmtCtx = avformat_alloc_context();\n if (Config.AllowInterrupts)\n fmtCtx->interrupt_callback.callback = Interrupter.interruptClbk;\n\n fmtCtx->flags |= (FmtFlags2)Config.FormatFlags;\n\n // Force Format (url as input and Config.FormatOpt for options)\n if (Config.ForceFormat != null)\n {\n inFmt = av_find_input_format(Config.ForceFormat);\n if (inFmt == null)\n return error = $\"[av_find_input_format] {Config.ForceFormat} not found\";\n }\n\n // Force Custom IO Stream Context (url should be null)\n if (stream != null)\n {\n CustomIOContext.Initialize(stream);\n stream.Seek(0, SeekOrigin.Begin);\n url = null;\n }\n\n /* Force Format with Url syntax to support format, url and options within the input url\n *\n * fmt://$format$[/]?$input$&$options$\n *\n * deprecate support for device://\n *\n * Examples:\n * See: https://ffmpeg.org/ffmpeg-devices.html for devices formats and options\n *\n * 1. fmt://gdigrab?title=Command Prompt&framerate=2\n * 2. fmt://gdigrab?desktop\n * 3. fmt://dshow?audio=Microphone (Relatek):video=Lenovo Camera\n * 4. fmt://rawvideo?C:\\root\\dev\\Flyleaf\\VideoSamples\\rawfile.raw&pixel_format=uyvy422&video_size=1920x1080&framerate=60\n *\n */\n else if (url.StartsWith(\"fmt://\") || url.StartsWith(\"device://\"))\n {\n string urlFromUrl = null;\n string fmtStr = \"\";\n int fmtStarts = url.IndexOf('/') + 2;\n int queryStarts = url.IndexOf('?');\n\n if (queryStarts == -1)\n fmtStr = url[fmtStarts..];\n else\n {\n fmtStr = url[fmtStarts..queryStarts];\n\n string query = url[(queryStarts + 1)..];\n int inputEnds = query.IndexOf('&');\n\n if (inputEnds == -1)\n urlFromUrl = query;\n else\n {\n urlFromUrl = query[..inputEnds];\n query = query[(inputEnds + 1)..];\n\n fmtOptExtra = Utils.ParseQueryString(query);\n }\n }\n\n url = urlFromUrl;\n fmtStr = fmtStr.Replace(\"/\", \"\");\n inFmt = av_find_input_format(fmtStr);\n if (inFmt == null)\n return error = $\"[av_find_input_format] {fmtStr} not found\";\n }\n else if (url.StartsWith(\"srt://\"))\n {\n ReadOnlySpan urlSpan = url.AsSpan();\n int queryPos = urlSpan.IndexOf('?');\n\n if (queryPos != -1)\n {\n fmtOptExtra = Utils.ParseQueryString(urlSpan.Slice(queryPos + 1));\n url = urlSpan[..queryPos].ToString();\n }\n }\n\n if (Config.FormatOptToUnderlying && url != null && (url.StartsWith(\"http://\") || url.StartsWith(\"https://\")))\n {\n queryParams = [];\n if (Config.DefaultHTTPQueryToUnderlying)\n {\n int queryStarts = url.IndexOf('?');\n if (queryStarts != -1)\n {\n var qp = Utils.ParseQueryString(url.AsSpan()[(queryStarts + 1)..]);\n foreach (var kv in qp)\n queryParams[kv.Key] = kv.Value;\n }\n }\n\n foreach (var kv in Config.ExtraHTTPQueryParamsToUnderlying)\n queryParams[kv.Key] = kv.Value;\n\n if (queryParams.Count > 0)\n {\n var queryCachedStr = \"?\";\n foreach (var kv in queryParams)\n queryCachedStr += kv.Value == null ? $\"{kv.Key}&\" : $\"{kv.Key}={kv.Value}&\";\n\n queryCachedStr = queryCachedStr[..^1];\n queryCachedBytes = Encoding.UTF8.GetBytes(queryCachedStr);\n }\n else\n queryParams = null;\n }\n\n if (Type == MediaType.Subs &&\n Utils.ExtensionsSubtitlesText.Contains(Utils.GetUrlExtention(url)) &&\n File.Exists(url))\n {\n // If the files can be read with text subtitles, load them all into memory and convert them to UTF8.\n // Because ffmpeg expects UTF8 text.\n try\n {\n FileInfo file = new(url);\n if (file.Length >= 10 * 1024 * 1024)\n {\n throw new InvalidOperationException($\"TEXT subtitle is too big (>=10MB) to load: {file.Length}\");\n }\n\n // Detects character encoding, reads text and converts to UTF8\n Encoding encoding = Encoding.UTF8;\n\n Encoding detected = TextEncodings.DetectEncoding(url);\n if (detected != null)\n {\n encoding = detected;\n }\n\n string content = File.ReadAllText(url, encoding);\n byte[] contentBytes = Encoding.UTF8.GetBytes(content);\n\n inputDataSize = contentBytes.Length;\n inputData = (byte*)av_malloc((nuint)inputDataSize);\n\n Span src = new(contentBytes);\n Span dst = new(inputData, inputDataSize);\n src.CopyTo(dst);\n\n avioCtx = avio_alloc_context(inputData, inputDataSize, 0, null, null, null, null);\n if (avioCtx == null)\n {\n throw new InvalidOperationException(\"avio_alloc_context\");\n }\n\n // Pass to ffmpeg by on-memory\n fmtCtx->pb = avioCtx;\n fmtCtx->flags |= FmtFlags2.CustomIo;\n }\n catch (Exception ex)\n {\n Log.Warn($\"Could not load text subtitles to memory: {ex.Message}\");\n }\n }\n\n // Some devices required to be opened from a UI or STA thread | after 20-40 sec. of demuxing -> [gdigrab @ 0000019affe3f2c0] Failed to capture image (error 6) or (error 8)\n bool isDevice = inFmt != null && inFmt->priv_class != null && (\n inFmt->priv_class->category.HasFlag(AVClassCategory.DeviceAudioInput) ||\n inFmt->priv_class->category.HasFlag(AVClassCategory.DeviceAudioOutput) ||\n inFmt->priv_class->category.HasFlag(AVClassCategory.DeviceInput) ||\n inFmt->priv_class->category.HasFlag(AVClassCategory.DeviceOutput) ||\n inFmt->priv_class->category.HasFlag(AVClassCategory.DeviceVideoInput) ||\n inFmt->priv_class->category.HasFlag(AVClassCategory.DeviceVideoOutput)\n );\n\n // Open Format Context\n allowReadInterrupts = true; // allow Open interrupts always\n Interrupter.OpenRequest();\n\n // Nesting the io_open (to pass the options to the underlying formats)\n if (Config.FormatOptToUnderlying)\n {\n ioopenDefault = (AVFormatContext_io_open)Marshal.GetDelegateForFunctionPointer(fmtCtx->io_open.Pointer, typeof(AVFormatContext_io_open));\n fmtCtx->io_open = ioopen;\n }\n\n if (isDevice)\n {\n string fmtName = Utils.BytePtrToStringUTF8(inFmt->name);\n\n if (fmtName == \"decklink\") // avoid using UI thread for decklink (STA should be enough for CoInitialize/CoCreateInstance)\n Utils.STAInvoke(() => OpenFormat(url, inFmt, fmtOptExtra, out ret));\n else\n Utils.UIInvoke(() => OpenFormat(url, inFmt, fmtOptExtra, out ret));\n }\n else\n OpenFormat(url, inFmt, fmtOptExtra, out ret);\n\n if ((ret == AVERROR_EXIT && !Interrupter.Timedout) || Status != Status.Opening || Interrupter.ForceInterrupt == 1) { if (ret < 0) fmtCtx = null; return error = \"Cancelled\"; }\n if (ret < 0) { fmtCtx = null; return error = Interrupter.Timedout ? \"[avformat_open_input] Timeout\" : $\"[avformat_open_input] {FFmpegEngine.ErrorCodeToMsg(ret)} ({ret})\"; }\n\n // Find Streams Info\n if (Config.AllowFindStreamInfo)\n {\n /* For some reason HdmvPgsSubtitle requires more analysis (even when it has already all the information)\n *\n * Increases delay & memory and it will not free it after analysis (fmtctx internal buffer)\n * - avformat_flush will release it but messes with the initial seek position (possible seek to start to force it releasing it but still we have the delay)\n *\n * Consider\n * - DVD/Blu-ray/mpegts only? (possible HLS -> mpegts?*)\n * - Re-open in case of \"Consider increasing the value for the 'analyzeduration'\" (catch from ffmpeg log)\n *\n * https://github.com/SuRGeoNix/Flyleaf/issues/502\n */\n\n if (Utils.BytePtrToStringUTF8(fmtCtx->iformat->name) == \"mpegts\")\n {\n bool requiresMoreAnalyse = false;\n\n for (int i = 0; i < fmtCtx->nb_streams; i++)\n if (fmtCtx->streams[i]->codecpar->codec_id == AVCodecID.HdmvPgsSubtitle ||\n fmtCtx->streams[i]->codecpar->codec_id == AVCodecID.DvdSubtitle\n )\n { requiresMoreAnalyse = true; break; }\n\n if (requiresMoreAnalyse)\n {\n fmtCtx->probesize = Math.Max(fmtCtx->probesize, 5000 * (long)1024 * 1024); // Bytes\n fmtCtx->max_analyze_duration = Math.Max(fmtCtx->max_analyze_duration, 1000 * (long)1000 * 1000); // Mcs\n }\n }\n\n ret = avformat_find_stream_info(fmtCtx, null);\n if (ret == AVERROR_EXIT || Status != Status.Opening || Interrupter.ForceInterrupt == 1) return error = \"Cancelled\";\n if (ret < 0) return error = $\"[avformat_find_stream_info] {FFmpegEngine.ErrorCodeToMsg(ret)} ({ret})\";\n }\n\n // Prevent Multiple Immediate exit requested on eof (maybe should not use avio_feof() to test for the end)\n if (fmtCtx->pb != null)\n fmtCtx->pb->eof_reached = 0;\n\n bool hasVideo = FillInfo();\n\n if (Type == MediaType.Video && !hasVideo && AudioStreams.Count == 0)\n return error = $\"No audio / video stream found\";\n else if (Type == MediaType.Audio && AudioStreams.Count == 0)\n return error = $\"No audio stream found\";\n else if (Type == MediaType.Subs && SubtitlesStreamsAll.Count == 0)\n return error = $\"No subtitles stream found\";\n\n packet = av_packet_alloc();\n Status = Status.Stopped;\n allowReadInterrupts = Config.AllowReadInterrupts && !Config.ExcludeInterruptFmts.Contains(Name);\n\n return error = null;\n }\n catch (Exception ex)\n {\n return error = $\"Unknown: {ex.Message}\";\n }\n finally\n {\n if (error != null)\n Dispose();\n\n if (gotLockFmtCtx) Monitor.Exit(lockFmtCtx);\n if (gotLockActions) Monitor.Exit(lockActions);\n }\n }\n\n int IOOpen(AVFormatContext* s, AVIOContext** pb, byte* urlb, IOFlags flags, AVDictionary** avFmtOpts)\n {\n int ret;\n AVDictionaryEntry *t = null;\n\n if (avoptCopy != null)\n {\n while ((t = av_dict_get(avoptCopy, \"\", t, DictReadFlags.IgnoreSuffix)) != null)\n _ = av_dict_set(avFmtOpts, Utils.BytePtrToStringUTF8(t->key), Utils.BytePtrToStringUTF8(t->value), 0);\n }\n\n if (queryParams == null)\n ret = ioopenDefault(s, pb, urlb, flags, avFmtOpts);\n else\n {\n int urlLength = 0;\n int queryPos = -1;\n while (urlb[urlLength] != '\\0')\n {\n if (urlb[urlLength] == '?' && queryPos == -1 && urlb[urlLength + 1] != '\\0')\n queryPos = urlLength;\n\n urlLength++;\n }\n\n // urlNoQuery + ? + queryCachedBytes\n if (queryPos == -1)\n {\n ReadOnlySpan urlNoQuery = new(urlb, urlLength);\n int newLength = urlLength + queryCachedBytes.Length + 1;\n Span urlSpan = newLength < 1024 ? stackalloc byte[newLength] : new byte[newLength];// new(urlPtr, newLength);\n urlNoQuery.CopyTo(urlSpan);\n queryCachedBytes.AsSpan().CopyTo(urlSpan[urlNoQuery.Length..]);\n\n fixed(byte* urlPtr = urlSpan)\n ret = ioopenDefault(s, pb, urlPtr, flags, avFmtOpts);\n }\n\n // urlNoQuery + ? + existingParams/queryParams combined\n else\n {\n ReadOnlySpan urlNoQuery = new(urlb, queryPos);\n ReadOnlySpan urlQuery = new(urlb + queryPos + 1, urlLength - queryPos - 1);\n var qps = Utils.ParseQueryString(Encoding.UTF8.GetString(urlQuery));\n\n foreach (var kv in queryParams)\n if (!qps.ContainsKey(kv.Key))\n qps[kv.Key] = kv.Value;\n\n string newQuery = \"?\";\n foreach (var kv in qps)\n newQuery += kv.Value == null ? $\"{kv.Key}&\" : $\"{kv.Key}={kv.Value}&\";\n\n int newLength = urlNoQuery.Length + newQuery.Length + 1;\n Span urlSpan = newLength < 1024 ? stackalloc byte[newLength] : new byte[newLength];// new(urlPtr, newLength);\n urlNoQuery.CopyTo(urlSpan);\n Encoding.UTF8.GetBytes(newQuery).AsSpan().CopyTo(urlSpan[urlNoQuery.Length..]);\n\n fixed(byte* urlPtr = urlSpan)\n ret = ioopenDefault(s, pb, urlPtr, flags, avFmtOpts);\n }\n }\n\n return ret;\n }\n\n private void OpenFormat(string url, AVInputFormat* inFmt, Dictionary opt, out int ret)\n {\n AVDictionary* avopt = null;\n var curOpt = Type == MediaType.Video ? Config.FormatOpt : (Type == MediaType.Audio ? Config.AudioFormatOpt : Config.SubtitlesFormatOpt);\n\n if (curOpt != null)\n foreach (var optKV in curOpt)\n av_dict_set(&avopt, optKV.Key, optKV.Value, 0);\n\n if (opt != null)\n foreach (var optKV in opt)\n av_dict_set(&avopt, optKV.Key, optKV.Value, 0);\n\n if (Config.FormatOptToUnderlying)\n fixed(AVDictionary** ptr = &avoptCopy)\n av_dict_copy(ptr, avopt, 0);\n\n fixed(AVFormatContext** fmtCtxPtr = &fmtCtx)\n ret = avformat_open_input(fmtCtxPtr, url, inFmt, avopt == null ? null : &avopt);\n\n if (avopt != null)\n {\n if (ret >= 0)\n {\n AVDictionaryEntry *t = null;\n\n while ((t = av_dict_get(avopt, \"\", t, DictReadFlags.IgnoreSuffix)) != null)\n Log.Debug($\"Ignoring format option {Utils.BytePtrToStringUTF8(t->key)}\");\n }\n\n av_dict_free(&avopt);\n }\n }\n private bool FillInfo()\n {\n Name = Utils.BytePtrToStringUTF8(fmtCtx->iformat->name);\n LongName = Utils.BytePtrToStringUTF8(fmtCtx->iformat->long_name);\n Extensions = Utils.BytePtrToStringUTF8(fmtCtx->iformat->extensions);\n\n StartTime = fmtCtx->start_time != AV_NOPTS_VALUE ? fmtCtx->start_time * 10 : 0;\n StartRealTime = fmtCtx->start_time_realtime != AV_NOPTS_VALUE ? fmtCtx->start_time_realtime * 10 : 0;\n Duration = fmtCtx->duration > 0 ? fmtCtx->duration * 10 : 0;\n\n // TBR: Possible we can get Apple HTTP Live Streaming/hls with HLSPlaylist->finished with Duration != 0\n if (Engine.Config.FFmpegHLSLiveSeek && Duration == 0 && Name == \"hls\" && Environment.Is64BitProcess) // HLSContext cast is not safe\n {\n hlsCtx = (HLSContext*) fmtCtx->priv_data;\n StartTime = 0;\n //UpdateHLSTime(); Maybe with default 0 playlist\n }\n\n if (fmtCtx->nb_streams == 1 && fmtCtx->streams[0]->codecpar->codec_type == AVMediaType.Subtitle) // External Streams (mainly for .sub will have as start time the first subs timestamp)\n StartTime = 0;\n\n IsLive = Duration == 0 || hlsCtx != null;\n\n bool hasVideo = false;\n AVStreamToStream = new Dictionary();\n\n Metadata.Clear();\n AVDictionaryEntry* b = null;\n while (true)\n {\n b = av_dict_get(fmtCtx->metadata, \"\", b, DictReadFlags.IgnoreSuffix);\n if (b == null) break;\n Metadata.Add(Utils.BytePtrToStringUTF8(b->key), Utils.BytePtrToStringUTF8(b->value));\n }\n\n Chapters.Clear();\n string dump = \"\";\n for (int i=0; inb_chapters; i++)\n {\n var chp = fmtCtx->chapters[i];\n double tb = av_q2d(chp->time_base) * 10000.0 * 1000.0;\n string title = \"\";\n\n b = null;\n while (true)\n {\n b = av_dict_get(chp->metadata, \"\", b, DictReadFlags.IgnoreSuffix);\n if (b == null) break;\n if (Utils.BytePtrToStringUTF8(b->key).ToLower() == \"title\")\n title = Utils.BytePtrToStringUTF8(b->value);\n }\n\n if (CanDebug)\n dump += $\"[Chapter {i+1,-2}] {Utils.TicksToTime((long)(chp->start * tb) - StartTime)} - {Utils.TicksToTime((long)(chp->end * tb) - StartTime)} | {title}\\r\\n\";\n\n Chapters.Add(new Chapter()\n {\n StartTime = (long)((chp->start * tb) - StartTime),\n EndTime = (long)((chp->end * tb) - StartTime),\n Title = title\n });\n }\n\n if (CanDebug && dump != \"\") Log.Debug($\"Chapters\\r\\n\\r\\n{dump}\");\n\n bool audioHasEng = false;\n bool subsHasEng = false;\n\n lock (lockStreams)\n {\n for (int i=0; inb_streams; i++)\n {\n fmtCtx->streams[i]->discard = AVDiscard.All;\n\n switch (fmtCtx->streams[i]->codecpar->codec_type)\n {\n case AVMediaType.Audio:\n AudioStreams.Add(new AudioStream(this, fmtCtx->streams[i]));\n AVStreamToStream.Add(fmtCtx->streams[i]->index, AudioStreams[^1]);\n audioHasEng = AudioStreams[^1].Language == Language.English;\n\n break;\n\n case AVMediaType.Video:\n if ((fmtCtx->streams[i]->disposition & DispositionFlags.AttachedPic) != 0)\n { Log.Info($\"Excluding image stream #{i}\"); continue; }\n\n // TBR: When AllowFindStreamInfo = false we can get valid pixel format during decoding (in case of remuxing only this might crash, possible check if usedecoders?)\n if (((AVPixelFormat)fmtCtx->streams[i]->codecpar->format) == AVPixelFormat.None && Config.AllowFindStreamInfo)\n {\n Log.Info($\"Excluding invalid video stream #{i}\");\n continue;\n }\n VideoStreams.Add(new VideoStream(this, fmtCtx->streams[i]));\n AVStreamToStream.Add(fmtCtx->streams[i]->index, VideoStreams[^1]);\n hasVideo |= !Config.AllowFindStreamInfo || VideoStreams[^1].PixelFormat != AVPixelFormat.None;\n\n break;\n\n case AVMediaType.Subtitle:\n SubtitlesStreamsAll.Add(new SubtitlesStream(this, fmtCtx->streams[i]));\n AVStreamToStream.Add(fmtCtx->streams[i]->index, SubtitlesStreamsAll[^1]);\n subsHasEng = SubtitlesStreamsAll[^1].Language == Language.English;\n break;\n\n case AVMediaType.Data:\n DataStreams.Add(new DataStream(this, fmtCtx->streams[i]));\n AVStreamToStream.Add(fmtCtx->streams[i]->index, DataStreams[^1]);\n\n break;\n\n default:\n Log.Info($\"#[Unknown #{i}] {fmtCtx->streams[i]->codecpar->codec_type}\");\n break;\n }\n }\n\n if (!audioHasEng)\n for (int i=0; inb_programs > 0)\n {\n for (int i = 0; i < fmtCtx->nb_programs; i++)\n {\n fmtCtx->programs[i]->discard = AVDiscard.All;\n Program program = new(fmtCtx->programs[i], this);\n Programs.Add(program);\n }\n }\n\n Extension = GetValidExtension();\n }\n\n PrintDump();\n return hasVideo;\n }\n\n public int SeekInQueue(long ticks, bool forward = false)\n {\n lock (lockActions)\n {\n if (Disposed) return -1;\n\n /* Seek within current bufffered queue\n *\n * 10 seconds because of video keyframe distances or 1 seconds for other (can be fixed also with CurTime+X seek instead of timestamps)\n * For subtitles it should keep (prev packet) the last presented as it can have a lot of distance with CurTime (cur packet)\n * It doesn't work for HLS live streams\n * It doesn't work for decoders buffered queue (which is small only subs might be an issue if we have large decoder queue)\n */\n\n long startTime = StartTime;\n\n if (hlsCtx != null)\n {\n ticks += hlsStartTime - (hlsCtx->first_timestamp * 10);\n startTime = hlsStartTime;\n }\n\n if (ticks + (VideoStream != null && forward ? (10000 * 10000) : 1000 * 10000) > CurTime + startTime && ticks < CurTime + startTime + BufferedDuration)\n {\n bool found = false;\n while (VideoPackets.Count > 0)\n {\n var packet = VideoPackets.Peek();\n if (packet->pts != AV_NOPTS_VALUE && ticks < packet->pts * VideoStream.Timebase && (packet->flags & PktFlags.Key) != 0)\n {\n found = true;\n ticks = (long) (packet->pts * VideoStream.Timebase);\n\n break;\n }\n\n VideoPackets.Dequeue();\n av_packet_free(&packet);\n }\n\n while (AudioPackets.Count > 0)\n {\n var packet = AudioPackets.Peek();\n if (packet->pts != AV_NOPTS_VALUE && (packet->pts + packet->duration) * AudioStream.Timebase >= ticks)\n {\n if (Type == MediaType.Audio || VideoStream == null)\n found = true;\n\n break;\n }\n\n AudioPackets.Dequeue();\n av_packet_free(&packet);\n }\n\n for (int i = 0; i < subNum; i++)\n {\n while (SubtitlesPackets[i].Count > 0)\n {\n var packet = SubtitlesPackets[i].Peek();\n if (packet->pts != AV_NOPTS_VALUE && ticks < (packet->pts + packet->duration) * SubtitlesStreams[i].Timebase)\n {\n if (Type == MediaType.Subs)\n {\n found = true;\n }\n\n break;\n }\n\n SubtitlesPackets[i].Dequeue();\n av_packet_free(&packet);\n }\n }\n\n while (DataPackets.Count > 0)\n {\n var packet = DataPackets.Peek();\n if (packet->pts != AV_NOPTS_VALUE && ticks < (packet->pts + packet->duration) * DataStream.Timebase)\n {\n if (Type == MediaType.Data)\n found = true;\n\n break;\n }\n\n DataPackets.Dequeue();\n av_packet_free(&packet);\n }\n\n if (found)\n {\n Log.Debug(\"[Seek] Found in Queue\");\n return 0;\n }\n }\n\n return -1;\n }\n }\n public int Seek(long ticks, bool forward = false)\n {\n /* Current Issues\n *\n * HEVC/MPEG-TS: Fails to seek to keyframe https://blog.csdn.net/Annie_heyeqq/article/details/113649501 | https://trac.ffmpeg.org/ticket/9412\n * AVSEEK_FLAG_BACKWARD will not work on .dav even if it returns 0 (it will work after it fills the index table)\n * Strange delay (could be 200ms!) after seek on HEVC/yuv420p10le (10-bits) while trying to Present on swapchain (possible recreates texturearray?)\n * AVFMT_NOTIMESTAMPS unknown duration (can be calculated?) should perform byte seek instead (percentage based on total pb size)\n */\n\n lock (lockActions)\n {\n if (Disposed) return -1;\n\n int ret;\n long savedPbPos = 0;\n\n Interrupter.ForceInterrupt = 1;\n lock (lockFmtCtx)\n {\n Interrupter.ForceInterrupt = 0;\n\n // Flush required because of the interrupt\n if (fmtCtx->pb != null)\n {\n savedPbPos = fmtCtx->pb->pos;\n avio_flush(fmtCtx->pb);\n fmtCtx->pb->error = 0; // AVERROR_EXIT will stay forever and will cause the demuxer to go in Status Stopped instead of Ended (after interrupted seeks)\n fmtCtx->pb->eof_reached = 0;\n }\n avformat_flush(fmtCtx);\n\n // Forces seekable HLS\n if (hlsCtx != null)\n fmtCtx->ctx_flags &= ~FmtCtxFlags.Unseekable;\n\n Interrupter.SeekRequest();\n if (VideoStream != null)\n {\n if (CanDebug) Log.Debug($\"[Seek({(forward ? \"->\" : \"<-\")})] Requested at {new TimeSpan(ticks)}\");\n\n // TODO: After proper calculation of Duration\n //if (VideoStream.FixTimestamps && Duration > 0)\n //ret = av_seek_frame(fmtCtx, -1, (long)((ticks/(double)Duration) * avio_size(fmtCtx->pb)), AVSEEK_FLAG_BYTE);\n //else\n ret = ticks == StartTime // we should also call this if we seek anywhere within the first Gop\n ? avformat_seek_file(fmtCtx, -1, 0, 0, 0, 0)\n : av_seek_frame(fmtCtx, -1, ticks / 10, forward ? SeekFlags.Frame : SeekFlags.Backward);\n\n curReverseStopPts = AV_NOPTS_VALUE;\n curReverseStartPts= AV_NOPTS_VALUE;\n }\n else\n {\n if (CanDebug) Log.Debug($\"[Seek({(forward ? \"->\" : \"<-\")})] Requested at {new TimeSpan(ticks)} | ANY\");\n ret = forward ?\n avformat_seek_file(fmtCtx, -1, ticks / 10 , ticks / 10, long.MaxValue , SeekFlags.Any):\n avformat_seek_file(fmtCtx, -1, long.MinValue, ticks / 10, ticks / 10 , SeekFlags.Any);\n }\n\n if (ret < 0)\n {\n if (hlsCtx != null) fmtCtx->ctx_flags &= ~FmtCtxFlags.Unseekable;\n Log.Info($\"Seek failed 1/2 (retrying) {FFmpegEngine.ErrorCodeToMsg(ret)} ({ret})\");\n\n ret = VideoStream != null\n ? av_seek_frame(fmtCtx, -1, ticks / 10, forward ? SeekFlags.Backward : SeekFlags.Frame)\n : forward ?\n avformat_seek_file(fmtCtx, -1, long.MinValue, ticks / 10, ticks / 10 , SeekFlags.Any):\n avformat_seek_file(fmtCtx, -1, ticks / 10 , ticks / 10, long.MaxValue , SeekFlags.Any);\n\n if (ret < 0)\n {\n Log.Warn($\"Seek failed 2/2 {FFmpegEngine.ErrorCodeToMsg(ret)} ({ret})\");\n\n // Flush required because of seek failure (reset pb to last pos otherwise will be eof) - Mainly for NoTimestamps (TODO: byte seek/calc dur/percentage)\n if (fmtCtx->pb != null)\n {\n avio_flush(fmtCtx->pb);\n fmtCtx->pb->error = 0;\n fmtCtx->pb->eof_reached = 0;\n avio_seek(fmtCtx->pb, savedPbPos, 0);\n }\n avformat_flush(fmtCtx);\n }\n else\n lastSeekTime = ticks - StartTime - (hlsCtx != null ? hlsStartTime : 0);\n }\n else\n lastSeekTime = ticks - StartTime - (hlsCtx != null ? hlsStartTime : 0);\n\n DisposePackets();\n lock (lockStatus) if (Status == Status.Ended) Status = Status.Stopped;\n }\n\n return ret; // >= 0 for success\n }\n }\n\n protected override void RunInternal()\n {\n if (IsReversePlayback)\n {\n RunInternalReverse();\n return;\n }\n\n int ret = 0;\n int allowedErrors = Config.MaxErrors;\n bool gotAVERROR_EXIT = false;\n audioBufferLimitFired = false;\n long lastVideoPacketPts = 0;\n\n do\n {\n // Wait until not QueueFull\n if (BufferedDuration > Config.BufferDuration || (Config.BufferPackets != 0 && CurPackets.Count > Config.BufferPackets))\n {\n lock (lockStatus)\n if (Status == Status.Running) Status = Status.QueueFull;\n\n while (!PauseOnQueueFull && (BufferedDuration > Config.BufferDuration || (Config.BufferPackets != 0 && CurPackets.Count > Config.BufferPackets)) && Status == Status.QueueFull)\n Thread.Sleep(20);\n\n lock (lockStatus)\n {\n if (PauseOnQueueFull) { PauseOnQueueFull = false; Status = Status.Pausing; }\n if (Status != Status.QueueFull) break;\n Status = Status.Running;\n }\n }\n\n // Wait possible someone asks for lockFmtCtx\n else if (gotAVERROR_EXIT)\n {\n gotAVERROR_EXIT = false;\n Thread.Sleep(5);\n }\n\n // Demux Packet\n lock (lockFmtCtx)\n {\n Interrupter.ReadRequest();\n ret = av_read_frame(fmtCtx, packet);\n if (Interrupter.ForceInterrupt != 0)\n {\n av_packet_unref(packet);\n gotAVERROR_EXIT = true;\n continue;\n }\n\n // Possible check if interrupt/timeout and we dont seek to reset the backend pb->pos = 0?\n if (ret != 0)\n {\n av_packet_unref(packet);\n\n if (ret == AVERROR_EOF)\n {\n Status = Status.Ended;\n break;\n }\n\n if (Interrupter.Timedout)\n {\n Status = Status.Stopping;\n break;\n }\n\n allowedErrors--;\n if (CanWarn) Log.Warn($\"{FFmpegEngine.ErrorCodeToMsg(ret)} ({ret})\");\n\n if (allowedErrors == 0) { Log.Error(\"Too many errors!\"); Status = Status.Stopping; break; }\n\n gotAVERROR_EXIT = true;\n continue;\n }\n\n TotalBytes += packet->size;\n\n // Skip Disabled Streams | TODO: It's possible that the streams will changed (add/remove or even update/change of codecs)\n if (!EnabledStreams.Contains(packet->stream_index)) { av_packet_unref(packet); continue; }\n\n if (IsHLSLive)\n UpdateHLSTime();\n\n if (CanTrace)\n {\n var stream = AVStreamToStream[packet->stream_index];\n long dts = packet->dts == AV_NOPTS_VALUE ? -1 : (long)(packet->dts * stream.Timebase);\n long pts = packet->pts == AV_NOPTS_VALUE ? -1 : (long)(packet->pts * stream.Timebase);\n Log.Trace($\"[{stream.Type}] DTS: {(dts == -1 ? \"-\" : Utils.TicksToTime(dts))} PTS: {(pts == -1 ? \"-\" : Utils.TicksToTime(pts))} | FLPTS: {(pts == -1 ? \"-\" : Utils.TicksToTime(pts - StartTime))} | CurTime: {Utils.TicksToTime(CurTime)} | Buffered: {Utils.TicksToTime(BufferedDuration)}\");\n }\n\n // Enqueue Packet (AVS Queue or Single Queue)\n if (UseAVSPackets)\n {\n switch (fmtCtx->streams[packet->stream_index]->codecpar->codec_type)\n {\n case AVMediaType.Audio:\n //Log($\"Audio => {Utils.TicksToTime((long)(packet->pts * AudioStream.Timebase))} | {Utils.TicksToTime(CurTime)}\");\n\n // Handles A/V de-sync and ffmpeg bug with 2^33 timestamps wrapping\n if (Config.MaxAudioPackets != 0 && AudioPackets.Count > Config.MaxAudioPackets)\n {\n av_packet_unref(packet);\n packet = av_packet_alloc();\n\n if (!audioBufferLimitFired)\n {\n audioBufferLimitFired = true;\n OnAudioLimit();\n }\n\n break;\n }\n\n AudioPackets.Enqueue(packet);\n packet = av_packet_alloc();\n\n break;\n\n case AVMediaType.Video:\n //Log($\"Video => {Utils.TicksToTime((long)(packet->pts * VideoStream.Timebase))} | {Utils.TicksToTime(CurTime)}\");\n lastVideoPacketPts = packet->pts;\n VideoPackets.Enqueue(packet);\n packet = av_packet_alloc();\n\n break;\n\n case AVMediaType.Subtitle:\n for (int i = 0; i < subNum; i++)\n {\n // Clone packets to support simultaneous display of the same subtitle\n if (packet->stream_index == SubtitlesStreams[i]?.StreamIndex)\n {\n SubtitlesPackets[i].Enqueue(av_packet_clone(packet));\n }\n }\n\n // cloned, so free packet\n av_packet_unref(packet);\n\n break;\n\n case AVMediaType.Data:\n // Some data streams only have nopts, set pts to last video packet pts\n if (packet->pts == AV_NOPTS_VALUE)\n packet->pts = lastVideoPacketPts;\n DataPackets.Enqueue(packet);\n packet = av_packet_alloc();\n\n break;\n\n default:\n av_packet_unref(packet);\n break;\n }\n }\n else\n {\n Packets.Enqueue(packet);\n packet = av_packet_alloc();\n }\n }\n } while (Status == Status.Running);\n }\n private void RunInternalReverse()\n {\n int ret = 0;\n int allowedErrors = Config.MaxErrors;\n bool gotAVERROR_EXIT = false;\n\n // To demux further for buffering (related to BufferDuration)\n int maxQueueSize = 2;\n curReverseSeekOffset = av_rescale_q(3 * 1000 * 10000 / 10, Engine.FFmpeg.AV_TIMEBASE_Q, VideoStream.AVStream->time_base);\n\n do\n {\n // Wait until not QueueFull\n if (VideoPacketsReverse.Count > maxQueueSize)\n {\n lock (lockStatus)\n if (Status == Status.Running) Status = Status.QueueFull;\n\n while (!PauseOnQueueFull && VideoPacketsReverse.Count > maxQueueSize && Status == Status.QueueFull) { Thread.Sleep(20); }\n\n lock (lockStatus)\n {\n if (PauseOnQueueFull) { PauseOnQueueFull = false; Status = Status.Pausing; }\n if (Status != Status.QueueFull) break;\n Status = Status.Running;\n }\n }\n\n // Wait possible someone asks for lockFmtCtx\n else if (gotAVERROR_EXIT)\n {\n gotAVERROR_EXIT = false;\n Thread.Sleep(5);\n }\n\n // Demux Packet\n lock (lockFmtCtx)\n {\n Interrupter.ReadRequest();\n ret = av_read_frame(fmtCtx, packet);\n if (Interrupter.ForceInterrupt != 0)\n {\n av_packet_unref(packet); gotAVERROR_EXIT = true;\n continue;\n }\n\n // Possible check if interrupt/timeout and we dont seek to reset the backend pb->pos = 0?\n if (ret != 0)\n {\n av_packet_unref(packet);\n\n if (ret == AVERROR_EOF)\n {\n if (curReverseVideoPackets.Count > 0)\n {\n var drainPacket = av_packet_alloc();\n drainPacket->data = null;\n drainPacket->size = 0;\n curReverseVideoPackets.Add((IntPtr)drainPacket);\n curReverseVideoStack.Push(curReverseVideoPackets);\n curReverseVideoPackets = new List();\n }\n\n if (!curReverseVideoStack.IsEmpty)\n {\n VideoPacketsReverse.Enqueue(curReverseVideoStack);\n curReverseVideoStack = new ConcurrentStack>();\n }\n\n if (curReverseStartPts != AV_NOPTS_VALUE && curReverseStartPts <= VideoStream.StartTimePts)\n {\n Status = Status.Ended;\n break;\n }\n\n //Log($\"[][][SEEK END] {curReverseStartPts} | {Utils.TicksToTime((long) (curReverseStartPts * VideoStream.Timebase))}\");\n Interrupter.SeekRequest();\n ret = av_seek_frame(fmtCtx, VideoStream.StreamIndex, Math.Max(curReverseStartPts - curReverseSeekOffset, VideoStream.StartTimePts), SeekFlags.Backward);\n\n if (ret != 0)\n {\n Status = Status.Stopping;\n break;\n }\n\n curReverseStopPts = curReverseStartPts;\n curReverseStartPts = AV_NOPTS_VALUE;\n continue;\n }\n\n allowedErrors--;\n if (CanWarn) Log.Warn($\"{ FFmpegEngine.ErrorCodeToMsg(ret)} ({ret})\");\n\n if (allowedErrors == 0) { Log.Error(\"Too many errors!\"); Status = Status.Stopping; break; }\n\n gotAVERROR_EXIT = true;\n continue;\n }\n\n if (VideoStream.StreamIndex != packet->stream_index) { av_packet_unref(packet); continue; }\n\n if ((packet->flags & PktFlags.Key) != 0)\n {\n if (curReverseStartPts == AV_NOPTS_VALUE)\n curReverseStartPts = packet->pts;\n\n if (curReverseVideoPackets.Count > 0)\n {\n var drainPacket = av_packet_alloc();\n drainPacket->data = null;\n drainPacket->size = 0;\n curReverseVideoPackets.Add((IntPtr)drainPacket);\n curReverseVideoStack.Push(curReverseVideoPackets);\n curReverseVideoPackets = new List();\n }\n }\n\n if (packet->pts != AV_NOPTS_VALUE && (\n (curReverseStopRequestedPts != AV_NOPTS_VALUE && curReverseStopRequestedPts <= packet->pts) ||\n (curReverseStopPts == AV_NOPTS_VALUE && (packet->flags & PktFlags.Key) != 0 && packet->pts != curReverseStartPts) ||\n (packet->pts == curReverseStopPts)\n ))\n {\n if (curReverseStartPts == AV_NOPTS_VALUE || curReverseStopPts == curReverseStartPts)\n {\n curReverseSeekOffset *= 2;\n if (curReverseStartPts == AV_NOPTS_VALUE) curReverseStartPts = curReverseStopPts;\n if (curReverseStartPts == AV_NOPTS_VALUE) curReverseStartPts = curReverseStopRequestedPts;\n }\n\n curReverseStopRequestedPts = AV_NOPTS_VALUE;\n\n if ((packet->flags & PktFlags.Key) == 0 && curReverseVideoPackets.Count > 0)\n {\n var drainPacket = av_packet_alloc();\n drainPacket->data = null;\n drainPacket->size = 0;\n curReverseVideoPackets.Add((IntPtr)drainPacket);\n curReverseVideoStack.Push(curReverseVideoPackets);\n curReverseVideoPackets = new List();\n }\n\n if (!curReverseVideoStack.IsEmpty)\n {\n VideoPacketsReverse.Enqueue(curReverseVideoStack);\n curReverseVideoStack = new ConcurrentStack>();\n }\n\n av_packet_unref(packet);\n\n if (curReverseStartPts != AV_NOPTS_VALUE && curReverseStartPts <= VideoStream.StartTimePts)\n {\n Status = Status.Ended;\n break;\n }\n\n //Log($\"[][][SEEK] {curReverseStartPts} | {Utils.TicksToTime((long) (curReverseStartPts * VideoStream.Timebase))}\");\n Interrupter.SeekRequest();\n ret = av_seek_frame(fmtCtx, VideoStream.StreamIndex, Math.Max(curReverseStartPts - curReverseSeekOffset, 0), SeekFlags.Backward);\n\n if (ret != 0)\n {\n Status = Status.Stopping;\n break;\n }\n\n curReverseStopPts = curReverseStartPts;\n curReverseStartPts = AV_NOPTS_VALUE;\n }\n else\n {\n if (curReverseStartPts != AV_NOPTS_VALUE)\n {\n curReverseVideoPackets.Add((IntPtr)packet);\n packet = av_packet_alloc();\n }\n else\n av_packet_unref(packet);\n }\n }\n\n } while (Status == Status.Running);\n }\n\n public void EnableReversePlayback(long timestamp)\n {\n IsReversePlayback = true;\n Seek(StartTime + timestamp);\n curReverseStopRequestedPts = av_rescale_q((StartTime + timestamp) / 10, Engine.FFmpeg.AV_TIMEBASE_Q, VideoStream.AVStream->time_base);\n }\n public void DisableReversePlayback() => IsReversePlayback = false;\n #endregion\n\n #region Switch Programs / Streams\n public bool IsProgramEnabled(StreamBase stream)\n {\n for (int i=0; iprograms[i]->discard != AVDiscard.All)\n return true;\n\n return false;\n }\n public void EnableProgram(StreamBase stream)\n {\n if (IsProgramEnabled(stream))\n {\n if (CanDebug) Log.Debug($\"[Stream #{stream.StreamIndex}] Program already enabled\");\n return;\n }\n\n for (int i=0; iprograms[i]->discard = AVDiscard.Default;\n return;\n }\n }\n public void DisableProgram(StreamBase stream)\n {\n for (int i=0; iprograms[i]->discard != AVDiscard.All)\n {\n bool isNeeded = false;\n for (int l2=0; l2programs[i]->discard = AVDiscard.All;\n }\n else if (CanDebug)\n Log.Debug($\"[Stream #{stream.StreamIndex}] Program #{i} is needed\");\n }\n }\n\n public void EnableStream(StreamBase stream)\n {\n lock (lockFmtCtx)\n {\n if (Disposed || stream == null || EnabledStreams.Contains(stream.StreamIndex))\n {\n // If it detects that the primary and secondary are trying to select the same subtitle\n // Put the same instance in SubtitlesStreams and return.\n if (stream != null && stream.Type == MediaType.Subs && EnabledStreams.Contains(stream.StreamIndex))\n {\n SubtitlesStreams[SubtitlesSelectedHelper.CurIndex] = (SubtitlesStream)stream;\n // Necessary to update UI immediately\n stream.Enabled = stream.Enabled;\n }\n return;\n };\n\n EnabledStreams.Add(stream.StreamIndex);\n fmtCtx->streams[stream.StreamIndex]->discard = AVDiscard.Default;\n stream.Enabled = true;\n EnableProgram(stream);\n\n switch (stream.Type)\n {\n case MediaType.Audio:\n AudioStream = (AudioStream) stream;\n if (VideoStream == null)\n {\n if (AudioStream.HLSPlaylist != null)\n {\n IsHLSLive = true;\n HLSPlaylist = AudioStream.HLSPlaylist;\n UpdateHLSTime();\n }\n else\n {\n HLSPlaylist = null;\n IsHLSLive = false;\n }\n }\n\n break;\n\n case MediaType.Video:\n VideoStream = (VideoStream) stream;\n VideoPackets.frameDuration = VideoStream.FrameDuration > 0 ? VideoStream.FrameDuration : 30 * 1000 * 10000;\n if (VideoStream.HLSPlaylist != null)\n {\n IsHLSLive = true;\n HLSPlaylist = VideoStream.HLSPlaylist;\n UpdateHLSTime();\n }\n else\n {\n HLSPlaylist = null;\n IsHLSLive = false;\n }\n\n break;\n\n case MediaType.Subs:\n SubtitlesStreams[SubtitlesSelectedHelper.CurIndex] = (SubtitlesStream)stream;\n\n break;\n\n case MediaType.Data:\n DataStream = (DataStream) stream;\n\n break;\n }\n\n if (UseAVSPackets)\n CurPackets = VideoStream != null ? VideoPackets : (AudioStream != null ? AudioPackets : (SubtitlesStreams[0] != null ? SubtitlesPackets[0] : DataPackets));\n\n if (CanInfo) Log.Info($\"[{stream.Type} #{stream.StreamIndex}] Enabled\");\n }\n }\n public void DisableStream(StreamBase stream)\n {\n lock (lockFmtCtx)\n {\n if (Disposed || stream == null || !EnabledStreams.Contains(stream.StreamIndex)) return;\n\n // If it is the same subtitle, do not disable it.\n if (stream.Type == MediaType.Subs && SubtitlesStreams[0] != null && SubtitlesStreams[0] == SubtitlesStreams[1])\n {\n // clear only what is needed\n SubtitlesStreams[SubtitlesSelectedHelper.CurIndex] = null;\n SubtitlesPackets[SubtitlesSelectedHelper.CurIndex].Clear();\n // Necessary to update UI immediately\n stream.Enabled = stream.Enabled;\n return;\n }\n\n /* AVDISCARD_ALL causes syncing issues between streams (TBR: bandwidth?)\n * 1) While switching video streams will not switch at the same timestamp\n * 2) By disabling video stream after a seek, audio will not seek properly\n * 3) HLS needs to update hlsCtx->first_time and read at least on package before seek to be accurate\n */\n\n fmtCtx->streams[stream.StreamIndex]->discard = AVDiscard.All;\n EnabledStreams.Remove(stream.StreamIndex);\n stream.Enabled = false;\n DisableProgram(stream);\n\n switch (stream.Type)\n {\n case MediaType.Audio:\n AudioStream = null;\n if (VideoStream != null)\n {\n if (VideoStream.HLSPlaylist != null)\n {\n IsHLSLive = true;\n HLSPlaylist = VideoStream.HLSPlaylist;\n UpdateHLSTime();\n }\n else\n {\n HLSPlaylist = null;\n IsHLSLive = false;\n }\n }\n\n AudioPackets.Clear();\n\n break;\n\n case MediaType.Video:\n VideoStream = null;\n if (AudioStream != null)\n {\n if (AudioStream.HLSPlaylist != null)\n {\n IsHLSLive = true;\n HLSPlaylist = AudioStream.HLSPlaylist;\n UpdateHLSTime();\n }\n else\n {\n HLSPlaylist = null;\n IsHLSLive = false;\n }\n }\n\n VideoPackets.Clear();\n break;\n\n case MediaType.Subs:\n SubtitlesStreams[SubtitlesSelectedHelper.CurIndex] = null;\n SubtitlesPackets[SubtitlesSelectedHelper.CurIndex].Clear();\n\n break;\n\n case MediaType.Data:\n DataStream = null;\n DataPackets.Clear();\n\n break;\n }\n\n if (UseAVSPackets)\n CurPackets = VideoStream != null ? VideoPackets : (AudioStream != null ? AudioPackets : SubtitlesPackets[0]);\n\n if (CanInfo) Log.Info($\"[{stream.Type} #{stream.StreamIndex}] Disabled\");\n }\n }\n public void SwitchStream(StreamBase stream)\n {\n lock (lockFmtCtx)\n {\n if (stream.Type == MediaType.Audio)\n DisableStream(AudioStream);\n else if (stream.Type == MediaType.Video)\n DisableStream(VideoStream);\n else if (stream.Type == MediaType.Subs)\n DisableStream(SubtitlesStreams[SubtitlesSelectedHelper.CurIndex]);\n else\n DisableStream(DataStream);\n\n EnableStream(stream);\n }\n }\n #endregion\n\n #region Misc\n internal void UpdateHLSTime()\n {\n // TBR: Access Violation\n // [hls @ 00000269f9cdb400] Media sequence changed unexpectedly: 150070 -> 0\n\n if (hlsPrevSeqNo != HLSPlaylist->cur_seq_no)\n {\n hlsPrevSeqNo = HLSPlaylist->cur_seq_no;\n hlsStartTime = AV_NOPTS_VALUE;\n\n hlsCurDuration = 0;\n long duration = 0;\n\n for (long i=0; icur_seq_no - HLSPlaylist->start_seq_no; i++)\n {\n hlsCurDuration += HLSPlaylist->segments[i]->duration;\n duration += HLSPlaylist->segments[i]->duration;\n }\n\n for (long i=HLSPlaylist->cur_seq_no - HLSPlaylist->start_seq_no; in_segments; i++)\n duration += HLSPlaylist->segments[i]->duration;\n\n hlsCurDuration *= 10;\n duration *= 10;\n Duration = duration;\n }\n\n if (hlsStartTime == AV_NOPTS_VALUE && CurPackets.LastTimestamp != AV_NOPTS_VALUE)\n {\n hlsStartTime = CurPackets.LastTimestamp - hlsCurDuration;\n CurPackets.UpdateCurTime();\n }\n }\n\n private string GetValidExtension()\n {\n // TODO\n // Should check for all supported output formats (there is no list in ffmpeg.autogen ?)\n // Should check for inner input format (not outer protocol eg. hls/rtsp)\n // Should check for raw codecs it can be mp4/mov but it will not work in mp4 only in mov (or avi for raw)\n\n if (Name == \"mpegts\")\n return \"ts\";\n else if (Name == \"mpeg\")\n return \"mpeg\";\n\n List supportedOutput = new() { \"mp4\", \"avi\", \"flv\", \"flac\", \"mpeg\", \"mpegts\", \"mkv\", \"ogg\", \"ts\"};\n string defaultExtenstion = \"mp4\";\n bool hasPcm = false;\n bool isRaw = false;\n\n foreach (var stream in AudioStreams)\n if (stream.Codec.Contains(\"pcm\")) hasPcm = true;\n\n foreach (var stream in VideoStreams)\n if (stream.Codec.Contains(\"raw\")) isRaw = true;\n\n if (isRaw) defaultExtenstion = \"avi\";\n\n // MP4 container doesn't support PCM\n if (hasPcm) defaultExtenstion = \"mkv\";\n\n // TODO\n // Check also shortnames\n //if (Name == \"mpegts\") return \"ts\";\n //if ((fmtCtx->iformat->flags & AVFMT_TS_DISCONT) != 0) should be mp4 or container that supports segments\n\n if (string.IsNullOrEmpty(Extensions)) return defaultExtenstion;\n string[] extensions = Extensions.Split(',');\n if (extensions == null || extensions.Length < 1) return defaultExtenstion;\n\n // Try to set the output container same as input\n for (int i=0; istart_time * 10)}/{Utils.TicksToTime(fmtCtx->duration * 10)} | {Utils.TicksToTime(StartTime)}/{Utils.TicksToTime(Duration)}\";\n\n foreach(var stream in VideoStreams) dump += \"\\r\\n\" + stream.GetDump();\n foreach(var stream in AudioStreams) dump += \"\\r\\n\" + stream.GetDump();\n foreach(var stream in SubtitlesStreamsAll) dump += \"\\r\\n\" + stream.GetDump();\n\n if (fmtCtx->nb_programs > 0)\n dump += $\"\\r\\n[Programs] {fmtCtx->nb_programs}\";\n\n for (int i=0; inb_programs; i++)\n {\n dump += $\"\\r\\n\\tProgram #{i}\";\n\n if (fmtCtx->programs[i]->nb_stream_indexes > 0)\n dump += $\"\\r\\n\\t\\tStreams [{fmtCtx->programs[i]->nb_stream_indexes}]: \";\n\n for (int l=0; lprograms[i]->nb_stream_indexes; l++)\n dump += $\"{fmtCtx->programs[i]->stream_index[l]},\";\n\n if (fmtCtx->programs[i]->nb_stream_indexes > 0)\n dump = dump[..^1];\n }\n\n if (CanInfo) Log.Info($\"Format Context Info {dump}\\r\\n\");\n }\n\n /// \n /// Gets next VideoPacket from the existing queue or demuxes it if required (Demuxer must not be running)\n /// \n /// 0 on success\n public int GetNextVideoPacket()\n {\n if (VideoPackets.Count > 0)\n {\n packet = VideoPackets.Dequeue();\n return 0;\n }\n else\n return GetNextPacket(VideoStream.StreamIndex);\n }\n\n /// \n /// Pushes the demuxer to the next available packet (Demuxer must not be running)\n /// \n /// Packet's stream index\n /// 0 on success\n public int GetNextPacket(int streamIndex = -1)\n {\n int ret;\n\n while (true)\n {\n Interrupter.ReadRequest();\n ret = av_read_frame(fmtCtx, packet);\n\n if (ret != 0)\n {\n av_packet_unref(packet);\n\n if ((ret == AVERROR_EXIT && fmtCtx->pb != null && fmtCtx->pb->eof_reached != 0) || ret == AVERROR_EOF)\n {\n packet = av_packet_alloc();\n packet->data = null;\n packet->size = 0;\n\n Stop();\n Status = Status.Ended;\n }\n\n return ret;\n }\n\n if (streamIndex != -1)\n {\n if (packet->stream_index == streamIndex)\n return 0;\n }\n else if (EnabledStreams.Contains(packet->stream_index))\n return 0;\n\n av_packet_unref(packet);\n }\n }\n #endregion\n}\n\npublic unsafe class PacketQueue\n{\n // TODO: DTS might not be available without avformat_find_stream_info (should changed based on packet->duration and fallback should be removed)\n readonly Demuxer demuxer;\n readonly ConcurrentQueue packets = new();\n public long frameDuration = 30 * 1000 * 10000; // in case of negative buffer duration calculate it based on packets count / FPS\n\n public long Bytes { get; private set; }\n public long BufferedDuration { get; private set; }\n public long CurTime { get; private set; }\n public int Count => packets.Count;\n public bool IsEmpty => packets.IsEmpty;\n\n public long FirstTimestamp { get; private set; } = AV_NOPTS_VALUE;\n public long LastTimestamp { get; private set; } = AV_NOPTS_VALUE;\n\n public PacketQueue(Demuxer demuxer)\n => this.demuxer = demuxer;\n\n public void Clear()\n {\n lock(packets)\n {\n while (!packets.IsEmpty)\n {\n packets.TryDequeue(out IntPtr packetPtr);\n if (packetPtr == IntPtr.Zero) continue;\n AVPacket* packet = (AVPacket*)packetPtr;\n av_packet_free(&packet);\n }\n\n FirstTimestamp = AV_NOPTS_VALUE;\n LastTimestamp = AV_NOPTS_VALUE;\n Bytes = 0;\n BufferedDuration = 0;\n CurTime = 0;\n }\n }\n\n public void Enqueue(AVPacket* packet)\n {\n lock (packets)\n {\n packets.Enqueue((IntPtr)packet);\n\n if (packet->dts != AV_NOPTS_VALUE || packet->pts != AV_NOPTS_VALUE)\n {\n LastTimestamp = packet->dts != AV_NOPTS_VALUE ?\n (long)(packet->dts * demuxer.AVStreamToStream[packet->stream_index].Timebase):\n (long)(packet->pts * demuxer.AVStreamToStream[packet->stream_index].Timebase);\n\n if (FirstTimestamp == AV_NOPTS_VALUE)\n {\n FirstTimestamp = LastTimestamp;\n UpdateCurTime();\n }\n else\n {\n BufferedDuration = LastTimestamp - FirstTimestamp;\n if (BufferedDuration < 0)\n BufferedDuration = packets.Count * frameDuration;\n }\n }\n else\n BufferedDuration = packets.Count * frameDuration;\n\n Bytes += packet->size;\n }\n }\n\n public AVPacket* Dequeue()\n {\n lock(packets)\n if (packets.TryDequeue(out IntPtr packetPtr))\n {\n AVPacket* packet = (AVPacket*)packetPtr;\n\n if (packet->dts != AV_NOPTS_VALUE || packet->pts != AV_NOPTS_VALUE)\n {\n FirstTimestamp = packet->dts != AV_NOPTS_VALUE ?\n (long)(packet->dts * demuxer.AVStreamToStream[packet->stream_index].Timebase):\n (long)(packet->pts * demuxer.AVStreamToStream[packet->stream_index].Timebase);\n UpdateCurTime();\n }\n else\n BufferedDuration = packets.Count * frameDuration;\n\n return (AVPacket*)packetPtr;\n }\n\n return null;\n }\n\n public AVPacket* Peek()\n => packets.TryPeek(out IntPtr packetPtr)\n ? (AVPacket*)packetPtr\n : (AVPacket*)null;\n\n internal void UpdateCurTime()\n {\n if (demuxer.hlsCtx != null)\n {\n if (demuxer.hlsStartTime != AV_NOPTS_VALUE)\n {\n if (FirstTimestamp < demuxer.hlsStartTime)\n {\n demuxer.Duration += demuxer.hlsStartTime - FirstTimestamp;\n demuxer.hlsStartTime = FirstTimestamp;\n CurTime = 0;\n }\n else\n CurTime = FirstTimestamp - demuxer.hlsStartTime;\n }\n }\n else\n CurTime = FirstTimestamp - demuxer.StartTime;\n\n if (CurTime < 0)\n CurTime = 0;\n\n BufferedDuration = LastTimestamp - FirstTimestamp;\n\n if (BufferedDuration < 0)\n BufferedDuration = packets.Count * frameDuration;\n }\n}\n"], ["/LLPlayer/FlyleafLib/MediaPlayer/Player.Open.cs", "using System;\nusing System.Collections.Concurrent;\nusing System.IO;\nusing System.Threading.Tasks;\n\nusing FlyleafLib.MediaFramework.MediaDecoder;\nusing FlyleafLib.MediaFramework.MediaPlaylist;\nusing FlyleafLib.MediaFramework.MediaStream;\n\nusing static FlyleafLib.Logger;\nusing static FlyleafLib.MediaFramework.MediaContext.DecoderContext;\nusing static FlyleafLib.Utils;\n\nnamespace FlyleafLib.MediaPlayer;\n\nunsafe partial class Player\n{\n #region Events\n\n public event EventHandler Opening; // Will be also used for subtitles\n public event EventHandler OpenCompleted; // Will be also used for subtitles\n public event EventHandler OpenPlaylistItemCompleted;\n public event EventHandler OpenSessionCompleted;\n\n public event EventHandler OpenAudioStreamCompleted;\n public event EventHandler OpenVideoStreamCompleted;\n public event EventHandler OpenSubtitlesStreamCompleted;\n public event EventHandler OpenDataStreamCompleted;\n\n public event EventHandler OpenExternalAudioStreamCompleted;\n public event EventHandler OpenExternalVideoStreamCompleted;\n public event EventHandler OpenExternalSubtitlesStreamCompleted;\n\n private void OnOpening(OpeningArgs args = null)\n => Opening?.Invoke(this, args);\n private void OnOpenCompleted(OpenCompletedArgs args = null)\n => OpenCompleted?.Invoke(this, args);\n private void OnOpenSessionCompleted(OpenSessionCompletedArgs args = null)\n => OpenSessionCompleted?.Invoke(this, args);\n private void OnOpenPlaylistItemCompleted(OpenPlaylistItemCompletedArgs args = null)\n => OpenPlaylistItemCompleted?.Invoke(this, args);\n\n private void OnOpenAudioStreamCompleted(OpenAudioStreamCompletedArgs args = null)\n => OpenAudioStreamCompleted?.Invoke(this, args);\n private void OnOpenVideoStreamCompleted(OpenVideoStreamCompletedArgs args = null)\n => OpenVideoStreamCompleted?.Invoke(this, args);\n private void OnOpenSubtitlesStreamCompleted(OpenSubtitlesStreamCompletedArgs args = null)\n => OpenSubtitlesStreamCompleted?.Invoke(this, args);\n private void OnOpenDataStreamCompleted(OpenDataStreamCompletedArgs args = null)\n => OpenDataStreamCompleted?.Invoke(this, args);\n\n private void OnOpenExternalAudioStreamCompleted(OpenExternalAudioStreamCompletedArgs args = null)\n => OpenExternalAudioStreamCompleted?.Invoke(this, args);\n private void OnOpenExternalVideoStreamCompleted(OpenExternalVideoStreamCompletedArgs args = null)\n => OpenExternalVideoStreamCompleted?.Invoke(this, args);\n private void OnOpenExternalSubtitlesStreamCompleted(OpenExternalSubtitlesStreamCompletedArgs args = null)\n => OpenExternalSubtitlesStreamCompleted?.Invoke(this, args);\n #endregion\n\n #region Decoder Events\n private void Decoder_AudioCodecChanged(DecoderBase x)\n {\n Audio.Refresh();\n UIAll();\n }\n private void Decoder_VideoCodecChanged(DecoderBase x)\n {\n Video.Refresh();\n UIAll();\n }\n\n private void Decoder_OpenAudioStreamCompleted(object sender, OpenAudioStreamCompletedArgs e)\n {\n Config.Audio.SetDelay(0);\n Audio.Refresh();\n canPlay = Video.IsOpened || Audio.IsOpened;\n isLive = MainDemuxer.IsLive;\n duration= MainDemuxer.Duration;\n\n UIAdd(() =>\n {\n IsLive = IsLive;\n CanPlay = CanPlay;\n Duration=Duration;\n });\n UIAll();\n }\n private void Decoder_OpenVideoStreamCompleted(object sender, OpenVideoStreamCompletedArgs e)\n {\n Video.Refresh();\n canPlay = Video.IsOpened || Audio.IsOpened;\n isLive = MainDemuxer.IsLive;\n duration= MainDemuxer.Duration;\n\n UIAdd(() =>\n {\n IsLive = IsLive;\n CanPlay = CanPlay;\n Duration=Duration;\n });\n UIAll();\n }\n private void Decoder_OpenSubtitlesStreamCompleted(object sender, OpenSubtitlesStreamCompletedArgs e)\n {\n int i = SubtitlesSelectedHelper.CurIndex;\n\n Config.Subtitles[i].SetDelay(0);\n Subtitles[i].Refresh();\n UIAll();\n\n if (IsPlaying && Config.Subtitles.Enabled) // TBR (First run mainly with -from DecoderContext->OpenSuggestedSubtitles-> Task.Run causes late open, possible resync?)\n {\n if (!Subtitles[i].IsOpened)\n {\n return;\n }\n\n lock (lockSubtitles)\n {\n if (SubtitlesDecoders[i].OnVideoDemuxer)\n {\n SubtitlesDecoders[i].Start();\n }\n //else// if (!decoder.RequiresResync)\n //{\n // SubtitlesDemuxers[i].Start();\n // SubtitlesDecoders[i].Start();\n //}\n }\n }\n }\n\n private void Decoder_OpenDataStreamCompleted(object sender, OpenDataStreamCompletedArgs e)\n {\n Data.Refresh();\n UIAll();\n if (Config.Data.Enabled)\n {\n lock (lockSubtitles)\n if (DataDecoder.OnVideoDemuxer)\n DataDecoder.Start();\n else// if (!decoder.RequiresResync)\n {\n DataDemuxer.Start();\n DataDecoder.Start();\n }\n }\n }\n\n private void Decoder_OpenExternalAudioStreamCompleted(object sender, OpenExternalAudioStreamCompletedArgs e)\n {\n if (!e.Success)\n {\n canPlay = Video.IsOpened || Audio.IsOpened;\n UIAdd(() => CanPlay = CanPlay);\n UIAll();\n }\n }\n private void Decoder_OpenExternalVideoStreamCompleted(object sender, OpenExternalVideoStreamCompletedArgs e)\n {\n if (!e.Success)\n {\n canPlay = Video.IsOpened || Audio.IsOpened;\n UIAdd(() => CanPlay = CanPlay);\n UIAll();\n }\n }\n private void Decoder_OpenExternalSubtitlesStreamCompleted(object sender, OpenExternalSubtitlesStreamCompletedArgs e)\n {\n if (e.Success)\n {\n lock (lockSubtitles)\n ReSync(decoder.SubtitlesStreams[SubtitlesSelectedHelper.CurIndex], decoder.GetCurTimeMs());\n }\n }\n #endregion\n\n #region Open Implementation\n private OpenCompletedArgs OpenInternal(object url_iostream, bool defaultPlaylistItem = true, bool defaultVideo = true, bool defaultAudio = true, bool defaultSubtitles = true)\n {\n OpenCompletedArgs args = new();\n\n try\n {\n if (url_iostream == null)\n {\n args.Error = \"Invalid empty/null input\";\n return args;\n }\n\n if (CanInfo) Log.Info($\"Opening {url_iostream}\");\n\n Initialize(Status.Opening);\n var args2 = decoder.Open(url_iostream, defaultPlaylistItem, defaultVideo, defaultAudio, defaultSubtitles);\n\n args.Url = args2.Url;\n args.IOStream = args2.IOStream;\n args.Error = args2.Error;\n\n if (!args.Success)\n {\n status = Status.Failed;\n lastError = args.Error;\n }\n else if (CanPlay)\n {\n status = Status.Paused;\n\n if (Config.Player.AutoPlay)\n Play();\n }\n else if (!defaultVideo && !defaultAudio)\n {\n isLive = MainDemuxer.IsLive;\n duration= MainDemuxer.Duration;\n UIAdd(() =>\n {\n IsLive = IsLive;\n Duration=Duration;\n });\n }\n\n UIAdd(() =>\n {\n LastError=LastError;\n Status = Status;\n });\n\n UIAll();\n\n return args;\n\n } catch (Exception e)\n {\n args.Error = !args.Success ? args.Error + \"\\r\\n\" + e.Message : e.Message;\n return args;\n } finally\n {\n OnOpenCompleted(args);\n }\n }\n private OpenCompletedArgs OpenSubtitles(string url)\n {\n OpenCompletedArgs args = new(url, null, null, true);\n\n try\n {\n if (CanInfo) Log.Info($\"Opening subtitles {url}\");\n\n if (!Video.IsOpened)\n {\n args.Error = \"Cannot open subtitles without video\";\n return args;\n }\n\n Config.Subtitles.SetEnabled(true);\n args.Error = decoder.OpenSubtitles(url).Error;\n\n if (args.Success)\n ReSync(decoder.SubtitlesStreams[SubtitlesSelectedHelper.CurIndex]);\n\n return args;\n\n } catch (Exception e)\n {\n args.Error = !args.Success ? args.Error + \"\\r\\n\" + e.Message : e.Message;\n return args;\n } finally\n {\n OnOpenCompleted(args);\n }\n }\n\n /// \n /// Opens a new media file (audio/subtitles/video)\n /// \n /// Media file's url\n /// Whether to open the first/default item in case of playlist\n /// Whether to open the default video stream from plugin suggestions\n /// Whether to open the default audio stream from plugin suggestions\n /// Whether to open the default subtitles stream from plugin suggestions\n /// Forces input url to be handled as subtitles\n /// \n public OpenCompletedArgs Open(string url, bool defaultPlaylistItem = true, bool defaultVideo = true, bool defaultAudio = true, bool defaultSubtitles = true, bool forceSubtitles = false)\n {\n if (forceSubtitles || ExtensionsSubtitles.Contains(GetUrlExtention(url)))\n {\n OnOpening(new() { Url = url, IsSubtitles = true});\n return OpenSubtitles(url);\n }\n else\n {\n OnOpening(new() { Url = url });\n return OpenInternal(url, defaultPlaylistItem, defaultVideo, defaultAudio, defaultSubtitles);\n }\n }\n\n /// \n /// Opens a new media file (audio/subtitles/video) without blocking\n /// You can get the results from \n /// \n /// Media file's url\n /// Whether to open the first/default item in case of playlist\n /// Whether to open the default video stream from plugin suggestions\n /// Whether to open the default audio stream from plugin suggestions\n /// Whether to open the default subtitles stream from plugin suggestions\n public void OpenAsync(string url, bool defaultPlaylistItem = true, bool defaultVideo = true, bool defaultAudio = true, bool defaultSubtitles = true)\n => OpenAsyncPush(url, defaultPlaylistItem, defaultVideo, defaultAudio, defaultSubtitles);\n\n /// \n /// Opens a new media I/O stream (audio/video) without blocking\n /// \n /// Media stream\n /// Whether to open the first/default item in case of playlist\n /// Whether to open the default video stream from plugin suggestions\n /// Whether to open the default audio stream from plugin suggestions\n /// Whether to open the default subtitles stream from plugin suggestions\n /// \n public OpenCompletedArgs Open(Stream iostream, bool defaultPlaylistItem = true, bool defaultVideo = true, bool defaultAudio = true, bool defaultSubtitles = true)\n {\n OnOpening(new() { IOStream = iostream });\n return OpenInternal(iostream, defaultPlaylistItem, defaultVideo, defaultAudio, defaultSubtitles);\n }\n\n /// \n /// Opens a new media I/O stream (audio/video) without blocking\n /// You can get the results from \n /// \n /// Media stream\n /// Whether to open the first/default item in case of playlist\n /// Whether to open the default video stream from plugin suggestions\n /// Whether to open the default audio stream from plugin suggestions\n /// Whether to open the default subtitles stream from plugin suggestions\n public void OpenAsync(Stream iostream, bool defaultPlaylistItem = true, bool defaultVideo = true, bool defaultAudio = true, bool defaultSubtitles = true)\n => OpenAsyncPush(iostream, defaultPlaylistItem, defaultVideo, defaultAudio, defaultSubtitles);\n\n /// \n /// Opens a new media session\n /// \n /// Media session\n /// \n public OpenSessionCompletedArgs Open(Session session)\n {\n OpenSessionCompletedArgs args = new(session);\n\n try\n {\n Playlist.Selected?.AddTag(GetCurrentSession(), playerSessionTag);\n\n Initialize(Status.Opening, true, session.isReopen);\n args.Error = decoder.Open(session).Error;\n\n if (!args.Success || !CanPlay)\n {\n status = Status.Failed;\n lastError = args.Error;\n }\n else\n {\n status = Status.Paused;\n\n if (Config.Player.AutoPlay)\n Play();\n }\n\n UIAdd(() =>\n {\n LastError=LastError;\n Status = Status;\n });\n\n UIAll();\n\n return args;\n } catch (Exception e)\n {\n args.Error = !args.Success ? args.Error + \"\\r\\n\" + e.Message : e.Message;\n return args;\n } finally\n {\n OnOpenSessionCompleted(args);\n }\n }\n\n /// \n /// Opens a new media session without blocking\n /// \n /// Media session\n public void OpenAsync(Session session) => OpenAsyncPush(session);\n\n /// \n /// Opens a playlist item \n /// \n /// The playlist item to open\n /// Whether to open the default video stream from plugin suggestions\n /// Whether to open the default audio stream from plugin suggestions\n /// Whether to open the default subtitles stream from plugin suggestions\n /// \n public OpenPlaylistItemCompletedArgs Open(PlaylistItem item, bool defaultVideo = true, bool defaultAudio = true, bool defaultSubtitles = true)\n {\n OpenPlaylistItemCompletedArgs args = new(item, Playlist.Selected);\n\n try\n {\n Playlist.Selected?.AddTag(GetCurrentSession(), playerSessionTag);\n\n Initialize(Status.Opening, true, true);\n\n // TODO: Config.Player.Reopen? to reopen session if (item.OpenedCounter > 0)\n args = decoder.Open(item, defaultVideo, defaultAudio, defaultSubtitles);\n\n if (!args.Success)\n {\n status = Status.Failed;\n lastError = args.Error;\n }\n else if (CanPlay)\n {\n status = Status.Paused;\n\n if (Config.Player.AutoPlay)\n Play();\n // TODO: else Show on frame?\n }\n else if (!defaultVideo && !defaultAudio)\n {\n isLive = MainDemuxer.IsLive;\n duration= MainDemuxer.Duration;\n UIAdd(() =>\n {\n IsLive = IsLive;\n Duration=Duration;\n });\n }\n\n UIAdd(() =>\n {\n LastError=LastError;\n Status = Status;\n });\n\n UIAll();\n\n return args;\n\n } catch (Exception e)\n {\n args.Error = !args.Success ? args.Error + \"\\r\\n\" + e.Message : e.Message;\n return args;\n } finally\n {\n OnOpenPlaylistItemCompleted(args);\n }\n }\n\n /// \n /// Opens a playlist item without blocking\n /// You can get the results from \n /// \n /// The playlist item to open\n /// Whether to open the default video stream from plugin suggestions\n /// Whether to open the default audio stream from plugin suggestions\n /// Whether to open the default subtitles stream from plugin suggestions\n /// \n public void OpenAsync(PlaylistItem item, bool defaultVideo = true, bool defaultAudio = true, bool defaultSubtitles = true)\n => OpenAsyncPush(item, defaultVideo, defaultAudio, defaultSubtitles);\n\n /// \n /// Opens an external stream (audio/subtitles/video)\n /// \n /// The external stream to open\n /// Whether to force resync with other streams\n /// Whether to open the default audio stream from plugin suggestions\n /// -2: None, -1: Suggested/Default, X: Specified embedded stream index\n /// \n public ExternalStreamOpenedArgs Open(ExternalStream extStream, bool resync = true, bool defaultAudio = true, int streamIndex = -1)\n {\n /* TODO\n *\n * Decoder.Stop() should not be called on video input switch as it will close the other inputs as well (audio/subs)\n * If the input is from different plugin we don't dispose the current plugin (eg. switching between recent/history plugin with torrents) (?)\n */\n\n ExternalStreamOpenedArgs args = null;\n\n try\n {\n int syncMs = decoder.GetCurTimeMs();\n\n if (LastError != null)\n {\n lastError = null;\n UI(() => LastError = LastError);\n }\n\n if (extStream is ExternalAudioStream)\n {\n if (decoder.VideoStream == null)\n requiresBuffering = true;\n\n isAudioSwitch = true;\n Config.Audio.SetEnabled(true);\n args = decoder.Open(extStream, false, streamIndex);\n\n if (!args.Success)\n {\n isAudioSwitch = false;\n return args;\n }\n\n if (resync)\n ReSync(decoder.AudioStream, syncMs);\n\n if (VideoDemuxer.VideoStream == null)\n {\n isLive = MainDemuxer.IsLive;\n duration = MainDemuxer.Duration;\n }\n\n isAudioSwitch = false;\n }\n else if (extStream is ExternalVideoStream)\n {\n bool shouldPlay = false;\n if (IsPlaying)\n {\n shouldPlay = true;\n Pause();\n }\n\n Initialize(Status.Opening, false, true);\n args = decoder.Open(extStream, defaultAudio, streamIndex);\n\n if (!args.Success || !CanPlay)\n return args;\n\n decoder.Seek(syncMs, false, false);\n decoder.GetVideoFrame(syncMs * (long)10000);\n VideoDemuxer.Start();\n AudioDemuxer.Start();\n //for (int i = 0; i < subNum; i++)\n //{\n // SubtitlesDemuxers[i].Start();\n //}\n DataDemuxer.Start();\n decoder.PauseOnQueueFull();\n\n // Initialize will Reset those and is posible that Codec Changed will not be called (as they are not chaning necessary)\n Decoder_OpenAudioStreamCompleted(null, null);\n Decoder_OpenSubtitlesStreamCompleted(null, null);\n\n if (shouldPlay)\n Play();\n else\n ShowOneFrame();\n }\n else // ExternalSubtitlesStream\n {\n if (!Video.IsOpened)\n {\n args.Error = \"Subtitles require opened video stream\";\n return args;\n }\n\n Config.Subtitles.SetEnabled(true);\n args = decoder.Open(extStream, false, streamIndex);\n }\n\n return args;\n\n } catch (Exception e)\n {\n args.Error = !args.Success ? args.Error + \"\\r\\n\" + e.Message : e.Message;\n return args;\n } finally\n {\n if (extStream is ExternalVideoStream)\n OnOpenExternalVideoStreamCompleted((OpenExternalVideoStreamCompletedArgs)args);\n else if (extStream is ExternalAudioStream)\n OnOpenExternalAudioStreamCompleted((OpenExternalAudioStreamCompletedArgs)args);\n else\n OnOpenExternalSubtitlesStreamCompleted((OpenExternalSubtitlesStreamCompletedArgs)args);\n }\n }\n\n /// \n /// Opens an external stream (audio/subtitles/video) without blocking\n /// You can get the results from , , \n /// \n /// The external stream to open\n /// Whether to force resync with other streams\n /// Whether to open the default audio stream from plugin suggestions\n public void OpenAsync(ExternalStream extStream, bool resync = true, bool defaultAudio = true)\n => OpenAsyncPush(extStream, resync, defaultAudio);\n\n /// \n /// Opens an embedded stream (audio/subtitles/video)\n /// \n /// An existing Player's media stream\n /// Whether to force resync with other streams\n /// Whether to re-suggest audio based on the new video stream (has effect only on VideoStream)\n /// \n public StreamOpenedArgs Open(StreamBase stream, bool resync = true, bool defaultAudio = true)\n {\n StreamOpenedArgs args = new();\n\n try\n {\n long delay = DateTime.UtcNow.Ticks;\n long fromEnd = Duration - CurTime;\n\n if (stream.Demuxer.Type == MediaType.Video)\n {\n isVideoSwitch = true;\n requiresBuffering = true;\n }\n\n if (stream is AudioStream astream)\n {\n Config.Audio.SetEnabled(true);\n args = decoder.OpenAudioStream(astream);\n }\n else if (stream is VideoStream vstream)\n args = decoder.OpenVideoStream(vstream, defaultAudio);\n else if (stream is SubtitlesStream sstream)\n {\n Config.Subtitles.SetEnabled(true);\n args = decoder.OpenSubtitlesStream(sstream);\n }\n else if (stream is DataStream dstream)\n {\n Config.Data.SetEnabled(true);\n args = decoder.OpenDataStream(dstream);\n }\n\n if (resync)\n {\n // Wait for at least on package before seek to update the HLS context first_time\n if (stream.Demuxer.IsHLSLive)\n {\n while (stream.Demuxer.IsRunning && stream.Demuxer.GetPacketsPtr(stream).Count < 3)\n System.Threading.Thread.Sleep(20);\n\n ReSync(stream, (int) ((Duration - fromEnd - (DateTime.UtcNow.Ticks - delay))/ 10000));\n }\n else\n ReSync(stream, (int) (CurTime / 10000), true);\n }\n else\n isVideoSwitch = false;\n\n return args;\n\n } catch (Exception e)\n {\n args.Error = !args.Success ? args.Error + \"\\r\\n\" + e.Message : e.Message;\n return args;\n } finally\n {\n if (stream is VideoStream)\n OnOpenVideoStreamCompleted((OpenVideoStreamCompletedArgs)args);\n else if (stream is AudioStream)\n OnOpenAudioStreamCompleted((OpenAudioStreamCompletedArgs)args);\n else if (stream is SubtitlesStream)\n OnOpenSubtitlesStreamCompleted((OpenSubtitlesStreamCompletedArgs)args);\n else\n OnOpenDataStreamCompleted((OpenDataStreamCompletedArgs)args);\n }\n }\n\n /// \n /// Opens an embedded stream (audio/subtitles/video) without blocking\n /// You can get the results from , , \n /// \n /// An existing Player's media stream\n /// Whether to force resync with other streams\n /// Whether to re-suggest audio based on the new video stream (has effect only on VideoStream)\n public void OpenAsync(StreamBase stream, bool resync = true, bool defaultAudio = true)\n => OpenAsyncPush(stream, resync, defaultAudio);\n\n /// \n /// Gets a session that can be re-opened later on with \n /// \n /// The current selected playlist item if null\n /// \n public Session GetSession(PlaylistItem item = null)\n => Playlist.Selected != null && (item == null || item.Index == Playlist.Selected.Index)\n ? GetCurrentSession()\n : item != null && item.GetTag(playerSessionTag) != null ? (Session)item.GetTag(playerSessionTag) : null;\n string playerSessionTag = \"_session\";\n private Session GetCurrentSession()\n {\n Session session = new();\n var item = Playlist.Selected;\n\n session.Url = Playlist.Url;\n session.PlaylistItem = item.Index;\n\n if (item.ExternalAudioStream != null)\n session.ExternalAudioStream = item.ExternalAudioStream.Index;\n\n if (item.ExternalVideoStream != null)\n session.ExternalVideoStream = item.ExternalVideoStream.Index;\n\n // TODO: L: Support secondary subtitles\n if (item.ExternalSubtitlesStreams[0] != null)\n session.ExternalSubtitlesUrl = item.ExternalSubtitlesStreams[0].Url;\n else if (decoder.SubtitlesStreams[0] != null)\n session.SubtitlesStream = decoder.SubtitlesStreams[0].StreamIndex;\n\n if (decoder.AudioStream != null)\n session.AudioStream = decoder.AudioStream.StreamIndex;\n\n if (decoder.VideoStream != null)\n session.VideoStream = decoder.VideoStream.StreamIndex;\n\n session.CurTime = CurTime;\n session.AudioDelay = Config.Audio.Delay;\n // TODO: L: Support secondary subtitles\n session.SubtitlesDelay = Config.Subtitles[0].Delay;\n\n return session;\n }\n\n internal void ReSync(StreamBase stream, int syncMs = -1, bool accurate = false)\n {\n /* TODO\n *\n * HLS live resync on stream switch should be from the end not from the start (could have different cache/duration)\n */\n\n if (stream == null) return;\n //if (stream == null || (syncMs == 0 || (syncMs == -1 && decoder.GetCurTimeMs() == 0))) return; // Avoid initial open resync?\n\n if (stream.Demuxer.Type == MediaType.Video)\n {\n isVideoSwitch = true;\n isAudioSwitch = true;\n for (int i = 0; i < subNum; i++)\n {\n isSubsSwitches[i] = true;\n }\n isDataSwitch = true;\n requiresBuffering = true;\n\n if (accurate && Video.IsOpened)\n {\n decoder.PauseDecoders();\n decoder.Seek(syncMs, false, false);\n decoder.GetVideoFrame(syncMs * (long)10000); // TBR: syncMs should not be -1 here\n }\n else\n decoder.Seek(syncMs, false, false);\n\n aFrame = null;\n isAudioSwitch = false;\n isVideoSwitch = false;\n for (int i = 0; i < subNum; i++)\n {\n sFrames[i] = sFramesPrev[i] = null;\n isSubsSwitches[i] = false;\n }\n dFrame = null;\n isDataSwitch = false;\n\n if (!IsPlaying)\n {\n decoder.PauseDecoders();\n decoder.GetVideoFrame();\n ShowOneFrame();\n }\n else\n {\n SubtitleClear();\n }\n }\n else\n {\n if (stream.Demuxer.Type == MediaType.Audio)\n {\n isAudioSwitch = true;\n decoder.SeekAudio();\n aFrame = null;\n isAudioSwitch = false;\n }\n else if (stream.Demuxer.Type == MediaType.Subs)\n {\n int i = SubtitlesSelectedHelper.CurIndex;\n\n isSubsSwitches[i] = true;\n\n //decoder.SeekSubtitles(i);\n sFrames[i] = sFramesPrev[i] = null;\n SubtitleClear(i);\n isSubsSwitches[i] = false;\n\n // do not start demuxer and decoder for external subs\n return;\n }\n else if (stream.Demuxer.Type == MediaType.Data)\n {\n isDataSwitch = true;\n decoder.SeekData();\n dFrame = null;\n isDataSwitch = false;\n }\n\n if (IsPlaying)\n {\n stream.Demuxer.Start();\n decoder.GetDecoderPtr(stream).Start();\n }\n }\n }\n #endregion\n\n #region OpenAsync Implementation\n private void OpenAsync()\n {\n lock (lockActions)\n if (taskOpenAsyncRuns)\n return;\n\n taskOpenAsyncRuns = true;\n\n Task.Run(() =>\n {\n if (IsDisposed)\n return;\n\n while (true)\n {\n if (openInputs.TryPop(out var data))\n {\n openInputs.Clear();\n decoder.Interrupt = true;\n OpenInternal(data.url_iostream, data.defaultPlaylistItem, data.defaultVideo, data.defaultAudio, data.defaultSubtitles);\n }\n else if (openSessions.TryPop(out data))\n {\n openSessions.Clear();\n decoder.Interrupt = true;\n Open(data.session);\n }\n else if (openItems.TryPop(out data))\n {\n openItems.Clear();\n decoder.Interrupt = true;\n Open(data.playlistItem, data.defaultVideo, data.defaultAudio, data.defaultSubtitles);\n }\n else if (openVideo.TryPop(out data))\n {\n openVideo.Clear();\n if (data.extStream != null)\n Open(data.extStream, data.resync, data.defaultAudio);\n else\n Open(data.stream, data.resync, data.defaultAudio);\n }\n else if (openAudio.TryPop(out data))\n {\n openAudio.Clear();\n if (data.extStream != null)\n Open(data.extStream, data.resync);\n else\n Open(data.stream, data.resync);\n }\n else if (openSubtitles.TryPop(out data))\n {\n openSubtitles.Clear();\n if (data.url_iostream != null)\n OpenSubtitles(data.url_iostream.ToString());\n else if (data.extStream != null)\n Open(data.extStream, data.resync);\n else if (data.stream != null)\n Open(data.stream, data.resync);\n }\n else\n {\n lock (lockActions)\n {\n if (openInputs.IsEmpty && openSessions.IsEmpty && openItems.IsEmpty && openVideo.IsEmpty && openAudio.IsEmpty && openSubtitles.IsEmpty)\n {\n taskOpenAsyncRuns = false;\n break;\n }\n }\n }\n }\n });\n }\n\n private void OpenAsyncPush(object url_iostream, bool defaultPlaylistItem = true, bool defaultVideo = true, bool defaultAudio = true, bool defaultSubtitles = true)\n {\n lock (lockActions)\n {\n if (url_iostream is string url_iostream_str)\n {\n // convert Windows lnk file to targetPath\n if (Path.GetExtension(url_iostream_str).Equals(\".lnk\", StringComparison.OrdinalIgnoreCase))\n {\n var targetPath = GetLnkTargetPath(url_iostream_str);\n if (targetPath != null)\n url_iostream = targetPath;\n }\n }\n\n if ((url_iostream is string) && ExtensionsSubtitles.Contains(GetUrlExtention(url_iostream.ToString())))\n {\n OnOpening(new() { Url = url_iostream.ToString(), IsSubtitles = true});\n openSubtitles.Push(new OpenAsyncData(url_iostream));\n }\n else\n {\n decoder.Interrupt = true;\n\n if (url_iostream is string)\n OnOpening(new() { Url = url_iostream.ToString() });\n else\n OnOpening(new() { IOStream = (Stream)url_iostream });\n\n openInputs.Push(new OpenAsyncData(url_iostream, defaultPlaylistItem, defaultVideo, defaultAudio, defaultSubtitles));\n }\n\n // Select primary subtitle & original mode when dropped\n SubtitlesSelectedHelper.CurIndex = 0;\n SubtitlesSelectedHelper.PrimaryMethod = SelectSubMethod.Original;\n\n OpenAsync();\n }\n }\n private void OpenAsyncPush(Session session)\n {\n lock (lockActions)\n {\n if (!openInputs.IsEmpty)\n return;\n\n decoder.Interrupt = true;\n openSessions.Clear();\n openSessions.Push(new OpenAsyncData(session));\n\n OpenAsync();\n }\n }\n private void OpenAsyncPush(PlaylistItem playlistItem, bool defaultVideo = true, bool defaultAudio = true, bool defaultSubtitles = true)\n {\n lock (lockActions)\n {\n if (!openInputs.IsEmpty || !openSessions.IsEmpty)\n return;\n\n decoder.Interrupt = true;\n openItems.Push(new OpenAsyncData(playlistItem, defaultVideo, defaultAudio, defaultSubtitles));\n\n OpenAsync();\n }\n }\n private void OpenAsyncPush(ExternalStream extStream, bool resync = true, bool defaultAudio = true, int streamIndex = -1)\n {\n lock (lockActions)\n {\n if (!openInputs.IsEmpty || !openItems.IsEmpty || !openSessions.IsEmpty)\n return;\n\n if (extStream is ExternalAudioStream)\n {\n openAudio.Clear();\n openAudio.Push(new OpenAsyncData(extStream, resync, false, streamIndex));\n }\n else if (extStream is ExternalVideoStream)\n {\n openVideo.Clear();\n openVideo.Push(new OpenAsyncData(extStream, resync, defaultAudio, streamIndex));\n }\n else\n {\n openSubtitles.Clear();\n openSubtitles.Push(new OpenAsyncData(extStream, resync, false, streamIndex));\n }\n\n OpenAsync();\n }\n }\n private void OpenAsyncPush(StreamBase stream, bool resync = true, bool defaultAudio = true)\n {\n lock (lockActions)\n {\n if (!openInputs.IsEmpty || !openItems.IsEmpty || !openSessions.IsEmpty)\n return;\n\n if (stream is AudioStream)\n {\n openAudio.Clear();\n openAudio.Push(new OpenAsyncData(stream, resync));\n }\n else if (stream is VideoStream)\n {\n openVideo.Clear();\n openVideo.Push(new OpenAsyncData(stream, resync, defaultAudio));\n }\n else\n {\n openSubtitles.Clear();\n openSubtitles.Push(new OpenAsyncData(stream, resync));\n }\n\n OpenAsync();\n }\n }\n\n ConcurrentStack openInputs = new();\n ConcurrentStack openSessions = new();\n ConcurrentStack openItems = new();\n ConcurrentStack openVideo = new();\n ConcurrentStack openAudio = new();\n ConcurrentStack openSubtitles= new();\n #endregion\n}\n\npublic class OpeningArgs\n{\n public string Url;\n public Stream IOStream;\n public bool IsSubtitles;\n}\n\npublic class OpenCompletedArgs\n{\n public string Url;\n public Stream IOStream;\n public string Error;\n public bool Success => Error == null;\n public bool IsSubtitles;\n\n public OpenCompletedArgs(string url = null, Stream iostream = null, string error = null, bool isSubtitles = false) { Url = url; IOStream = iostream; Error = error; IsSubtitles = isSubtitles; }\n}\n\nclass OpenAsyncData\n{\n public object url_iostream;\n public Session session;\n public PlaylistItem playlistItem;\n public ExternalStream extStream;\n public int streamIndex;\n public StreamBase stream;\n public bool resync;\n public bool defaultPlaylistItem;\n public bool defaultAudio;\n public bool defaultVideo;\n public bool defaultSubtitles;\n\n public OpenAsyncData(object url_iostream, bool defaultPlaylistItem = true, bool defaultVideo = true, bool defaultAudio = true, bool defaultSubtitles = true)\n { this.url_iostream = url_iostream; this.defaultPlaylistItem = defaultPlaylistItem; this.defaultVideo = defaultVideo; this.defaultAudio = defaultAudio; this.defaultSubtitles = defaultSubtitles; }\n public OpenAsyncData(Session session) => this.session = session;\n public OpenAsyncData(PlaylistItem playlistItem, bool defaultVideo = true, bool defaultAudio = true, bool defaultSubtitles = true)\n { this.playlistItem = playlistItem; this.defaultVideo = defaultVideo; this.defaultAudio = defaultAudio; this.defaultSubtitles = defaultSubtitles; }\n public OpenAsyncData(ExternalStream extStream, bool resync = true, bool defaultAudio = true, int streamIndex = -1)\n { this.extStream = extStream; this.resync = resync; this.defaultAudio = defaultAudio; this.streamIndex = streamIndex; }\n public OpenAsyncData(StreamBase stream, bool resync = true, bool defaultAudio = true)\n { this.stream = stream; this.resync = resync; this.defaultAudio = defaultAudio; }\n}\n"], ["/LLPlayer/Plugins/YoutubeDL/YoutubeDL.cs", "using System;\nusing System.Collections.Generic;\nusing System.Diagnostics;\nusing System.IO;\nusing System.Linq;\nusing System.Text.Json;\nusing System.Text.Json.Serialization;\nusing System.Text.RegularExpressions;\nusing System.Threading;\nusing System.Threading.Tasks;\nusing FlyleafLib.MediaFramework.MediaDemuxer;\nusing FlyleafLib.MediaFramework.MediaPlaylist;\nusing FlyleafLib.MediaFramework.MediaStream;\n\nusing static FlyleafLib.Utils;\n\nnamespace FlyleafLib.Plugins\n{\n public class YoutubeDL : PluginBase, IOpen, ISuggestExternalAudio, ISuggestExternalVideo\n {\n /* TODO\n * 1) Check Audio streams if we need to add also video streams with audio\n * 2) Check Best Audio bitrates/quality (mainly for audio only player)\n * 3) Dispose ytdl and not tag it to every item (use only format if required)\n * 4) Use playlist_index to set the default playlist item\n */\n\n public new int Priority { get; set; } = 1999;\n static string plugin_path = \"yt-dlp.exe\";\n static JsonSerializerOptions\n jsonSettings = new() { DefaultIgnoreCondition = JsonIgnoreCondition.WhenWritingNull };\n\n FileSystemWatcher watcher;\n string workingDir;\n\n Process proc;\n int procId = -1;\n object procLocker = new();\n\n bool addingItem;\n string dynamicOptions = \"\";\n bool errGenericImpersonate;\n long sessionId = -1; // same for playlists\n int retries;\n\n static HashSet\n subsExt = new(StringComparer.OrdinalIgnoreCase) { \"vtt\", \"srt\", \"ass\", \"ssa\" };\n\n public override Dictionary GetDefaultOptions()\n => new()\n {\n { \"ExtraArguments\", \"\" }, // TBR: Restore default functionality with --cookies-from-browser {defaultBrowser} || https://github.com/yt-dlp/yt-dlp/issues/7271\n { \"MaxVideoHeight\", \"720\" },\n { \"PreferVideoWithAudio\", \"False\" },\n };\n\n public override void OnInitializing()\n => DisposeInternal();\n\n public override void Dispose()\n => DisposeInternal();\n\n private Format GetAudioOnly(YoutubeDLJson ytdl)\n {\n // Prefer best with no video and protocol\n // Prioritize m3u8 protocol because https is very slow on YouTube\n var m3u8Formats = ytdl.formats.Where(f => f.protocol == \"m3u8_native\").ToList();\n for (int i = m3u8Formats.Count - 1; i >= 0; i--)\n if (HasAudio(m3u8Formats[i]) && !HasVideo(m3u8Formats[i]))\n return m3u8Formats[i];\n\n // Prefer best with no video (dont waste bandwidth)\n for (int i = ytdl.formats.Count - 1; i >= 0; i--)\n if (HasAudio(ytdl.formats[i]) && !HasVideo(ytdl.formats[i]))\n return ytdl.formats[i];\n\n // Prefer audio from worst video?\n for (int i = 0; i < ytdl.formats.Count; i++)\n if (HasAudio(ytdl.formats[i]))\n return ytdl.formats[i];\n\n return null;\n }\n private Format GetBestMatch(YoutubeDLJson ytdl)\n {\n // TODO: Expose in settings (vCodecs Blacklist) || Create a HW decoding failed list dynamic (check also for whitelist)\n List vCodecsBlacklist = [];\n\n int maxHeight;\n\n if (int.TryParse(Options[\"MaxVideoHeight\"], out var height) && height > 0)\n maxHeight = Math.Min(Config.Video.MaxVerticalResolution, height);\n else\n maxHeight = Config.Video.MaxVerticalResolution;\n\n // Video Streams Order based on Screen Resolution\n var iresults =\n from format in ytdl.formats\n where HasVideo(format) && format.height <= maxHeight && (!Regex.IsMatch(format.protocol, \"dash\", RegexOptions.IgnoreCase) || format.vcodec.ToLower() == \"vp9\")\n orderby format.width descending,\n format.height descending,\n format.protocol descending, // prefer m3u8 over https (for performance)\n format.vcodec descending, // prefer vp09 over avc (for performance)\n format.tbr descending,\n format.fps descending\n select format;\n\n if (iresults == null || iresults.Count() == 0)\n {\n // Fall-back to any\n iresults =\n from format in ytdl.formats\n where HasVideo(format)\n orderby format.width descending,\n format.height descending,\n format.protocol descending,\n format.vcodec descending,\n format.tbr descending,\n format.fps descending\n select format;\n\n if (iresults == null || iresults.Count() == 0) return null;\n }\n\n List results = iresults.ToList();\n\n // Best Resolution\n double bestWidth = results[0].width;\n double bestHeight = results[0].height;\n\n // Choose from the best resolution (0. with acodec and not blacklisted 1. not blacklisted 2. any)\n int priority = 1;\n if (bool.TryParse(Options[\"PreferVideoWithAudio\"], out var v) && v)\n {\n priority = 0;\n }\n while (priority < 3)\n {\n for (int i = 0; i < results.Count; i++)\n {\n if (results[i].width != bestWidth || results[i].height != bestHeight)\n break;\n\n if (priority == 0 && !IsBlackListed(vCodecsBlacklist, results[i].vcodec) && results[i].acodec != \"none\")\n return results[i];\n else if (priority == 1 && !IsBlackListed(vCodecsBlacklist, results[i].vcodec))\n return results[i];\n else if (priority == 2)\n return results[i];\n }\n\n priority++;\n }\n\n return results[results.Count - 1]; // Fall-back to any\n }\n private static bool IsBlackListed(List blacklist, string codec)\n {\n foreach (string codec2 in blacklist)\n if (Regex.IsMatch(codec, codec2, RegexOptions.IgnoreCase))\n return true;\n\n return false;\n }\n private static bool HasVideo(Format fmt)\n {\n if (fmt.height > 0 || fmt.vbr > 0 || fmt.vcodec != \"none\")\n return true;\n\n return false;\n }\n private static bool HasAudio(Format fmt)\n {\n if (fmt.abr > 0 || fmt.acodec != \"none\")\n return true;\n\n return false;\n }\n\n private static bool IsAutomaticSubtitle(string url)\n {\n if (url.Contains(\"youtube\") && url.Contains(\"/api/timedtext\"))\n return true;\n\n return false;\n }\n\n private void DisposeInternal()\n {\n lock (procLocker)\n {\n if (Disposed)\n return;\n\n Log.Debug($\"Disposing ({procId})\");\n\n if (procId != -1)\n {\n Process.Start(new ProcessStartInfo\n {\n FileName = \"taskkill\",\n Arguments = $\"/pid {procId} /f /t\",\n CreateNoWindow = true,\n UseShellExecute = false,\n WindowStyle = ProcessWindowStyle.Hidden,\n }).WaitForExit();\n }\n\n retries = 0;\n sessionId = -1;\n dynamicOptions = \"\";\n errGenericImpersonate = false;\n\n if (watcher != null)\n {\n watcher.Dispose();\n watcher = null;\n }\n\n if (workingDir != null)\n {\n Log.Debug($\"Folder deleted ({workingDir})\");\n Directory.Delete(workingDir, true);\n workingDir = null;\n }\n\n Disposed = true;\n Log.Debug($\"Disposed ({procId})\");\n }\n }\n\n private void NewPlaylistItem(string path)\n {\n string json = null;\n\n // File Watcher informs us on rename but the process still accessing the file\n for (int i=0; i<3; i++)\n {\n Thread.Sleep(20);\n try { json = File.ReadAllText(path); } catch { if (sessionId != Handler.OpenCounter) return; continue; }\n break;\n }\n\n YoutubeDLJson ytdl = null;\n\n try\n {\n ytdl = JsonSerializer.Deserialize(json, jsonSettings);\n } catch (Exception e)\n {\n Log.Error($\"[JsonSerializer] {e.Message}\");\n }\n\n if (sessionId != Handler.OpenCounter) return;\n\n if (ytdl == null)\n return;\n\n if (ytdl._type == \"playlist\")\n return;\n\n PlaylistItem item = new();\n\n if (Playlist.ExpectingItems == 0)\n Playlist.ExpectingItems = (int)ytdl.playlist_count;\n\n if (Playlist.Title == null)\n {\n if (!string.IsNullOrEmpty(ytdl.playlist_title))\n {\n Playlist.Title = ytdl.playlist_title;\n Log.Debug($\"Playlist Title -> {Playlist.Title}\");\n }\n else if (!string.IsNullOrEmpty(ytdl.playlist))\n {\n Playlist.Title = ytdl.playlist;\n Log.Debug($\"Playlist Title -> {Playlist.Title}\");\n }\n }\n\n item.Title = ytdl.title;\n Log.Debug($\"Adding {item.Title}\");\n\n item.DirectUrl = ytdl.webpage_url;\n\n if (ytdl.chapters != null && ytdl.chapters.Count > 0)\n {\n item.Chapters.AddRange(ytdl.chapters.Select(c => new Demuxer.Chapter()\n {\n StartTime = TimeSpan.FromSeconds(c.start_time).Ticks,\n EndTime = TimeSpan.FromSeconds(c.end_time).Ticks,\n Title = c.title\n }));\n }\n\n // If no formats still could have a single format attched to the main root class\n if (ytdl.formats == null)\n ytdl.formats = [ytdl];\n\n // Audio / Video Streams\n for (int i=0; i addedUrl = new(); // for de-duplication\n\n if (ytdl.automatic_captions != null)\n {\n foreach (var subtitle1 in ytdl.automatic_captions)\n {\n if (sessionId != Handler.OpenCounter)\n return;\n\n // original (source) language has this suffix\n const string suffix = \"-orig\";\n\n string langCode = subtitle1.Key;\n bool isOriginal = langCode.EndsWith(suffix, StringComparison.OrdinalIgnoreCase);\n\n if (isOriginal)\n {\n // remove -orig suffix\n langCode = langCode[..^suffix.Length];\n }\n\n Language lang = Language.Get(langCode);\n\n foreach (var subtitle in subtitle1.Value)\n {\n if (!subsExt.Contains(subtitle.ext))\n continue;\n\n bool automatic = IsAutomaticSubtitle(subtitle.url);\n\n if (!isOriginal && automatic) // always load original subtitle\n {\n // Automatic subtitles are loaded under the following ORed conditions\n // 1. If the language matches the set language\n // 2. Subtitles in the same language as the video\n if (!(Config.Subtitles.Languages.Contains(lang) || videoLang != Language.Unknown && videoLang == lang))\n {\n continue;\n }\n }\n\n // because -orig may be duplicated\n if (!addedUrl.Add(subtitle.url))\n continue;\n\n AddExternalStream(new ExternalSubtitlesStream()\n {\n Downloaded = true,\n Protocol = subtitle.ext,\n Language = lang,\n Url = subtitle.url,\n Automatic = automatic\n }, null, item);\n }\n }\n }\n } catch (Exception e) { Log.Warn($\"Failed to add subtitles ({e.Message})\"); }\n\n AddPlaylistItem(item, ytdl);\n }\n public void AddHeaders(ExternalStream extStream, Format fmt)\n {\n if (fmt.http_headers != null)\n {\n if (fmt.http_headers.TryGetValue(\"User-Agent\", out string value))\n {\n extStream.UserAgent = value;\n fmt.http_headers.Remove(\"User-Agent\");\n }\n\n if (fmt.http_headers.TryGetValue(\"Referer\", out value))\n {\n extStream.Referrer = value;\n fmt.http_headers.Remove(\"Referer\");\n }\n\n extStream.HTTPHeaders = fmt.http_headers;\n\n if (!string.IsNullOrEmpty(fmt.cookies))\n extStream.HTTPHeaders.Add(\"Cookies\", fmt.cookies);\n\n }\n }\n\n public bool CanOpen()\n {\n try\n {\n if (Playlist.IOStream != null)\n return false;\n\n Uri uri = new(Playlist.Url);\n string scheme = uri.Scheme.ToLower();\n\n if (scheme != \"http\" && scheme != \"https\")\n return false;\n\n string ext = GetUrlExtention(uri.AbsolutePath);\n\n if (ext == \"m3u8\" || ext == \"mp3\" || ext == \"m3u\" || ext == \"pls\")\n return false;\n\n // TBR: try to avoid processing radio stations\n if (string.IsNullOrEmpty(uri.PathAndQuery) || uri.PathAndQuery.Length < 5)\n return false;\n\n } catch (Exception) { return false; }\n\n return true;\n }\n public OpenResults Open()\n {\n try\n {\n lock (procLocker)\n {\n Disposed = false;\n sessionId = Handler.OpenCounter;\n Playlist.InputType = InputType.Web;\n\n workingDir = Path.GetTempPath() + Guid.NewGuid().ToString();\n\n Log.Debug($\"Folder created ({workingDir})\");\n Directory.CreateDirectory(workingDir);\n proc = new Process\n {\n EnableRaisingEvents = true,\n\n StartInfo = new ProcessStartInfo\n {\n FileName = Path.Combine(Engine.Plugins.Folder, Name, plugin_path),\n Arguments = $\"{dynamicOptions}{Options[\"ExtraArguments\"]} --no-check-certificate --skip-download --youtube-skip-dash-manifest --write-info-json -P \\\"{workingDir}\\\" \\\"{Playlist.Url}\\\" -o \\\"%(title).220B\\\"\", // 418 max filename length\n CreateNoWindow = true,\n UseShellExecute = false,\n WindowStyle = ProcessWindowStyle.Hidden,\n RedirectStandardError = true,\n RedirectStandardOutput = Logger.CanDebug,\n }\n };\n\n proc.Exited += (o, e) =>\n {\n lock (procLocker)\n {\n if (Logger.CanDebug)\n Log.Debug($\"Process completed ({(procId == -1 ? \"Killed\" : $\"{procId}\")})\");\n\n proc.Close();\n proc = null;\n procId = -1;\n }\n };\n\n proc.ErrorDataReceived += (o, e) =>\n {\n if (sessionId != Handler.OpenCounter || e.Data == null)\n return;\n\n Log.Debug($\"[stderr] {e.Data}\");\n\n if (!errGenericImpersonate && e.Data.Contains(\"generic:impersonate\"))\n errGenericImpersonate = true;\n };\n\n if (Logger.CanDebug)\n proc.OutputDataReceived += (o, e) =>\n {\n if (sessionId == Handler.OpenCounter)\n Log.Debug($\"[stdout] {e.Data}\");\n };\n\n watcher = new()\n {\n Path = workingDir,\n EnableRaisingEvents = true,\n };\n watcher.Renamed += (o, e) =>\n {\n try\n {\n if (sessionId != Handler.OpenCounter)\n return;\n\n addingItem = true;\n\n NewPlaylistItem(e.FullPath);\n\n if (Playlist.Items.Count == 1)\n Handler.OnPlaylistCompleted();\n\n } catch (Exception e2) { Log.Warn($\"Renamed Event Error {e2.Message} | {sessionId != Handler.OpenCounter}\");\n } finally { addingItem = false; }\n };\n\n proc.Start();\n procId = proc.Id;\n Log.Debug($\"Process started ({procId})\");\n\n // Don't try to read them at once at the end as the buffers (hardcoded to 4096) can be full and proc will freeze\n proc.BeginErrorReadLine();\n if (Logger.CanDebug)\n proc.BeginOutputReadLine();\n }\n\n while (Playlist.Items.Count < 1 && (proc != null || addingItem) && sessionId == Handler.OpenCounter)\n Thread.Sleep(35);\n\n if (sessionId != Handler.OpenCounter)\n {\n Log.Info(\"Session cancelled\");\n DisposeInternal();\n return null;\n }\n\n if (Playlist.Items.Count == 0) // Allow fallback to default plugin in case of YT-DLP bug with windows filename (this affects proper direct URLs as well)\n {\n if (!errGenericImpersonate || retries > 0)\n return null;\n\n Log.Warn(\"Re-trying with --extractor-args \\\"generic:impersonate\\\"\");\n DisposeInternal();\n retries = 1;\n dynamicOptions = \"--extractor-args \\\"generic:impersonate\\\" \";\n return Open();\n }\n }\n catch (Exception e) { Log.Error($\"Open ({e.Message})\"); return new(e.Message); }\n\n return new();\n }\n\n public OpenResults OpenItem()\n => new();\n\n public ExternalAudioStream SuggestExternalAudio()\n {\n if (Handler.OpenedPlugin == null || Handler.OpenedPlugin.Name != Name)\n return null;\n\n var fmt = GetAudioOnly((YoutubeDLJson)GetTag(Selected));\n if (fmt == null)\n return null;\n\n foreach (var extStream in Selected.ExternalAudioStreams)\n if (fmt.url == extStream.Url)\n return extStream;\n\n return null;\n }\n public ExternalVideoStream SuggestExternalVideo()\n {\n if (Handler.OpenedPlugin == null || Handler.OpenedPlugin.Name != Name)\n return null;\n\n Format fmt = GetBestMatch((YoutubeDLJson)GetTag(Selected));\n if (fmt == null)\n return null;\n\n foreach (var extStream in Selected.ExternalVideoStreams)\n if (fmt.url == extStream.Url)\n return extStream;\n\n return null;\n }\n }\n}\n"], ["/LLPlayer/FlyleafLib/MediaFramework/MediaContext/DecoderContext.cs", "using FlyleafLib.MediaFramework.MediaDecoder;\nusing FlyleafLib.MediaFramework.MediaDemuxer;\nusing FlyleafLib.MediaFramework.MediaRemuxer;\nusing FlyleafLib.MediaFramework.MediaStream;\nusing FlyleafLib.MediaPlayer;\nusing FlyleafLib.Plugins;\n\nusing static FlyleafLib.Logger;\nusing static FlyleafLib.Utils;\n\nnamespace FlyleafLib.MediaFramework.MediaContext;\n\npublic unsafe partial class DecoderContext : PluginHandler\n{\n /* TODO\n *\n * 1) Lock delay on demuxers' Format Context (for network streams)\n * Ensure we interrupt if we are planning to seek\n * Merge Seek witih GetVideoFrame (To seek accurate or to ensure keyframe)\n * Long delay on Enable/Disable demuxer's streams (lock might not required)\n *\n * 2) Resync implementation / CurTime\n * Transfer player's resync implementation here\n * Ensure we can trust CurTime on lower level (eg. on decoders - demuxers using dts)\n *\n * 3) Timestamps / Memory leak\n * If we have embedded audio/video and the audio decoder will stop/fail for some reason the demuxer will keep filling audio packets\n * Should also check at lower level (demuxer) to prevent wrong packet timestamps (too early or too late)\n * This is normal if it happens on live HLS (probably an ffmpeg bug)\n */\n\n #region Properties\n public object Tag { get; set; } // Upper Layer Object (eg. Player, Downloader) - mainly for plugins to access it\n public bool EnableDecoding { get; set; }\n public new bool Interrupt\n {\n get => base.Interrupt;\n set\n {\n base.Interrupt = value;\n\n if (value)\n {\n VideoDemuxer.Interrupter.ForceInterrupt = 1;\n AudioDemuxer.Interrupter.ForceInterrupt = 1;\n\n for (int i = 0; i < subNum; i++)\n {\n SubtitlesDemuxers[i].Interrupter.ForceInterrupt = 1;\n }\n DataDemuxer.Interrupter.ForceInterrupt = 1;\n }\n else\n {\n VideoDemuxer.Interrupter.ForceInterrupt = 0;\n AudioDemuxer.Interrupter.ForceInterrupt = 0;\n\n for (int i = 0; i < subNum; i++)\n {\n SubtitlesDemuxers[i].Interrupter.ForceInterrupt = 0;\n }\n DataDemuxer.Interrupter.ForceInterrupt = 0;\n }\n }\n }\n\n /// \n /// It will not resync by itself. Requires manual call to ReSync()\n /// \n public bool RequiresResync { get; set; }\n\n public string Extension => VideoDemuxer.Disposed ? AudioDemuxer.Extension : VideoDemuxer.Extension;\n\n // Demuxers\n public Demuxer MainDemuxer { get; private set; }\n public Demuxer AudioDemuxer { get; private set; }\n public Demuxer VideoDemuxer { get; private set; }\n // Demuxer for external subtitles, currently not used for subtitles, just used for stream info\n // Subtitles are displayed using SubtitlesManager\n public Demuxer[] SubtitlesDemuxers { get; private set; }\n public SubtitlesManager SubtitlesManager { get; private set; }\n\n public SubtitlesOCR SubtitlesOCR { get; private set; }\n public SubtitlesASR SubtitlesASR { get; private set; }\n\n public Demuxer DataDemuxer { get; private set; }\n\n // Decoders\n public AudioDecoder AudioDecoder { get; private set; }\n public VideoDecoder VideoDecoder { get; internal set;}\n public SubtitlesDecoder[] SubtitlesDecoders { get; private set; }\n public DataDecoder DataDecoder { get; private set; }\n public DecoderBase GetDecoderPtr(StreamBase stream)\n {\n switch (stream.Type)\n {\n case MediaType.Audio:\n return AudioDecoder;\n case MediaType.Video:\n return VideoDecoder;\n case MediaType.Data:\n return DataDecoder;\n case MediaType.Subs:\n return SubtitlesDecoders[SubtitlesSelectedHelper.CurIndex];\n default:\n throw new InvalidOperationException();\n }\n }\n // Streams\n public AudioStream AudioStream => (VideoDemuxer?.AudioStream) ?? AudioDemuxer.AudioStream;\n public VideoStream VideoStream => VideoDemuxer?.VideoStream;\n public SubtitlesStream[] SubtitlesStreams\n {\n get\n {\n SubtitlesStream[] streams = new SubtitlesStream[subNum];\n\n for (int i = 0; i < subNum; i++)\n {\n if (VideoDemuxer?.SubtitlesStreams?[i] != null)\n {\n streams[i] = VideoDemuxer.SubtitlesStreams[i];\n }\n else if (SubtitlesDemuxers[i]?.SubtitlesStreams?[i] != null)\n {\n streams[i] = SubtitlesDemuxers[i].SubtitlesStreams[i];\n }\n }\n\n return streams;\n }\n }\n public DataStream DataStream => (VideoDemuxer?.DataStream) ?? DataDemuxer.DataStream;\n\n public Tuple ClosedAudioStream { get; private set; }\n public Tuple ClosedVideoStream { get; private set; }\n #endregion\n\n #region Initialize\n LogHandler Log;\n bool shouldDispose;\n int subNum => Config.Subtitles.Max;\n\n public DecoderContext(Config config = null, int uniqueId = -1, bool enableDecoding = true) : base(config, uniqueId)\n {\n Log = new LogHandler((\"[#\" + UniqueId + \"]\").PadRight(8, ' ') + \" [DecoderContext] \");\n Playlist.decoder = this;\n\n EnableDecoding = enableDecoding;\n\n AudioDemuxer = new Demuxer(Config.Demuxer, MediaType.Audio, UniqueId, EnableDecoding);\n VideoDemuxer = new Demuxer(Config.Demuxer, MediaType.Video, UniqueId, EnableDecoding);\n SubtitlesDemuxers = new Demuxer[subNum];\n for (int i = 0; i < subNum; i++)\n {\n SubtitlesDemuxers[i] = new Demuxer(Config.Demuxer, MediaType.Subs, UniqueId, EnableDecoding);\n }\n DataDemuxer = new Demuxer(Config.Demuxer, MediaType.Data, UniqueId, EnableDecoding);\n\n SubtitlesManager = new SubtitlesManager(Config, subNum);\n SubtitlesOCR = new SubtitlesOCR(Config.Subtitles, subNum);\n SubtitlesASR = new SubtitlesASR(SubtitlesManager, Config);\n\n Recorder = new Remuxer(UniqueId);\n\n VideoDecoder = new VideoDecoder(Config, UniqueId);\n AudioDecoder = new AudioDecoder(Config, UniqueId, VideoDecoder);\n SubtitlesDecoders = new SubtitlesDecoder[subNum];\n for (int i = 0; i < subNum; i++)\n {\n SubtitlesDecoders[i] = new SubtitlesDecoder(Config, UniqueId, i);\n }\n DataDecoder = new DataDecoder(Config, UniqueId);\n\n if (EnableDecoding && config.Player.Usage != MediaPlayer.Usage.Audio)\n VideoDecoder.CreateRenderer();\n\n VideoDecoder.recCompleted = RecordCompleted;\n AudioDecoder.recCompleted = RecordCompleted;\n }\n\n public void Initialize()\n {\n VideoDecoder.Renderer?.ClearScreen();\n RequiresResync = false;\n\n OnInitializing();\n Stop();\n OnInitialized();\n }\n public void InitializeSwitch()\n {\n VideoDecoder.Renderer?.ClearScreen();\n RequiresResync = false;\n ClosedAudioStream = null;\n ClosedVideoStream = null;\n\n OnInitializingSwitch();\n Stop();\n OnInitializedSwitch();\n }\n #endregion\n\n #region Seek\n public int Seek(long ms = -1, bool forward = false, bool seekInQueue = true)\n {\n int ret = 0;\n\n if (ms == -1) ms = GetCurTimeMs();\n\n // Review decoder locks (lockAction should be added to avoid dead locks with flush mainly before lockCodecCtx)\n AudioDecoder.resyncWithVideoRequired = false; // Temporary to avoid dead lock on AudioDecoder.lockCodecCtx\n lock (VideoDecoder.lockCodecCtx)\n lock (AudioDecoder.lockCodecCtx)\n lock (SubtitlesDecoders[0].lockCodecCtx)\n lock (SubtitlesDecoders[1].lockCodecCtx)\n lock (DataDecoder.lockCodecCtx)\n {\n long seekTimestamp = CalcSeekTimestamp(VideoDemuxer, ms, ref forward);\n\n // Should exclude seek in queue for all \"local/fast\" files\n lock (VideoDemuxer.lockActions)\n if (Playlist.InputType == InputType.Torrent || ms == 0 || !seekInQueue || VideoDemuxer.SeekInQueue(seekTimestamp, forward) != 0)\n {\n VideoDemuxer.Interrupter.ForceInterrupt = 1;\n OpenedPlugin.OnBuffering();\n lock (VideoDemuxer.lockFmtCtx)\n {\n if (VideoDemuxer.Disposed) { VideoDemuxer.Interrupter.ForceInterrupt = 0; return -1; }\n ret = VideoDemuxer.Seek(seekTimestamp, forward);\n }\n }\n\n VideoDecoder.Flush();\n if (ms == 0)\n VideoDecoder.keyPacketRequired = false; // TBR\n\n if (AudioStream != null && AudioDecoder.OnVideoDemuxer)\n {\n AudioDecoder.Flush();\n if (ms == 0)\n AudioDecoder.nextPts = AudioDecoder.Stream.StartTimePts;\n }\n\n for (int i = 0; i < subNum; i++)\n {\n if (SubtitlesStreams[i] != null && SubtitlesDecoders[i].OnVideoDemuxer)\n {\n SubtitlesDecoders[i].Flush();\n }\n }\n\n if (DataStream != null && DataDecoder.OnVideoDemuxer)\n DataDecoder.Flush();\n }\n\n if (AudioStream != null && !AudioDecoder.OnVideoDemuxer)\n {\n AudioDecoder.Pause();\n AudioDecoder.Flush();\n AudioDemuxer.PauseOnQueueFull = true;\n RequiresResync = true;\n }\n\n //for (int i = 0; i < subNum; i++)\n //{\n // if (SubtitlesStreams[i] != null && !SubtitlesDecoders[i].OnVideoDemuxer)\n // {\n // SubtitlesDecoders[i].Pause();\n // SubtitlesDecoders[i].Flush();\n // SubtitlesDemuxers[i].PauseOnQueueFull = true;\n // RequiresResync = true;\n // }\n //}\n\n if (DataStream != null && !DataDecoder.OnVideoDemuxer)\n {\n DataDecoder.Pause();\n DataDecoder.Flush();\n DataDemuxer.PauseOnQueueFull = true;\n RequiresResync = true;\n }\n\n return ret;\n }\n public int SeekAudio(long ms = -1, bool forward = false)\n {\n int ret = 0;\n\n if (AudioDemuxer.Disposed || AudioDecoder.OnVideoDemuxer || !Config.Audio.Enabled) return -1;\n\n if (ms == -1) ms = GetCurTimeMs();\n\n long seekTimestamp = CalcSeekTimestamp(AudioDemuxer, ms, ref forward);\n\n AudioDecoder.resyncWithVideoRequired = false; // Temporary to avoid dead lock on AudioDecoder.lockCodecCtx\n lock (AudioDecoder.lockActions)\n lock (AudioDecoder.lockCodecCtx)\n {\n lock (AudioDemuxer.lockActions)\n if (AudioDemuxer.SeekInQueue(seekTimestamp, forward) != 0)\n ret = AudioDemuxer.Seek(seekTimestamp, forward);\n\n AudioDecoder.Flush();\n if (VideoDecoder.IsRunning)\n {\n AudioDemuxer.Start();\n AudioDecoder.Start();\n }\n }\n\n return ret;\n }\n\n //public int SeekSubtitles(int subIndex = -1, long ms = -1, bool forward = false)\n //{\n // int ret = -1;\n\n // if (!Config.Subtitles.Enabled)\n // return ret;\n\n // // all sub streams\n // int startIndex = 0;\n // int endIndex = subNum - 1;\n // if (subIndex != -1)\n // {\n // // specific sub stream\n // startIndex = subIndex;\n // endIndex = subIndex;\n // }\n\n // for (int i = startIndex; i <= endIndex; i++)\n // {\n // // Perform seek only for external subtitles\n // if (SubtitlesDemuxers[i].Disposed || SubtitlesDecoders[i].OnVideoDemuxer)\n // {\n // continue;\n // }\n\n // long localMs = ms;\n // if (localMs == -1)\n // {\n // localMs = GetCurTimeMs();\n // }\n\n // long seekTimestamp = CalcSeekTimestamp(SubtitlesDemuxers[i], localMs, ref forward);\n\n // lock (SubtitlesDecoders[i].lockActions)\n // lock (SubtitlesDecoders[i].lockCodecCtx)\n // {\n // // Currently disabled as it will fail to seek within the queue the most of the times\n // //lock (SubtitlesDemuxer.lockActions)\n // //if (SubtitlesDemuxer.SeekInQueue(seekTimestamp, forward) != 0)\n // ret = SubtitlesDemuxers[i].Seek(seekTimestamp, forward);\n\n // SubtitlesDecoders[i].Flush();\n // if (VideoDecoder.IsRunning)\n // {\n // SubtitlesDemuxers[i].Start();\n // SubtitlesDecoders[i].Start();\n // }\n // }\n // }\n // return ret;\n //}\n\n public int SeekData(long ms = -1, bool forward = false)\n {\n int ret = 0;\n\n if (DataDemuxer.Disposed || DataDecoder.OnVideoDemuxer)\n return -1;\n\n if (ms == -1)\n ms = GetCurTimeMs();\n\n long seekTimestamp = CalcSeekTimestamp(DataDemuxer, ms, ref forward);\n\n lock (DataDecoder.lockActions)\n lock (DataDecoder.lockCodecCtx)\n {\n ret = DataDemuxer.Seek(seekTimestamp, forward);\n\n DataDecoder.Flush();\n if (VideoDecoder.IsRunning)\n {\n DataDemuxer.Start();\n DataDecoder.Start();\n }\n }\n\n return ret;\n }\n\n public long GetCurTime() => !VideoDemuxer.Disposed ? VideoDemuxer.CurTime : !AudioDemuxer.Disposed ? AudioDemuxer.CurTime : 0;\n public int GetCurTimeMs() => !VideoDemuxer.Disposed ? (int)(VideoDemuxer.CurTime / 10000) : (!AudioDemuxer.Disposed ? (int)(AudioDemuxer.CurTime / 10000) : 0);\n\n private long CalcSeekTimestamp(Demuxer demuxer, long ms, ref bool forward)\n {\n long startTime = demuxer.hlsCtx == null ? demuxer.StartTime : demuxer.hlsCtx->first_timestamp * 10;\n long ticks = (ms * 10000) + startTime;\n\n if (demuxer.Type == MediaType.Audio) ticks -= Config.Audio.Delay;\n //if (demuxer.Type == MediaType.Subs)\n //{\n // int i = SubtitlesDemuxers[0] == demuxer ? 0 : 1;\n // ticks -= Config.Subtitles[i].Delay + (2 * 1000 * 10000); // We even want the previous subtitles\n //}\n\n if (ticks < startTime)\n {\n ticks = startTime;\n forward = true;\n }\n else if (ticks > startTime + (!VideoDemuxer.Disposed ? VideoDemuxer.Duration : AudioDemuxer.Duration) - (50 * 10000))\n {\n ticks = Math.Max(startTime, startTime + demuxer.Duration - (50 * 10000));\n forward = false;\n }\n\n return ticks;\n }\n #endregion\n\n #region Start/Pause/Stop\n public void Pause()\n {\n VideoDecoder.Pause();\n AudioDecoder.Pause();\n for (int i = 0; i < subNum; i++)\n {\n SubtitlesDecoders[i].Pause();\n }\n DataDecoder.Pause();\n\n VideoDemuxer.Pause();\n AudioDemuxer.Pause();\n for (int i = 0; i < subNum; i++)\n {\n SubtitlesDemuxers[i].Pause();\n }\n DataDemuxer.Pause();\n }\n public void PauseDecoders()\n {\n VideoDecoder.Pause();\n AudioDecoder.Pause();\n for (int i = 0; i < subNum; i++)\n {\n SubtitlesDecoders[i].Pause();\n }\n DataDecoder.Pause();\n }\n public void PauseOnQueueFull()\n {\n VideoDemuxer.PauseOnQueueFull = true;\n AudioDemuxer.PauseOnQueueFull = true;\n for (int i = 0; i < subNum; i++)\n {\n SubtitlesDemuxers[i].PauseOnQueueFull = true;\n }\n DataDecoder.PauseOnQueueFull = true;\n }\n public void Start()\n {\n //if (RequiresResync) Resync();\n\n if (Config.Audio.Enabled)\n {\n AudioDemuxer.Start();\n AudioDecoder.Start();\n }\n\n if (Config.Video.Enabled)\n {\n VideoDemuxer.Start();\n VideoDecoder.Start();\n }\n\n if (Config.Subtitles.Enabled)\n {\n for (int i = 0; i < subNum; i++)\n {\n //if (SubtitlesStreams[i] != null && !SubtitlesDecoders[i].OnVideoDemuxer)\n // SubtitlesDemuxers[i].Start();\n\n //if (SubtitlesStreams[i] != null)\n if (SubtitlesStreams[i] != null && SubtitlesDecoders[i].OnVideoDemuxer)\n SubtitlesDecoders[i].Start();\n }\n }\n\n if (Config.Data.Enabled)\n {\n DataDemuxer.Start();\n DataDecoder.Start();\n }\n }\n public void Stop()\n {\n Interrupt = true;\n\n VideoDecoder.Dispose();\n AudioDecoder.Dispose();\n for (int i = 0; i < subNum; i++)\n {\n SubtitlesDecoders[i].Dispose();\n }\n\n DataDecoder.Dispose();\n AudioDemuxer.Dispose();\n for (int i = 0; i < subNum; i++)\n {\n SubtitlesDemuxers[i].Dispose();\n }\n\n DataDemuxer.Dispose();\n VideoDemuxer.Dispose();\n\n Interrupt = false;\n }\n public void StopThreads()\n {\n Interrupt = true;\n\n VideoDecoder.Stop();\n AudioDecoder.Stop();\n for (int i = 0; i < subNum; i++)\n {\n SubtitlesDecoders[i].Stop();\n }\n\n DataDecoder.Stop();\n AudioDemuxer.Stop();\n for (int i = 0; i < subNum; i++)\n {\n SubtitlesDemuxers[i].Stop();\n }\n DataDemuxer.Stop();\n VideoDemuxer.Stop();\n\n Interrupt = false;\n }\n #endregion\n\n public void Resync(long timestamp = -1)\n {\n bool isRunning = VideoDemuxer.IsRunning;\n\n if (AudioStream != null && AudioStream.Demuxer.Type != MediaType.Video && Config.Audio.Enabled)\n {\n if (timestamp == -1) timestamp = VideoDemuxer.CurTime;\n if (CanInfo) Log.Info($\"Resync audio to {TicksToTime(timestamp)}\");\n\n SeekAudio(timestamp / 10000);\n if (isRunning)\n {\n AudioDemuxer.Start();\n AudioDecoder.Start();\n }\n }\n\n //for (int i = 0; i < subNum; i++)\n //{\n // if (SubtitlesStreams[i] != null && SubtitlesStreams[i].Demuxer.Type != MediaType.Video && Config.Subtitles.Enabled)\n // {\n // if (timestamp == -1)\n // timestamp = VideoDemuxer.CurTime;\n // if (CanInfo)\n // Log.Info($\"Resync subs:{i} to {TicksToTime(timestamp)}\");\n\n // SeekSubtitles(i, timestamp / 10000, false);\n // if (isRunning)\n // {\n // SubtitlesDemuxers[i].Start();\n // SubtitlesDecoders[i].Start();\n // }\n // }\n //}\n\n if (DataStream != null && Config.Data.Enabled) // Should check if it actually an external (not embedded) stream DataStream.Demuxer.Type != MediaType.Video ?\n {\n if (timestamp == -1)\n timestamp = VideoDemuxer.CurTime;\n if (CanInfo)\n Log.Info($\"Resync data to {TicksToTime(timestamp)}\");\n\n SeekData(timestamp / 10000);\n if (isRunning)\n {\n DataDemuxer.Start();\n DataDecoder.Start();\n }\n }\n\n RequiresResync = false;\n }\n\n //public void ResyncSubtitles(long timestamp = -1)\n //{\n // if (SubtitlesStream != null && Config.Subtitles.Enabled)\n // {\n // if (timestamp == -1) timestamp = VideoDemuxer.CurTime;\n // if (CanInfo) Log.Info($\"Resync subs to {TicksToTime(timestamp)}\");\n\n // if (SubtitlesStream.Demuxer.Type != MediaType.Video)\n // SeekSubtitles(timestamp / 10000);\n // else\n\n // if (VideoDemuxer.IsRunning)\n // {\n // SubtitlesDemuxer.Start();\n // SubtitlesDecoder.Start();\n // }\n // }\n //}\n public void Flush()\n {\n VideoDemuxer.DisposePackets();\n AudioDemuxer.DisposePackets();\n for (int i = 0; i < subNum; i++)\n {\n SubtitlesDemuxers[i].DisposePackets();\n }\n DataDemuxer.DisposePackets();\n\n VideoDecoder.Flush();\n AudioDecoder.Flush();\n for (int i = 0; i < subNum; i++)\n {\n SubtitlesDecoders[i].Flush();\n }\n DataDecoder.Flush();\n }\n\n // !!! NEEDS RECODING\n public long GetVideoFrame(long timestamp = -1)\n {\n // TBR: Between seek and GetVideoFrame lockCodecCtx is lost and if VideoDecoder is running will already have decoded some frames (Currently ensure you pause VideDecoder before seek)\n\n int ret;\n int allowedErrors = Config.Decoder.MaxErrors;\n AVPacket* packet;\n\n lock (VideoDemuxer.lockFmtCtx)\n lock (VideoDecoder.lockCodecCtx)\n while (VideoDemuxer.VideoStream != null && !Interrupt)\n {\n if (VideoDemuxer.VideoPackets.IsEmpty)\n {\n packet = av_packet_alloc();\n VideoDemuxer.Interrupter.ReadRequest();\n ret = av_read_frame(VideoDemuxer.FormatContext, packet);\n if (ret != 0)\n {\n av_packet_free(&packet);\n return -1;\n }\n }\n else\n packet = VideoDemuxer.VideoPackets.Dequeue();\n\n if (!VideoDemuxer.EnabledStreams.Contains(packet->stream_index)) { av_packet_free(&packet); continue; }\n\n if (CanTrace)\n {\n var stream = VideoDemuxer.AVStreamToStream[packet->stream_index];\n long dts = packet->dts == AV_NOPTS_VALUE ? -1 : (long)(packet->dts * stream.Timebase);\n long pts = packet->pts == AV_NOPTS_VALUE ? -1 : (long)(packet->pts * stream.Timebase);\n Log.Trace($\"[{stream.Type}] DTS: {(dts == -1 ? \"-\" : TicksToTime(dts))} PTS: {(pts == -1 ? \"-\" : TicksToTime(pts))} | FLPTS: {(pts == -1 ? \"-\" : TicksToTime(pts - VideoDemuxer.StartTime))} | CurTime: {TicksToTime(VideoDemuxer.CurTime)} | Buffered: {TicksToTime(VideoDemuxer.BufferedDuration)}\");\n }\n\n var codecType = VideoDemuxer.FormatContext->streams[packet->stream_index]->codecpar->codec_type;\n\n if (codecType == AVMediaType.Video && VideoDecoder.keyPacketRequired)\n {\n if (packet->flags.HasFlag(PktFlags.Key))\n VideoDecoder.keyPacketRequired = false;\n else\n {\n if (CanWarn) Log.Warn(\"Ignoring non-key packet\");\n av_packet_free(&packet);\n continue;\n }\n }\n\n if (VideoDemuxer.IsHLSLive)\n VideoDemuxer.UpdateHLSTime();\n\n switch (codecType)\n {\n case AVMediaType.Audio:\n if (timestamp == -1 || (long)(packet->pts * AudioStream.Timebase) - VideoDemuxer.StartTime + (VideoStream.FrameDuration / 2) > timestamp)\n VideoDemuxer.AudioPackets.Enqueue(packet);\n else\n av_packet_free(&packet);\n\n continue;\n\n case AVMediaType.Subtitle:\n for (int i = 0; i < subNum; i++)\n {\n if (SubtitlesStreams[i]?.StreamIndex != packet->stream_index)\n {\n continue;\n }\n\n if (timestamp == -1 ||\n (long)(packet->pts * SubtitlesStreams[i].Timebase) - VideoDemuxer.StartTime +\n (VideoStream.FrameDuration / 2) > timestamp)\n {\n // Clone packets to support simultaneous display of the same subtitle\n VideoDemuxer.SubtitlesPackets[i].Enqueue(av_packet_clone(packet));\n }\n }\n\n // cloned, so free packet\n av_packet_free(&packet);\n\n continue;\n\n case AVMediaType.Data: // this should catch the data stream packets until we have a valid vidoe keyframe (it should fill the pts if NOPTS with lastVideoPacketPts similarly to the demuxer)\n if ((timestamp == -1 && VideoDecoder.StartTime != NoTs) || (long)(packet->pts * DataStream.Timebase) - VideoDemuxer.StartTime + (VideoStream.FrameDuration / 2) > timestamp)\n VideoDemuxer.DataPackets.Enqueue(packet);\n\n packet = av_packet_alloc();\n\n continue;\n\n case AVMediaType.Video:\n ret = avcodec_send_packet(VideoDecoder.CodecCtx, packet);\n\n if (VideoDecoder.swFallback)\n {\n VideoDecoder.SWFallback();\n ret = avcodec_send_packet(VideoDecoder.CodecCtx, packet);\n }\n\n av_packet_free(&packet);\n\n if (ret != 0)\n {\n allowedErrors--;\n if (CanWarn) Log.Warn($\"{FFmpegEngine.ErrorCodeToMsg(ret)} ({ret})\");\n\n if (allowedErrors == 0) { Log.Error(\"Too many errors!\"); return -1; }\n\n continue;\n }\n\n //VideoDemuxer.UpdateCurTime();\n\n var frame = av_frame_alloc();\n while (VideoDemuxer.VideoStream != null && !Interrupt)\n {\n ret = avcodec_receive_frame(VideoDecoder.CodecCtx, frame);\n if (ret != 0) { av_frame_unref(frame); break; }\n\n if (frame->best_effort_timestamp != AV_NOPTS_VALUE)\n frame->pts = frame->best_effort_timestamp;\n else if (frame->pts == AV_NOPTS_VALUE)\n {\n if (!VideoStream.FixTimestamps)\n {\n av_frame_unref(frame);\n continue;\n }\n\n frame->pts = VideoDecoder.lastFixedPts + VideoStream.StartTimePts;\n VideoDecoder.lastFixedPts += av_rescale_q(VideoStream.FrameDuration / 10, Engine.FFmpeg.AV_TIMEBASE_Q, VideoStream.AVStream->time_base);\n }\n\n if (!VideoDecoder.filledFromCodec)\n {\n ret = VideoDecoder.FillFromCodec(frame);\n\n if (ret == -1234)\n {\n av_frame_free(&frame);\n return -1;\n }\n }\n\n // Accurate seek with +- half frame distance\n if (timestamp != -1 && (long)(frame->pts * VideoStream.Timebase) - VideoDemuxer.StartTime + (VideoStream.FrameDuration / 2) < timestamp)\n {\n av_frame_unref(frame);\n continue;\n }\n\n //if (CanInfo) Info($\"Asked for {Utils.TicksToTime(timestamp)} and got {Utils.TicksToTime((long)(frame->pts * VideoStream.Timebase) - VideoDemuxer.StartTime)} | Diff {Utils.TicksToTime(timestamp - ((long)(frame->pts * VideoStream.Timebase) - VideoDemuxer.StartTime))}\");\n VideoDecoder.StartTime = (long)(frame->pts * VideoStream.Timebase) - VideoDemuxer.StartTime;\n\n var mFrame = VideoDecoder.Renderer.FillPlanes(frame);\n if (mFrame != null) VideoDecoder.Frames.Enqueue(mFrame);\n\n do\n {\n ret = avcodec_receive_frame(VideoDecoder.CodecCtx, frame);\n if (ret != 0) break;\n mFrame = VideoDecoder.Renderer.FillPlanes(frame);\n if (mFrame != null) VideoDecoder.Frames.Enqueue(mFrame);\n } while (!VideoDemuxer.Disposed && !Interrupt);\n\n av_frame_free(&frame);\n return mFrame.timestamp;\n }\n\n av_frame_free(&frame);\n\n break; // Switch break\n\n default:\n av_packet_free(&packet);\n continue;\n\n } // Switch\n\n } // While\n\n return -1;\n }\n public new void Dispose()\n {\n shouldDispose = true;\n Stop();\n Interrupt = true;\n VideoDecoder.DestroyRenderer();\n base.Dispose();\n }\n\n public void PrintStats()\n {\n string dump = \"\\r\\n-===== Streams / Packets / Frames =====-\\r\\n\";\n dump += $\"\\r\\n AudioPackets ({VideoDemuxer.AudioStreams.Count}): {VideoDemuxer.AudioPackets.Count}\";\n dump += $\"\\r\\n VideoPackets ({VideoDemuxer.VideoStreams.Count}): {VideoDemuxer.VideoPackets.Count}\";\n for (int i = 0; i < subNum; i++)\n {\n dump += $\"\\r\\n SubtitlesPackets{i+1} ({VideoDemuxer.SubtitlesStreamsAll.Count}): {VideoDemuxer.SubtitlesPackets[i].Count}\";\n }\n\n dump += $\"\\r\\n AudioPackets ({AudioDemuxer.AudioStreams.Count}): {AudioDemuxer.AudioPackets.Count} (AudioDemuxer)\";\n\n for (int i = 0; i < subNum; i++)\n {\n dump += $\"\\r\\n SubtitlesPackets{i+1} ({SubtitlesDemuxers[i].SubtitlesStreamsAll.Count}): {SubtitlesDemuxers[i].SubtitlesPackets[0].Count} (SubtitlesDemuxer)\";\n }\n\n dump += $\"\\r\\n Video Frames : {VideoDecoder.Frames.Count}\";\n dump += $\"\\r\\n Audio Frames : {AudioDecoder.Frames.Count}\";\n for (int i = 0; i < subNum; i++)\n {\n dump += $\"\\r\\n Subtitles Frames{i+1} : {SubtitlesDecoders[i].Frames.Count}\";\n }\n\n if (CanInfo) Log.Info(dump);\n }\n\n #region Recorder\n Remuxer Recorder;\n public event EventHandler RecordingCompleted;\n public bool IsRecording => VideoDecoder.isRecording || AudioDecoder.isRecording;\n int oldMaxAudioFrames;\n bool recHasVideo;\n public void StartRecording(ref string filename, bool useRecommendedExtension = true)\n {\n if (IsRecording) StopRecording();\n\n oldMaxAudioFrames = -1;\n recHasVideo = false;\n\n if (CanInfo) Log.Info(\"Record Start\");\n\n recHasVideo = !VideoDecoder.Disposed && VideoDecoder.Stream != null;\n\n if (useRecommendedExtension)\n filename = $\"{filename}.{(recHasVideo ? VideoDecoder.Stream.Demuxer.Extension : AudioDecoder.Stream.Demuxer.Extension)}\";\n\n Recorder.Open(filename);\n\n bool failed;\n\n if (recHasVideo)\n {\n failed = Recorder.AddStream(VideoDecoder.Stream.AVStream) != 0;\n if (CanInfo) Log.Info(failed ? \"Failed to add video stream\" : \"Video stream added to the recorder\");\n }\n\n if (!AudioDecoder.Disposed && AudioDecoder.Stream != null)\n {\n failed = Recorder.AddStream(AudioDecoder.Stream.AVStream, !AudioDecoder.OnVideoDemuxer) != 0;\n if (CanInfo) Log.Info(failed ? \"Failed to add audio stream\" : \"Audio stream added to the recorder\");\n }\n\n if (!Recorder.HasStreams || Recorder.WriteHeader() != 0) return; //throw new Exception(\"Invalid remuxer configuration\");\n\n // Check also buffering and possible Diff of first audio/video timestamp to remuxer to ensure sync between each other (shouldn't be more than 30-50ms)\n oldMaxAudioFrames = Config.Decoder.MaxAudioFrames;\n //long timestamp = Math.Max(VideoDemuxer.CurTime + VideoDemuxer.BufferedDuration, AudioDemuxer.CurTime + AudioDemuxer.BufferedDuration) + 1500 * 10000;\n Config.Decoder.MaxAudioFrames = Config.Decoder.MaxVideoFrames;\n\n VideoDecoder.StartRecording(Recorder);\n AudioDecoder.StartRecording(Recorder);\n }\n public void StopRecording()\n {\n if (oldMaxAudioFrames != -1) Config.Decoder.MaxAudioFrames = oldMaxAudioFrames;\n\n VideoDecoder.StopRecording();\n AudioDecoder.StopRecording();\n Recorder.Dispose();\n oldMaxAudioFrames = -1;\n if (CanInfo) Log.Info(\"Record Completed\");\n }\n internal void RecordCompleted(MediaType type)\n {\n if (!recHasVideo || (recHasVideo && type == MediaType.Video))\n {\n StopRecording();\n RecordingCompleted?.Invoke(this, new EventArgs());\n }\n }\n #endregion\n}\n"], ["/LLPlayer/FlyleafLib/MediaPlayer/SubtitlesASR.cs", "using System.Collections.Concurrent;\nusing System.Collections.Generic;\nusing System.Diagnostics;\nusing System.IO;\nusing System.Linq;\nusing System.Runtime.CompilerServices;\nusing System.Text;\nusing System.Text.RegularExpressions;\nusing System.Threading;\nusing System.Threading.Channels;\nusing System.Threading.Tasks;\nusing CliWrap;\nusing CliWrap.Builders;\nusing CliWrap.EventStream;\nusing FlyleafLib.MediaFramework.MediaDecoder;\nusing FlyleafLib.MediaFramework.MediaDemuxer;\nusing FlyleafLib.MediaFramework.MediaStream;\nusing Whisper.net;\nusing Whisper.net.LibraryLoader;\nusing Whisper.net.Logger;\nusing static FlyleafLib.Logger;\n\nnamespace FlyleafLib.MediaPlayer;\n\n#nullable enable\n\n// TODO: L: Pause and resume ASR\n\n/// \n/// Running ASR from a media file\n/// \n/// \n/// Read in a separate thread from the video playback.\n/// Note that multiple threads cannot seek to multiple locations for a single AVFormatContext,\n/// so it is necessary to open it with another avformat_open_input for the same video.\n/// \npublic class SubtitlesASR\n{\n private readonly SubtitlesManager _subtitlesManager;\n private readonly Config _config;\n private readonly Lock _locker = new();\n private readonly Lock _lockerSubs = new();\n private CancellationTokenSource? _cts = null;\n public HashSet SubIndexSet { get; } = new();\n\n private readonly LogHandler Log;\n\n public SubtitlesASR(SubtitlesManager subtitlesManager, Config config)\n {\n _subtitlesManager = subtitlesManager;\n _config = config;\n\n Log = new LogHandler((\"[#1]\").PadRight(8, ' ') + \" [SubtitlesASR ] \");\n }\n\n /// \n /// Check that ASR is executable\n /// \n /// error information\n /// \n public bool CanExecute(out string err)\n {\n if (_config.Subtitles.ASREngine == SubASREngineType.WhisperCpp)\n {\n if (_config.Subtitles.WhisperCppConfig.Model == null)\n {\n err = \"whisper.cpp model is not set. Please download it from the settings.\";\n return false;\n }\n\n if (!File.Exists(_config.Subtitles.WhisperCppConfig.Model.ModelFilePath))\n {\n err = $\"whisper.cpp model file '{_config.Subtitles.WhisperCppConfig.Model.ModelFileName}' does not exist in the folder. Please download it from the settings.\";\n return false;\n }\n }\n else if (_config.Subtitles.ASREngine == SubASREngineType.FasterWhisper)\n {\n if (_config.Subtitles.FasterWhisperConfig.UseManualEngine)\n {\n if (!File.Exists(_config.Subtitles.FasterWhisperConfig.ManualEnginePath))\n {\n err = \"faster-whisper engine does not exist in the manual path.\";\n return false;\n }\n }\n else\n {\n if (!File.Exists(FasterWhisperConfig.DefaultEnginePath))\n {\n err = \"faster-whisper engine is not downloaded. Please download it from the settings.\";\n return false;\n }\n }\n\n if (_config.Subtitles.FasterWhisperConfig.UseManualModel)\n {\n if (!Directory.Exists(_config.Subtitles.FasterWhisperConfig.ManualModelDir))\n {\n err = \"faster-whisper manual model directory does not exist.\";\n return false;\n }\n }\n }\n\n err = \"\";\n\n return true;\n }\n\n /// \n /// Open media file and read all subtitle data from audio\n /// \n /// 0: Primary, 1: Secondary\n /// media file path\n /// Audio streamIndex\n /// Demuxer type\n /// Current playback timestamp, from which whisper is run\n /// true: process completed, false: run in progress\n public bool Execute(int subIndex, string url, int streamIndex, MediaType type, TimeSpan curTime)\n {\n // When Dual ASR: Copy the other ASR result and return early\n if (SubIndexSet.Count > 0 && !SubIndexSet.Contains(subIndex))\n {\n lock (_lockerSubs)\n {\n SubIndexSet.Add(subIndex);\n int otherIndex = (subIndex + 1) % 2;\n\n if (_subtitlesManager[otherIndex].Subs.Count > 0)\n {\n bool enableTranslated = _config.Subtitles[subIndex].EnabledTranslated;\n\n // Copy other ASR result\n _subtitlesManager[subIndex]\n .Load(_subtitlesManager[otherIndex].Subs.Select(s =>\n {\n SubtitleData clone = s.Clone();\n\n if (!enableTranslated)\n {\n clone.TranslatedText = null;\n clone.EnabledTranslated = true;\n }\n\n return clone;\n }));\n\n if (!_subtitlesManager[otherIndex].IsLoading)\n {\n // Copy the language source if one of them is already done.\n _subtitlesManager[subIndex].LanguageSource = _subtitlesManager[otherIndex].LanguageSource;\n }\n }\n }\n\n // return early\n return false;\n }\n\n // If it has already been executed, cancel it to start over from the current playback position.\n if (SubIndexSet.Contains(subIndex))\n {\n Dictionary> prevSubs = new();\n HashSet prevSubIndexSet = [.. SubIndexSet];\n lock (_lockerSubs)\n {\n // backup current result\n foreach (int i in SubIndexSet)\n {\n prevSubs[i] = _subtitlesManager[i].Subs.ToList();\n }\n }\n // Cancel preceding execution and wait\n TryCancel(true);\n\n // restore previous result\n lock (_lockerSubs)\n {\n foreach (int i in prevSubIndexSet)\n {\n _subtitlesManager[i].Load(prevSubs[i]);\n // Re-enable spinner\n _subtitlesManager[i].StartLoading();\n\n SubIndexSet.Add(i);\n }\n }\n }\n\n lock (_locker)\n {\n SubIndexSet.Add(subIndex);\n\n _cts = new CancellationTokenSource();\n using AudioReader reader = new(_config, subIndex);\n reader.Open(url, streamIndex, type, _cts.Token);\n\n if (_cts.Token.IsCancellationRequested)\n {\n return true;\n }\n\n reader.ReadAll(curTime, data =>\n {\n if (_cts.Token.IsCancellationRequested)\n {\n return;\n }\n\n lock (_lockerSubs)\n {\n foreach (int i in SubIndexSet)\n {\n bool isInit = false;\n if (_subtitlesManager[i].LanguageSource == null)\n {\n isInit = true;\n\n // Delete subtitles after the first subtitle to be added (leave the previous one)\n _subtitlesManager[i].DeleteAfter(data.StartTime);\n\n // Set language\n // Can currently only be set for the whole, not per subtitle\n _subtitlesManager[i].LanguageSource = Language.Get(data.Language);\n }\n\n SubtitleData sub = new()\n {\n Text = data.Text,\n StartTime = data.StartTime,\n EndTime = data.EndTime,\n#if DEBUG\n ChunkNo = data.ChunkNo,\n StartTimeChunk = data.StartTimeChunk,\n EndTimeChunk = data.EndTimeChunk,\n#endif\n };\n\n _subtitlesManager[i].Add(sub);\n if (isInit)\n {\n _subtitlesManager[i].SetCurrentTime(new TimeSpan(_config.Subtitles.player.CurTime));\n }\n }\n }\n }, _cts.Token);\n\n if (!_cts.Token.IsCancellationRequested)\n {\n // TODO: L: Notify, express completion in some way\n Utils.PlayCompletionSound();\n }\n\n foreach (int i in SubIndexSet)\n {\n lock (_lockerSubs)\n {\n // Stop spinner (required when dual ASR)\n _subtitlesManager[i].StartLoading().Dispose();\n }\n }\n }\n\n return true;\n }\n\n public void TryCancel(bool isWait)\n {\n var cts = _cts;\n if (cts != null)\n {\n if (!cts.IsCancellationRequested)\n {\n lock (_lockerSubs)\n {\n foreach (var i in SubIndexSet)\n {\n _subtitlesManager[i].Clear();\n }\n }\n\n cts.Cancel();\n lock (_lockerSubs)\n {\n SubIndexSet.Clear();\n }\n }\n else\n {\n Log.Info(\"Already cancel requested\");\n }\n\n if (!isWait)\n {\n return;\n }\n\n lock (_locker)\n {\n // dispose after it is no longer used.\n cts.Dispose();\n _cts = null;\n }\n }\n }\n\n public void Reset(int subIndex)\n {\n if (!SubIndexSet.Contains(subIndex))\n return;\n\n if (SubIndexSet.Count == 2)\n {\n lock (_lockerSubs)\n {\n // When Dual ASR: only the state is cleared without stopping ASR execution.\n SubIndexSet.Remove(subIndex);\n _subtitlesManager[subIndex].Clear();\n }\n\n return;\n }\n\n // cancel asynchronously as it takes time to cancel.\n TryCancel(false);\n }\n}\n\npublic class AudioReader : IDisposable\n{\n private readonly Config _config;\n private readonly int _subIndex;\n\n private Demuxer? _demuxer;\n private AudioDecoder? _decoder;\n private AudioStream? _stream;\n\n private unsafe AVPacket* _packet = null;\n private unsafe AVFrame* _frame = null;\n private unsafe SwrContext* _swrContext = null;\n\n private bool _isFile;\n\n private readonly LogHandler Log;\n\n public AudioReader(Config config, int subIndex)\n {\n _config = config;\n _subIndex = subIndex;\n Log = new LogHandler((\"[#1]\").PadRight(8, ' ') + \" [AudioReader ] \");\n }\n\n public void Open(string url, int streamIndex, MediaType type, CancellationToken token)\n {\n _demuxer = new Demuxer(_config.Demuxer, type, _subIndex + 1, false);\n\n token.Register(() =>\n {\n if (_demuxer != null)\n _demuxer.Interrupter.ForceInterrupt = 1;\n });\n\n _demuxer.Log.Prefix = _demuxer.Log.Prefix.Replace(\"Demuxer: \", \"DemuxerA:\");\n string? error = _demuxer.Open(url);\n\n if (error != null)\n {\n if (token.IsCancellationRequested)\n return;\n\n throw new InvalidOperationException($\"demuxer open error: {error}\");\n }\n\n _stream = (AudioStream)_demuxer.AVStreamToStream[streamIndex];\n\n _decoder = new AudioDecoder(_config, _subIndex + 1);\n _decoder.Log.Prefix = _decoder.Log.Prefix.Replace(\"Decoder: \", \"DecoderA:\");\n\n error = _decoder.Open(_stream);\n\n if (error != null)\n {\n if (token.IsCancellationRequested)\n return;\n\n throw new InvalidOperationException($\"decoder open error: {error}\");\n }\n\n _isFile = File.Exists(url);\n }\n\n private record struct AudioChunk(MemoryStream Stream, int ChunkNumber, TimeSpan Start, TimeSpan End);\n\n /// \n /// Extract audio files in WAV format and run Whisper\n /// \n /// Current playback timestamp, from which whisper is run\n /// Action to process one result\n /// \n /// \n /// \n public void ReadAll(TimeSpan curTime, Action addSub, CancellationToken cancellationToken)\n {\n if (_demuxer == null || _decoder == null || _stream == null)\n throw new InvalidOperationException(\"Open() is not called\");\n\n // Assume a network stream and parallelize the reading of packets and the execution of whisper.\n // For network video, increase capacity as downloads may take longer.\n // (concern that memory usage will increase by three times the chunk size)\n int capacity = _isFile ? 1 : 2;\n BoundedChannelOptions channelOptions = new(capacity)\n {\n SingleReader = true,\n SingleWriter = true,\n };\n Channel channel = Channel.CreateBounded(channelOptions);\n\n // own cancellation for producer/consumer\n var cts = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken);\n CancellationToken token = cts.Token;\n\n ConcurrentStack memoryStreamPool = new();\n\n // Consumer: Run whisper\n Task consumerTask = Task.Run(DoConsumer, token);\n\n // Producer: Extract WAV and pass to consumer\n Task producerTask = Task.Run(DoProducer, token);\n\n // complete channel\n producerTask.ContinueWith(t =>\n channel.Writer.Complete(), token);\n\n // When an exception occurs in both consumer and producer, the other is canceled.\n consumerTask.ContinueWith(t =>\n cts.Cancel(), TaskContinuationOptions.OnlyOnFaulted);\n producerTask.ContinueWith(t =>\n cts.Cancel(), TaskContinuationOptions.OnlyOnFaulted);\n\n try\n {\n Task.WhenAll(consumerTask, producerTask).Wait();\n }\n catch (AggregateException)\n {\n if (cancellationToken.IsCancellationRequested)\n {\n // canceled by caller\n if (CanDebug) Log.Debug(\"Whisper canceled\");\n return;\n }\n\n // canceled because of exceptions\n throw;\n }\n\n return;\n\n async Task DoConsumer()\n {\n await using IASRService asrService = _config.Subtitles.ASREngine switch\n {\n SubASREngineType.WhisperCpp => new WhisperCppASRService(_config),\n SubASREngineType.FasterWhisper => new FasterWhisperASRService(_config),\n _ => throw new InvalidOperationException()\n };\n\n while (await channel.Reader.WaitToReadAsync(token))\n {\n // Use TryPeek() to reduce the channel capacity by one.\n if (!channel.Reader.TryPeek(out AudioChunk chunk))\n throw new InvalidOperationException(\"can not peek AudioChunk from channel\");\n\n try\n {\n if (CanDebug) Log.Debug(\n $\"Reading chunk from channel (chunkNo: {chunk.ChunkNumber}, start: {chunk.Start}, end: {chunk.End})\");\n\n //// Output wav file for debugging\n //await using (FileStream fs = new($\"subtitlewhisper-{chunk.ChunkNumber}.wav\", FileMode.Create, FileAccess.Write))\n //{\n // chunk.Stream.WriteTo(fs);\n // chunk.Stream.Position = 0;\n //}\n\n await foreach (var data in asrService.Do(chunk.Stream, token))\n {\n TimeSpan start = chunk.Start.Add(data.start);\n TimeSpan end = chunk.Start.Add(data.end);\n if (end > chunk.End)\n {\n // Shorten by 20 ms to prevent the next subtitle from being covered\n end = chunk.End.Subtract(TimeSpan.FromMilliseconds(20));\n }\n\n SubtitleASRData subData = new()\n {\n Text = data.text,\n Language = data.language,\n StartTime = start,\n EndTime = end,\n#if DEBUG\n ChunkNo = chunk.ChunkNumber,\n StartTimeChunk = chunk.Start,\n EndTimeChunk = chunk.End\n#endif\n };\n\n if (CanDebug) Log.Debug(string.Format(\"{0}->{1} ({2}->{3}): {4}\",\n start, end,\n chunk.Start, chunk.End,\n data.text));\n\n addSub(subData);\n }\n }\n finally\n {\n chunk.Stream.SetLength(0);\n memoryStreamPool.Push(chunk.Stream);\n\n if (!channel.Reader.TryRead(out _))\n throw new InvalidOperationException(\"can not discard AudioChunk from channel\");\n }\n }\n }\n\n unsafe void DoProducer()\n {\n _packet = av_packet_alloc();\n _frame = av_frame_alloc();\n\n // Whisper from the current playback position\n // TODO: L: Fold back and allow the first half to run as well.\n if (curTime > TimeSpan.FromSeconds(30))\n {\n // copy from DecoderContext.CalcSeekTimestamp()\n long startTime = _demuxer.hlsCtx == null ? _demuxer.StartTime : _demuxer.hlsCtx->first_timestamp * 10;\n long ticks = curTime.Ticks + startTime;\n\n bool forward = false;\n\n if (_demuxer.Type == MediaType.Audio) ticks -= _config.Audio.Delay;\n\n if (ticks < startTime)\n {\n ticks = startTime;\n forward = true;\n }\n else if (ticks > startTime + _demuxer.Duration - (50 * 10000))\n {\n ticks = Math.Max(startTime, startTime + _demuxer.Duration - (50 * 10000));\n forward = false;\n }\n\n _ = _demuxer.Seek(ticks, forward);\n }\n\n // When passing the audio file to Whisper, it must be converted to a 16000 sample rate WAV file.\n // For this purpose, the ffmpeg API is used to perform the conversion.\n // Audio files are divided by a certain size, stored in memory, and passed by memory stream.\n int targetSampleRate = 16000;\n int targetChannel = 1;\n MemoryStream waveStream = new(); // MemoryStream does not need to be disposed for releasing memory\n TimeSpan waveDuration = TimeSpan.Zero; // for logging\n\n const int waveHeaderSize = 44;\n\n // Stream processing is performed by dividing the audio by a certain size and passing it to whisper.\n long chunkSize = _config.Subtitles.ASRChunkSize;\n // Also split by elapsed seconds for live\n TimeSpan chunkElapsed = TimeSpan.FromSeconds(_config.Subtitles.ASRChunkSeconds);\n Stopwatch chunkSw = new();\n chunkSw.Start();\n\n WriteWavHeader(waveStream, targetSampleRate, targetChannel);\n\n int chunkCnt = 0;\n TimeSpan? chunkStart = null;\n long framePts = AV_NOPTS_VALUE;\n\n int demuxErrors = 0;\n int decodeErrors = 0;\n\n while (!token.IsCancellationRequested)\n {\n _demuxer.Interrupter.ReadRequest();\n int ret = av_read_frame(_demuxer.fmtCtx, _packet);\n\n if (ret != 0)\n {\n av_packet_unref(_packet);\n\n if (_demuxer.Interrupter.Timedout)\n {\n if (token.IsCancellationRequested)\n break;\n\n ret.ThrowExceptionIfError(\"av_read_frame (timed out)\");\n }\n\n if (ret == AVERROR_EOF || token.IsCancellationRequested)\n {\n break;\n }\n\n // demux error\n if (CanWarn) Log.Warn($\"av_read_frame: {FFmpegEngine.ErrorCodeToMsg(ret)} ({ret})\");\n\n if (++demuxErrors == _config.Demuxer.MaxErrors)\n {\n ret.ThrowExceptionIfError(\"av_read_frame\");\n }\n continue;\n }\n\n // Discard all but the selected audio stream.\n if (_packet->stream_index != _stream.StreamIndex)\n {\n av_packet_unref(_packet);\n continue;\n }\n\n ret = avcodec_send_packet(_decoder.CodecCtx, _packet);\n av_packet_unref(_packet);\n\n if (ret != 0)\n {\n if (ret == AVERROR(EAGAIN))\n {\n // Receive_frame and send_packet both returned EAGAIN, which is an API violation.\n ret.ThrowExceptionIfError(\"avcodec_send_packet (EAGAIN)\");\n }\n\n // decoder error\n if (CanWarn) Log.Warn($\"avcodec_send_packet: {FFmpegEngine.ErrorCodeToMsg(ret)} ({ret})\");\n\n if (++decodeErrors == _config.Decoder.MaxErrors)\n {\n ret.ThrowExceptionIfError(\"avcodec_send_packet\");\n }\n\n continue;\n }\n\n while (ret >= 0)\n {\n ret = avcodec_receive_frame(_decoder.CodecCtx, _frame);\n if (ret == AVERROR(EAGAIN) || ret == AVERROR_EOF)\n {\n break;\n }\n ret.ThrowExceptionIfError(\"avcodec_receive_frame\");\n\n if (_frame->best_effort_timestamp != AV_NOPTS_VALUE)\n {\n framePts = _frame->best_effort_timestamp;\n }\n else if (_frame->pts != AV_NOPTS_VALUE)\n {\n framePts = _frame->pts;\n }\n else\n {\n // Certain encoders sometimes cannot get pts (APE, Musepack)\n framePts += _frame->duration;\n }\n\n waveDuration = waveDuration.Add(new TimeSpan((long)(_frame->duration * _stream.Timebase)));\n\n if (chunkStart == null)\n {\n chunkStart = new TimeSpan((long)(framePts * _stream.Timebase) - _demuxer.StartTime);\n if (chunkStart.Value.Ticks < 0)\n {\n // Correct to 0 if negative\n chunkStart = new TimeSpan(0);\n }\n }\n\n ResampleTo(waveStream, _frame, targetSampleRate, targetChannel);\n\n // TODO: L: want it to split at the silent part\n if (waveStream.Length >= chunkSize || chunkSw.Elapsed >= chunkElapsed)\n {\n TimeSpan chunkEnd = new TimeSpan((long)(framePts * _stream.Timebase) - _demuxer.StartTime);\n chunkCnt++;\n\n if (CanInfo) Log.Info(\n $\"Process chunk (chunkNo: {chunkCnt}, sizeMB: {waveStream.Length / 1024 / 1024}, duration: {waveDuration}, elapsed: {chunkSw.Elapsed})\");\n\n UpdateWavHeader(waveStream);\n\n AudioChunk chunk = new(waveStream, chunkCnt, chunkStart.Value, chunkEnd);\n\n if (CanDebug) Log.Debug($\"Writing chunk to channel ({chunkCnt})\");\n // if channel capacity reached, it will be waited\n channel.Writer.WriteAsync(chunk, token).AsTask().Wait(token);\n if (CanDebug) Log.Debug($\"Done writing chunk to channel ({chunkCnt})\");\n\n if (memoryStreamPool.TryPop(out var stream))\n waveStream = stream;\n else\n waveStream = new MemoryStream();\n\n WriteWavHeader(waveStream, targetSampleRate, targetChannel);\n waveDuration = TimeSpan.Zero;\n\n chunkStart = null;\n chunkSw.Restart();\n framePts = AV_NOPTS_VALUE;\n }\n }\n }\n\n token.ThrowIfCancellationRequested();\n\n // Process remaining\n if (waveStream.Length > waveHeaderSize && framePts != AV_NOPTS_VALUE)\n {\n TimeSpan chunkEnd = new TimeSpan((long)(framePts * _stream.Timebase) - _demuxer.StartTime);\n\n chunkCnt++;\n\n if (CanInfo) Log.Info(\n $\"Process last chunk (chunkNo: {chunkCnt}, sizeMB: {waveStream.Length / 1024 / 1024}, duration: {waveDuration}, elapsed: {chunkSw.Elapsed})\");\n\n UpdateWavHeader(waveStream);\n\n AudioChunk chunk = new(waveStream, chunkCnt, chunkStart!.Value, chunkEnd);\n\n if (CanDebug) Log.Debug($\"Writing last chunk to channel ({chunkCnt})\");\n channel.Writer.WriteAsync(chunk, token).AsTask().Wait(token);\n if (CanDebug) Log.Debug($\"Done writing last chunk to channel ({chunkCnt})\");\n }\n }\n }\n\n private static void WriteWavHeader(Stream stream, int sampleRate, int channels)\n {\n using BinaryWriter writer = new(stream, Encoding.UTF8, true);\n writer.Write(['R', 'I', 'F', 'F']);\n writer.Write(0); // placeholder for file size\n writer.Write(['W', 'A', 'V', 'E']);\n writer.Write(['f', 'm', 't', ' ']);\n writer.Write(16); // PCM header size\n writer.Write((short)1); // PCM format\n writer.Write((short)channels);\n writer.Write(sampleRate);\n writer.Write(sampleRate * channels * 2); // Byte rate\n writer.Write((short)(channels * 2)); // Block align\n writer.Write((short)16); // Bits per sample\n writer.Write(['d', 'a', 't', 'a']);\n writer.Write(0); // placeholder for data size\n }\n\n private static void UpdateWavHeader(Stream stream)\n {\n long fileSize = stream.Length;\n stream.Seek(4, SeekOrigin.Begin);\n stream.Write(BitConverter.GetBytes((int)(fileSize - 8)), 0, 4);\n stream.Seek(40, SeekOrigin.Begin);\n stream.Write(BitConverter.GetBytes((int)(fileSize - 44)), 0, 4);\n stream.Position = 0;\n }\n\n private byte[] _sampledBuf = [];\n private int _sampledBufSize;\n\n // for codec change detection\n private int _lastFormat;\n private int _lastSampleRate;\n private ulong _lastChannelLayout;\n\n private unsafe void ResampleTo(Stream toStream, AVFrame* frame, int targetSampleRate, int targetChannel)\n {\n bool codecChanged = false;\n\n if (_lastFormat != frame->format)\n {\n _lastFormat = frame->format;\n codecChanged = true;\n }\n if (_lastSampleRate != frame->sample_rate)\n {\n _lastSampleRate = frame->sample_rate;\n codecChanged = true;\n }\n if (_lastChannelLayout != frame->ch_layout.u.mask)\n {\n _lastChannelLayout = frame->ch_layout.u.mask;\n codecChanged = true;\n }\n\n // Reinitialize SwrContext because codec changed\n // Note that native error will occur if not reinitialized.\n // Reference: AudioDecoder::RunInternal\n if (_swrContext != null && codecChanged)\n {\n fixed (SwrContext** ptr = &_swrContext)\n {\n swr_free(ptr);\n }\n _swrContext = null;\n }\n\n if (_swrContext == null)\n {\n AVChannelLayout outLayout;\n av_channel_layout_default(&outLayout, targetChannel);\n\n // NOTE: important to reuse this context\n fixed (SwrContext** ptr = &_swrContext)\n {\n swr_alloc_set_opts2(\n ptr,\n &outLayout,\n AVSampleFormat.S16,\n targetSampleRate,\n &frame->ch_layout,\n (AVSampleFormat)frame->format,\n frame->sample_rate,\n 0, null)\n .ThrowExceptionIfError(\"swr_alloc_set_opts2\");\n\n swr_init(_swrContext)\n .ThrowExceptionIfError(\"swr_init\");\n }\n }\n\n // ffmpeg ref: https://github.com/FFmpeg/FFmpeg/blob/504df09c34607967e4109b7b114ee084cf15a3ae/libavfilter/af_aresample.c#L171-L227\n double ratio = targetSampleRate * 1.0 / frame->sample_rate; // 16000:44100=0.36281179138321995\n int nOut = (int)(frame->nb_samples * ratio) + 32;\n\n long delay = swr_get_delay(_swrContext, targetSampleRate);\n if (delay > 0)\n {\n nOut += (int)Math.Min(delay, Math.Max(4096, nOut));\n }\n int needed = nOut * targetChannel * sizeof(ushort);\n\n if (_sampledBufSize < needed)\n {\n _sampledBuf = new byte[needed];\n _sampledBufSize = needed;\n }\n\n int samplesPerChannel;\n\n fixed (byte* dst = _sampledBuf)\n {\n samplesPerChannel = swr_convert(\n _swrContext,\n &dst,\n nOut,\n frame->extended_data,\n frame->nb_samples);\n }\n samplesPerChannel.ThrowExceptionIfError(\"swr_convert\");\n\n int resampledDataSize = samplesPerChannel * targetChannel * sizeof(ushort);\n\n toStream.Write(_sampledBuf, 0, resampledDataSize);\n }\n\n private bool _isDisposed;\n\n public unsafe void Dispose()\n {\n if (_isDisposed)\n return;\n\n // av_frame_alloc\n if (_frame != null)\n {\n fixed (AVFrame** ptr = &_frame)\n {\n av_frame_free(ptr);\n }\n }\n\n // av_packet_alloc\n if (_packet != null)\n {\n fixed (AVPacket** ptr = &_packet)\n {\n av_packet_free(ptr);\n }\n }\n\n // swr_init\n if (_swrContext != null)\n {\n fixed (SwrContext** ptr = &_swrContext)\n {\n swr_free(ptr);\n }\n }\n\n _decoder?.Dispose();\n if (_demuxer != null)\n {\n _demuxer.Interrupter.ForceInterrupt = 0;\n _demuxer.Dispose();\n }\n\n _isDisposed = true;\n }\n}\n\npublic interface IASRService : IAsyncDisposable\n{\n public IAsyncEnumerable<(string text, TimeSpan start, TimeSpan end, string language)> Do(MemoryStream waveStream, CancellationToken token);\n}\n\n// https://github.com/sandrohanea/whisper.net\n// https://github.com/ggerganov/whisper.cpp\npublic class WhisperCppASRService : IASRService\n{\n private readonly Config _config;\n\n private readonly LogHandler Log;\n private readonly IDisposable _logger;\n private readonly WhisperFactory _factory;\n private readonly WhisperProcessor _processor;\n\n private readonly bool _isLanguageDetect;\n private string? _detectedLanguage;\n\n public WhisperCppASRService(Config config)\n {\n _config = config;\n Log = new LogHandler((\"[#1]\").PadRight(8, ' ') + \" [WhisperCpp ] \");\n\n if (_config.Subtitles.WhisperCppConfig.RuntimeLibraries.Count >= 1)\n {\n RuntimeOptions.RuntimeLibraryOrder = [.. _config.Subtitles.WhisperCppConfig.RuntimeLibraries];\n }\n else\n {\n RuntimeOptions.RuntimeLibraryOrder = [RuntimeLibrary.Cpu, RuntimeLibrary.CpuNoAvx]; // fallback to default\n }\n\n _logger = CanDebug\n ? LogProvider.AddLogger((level, s) => Log.Debug($\"[Whisper.net] [{level.ToString()}] {s}\"))\n : Disposable.Empty;\n\n if (CanDebug) Log.Debug($\"Selecting whisper runtime libraries from ({string.Join(\",\", RuntimeOptions.RuntimeLibraryOrder)})\");\n\n _factory = WhisperFactory.FromPath(_config.Subtitles.WhisperCppConfig.Model!.ModelFilePath, _config.Subtitles.WhisperCppConfig.GetFactoryOptions());\n\n if (CanDebug) Log.Debug($\"Selected whisper runtime library '{RuntimeOptions.LoadedLibrary}'\");\n\n WhisperProcessorBuilder whisperBuilder = _factory.CreateBuilder();\n _processor = _config.Subtitles.WhisperCppConfig.ConfigureBuilder(_config.Subtitles.WhisperConfig, whisperBuilder).Build();\n\n if (_config.Subtitles.WhisperCppConfig.IsEnglishModel)\n {\n _isLanguageDetect = false;\n _detectedLanguage = \"en\";\n }\n else\n {\n _isLanguageDetect = _config.Subtitles.WhisperConfig.LanguageDetection;\n }\n }\n\n public async ValueTask DisposeAsync()\n {\n await _processor.DisposeAsync();\n _factory.Dispose();\n _logger.Dispose();\n }\n\n public async IAsyncEnumerable<(string text, TimeSpan start, TimeSpan end, string language)> Do(MemoryStream waveStream, [EnumeratorCancellation] CancellationToken token)\n {\n // If language detection is on, set detected language manually\n // TODO: L: Currently this is set because language information is managed for the entire subtitle,\n // but if language information is maintained for each subtitle, it should not be set.\n if (_isLanguageDetect && _detectedLanguage is not null)\n {\n _processor.ChangeLanguage(_detectedLanguage);\n }\n\n await foreach (var result in _processor.ProcessAsync(waveStream, token).ConfigureAwait(false))\n {\n token.ThrowIfCancellationRequested();\n\n if (_detectedLanguage is null && !string.IsNullOrEmpty(result.Language))\n {\n _detectedLanguage = result.Language;\n }\n\n string text = result.Text.Trim(); // remove leading whitespace\n\n yield return (text, result.Start, result.End, result.Language);\n }\n }\n}\n\n// https://github.com/Purfview/whisper-standalone-win\n// Purfview's Stand-alone Faster-Whisper-XXL & Faster-Whisper\n// Do not support official OpenAI Whisper version\npublic partial class FasterWhisperASRService : IASRService\n{\n private readonly Config _config;\n\n public FasterWhisperASRService(Config config)\n {\n _config = config;\n\n _cmdBase = BuildCommand(_config.Subtitles.FasterWhisperConfig, _config.Subtitles.WhisperConfig);\n\n if (_config.Subtitles.FasterWhisperConfig.IsEnglishModel)\n {\n // force English and disable auto-detection\n _isLanguageDetect = false;\n _manualLanguage = \"en\";\n }\n else\n {\n _isLanguageDetect = _config.Subtitles.WhisperConfig.LanguageDetection;\n _manualLanguage = _config.Subtitles.WhisperConfig.Language;\n }\n\n if (!_config.Subtitles.FasterWhisperConfig.UseManualModel)\n {\n WhisperConfig.EnsureModelsDirectory();\n }\n }\n\n private readonly Command _cmdBase;\n private readonly bool _isLanguageDetect;\n private readonly string _manualLanguage;\n private string? _detectedLanguage;\n\n [GeneratedRegex(\"^Detected language '(.+)' with probability\")]\n private static partial Regex LanguageReg { get; }\n\n [GeneratedRegex(@\"^\\[\\d{2}:\\d{2}\\.\\d{3} --> \\d{2}:\\d{2}\\.\\d{3}\\] \")]\n private static partial Regex SubShortReg { get; } // [08:15.050 --> 08:16.450] Text\n\n [GeneratedRegex(@\"^\\[\\d{2}:\\d{2}:\\d{2}\\.\\d{3} --> \\d{2}:\\d{2}:\\d{2}\\.\\d{3}\\] \")]\n private static partial Regex SubLongReg { get; } // [02:08:15.050 --> 02:08:16.450] Text\n\n [GeneratedRegex(\"^Operation finished in:\")]\n private static partial Regex EndReg { get; }\n\n\n public ValueTask DisposeAsync()\n {\n return ValueTask.CompletedTask;\n }\n\n public static Command BuildCommand(FasterWhisperConfig config, WhisperConfig commonConfig)\n {\n string tempFolder = Path.GetTempPath();\n string enginePath = config.UseManualEngine ? config.ManualEnginePath! : FasterWhisperConfig.DefaultEnginePath;\n\n ArgumentsBuilder args = new();\n args.Add(\"--output_dir\").Add(tempFolder);\n args.Add(\"--output_format\").Add(\"srt\");\n args.Add(\"--verbose\").Add(\"True\");\n args.Add(\"--beep_off\");\n args.Add(\"--model\").Add(config.Model);\n args.Add(\"--model_dir\")\n .Add(config.UseManualModel ? config.ManualModelDir! : WhisperConfig.ModelsDirectory);\n\n if (config.IsEnglishModel)\n {\n args.Add(\"--language\").Add(\"en\");\n }\n else\n {\n if (commonConfig.Translate)\n args.Add(\"--task\").Add(\"translate\");\n\n if (!commonConfig.LanguageDetection)\n args.Add(\"--language\").Add(commonConfig.Language);\n }\n\n string arguments = args.Build();\n\n if (!string.IsNullOrWhiteSpace(config.ExtraArguments))\n {\n arguments += $\" {config.ExtraArguments}\";\n }\n\n Command cmd = Cli.Wrap(enginePath)\n .WithArguments(arguments)\n .WithValidation(CommandResultValidation.None);\n\n if (config.ProcessPriority != ProcessPriorityClass.Normal)\n {\n cmd = cmd.WithResourcePolicy(builder =>\n builder.SetPriority(config.ProcessPriority));\n }\n\n return cmd;\n }\n\n private static TimeSpan ParseTime(ReadOnlySpan time, bool isLong)\n {\n if (isLong)\n {\n // 01:28:02.130\n // hh:mm:ss.fff\n int hours = int.Parse(time[..2]);\n int minutes = int.Parse(time[3..5]);\n int seconds = int.Parse(time[6..8]);\n int milliseconds = int.Parse(time[9..12]);\n return new TimeSpan(0, hours, minutes, seconds, milliseconds);\n }\n else\n {\n // 28:02.130\n // mm:ss.fff\n int minutes = int.Parse(time[..2]);\n int seconds = int.Parse(time[3..5]);\n int milliseconds = int.Parse(time[6..9]);\n return new TimeSpan(0, 0, minutes, seconds, milliseconds);\n }\n }\n\n public async IAsyncEnumerable<(string text, TimeSpan start, TimeSpan end, string language)> Do(MemoryStream waveStream, [EnumeratorCancellation] CancellationToken token)\n {\n string tempFilePath = Path.GetTempFileName();\n // because no output option\n string outputFilePath = Path.ChangeExtension(tempFilePath, \"srt\");\n\n // write WAV to tmp folder\n await using (FileStream fileStream = new(tempFilePath, FileMode.Create, FileAccess.Write))\n {\n waveStream.WriteTo(fileStream);\n }\n\n CancellationTokenSource forceCts = new();\n token.Register(() =>\n {\n // force kill if not exited when sending interrupt\n forceCts.CancelAfter(5000);\n });\n\n try\n {\n string? lastLine = null;\n StringBuilder output = new(); // for error output\n Lock outputLock = new();\n bool oneSuccess = false;\n\n ArgumentsBuilder args = new();\n if (_isLanguageDetect && !string.IsNullOrEmpty(_detectedLanguage))\n {\n args.Add(\"--language\").Add(_detectedLanguage);\n }\n args.Add(tempFilePath);\n string addedArgs = args.Build();\n\n Command cmd = _cmdBase.WithArguments($\"{_cmdBase.Arguments} {addedArgs}\");\n\n await foreach (var cmdEvent in cmd.ListenAsync(Encoding.Default, Encoding.Default, forceCts.Token, token))\n {\n token.ThrowIfCancellationRequested();\n\n if (cmdEvent is StandardErrorCommandEvent stdErr)\n {\n lock (outputLock)\n {\n output.AppendLine(stdErr.Text);\n }\n\n continue;\n }\n\n if (cmdEvent is not StandardOutputCommandEvent stdOut)\n {\n continue;\n }\n\n string line = stdOut.Text;\n\n // process stdout\n if (!oneSuccess)\n {\n lock (outputLock)\n {\n output.AppendLine(line);\n }\n\n }\n if (string.IsNullOrEmpty(line))\n {\n continue;\n }\n\n lastLine = line;\n\n if (_isLanguageDetect && _detectedLanguage == null)\n {\n var match = LanguageReg.Match(line);\n if (match.Success)\n {\n string languageName = match.Groups[1].Value;\n _detectedLanguage = WhisperLanguage.LanguageToCode[languageName];\n }\n\n continue;\n }\n\n bool isLong = false;\n\n Match subtitleMatch = SubShortReg.Match(line);\n if (!subtitleMatch.Success)\n {\n subtitleMatch = SubLongReg.Match(line);\n if (!subtitleMatch.Success)\n {\n continue;\n }\n\n isLong = true;\n }\n\n ReadOnlySpan lineSpan = line.AsSpan();\n\n Range startRange = 1..10;\n Range endRange = 15..24;\n Range textRange = 26..;\n\n if (isLong)\n {\n startRange = 1..13;\n endRange = 18..30;\n textRange = 32..;\n }\n\n TimeSpan start = ParseTime(lineSpan[startRange], isLong);\n TimeSpan end = ParseTime(lineSpan[endRange], isLong);\n // because some languages have leading spaces\n string text = lineSpan[textRange].Trim().ToString();\n\n yield return (text, start, end, _isLanguageDetect ? _detectedLanguage! : _manualLanguage);\n\n if (!oneSuccess)\n {\n oneSuccess = true;\n }\n }\n\n // validate if success\n if (lastLine == null || !EndReg.Match(lastLine).Success)\n {\n throw new InvalidOperationException(\"Failed to execute faster-whisper\")\n {\n Data =\n {\n [\"whisper_command\"] = cmd.CommandToText(),\n [\"whisper_output\"] = output.ToString()\n }\n };\n }\n }\n finally\n {\n // delete tmp wave\n if (File.Exists(tempFilePath))\n {\n File.Delete(tempFilePath);\n }\n // delete output srt\n if (File.Exists(outputFilePath))\n {\n File.Delete(outputFilePath);\n }\n }\n }\n}\n\npublic class SubtitleASRData\n{\n public required string Text { get; init; }\n public required TimeSpan StartTime { get; init; }\n public required TimeSpan EndTime { get; init; }\n\n#if DEBUG\n public required int ChunkNo { get; init; }\n public required TimeSpan StartTimeChunk { get; init; }\n public required TimeSpan EndTimeChunk { get; init; }\n#endif\n\n public TimeSpan Duration => EndTime - StartTime;\n\n // ISO6391\n // ref: https://github.com/openai/whisper/blob/main/whisper/tokenizer.py#L10\n public required string Language { get; init; }\n}\n"], ["/LLPlayer/FlyleafLib/MediaPlayer/Subtitles.cs", "using System.Collections.ObjectModel;\nusing FlyleafLib.MediaFramework.MediaContext;\nusing FlyleafLib.MediaFramework.MediaStream;\nusing System.ComponentModel;\nusing System.Diagnostics;\nusing System.Linq;\nusing System.Threading.Tasks;\nusing System.Windows;\nusing System.Windows.Media.Imaging;\nusing static FlyleafLib.Utils;\n\nnamespace FlyleafLib.MediaPlayer;\n\npublic class SubsBitmap\n{\n public WriteableBitmap Source { get; set; }\n public int X { get; set; }\n public int Y { get; set; }\n public int Width { get; set; }\n public int Height { get; set; }\n}\n\npublic class SubsBitmapPosition : NotifyPropertyChanged\n{\n private readonly Player _player;\n private readonly int _subIndex;\n\n public SubsBitmapPosition(Player player, int subIndex)\n {\n _player = player;\n _subIndex = subIndex;\n\n Calculate();\n }\n\n #region Config\n\n public double ConfScale\n {\n get;\n set\n {\n if (value <= 0)\n {\n return;\n }\n\n if (Set(ref field, Math.Round(value, 2)))\n {\n Calculate();\n }\n }\n } = 1.0; // x 1.0\n\n public double ConfPos\n {\n get;\n set\n {\n if (value < 0 || value > 150)\n {\n return;\n }\n\n if (Set(ref field, Math.Round(value)))\n {\n Calculate();\n }\n }\n } = 100; // 0 - 150\n\n #endregion\n\n #region WPF Property\n\n public Thickness? Margin { get; private set => Set(ref field, value); }\n\n public double ScaleX { get; private set => Set(ref field, value); } = 1.0;\n\n public double ScaleY { get; private set => Set(ref field, value); } = 1.0;\n\n /// \n /// True for horizontal subtitles\n /// Bitmap subtitles may be displayed vertically\n /// \n public bool IsHorizontal { get; private set; }\n\n #endregion\n\n public void Reset()\n {\n ConfScale = 1.0;\n ConfPos = 100;\n\n Margin = null;\n ScaleX = 1.0;\n ScaleY = 1.0;\n IsHorizontal = false;\n }\n\n public void Calculate()\n {\n if (_player.Subtitles == null ||\n _player.Subtitles[_subIndex].Data.Bitmap == null ||\n _player.SubtitlesDecoders[_subIndex].SubtitlesStream == null ||\n (_player.SubtitlesDecoders[_subIndex].Width == 0 && _player.SubtitlesManager[_subIndex].Width == 0) ||\n (_player.SubtitlesDecoders[_subIndex].Height == 0 && _player.SubtitlesManager[_subIndex].Height == 0))\n {\n return;\n }\n\n SubsBitmap bitmap = _player.Subtitles[_subIndex].Data.Bitmap;\n\n // Calculate the ratio of the current width of the window to the width of the video\n double renderWidth = _player.VideoDecoder.Renderer.GetViewport.Width;\n double videoWidth = _player.SubtitlesDecoders[_subIndex].Width;\n if (videoWidth == 0)\n {\n // Restore from cache because Width/Height may not be taken if the subtitle is not decoded enough.\n videoWidth = _player.SubtitlesManager[_subIndex].Width;\n }\n\n // double videoHeight_ = (int)(videoWidth / Player.VideoDemuxer.VideoStream.AspectRatio.Value);\n double renderHeight = _player.VideoDecoder.Renderer.GetViewport.Height;\n double videoHeight = _player.SubtitlesDecoders[_subIndex].Height;\n if (videoHeight == 0)\n {\n videoHeight = _player.SubtitlesManager[_subIndex].Height;\n }\n\n // In aspect ratio like a movie, a black background may be added to the top and bottom.\n // In this case, the subtitles should be placed based on the video display area, so the offset from the image rendering area excluding the black background should be taken into consideration.\n double yOffset = _player.renderer.GetViewport.Y;\n double xOffset = _player.renderer.GetViewport.X;\n\n double scaleFactorX = renderWidth / videoWidth;\n // double scaleFactorY = renderHeight / videoHeight;\n\n // Adjust subtitle size by the calculated ratio\n double scaleX = scaleFactorX;\n // double scaleY = scaleFactorY;\n\n // Note that if you are cropping videos with mkv in Handbrake, the subtitles will be crushed vertically if you don't use this one. vlc will crush them, but mpv will not have a problem.\n // It may be nice to be able to choose between the two.\n double scaleY = scaleX;\n\n double x = bitmap.X * scaleFactorX + xOffset;\n\n double yPosition = bitmap.Y / videoHeight;\n double y = renderHeight * yPosition + yOffset;\n\n // Adjust subtitle position(y - axis) by config.\n // However, if it detects that the subtitle is not a normal subtitle such as vertical subtitle, it will not be adjusted.\n // (Adjust only when it is below the center of the screen)\n // mpv: https://github.com/mpv-player/mpv/blob/df166c1333694cbfe70980dbded1984d48b0685a/sub/sd_lavc.c#L491-L494\n IsHorizontal = (bitmap.Y >= videoHeight / 2);\n if (IsHorizontal)\n {\n // mpv: https://github.com/mpv-player/mpv/blob/df166c1333694cbfe70980dbded1984d48b0685a/sub/sd_lavc.c#L486\n double offset = (100.0 - ConfPos) / 100.0 * videoHeight;\n y -= offset * scaleY;\n }\n\n // Adjust x and y axes when changing subtitle size(centering)\n if (ConfScale != 1.0)\n {\n // mpv: https://github.com/mpv-player/mpv/blob/df166c1333694cbfe70980dbded1984d48b0685a/sub/sd_lavc.c#L508-L515\n double ratio = (ConfScale - 1.0) / 2;\n\n double dw = bitmap.Width * scaleX;\n double dy = bitmap.Height * scaleY;\n\n x -= dw * ratio;\n y -= dy * ratio;\n\n scaleX *= ConfScale;\n scaleY *= ConfScale;\n }\n\n Margin = new Thickness(x, y, 0, 0);\n ScaleX = scaleX;\n ScaleY = scaleY;\n }\n}\n\npublic class SubsData : NotifyPropertyChanged\n{\n#nullable enable\n private readonly Player _player;\n private readonly int _subIndex;\n private Subtitles Subs => _player.Subtitles;\n private Config Config => _player.Config;\n\n public SubsData(Player player, int subIndex)\n {\n _player = player;\n _subIndex = subIndex;\n\n BitmapPosition = new SubsBitmapPosition(_player, _subIndex);\n\n Config.Subtitles[_subIndex].PropertyChanged += SubConfigOnPropertyChanged;\n }\n\n private void SubConfigOnPropertyChanged(object? sender, PropertyChangedEventArgs e)\n {\n if (e.PropertyName == nameof(Config.SubConfig.Visible))\n {\n Raise(nameof(IsVisible));\n Raise(nameof(IsAbsoluteVisible));\n Raise(nameof(IsDisplaying));\n }\n }\n\n /// \n /// Subtitles Position (Position & Scale)\n /// \n public SubsBitmapPosition BitmapPosition { get; }\n\n /// \n /// Subtitles Bitmap\n /// \n public SubsBitmap? Bitmap\n {\n get;\n internal set\n {\n if (!Set(ref field, value))\n {\n return;\n }\n\n BitmapPosition.Calculate();\n\n if (Bitmap != null)\n {\n // TODO: L: When vertical and horizontal subtitles are displayed at the same time, the subtitles are displayed incorrectly\n // Absolute display of Primary sub\n // 1. If Primary is true and Secondary is false\n // 2. When a vertical subtitle is detected\n\n // Absolute display of Secondary sub\n // 1. When a vertical subtitle is detected\n bool isAbsolute = Subs[0].Enabled && !Subs[1].Enabled;\n if (!BitmapPosition.IsHorizontal)\n {\n isAbsolute = true;\n }\n\n IsAbsolute = isAbsolute;\n }\n\n Raise(nameof(IsDisplaying));\n }\n }\n\n /// \n /// Whether subtitles are currently displayed or not\n /// (unless bitmap subtitles are displayed absolutely)\n /// \n public bool IsDisplaying => IsVisible && (Bitmap != null && !IsAbsolute // Bitmap subtitles, not absolute display\n ||\n !string.IsNullOrEmpty(Text)); // When text subtitles are available\n\n /// \n /// When vertical subtitle is detected in the case of bitmap sub, it becomes True and is displayed as absolute.\n /// \n public bool IsAbsolute\n {\n get;\n private set\n {\n if (Set(ref field, value))\n {\n Raise(nameof(IsAbsoluteVisible));\n Raise(nameof(IsDisplaying));\n }\n }\n } = false;\n\n /// \n /// Bind target Used for switching Visibility\n /// \n public bool IsAbsoluteVisible => IsAbsolute && IsVisible;\n\n /// \n /// Bind target Used for switching Visibility\n /// \n public bool IsVisible => Config.Subtitles[_subIndex].Visible;\n\n /// \n /// Subtitles Text (updates dynamically while playing based on the duration that it should be displayed)\n /// \n public string Text\n {\n get;\n internal set\n {\n if (Set(ref field, value))\n {\n Raise(nameof(IsDisplaying));\n }\n }\n } = \"\";\n\n public bool IsTranslated { get; set => Set(ref field, value); }\n\n public Language? Language { get; set => Set(ref field, value); }\n\n public void Reset()\n {\n Clear();\n UI(() =>\n {\n // Clear does not reset because there is a config in SubsBitmapPosition\n BitmapPosition.Reset();\n });\n }\n\n public void Clear()\n {\n if (Text != \"\" || Bitmap != null)\n {\n UI(() =>\n {\n Text = \"\";\n Bitmap = null;\n });\n }\n }\n#nullable restore\n}\n\n/// \n/// Preserve the state of streamIndex, URL, etc. of the currently selected subtitle in a global variable.\n/// TODO: L: Cannot use multiple Players in one app, required to change this?\n/// \npublic static class SubtitlesSelectedHelper\n{\n#nullable enable\n public static ValueTuple? Primary { get; set; }\n public static ValueTuple? Secondary { get; set; }\n\n public static SelectSubMethod PrimaryMethod { get; set; } = SelectSubMethod.Original;\n public static SelectSubMethod SecondaryMethod { get; set; } = SelectSubMethod.Original;\n\n /// \n /// Holds the index to switch (0: Primary, 1: Secondary)\n /// \n public static int CurIndex { get; set; } = 0;\n\n public static void Reset(int subIndex)\n {\n Debug.Assert(subIndex is 0 or 1);\n\n if (subIndex == 1)\n {\n Secondary = null;\n SecondaryMethod = SelectSubMethod.Original;\n }\n else\n {\n Primary = null;\n PrimaryMethod = SelectSubMethod.Original;\n }\n }\n\n public static SelectSubMethod GetMethod(int subIndex)\n {\n Debug.Assert(subIndex is 0 or 1);\n\n return subIndex == 1 ? SecondaryMethod : PrimaryMethod;\n }\n\n public static void SetMethod(int subIndex, SelectSubMethod method)\n {\n Debug.Assert(subIndex is 0 or 1);\n\n if (subIndex == 1)\n {\n SecondaryMethod = method;\n }\n else\n {\n PrimaryMethod = method;\n }\n }\n\n public static ValueTuple? Get(int subIndex)\n {\n Debug.Assert(subIndex is 0 or 1);\n return subIndex == 1 ? Secondary : Primary;\n }\n\n public static void Set(int subIndex, ValueTuple? tuple)\n {\n Debug.Assert(subIndex is 0 or 1);\n if (subIndex == 1)\n {\n Secondary = tuple;\n }\n else\n {\n Primary = tuple;\n }\n }\n\n public static bool GetSubEnabled(this StreamBase stream, int subIndex)\n {\n Debug.Assert(subIndex is 0 or 1);\n var tuple = subIndex == 1 ? Secondary : Primary;\n\n if (!tuple.HasValue)\n {\n return false;\n }\n\n if (tuple.Value.Item1.HasValue)\n {\n // internal sub\n return tuple.Value.Item1 == stream.StreamIndex;\n }\n\n if (tuple.Value.Item2 is not null && stream.ExternalStream is not null)\n {\n // external sub\n return GetSubEnabled(stream.ExternalStream, subIndex);\n }\n\n return false;\n }\n\n public static bool GetSubEnabled(this ExternalStream stream, int subIndex)\n {\n ArgumentNullException.ThrowIfNull(stream);\n\n return GetSubEnabled(stream.Url, subIndex);\n }\n\n public static bool GetSubEnabled(this string url, int subIndex)\n {\n Debug.Assert(subIndex is 0 or 1);\n var tuple = subIndex == 1 ? Secondary : Primary;\n\n if (!tuple.HasValue || tuple.Value.Item2 is null)\n {\n return false;\n }\n\n return tuple.Value.Item2.Url == url;\n }\n#nullable restore\n}\n\npublic class Subtitle : NotifyPropertyChanged\n{\n private readonly Player _player;\n private readonly int _subIndex;\n\n private Config Config => _player.Config;\n private DecoderContext Decoder => _player?.decoder;\n\n public Subtitle(int subIndex, Player player)\n {\n _player = player;\n _subIndex = subIndex;\n\n Data = new SubsData(_player, _subIndex);\n }\n\n #pragma warning disable CS9266\n public bool EnabledASR { get => _enabledASR; private set => Set(ref field, value); }\n private bool _enabledASR;\n\n /// \n /// Whether the input has subtitles and it is configured\n /// \n public bool IsOpened { get => _isOpened; private set => Set(ref field, value); }\n private bool _isOpened;\n\n public string Codec { get => _codec; private set => Set(ref field, value); }\n private string _codec;\n\n public bool IsBitmap { get => _isBitmap; private set => Set(ref field, value); }\n private bool _isBitmap;\n #pragma warning restore CS9266\n\n public bool Enabled => IsOpened || EnabledASR;\n\n public SubsData Data { get; }\n\n private void UpdateUI()\n {\n UI(() =>\n {\n IsOpened = IsOpened;\n Codec = Codec;\n IsBitmap = IsBitmap;\n EnabledASR = EnabledASR;\n });\n }\n\n internal void Reset()\n {\n _codec = null;\n _isOpened = false;\n _isBitmap = false;\n _player.sFramesPrev[_subIndex] = null;\n // TODO: L: Here it may be null when switching subs while displaying.\n _player.sFrames[_subIndex] = null;\n _enabledASR = false;\n\n _player.SubtitlesASR.Reset(_subIndex);\n _player.SubtitlesOCR.Reset(_subIndex);\n _player.SubtitlesManager[_subIndex].Reset();\n\n _player.SubtitleClear(_subIndex);\n //_player.renderer?.ClearOverlayTexture();\n\n SubtitlesSelectedHelper.Reset(_subIndex);\n\n Data.Reset();\n UpdateUI();\n }\n\n internal void Refresh()\n {\n var subStream = Decoder.SubtitlesStreams[_subIndex];\n\n if (subStream == null)\n {\n Reset();\n return;\n }\n\n _codec = subStream.Codec;\n _isOpened = !Decoder.SubtitlesDecoders[_subIndex].Disposed;\n _isBitmap = subStream is { IsBitmap: true };\n\n // Update the selection state of automatically opened subtitles\n // (also manually updated but no problem as it is no change, necessary for primary subtitles)\n if (subStream.ExternalStream is ExternalSubtitlesStream extStream)\n {\n // external sub\n SubtitlesSelectedHelper.Set(_subIndex, (null, extStream));\n }\n else if (subStream.StreamIndex != -1)\n {\n // internal sub\n SubtitlesSelectedHelper.Set(_subIndex, (subStream.StreamIndex, null));\n }\n\n Data.Reset();\n _player.sFramesPrev[_subIndex] = null;\n _player.sFrames[_subIndex] = null;\n _player.SubtitleClear(_subIndex);\n //player.renderer?.ClearOverlayTexture();\n\n _enabledASR = false;\n _player.SubtitlesASR.Reset(_subIndex);\n _player.SubtitlesOCR.Reset(_subIndex);\n _player.SubtitlesManager[_subIndex].Reset();\n\n if (_player.renderer != null)\n {\n // Adjust bitmap subtitle size when resizing screen\n _player.renderer.ViewportChanged -= RendererOnViewportChanged;\n _player.renderer.ViewportChanged += RendererOnViewportChanged;\n }\n\n UpdateUI();\n\n // Create cache of the all subtitles in a separate thread\n Task.Run(Load)\n .ContinueWith(t =>\n {\n // TODO: L: error handling - restore state gracefully?\n if (t.IsFaulted)\n {\n var ex = t.Exception.Flatten().InnerException;\n\n _player.RaiseUnknownErrorOccurred($\"Cannot load all subtitles on worker thread: {ex?.Message}\", UnknownErrorType.Subtitles, ex);\n }\n }, TaskContinuationOptions.OnlyOnFaulted);\n }\n\n internal void Load()\n {\n SubtitlesStream stream = Decoder.SubtitlesStreams[_subIndex];\n ExternalSubtitlesStream extStream = stream.ExternalStream as ExternalSubtitlesStream;\n\n if (extStream != null)\n {\n // external sub\n // always load all bitmaps on memory with external subtitles\n _player.SubtitlesManager.Open(_subIndex, stream.Demuxer.Url, stream.StreamIndex, stream.Demuxer.Type, true, extStream.Language);\n }\n else\n {\n // internal sub\n // load all bitmaps on memory when cache enabled or OCR used\n bool useBitmap = Config.Subtitles.EnabledCached || SubtitlesSelectedHelper.GetMethod(_subIndex) == SelectSubMethod.OCR;\n _player.SubtitlesManager.Open(_subIndex, stream.Demuxer.Url, stream.StreamIndex, stream.Demuxer.Type, useBitmap, stream.Language);\n }\n\n TimeSpan curTime = new(_player.CurTime);\n\n _player.SubtitlesManager[_subIndex].SetCurrentTime(curTime);\n\n // Do OCR\n // TODO: L: When OCR is performed while bitmap stream is loaded, the stream is reset and the bitmap is loaded again.\n // Is it better to reuse loaded bitmap?\n if (SubtitlesSelectedHelper.GetMethod(_subIndex) == SelectSubMethod.OCR)\n {\n using (_player.SubtitlesManager[_subIndex].StartLoading())\n {\n _player.SubtitlesOCR.Do(_subIndex, _player.SubtitlesManager[_subIndex].Subs.ToList(), curTime);\n }\n }\n }\n\n internal void Enable()\n {\n if (!_player.CanPlay)\n return;\n\n // TODO: L: For some reason, there is a problem with subtitles temporarily not being\n // displayed, waiting for about 10 seconds will fix it.\n Decoder.OpenSuggestedSubtitles(_subIndex);\n\n _player.ReSync(Decoder.SubtitlesStreams[_subIndex], (int)(_player.CurTime / 10000), true);\n\n Refresh();\n UpdateUI();\n }\n internal void Disable()\n {\n if (!Enabled)\n return;\n\n Decoder.CloseSubtitles(_subIndex);\n Reset();\n UpdateUI();\n\n SubtitlesSelectedHelper.Reset(_subIndex);\n }\n\n private void RendererOnViewportChanged(object sender, EventArgs e)\n {\n Data.BitmapPosition.Calculate();\n }\n\n public void EnableASR()\n {\n _enabledASR = true;\n\n var url = _player.AudioDecoder.Demuxer.Url;\n var type = _player.AudioDecoder.Demuxer.Type;\n var streamIndex = _player.AudioDecoder.AudioStream.StreamIndex;\n\n TimeSpan curTime = new(_player.CurTime);\n\n Task.Run(() =>\n {\n bool isDone;\n\n using (_player.SubtitlesManager[_subIndex].StartLoading())\n {\n isDone = _player.SubtitlesASR.Execute(_subIndex, url, streamIndex, type, curTime);\n }\n\n if (!isDone)\n {\n // re-enable spinner because it is running\n _player.SubtitlesManager[_subIndex].StartLoading();\n }\n })\n .ContinueWith(t =>\n {\n if (t.IsFaulted)\n {\n if (_player.SubtitlesManager[_subIndex].Subs.Count == 0)\n {\n // reset if not single subtitles generated\n Disable();\n }\n\n var ex = t.Exception.Flatten().InnerException;\n\n _player.RaiseUnknownErrorOccurred($\"Cannot execute ASR: {ex?.Message}\", UnknownErrorType.ASR, t.Exception);\n }\n }, TaskContinuationOptions.OnlyOnFaulted);\n\n UpdateUI();\n }\n}\n\npublic class Subtitles\n{\n /// \n /// Embedded Streams\n /// \n public ObservableCollection\n Streams => _player.decoder?.VideoDemuxer.SubtitlesStreamsAll;\n\n private readonly Subtitle[] _subs;\n\n // indexer\n public Subtitle this[int i] => _subs[i];\n\n public Player Player => _player;\n\n private readonly Player _player;\n\n private Config Config => _player.Config;\n\n private int subNum => Config.Subtitles.Max;\n\n public Subtitles(Player player)\n {\n _player = player;\n _subs = new Subtitle[subNum];\n\n for (int i = 0; i < subNum; i++)\n {\n _subs[i] = new Subtitle(i, _player);\n }\n }\n\n internal void Enable()\n {\n for (int i = 0; i < subNum; i++)\n {\n this[i].Enable();\n }\n }\n\n internal void Disable()\n {\n for (int i = 0; i < subNum; i++)\n {\n this[i].Disable();\n }\n }\n\n internal void Reset()\n {\n for (int i = 0; i < subNum; i++)\n {\n this[i].Reset();\n }\n }\n\n internal void Refresh()\n {\n for (int i = 0; i < subNum; i++)\n {\n this[i].Refresh();\n }\n }\n\n // TODO: L: refactor\n public void DelayRemovePrimary() => Config.Subtitles[0].Delay -= Config.Player.SubtitlesDelayOffset;\n public void DelayAddPrimary() => Config.Subtitles[0].Delay += Config.Player.SubtitlesDelayOffset;\n public void DelayRemove2Primary() => Config.Subtitles[0].Delay -= Config.Player.SubtitlesDelayOffset2;\n public void DelayAdd2Primary() => Config.Subtitles[0].Delay += Config.Player.SubtitlesDelayOffset2;\n\n public void DelayRemoveSecondary() => Config.Subtitles[1].Delay -= Config.Player.SubtitlesDelayOffset;\n public void DelayAddSecondary() => Config.Subtitles[1].Delay += Config.Player.SubtitlesDelayOffset;\n public void DelayRemove2Secondary() => Config.Subtitles[1].Delay -= Config.Player.SubtitlesDelayOffset2;\n public void DelayAdd2Secondary() => Config.Subtitles[1].Delay += Config.Player.SubtitlesDelayOffset2;\n\n public void ToggleEnabled() => Config.Subtitles.Enabled = !Config.Subtitles.Enabled;\n\n public void ToggleVisibility()\n {\n Config.Subtitles[0].Visible = !Config.Subtitles[0].Visible;\n Config.Subtitles[1].Visible = Config.Subtitles[0].Visible;\n }\n public void ToggleVisibilityPrimary()\n {\n Config.Subtitles[0].Visible = !Config.Subtitles[0].Visible;\n }\n\n public void ToggleVisibilitySecondary()\n {\n Config.Subtitles[1].Visible = !Config.Subtitles[1].Visible;\n }\n\n private bool _prevSeek(int subIndex)\n {\n var prev = _player.SubtitlesManager[subIndex].GetPrev();\n if (prev is not null)\n {\n _player.SeekAccurate(prev.StartTime, subIndex);\n return true;\n }\n\n return false;\n }\n\n public void PrevSeek() => _prevSeek(0);\n public void PrevSeek2() => _prevSeek(1);\n\n public void PrevSeekFallback()\n {\n if (!_prevSeek(0))\n {\n _player.SeekBackward2();\n }\n }\n public void PrevSeekFallback2()\n {\n if (!_prevSeek(1))\n {\n _player.SeekBackward2();\n }\n }\n\n private void _curSeek(int subIndex)\n {\n var cur = _player.SubtitlesManager[subIndex].GetCurrent();\n if (cur is not null)\n {\n _player.SeekAccurate(cur.StartTime, subIndex);\n }\n else\n {\n // fallback to prevSeek (same as mpv)\n _prevSeek(subIndex);\n }\n }\n\n public void CurSeek() => _curSeek(0);\n public void CurSeek2() => _curSeek(1);\n\n private bool _nextSeek(int subIndex)\n {\n var next = _player.SubtitlesManager[subIndex].GetNext();\n if (next is not null)\n {\n _player.SeekAccurate(next.StartTime, subIndex);\n return true;\n }\n return false;\n }\n\n public void NextSeek() => _nextSeek(0);\n public void NextSeek2() => _nextSeek(1);\n\n public void NextSeekFallback()\n {\n if (!_nextSeek(0))\n {\n _player.SeekForward2();\n }\n }\n public void NextSeekFallback2()\n {\n if (!_nextSeek(1))\n {\n _player.SeekForward2();\n }\n }\n}\n"], ["/LLPlayer/FlyleafLib/MediaPlayer/SubtitlesManager.cs", "using System.Collections.Generic;\nusing System.Collections.ObjectModel;\nusing System.Collections.Specialized;\nusing System.ComponentModel;\nusing System.Diagnostics;\nusing System.Linq;\nusing System.Runtime.CompilerServices;\nusing System.Runtime.InteropServices;\nusing System.Threading;\nusing System.Windows;\nusing System.Windows.Data;\nusing System.Windows.Media;\nusing System.Windows.Media.Imaging;\nusing FlyleafLib.MediaFramework.MediaDecoder;\nusing FlyleafLib.MediaFramework.MediaDemuxer;\nusing FlyleafLib.MediaFramework.MediaFrame;\nusing FlyleafLib.MediaFramework.MediaRenderer;\nusing FlyleafLib.MediaFramework.MediaStream;\nusing FlyleafLib.MediaPlayer.Translation;\nusing static FlyleafLib.Logger;\n\nnamespace FlyleafLib.MediaPlayer;\n\n#nullable enable\n\npublic class SubtitlesManager\n{\n private readonly SubManager[] _subManagers;\n public SubManager this[int subIndex] => _subManagers[subIndex];\n private readonly int _subNum;\n\n public SubtitlesManager(Config config, int subNum)\n {\n _subNum = subNum;\n _subManagers = new SubManager[subNum];\n for (int i = 0; i < subNum; i++)\n {\n _subManagers[i] = new SubManager(config, i);\n }\n }\n\n /// \n /// Open a file and read all subtitle data by streaming\n /// \n /// 0: Primary, 1: Secondary\n /// subtitle file path or video file path\n /// streamIndex of subtitle\n /// demuxer media type\n /// Use bitmap subtitles or immediately release bitmap if not used\n /// subtitle language\n public void Open(int subIndex, string url, int streamIndex, MediaType type, bool useBitmap, Language lang)\n {\n // TODO: L: Add caching subtitle data for the same stream and URL?\n this[subIndex].Open(url, streamIndex, type, useBitmap, lang);\n }\n\n public void SetCurrentTime(TimeSpan currentTime)\n {\n for (int i = 0; i < _subNum; i++)\n {\n this[i].SetCurrentTime(currentTime);\n }\n }\n}\n\npublic class SubManager : INotifyPropertyChanged\n{\n private readonly Lock _locker = new();\n private CancellationTokenSource? _cts;\n public SubtitleData? SelectedSub { get; set => Set(ref field, value); }\n public int CurrentIndex { get; private set => Set(ref field, value); } = -1;\n\n public PositionState State\n {\n get;\n private set\n {\n bool prevIsDisplaying = IsDisplaying;\n if (Set(ref field, value) && prevIsDisplaying != IsDisplaying)\n {\n OnPropertyChanged(nameof(IsDisplaying));\n }\n }\n } = PositionState.First;\n\n public bool IsDisplaying => State == PositionState.Showing;\n\n /// \n /// List of subtitles that can be bound to ItemsControl\n /// Must be sorted with timestamp to perform binary search.\n /// \n public BulkObservableCollection Subs { get; } = new();\n\n /// \n /// True when addition to Subs is running... (Reading all subtitles, OCR, ASR)\n /// \n public bool IsLoading { get; private set => Set(ref field, value); }\n\n // LanguageSource with fallback\n public Language? Language\n {\n get\n {\n if (LanguageSource == Language.Unknown)\n {\n // fallback to user set language\n return _subIndex == 0 ? _config.Subtitles.LanguageFallbackPrimary : _config.Subtitles.LanguageFallbackSecondary;\n }\n\n return LanguageSource;\n }\n }\n\n public Language? LanguageSource\n {\n get;\n set\n {\n if (Set(ref field, value))\n {\n OnPropertyChanged(nameof(Language));\n }\n }\n }\n\n // For displaying bitmap subtitles, manage video width and height\n public int Width { get; internal set; }\n public int Height { get; internal set; }\n\n private readonly object _subsLocker = new();\n private readonly Config _config;\n private readonly int _subIndex;\n private readonly SubTranslator _subTranslator;\n private readonly LogHandler Log;\n\n public SubManager(Config config, int subIndex, bool enableSync = true)\n {\n _config = config;\n _subIndex = subIndex;\n // TODO: L: Review whether to initialize it here.\n _subTranslator = new SubTranslator(this, config.Subtitles, subIndex);\n Log = new LogHandler((\"[#1]\").PadRight(8, ' ') + $\" [SubManager{subIndex + 1} ] \");\n\n if (enableSync)\n {\n // Enable binding to ItemsControl\n Utils.UIInvokeIfRequired(() =>\n {\n BindingOperations.EnableCollectionSynchronization(Subs, _subsLocker);\n });\n }\n }\n\n public enum PositionState\n {\n First, // still haven't reached the first subtitle\n Showing, // currently displaying\n Around, // not displayed and can seek before and after\n Last // After the last subtitle\n }\n\n /// \n /// Force UI refresh\n /// \n internal void Refresh()\n {\n // NOTE: If it is not executed in the main thread, the following error occurs.\n // System.NotSupportedException: 'This type of CollectionView does not support'\n Utils.UI(() =>\n {\n CollectionViewSource.GetDefaultView(Subs).Refresh();\n OnPropertyChanged(nameof(CurrentIndex)); // required for translating current sub\n });\n }\n\n /// \n /// This must be called when doing heavy operation\n /// \n /// \n internal IDisposable StartLoading()\n {\n IsLoading = true;\n\n return Disposable.Create(() =>\n {\n IsLoading = false;\n });\n }\n\n public void Load(IEnumerable items)\n {\n lock (_subsLocker)\n {\n CurrentIndex = -1;\n SelectedSub = null;\n Subs.Clear();\n Subs.AddRange(items);\n }\n }\n\n public void Add(SubtitleData sub)\n {\n lock (_subsLocker)\n {\n sub.Index = Subs.Count;\n Subs.Add(sub);\n }\n }\n\n public void AddRange(IEnumerable items)\n {\n lock (_subsLocker)\n {\n Subs.AddRange(items);\n }\n }\n\n public SubtitleData? GetCurrent()\n {\n lock (_subsLocker)\n {\n if (Subs.Count == 0 || CurrentIndex == -1)\n {\n return null;\n }\n\n Debug.Assert(CurrentIndex < Subs.Count);\n\n if (State == PositionState.Showing)\n {\n return Subs[CurrentIndex];\n }\n\n return null;\n }\n }\n\n public SubtitleData? GetNext()\n {\n lock (_subsLocker)\n {\n if (Subs.Count == 0)\n {\n return null;\n }\n\n switch (State)\n {\n case PositionState.First:\n return Subs[0];\n\n case PositionState.Showing:\n if (CurrentIndex < Subs.Count - 1)\n return Subs[CurrentIndex + 1];\n break;\n\n case PositionState.Around:\n if (CurrentIndex < Subs.Count - 1)\n return Subs[CurrentIndex + 1];\n break;\n }\n\n return null;\n }\n }\n\n public SubtitleData? GetPrev()\n {\n lock (_subsLocker)\n {\n if (Subs.Count == 0 || CurrentIndex == -1)\n return null;\n\n switch (State)\n {\n case PositionState.Showing:\n if (CurrentIndex > 0)\n return Subs[CurrentIndex - 1];\n break;\n\n case PositionState.Around:\n if (CurrentIndex >= 0)\n return Subs[CurrentIndex];\n break;\n\n case PositionState.Last:\n return Subs[^1];\n }\n }\n\n return null;\n }\n\n private readonly SubtitleData _searchSub = new();\n\n public SubManager SetCurrentTime(TimeSpan currentTime)\n {\n // Adjust the display timing of subtitles by adjusting the timestamp of the video\n currentTime = currentTime.Subtract(new TimeSpan(_config.Subtitles[_subIndex].Delay));\n\n lock (_subsLocker)\n {\n // If no subtitle data is loaded, nothing is done.\n if (Subs.Count == 0)\n return this;\n\n // If it is a subtitle that is displaying, it does nothing.\n var curSub = GetCurrent();\n if (curSub != null && curSub.StartTime < currentTime && curSub.EndTime > currentTime)\n {\n return this;\n }\n\n _searchSub.StartTime = currentTime;\n\n int ret = Subs.BinarySearch(_searchSub, SubtitleTimeStartComparer.Instance);\n int cur = -1;\n\n if (~ret == 0)\n {\n CurrentIndex = -1;\n SelectedSub = null;\n State = PositionState.First;\n return this;\n }\n\n if (ret < 0)\n {\n // The reason subtracting 1 is that the result of the binary search is the next big index.\n cur = (~ret) - 1;\n }\n else\n {\n // If the starting position is matched, it is unlikely\n cur = ret;\n }\n\n Debug.Assert(cur >= 0, \"negative index detected\");\n Debug.Assert(cur < Subs.Count, \"out of bounds detected\");\n\n if (cur == Subs.Count - 1)\n {\n if (Subs[cur].EndTime < currentTime)\n {\n CurrentIndex = cur;\n SelectedSub = Subs[cur];\n State = PositionState.Last;\n }\n else\n {\n CurrentIndex = cur;\n SelectedSub = Subs[cur];\n State = PositionState.Showing;\n }\n }\n else\n {\n if (Subs[cur].StartTime <= currentTime && Subs[cur].EndTime >= currentTime)\n {\n // Show subtitles\n CurrentIndex = cur;\n SelectedSub = Subs[cur];\n State = PositionState.Showing;\n }\n else if (Subs[cur].StartTime <= currentTime)\n {\n // Almost there to display in currentIndex.\n CurrentIndex = cur;\n SelectedSub = Subs[cur];\n State = PositionState.Around;\n }\n }\n }\n\n return this;\n }\n\n public void Sort()\n {\n lock (_subsLocker)\n {\n if (Subs.Count == 0)\n return;\n\n Subs.Sort(SubtitleTimeStartComparer.Instance);\n }\n }\n\n public void DeleteAfter(TimeSpan time)\n {\n lock (_subsLocker)\n {\n if (Subs.Count == 0)\n return;\n\n int index = Subs.BinarySearch(new SubtitleData { EndTime = time }, new SubtitleTimeEndComparer());\n\n if (index < 0)\n {\n index = ~index;\n }\n\n if (index < Subs.Count)\n {\n var newSubs = Subs.GetRange(0, index).ToList();\n var deleteSubs = Subs.GetRange(index, Subs.Count - index).ToList();\n Load(newSubs);\n\n foreach (var sub in deleteSubs)\n {\n sub.Dispose();\n }\n }\n }\n }\n\n public void Open(string url, int streamIndex, MediaType type, bool useBitmap, Language lang)\n {\n // Asynchronously read subtitle timestamps and text\n\n // Cancel if already executed\n TryCancelWait();\n\n lock (_locker)\n {\n using var loading = StartLoading();\n\n List subChunk = new();\n\n try\n {\n _cts = new CancellationTokenSource();\n using SubtitleReader reader = new(this, _config, _subIndex);\n reader.Open(url, streamIndex, type, _cts.Token);\n\n _cts.Token.ThrowIfCancellationRequested();\n\n bool isFirst = true;\n int subCnt = 0;\n\n Stopwatch refreshSw = new();\n refreshSw.Start();\n\n reader.ReadAll(useBitmap, data =>\n {\n if (isFirst)\n {\n isFirst = false;\n // Set the language at the timing of the first subtitle data set.\n LanguageSource = lang;\n\n Log.Info($\"Start loading subs... (lang:{lang.TopEnglishName})\");\n }\n\n data.Index = subCnt++;\n subChunk.Add(data);\n\n // Large files and network files take time to load to the end.\n // To prevent frequent UI updates, use AddRange to group files to some extent before adding them.\n if (subChunk.Count >= 2 && refreshSw.Elapsed > TimeSpan.FromMilliseconds(500))\n {\n AddRange(subChunk);\n subChunk.Clear();\n refreshSw.Restart();\n }\n }, _cts.Token);\n\n // Process remaining\n if (subChunk.Count > 0)\n {\n AddRange(subChunk);\n }\n refreshSw.Stop();\n Log.Info(\"End loading subs\");\n }\n catch (OperationCanceledException)\n {\n foreach (var sub in subChunk)\n {\n sub.Dispose();\n }\n\n Clear();\n }\n }\n }\n\n public void TryCancelWait()\n {\n if (_cts != null)\n {\n // If it has already been executed, cancel it and wait until the preceding process is finished.\n // (It waits because it has a lock)\n _cts.Cancel();\n lock (_locker)\n {\n // dispose after it is no longer used.\n _cts.Dispose();\n _cts = null;\n }\n }\n }\n\n public void Clear()\n {\n lock (_subsLocker)\n {\n CurrentIndex = -1;\n SelectedSub = null;\n foreach (var sub in Subs)\n {\n sub.Dispose();\n }\n Subs.Clear();\n State = PositionState.First;\n LanguageSource = null;\n IsLoading = false;\n Width = 0;\n Height = 0;\n }\n }\n\n public void Reset()\n {\n TryCancelWait();\n Clear();\n }\n\n #region INotifyPropertyChanged\n public event PropertyChangedEventHandler? PropertyChanged;\n\n protected virtual void OnPropertyChanged([CallerMemberName] string? propertyName = null)\n {\n PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));\n }\n\n protected bool Set(ref T field, T value, [CallerMemberName] string? propertyName = null)\n {\n if (EqualityComparer.Default.Equals(field, value))\n return false;\n field = value;\n OnPropertyChanged(propertyName);\n return true;\n }\n #endregion\n}\n\npublic unsafe class SubtitleReader : IDisposable\n{\n private readonly SubManager _manager;\n private readonly Config _config;\n private readonly LogHandler Log;\n private readonly int _subIndex;\n\n private Demuxer? _demuxer;\n private SubtitlesDecoder? _decoder;\n private SubtitlesStream? _stream;\n\n private AVPacket* _packet = null;\n\n public SubtitleReader(SubManager manager, Config config, int subIndex)\n {\n _manager = manager;\n _config = config;\n Log = new LogHandler((\"[#1]\").PadRight(8, ' ') + $\" [SubReader{subIndex + 1} ] \");\n\n _subIndex = subIndex;\n }\n\n public void Open(string url, int streamIndex, MediaType type, CancellationToken token)\n {\n _demuxer = new Demuxer(_config.Demuxer, type, _subIndex + 1, false);\n\n token.Register(() =>\n {\n if (_demuxer != null)\n _demuxer.Interrupter.ForceInterrupt = 1;\n });\n\n _demuxer.Log.Prefix = _demuxer.Log.Prefix.Replace(\"Demuxer: \", \"DemuxerS:\");\n string? error = _demuxer.Open(url);\n\n if (error != null)\n {\n token.ThrowIfCancellationRequested(); // if canceled\n\n throw new InvalidOperationException($\"demuxer open error: {error}\");\n }\n\n _stream = (SubtitlesStream)_demuxer.AVStreamToStream[streamIndex];\n\n if (type == MediaType.Subs)\n {\n\n _stream.ExternalStream = new ExternalSubtitlesStream()\n {\n Url = url,\n IsBitmap = _stream.IsBitmap\n };\n\n _stream.ExternalStreamAdded();\n }\n\n _decoder = new SubtitlesDecoder(_config, _subIndex + 1);\n _decoder.Log.Prefix = _decoder.Log.Prefix.Replace(\"Decoder: \", \"DecoderS:\");\n error = _decoder.Open(_stream);\n\n if (error != null)\n {\n token.ThrowIfCancellationRequested(); // if canceled\n\n throw new InvalidOperationException($\"decoder open error: {error}\");\n }\n }\n\n /// \n /// Read subtitle stream to the end and get all subtitle data\n /// \n /// \n /// \n /// \n /// The token has had cancellation requested.\n public void ReadAll(bool useBitmap, Action addSub, CancellationToken token)\n {\n if (_demuxer == null || _decoder == null || _stream == null)\n throw new InvalidOperationException(\"Open() is not called\");\n\n SubtitleData? prevSub = null;\n\n _packet = av_packet_alloc();\n\n int demuxErrors = 0;\n int decodeErrors = 0;\n\n while (!token.IsCancellationRequested)\n {\n _demuxer.Interrupter.ReadRequest();\n int ret = av_read_frame(_demuxer.fmtCtx, _packet);\n\n if (ret != 0)\n {\n av_packet_unref(_packet);\n\n if (_demuxer.Interrupter.Timedout)\n {\n if (token.IsCancellationRequested)\n break;\n\n ret.ThrowExceptionIfError(\"av_read_frame (timed out)\");\n }\n\n if (ret == AVERROR_EOF || token.IsCancellationRequested)\n {\n break;\n }\n\n // demux error\n if (CanWarn) Log.Warn($\"av_read_frame: {FFmpegEngine.ErrorCodeToMsg(ret)} ({ret})\");\n\n if (++demuxErrors == _config.Demuxer.MaxErrors)\n {\n ret.ThrowExceptionIfError(\"av_read_frame\");\n }\n\n continue;\n }\n\n // Discard all but the subtitle stream.\n if (_packet->stream_index != _stream.StreamIndex)\n {\n av_packet_unref(_packet);\n continue;\n }\n\n SubtitleData subData = new();\n int gotSub = 0;\n AVSubtitle sub = default;\n\n ret = avcodec_decode_subtitle2(_decoder.CodecCtx, &sub, &gotSub, _packet);\n if (ret < 0)\n {\n // decode error\n av_packet_unref(_packet);\n if (CanWarn) Log.Warn($\"avcodec_decode_subtitle2: {FFmpegEngine.ErrorCodeToMsg(ret)} ({ret})\");\n if (++decodeErrors == _config.Decoder.MaxErrors)\n {\n ret.ThrowExceptionIfError(\"avcodec_decode_subtitle2\");\n }\n\n continue;\n }\n\n if (gotSub == 0)\n {\n av_packet_unref(_packet);\n continue;\n }\n\n long pts = AV_NOPTS_VALUE; // 0.1us\n if (sub.pts != AV_NOPTS_VALUE)\n {\n pts = sub.pts /*us*/ * 10;\n }\n else if (_packet->pts != AV_NOPTS_VALUE)\n {\n pts = (long)(_packet->pts * _stream.Timebase);\n }\n\n av_packet_unref(_packet);\n\n if (pts == AV_NOPTS_VALUE)\n {\n continue;\n }\n\n if (_stream.IsBitmap)\n {\n // Cache the width and height of the video for use in displaying bitmap subtitles\n // width and height may be 0 unless after decoding the subtitles\n // In this case, bitmap subtitles cannot be displayed correctly, so the size should be cached here\n if (_manager.Width != _decoder.CodecCtx->width)\n _manager.Width = _decoder.CodecCtx->width;\n if (_manager.Height != _decoder.CodecCtx->height)\n _manager.Height = _decoder.CodecCtx->height;\n }\n\n // Bitmap PGS has a special format.\n if (_stream.IsBitmap && prevSub != null\n /*&& _stream->codecpar->codec_id == AVCodecID.AV_CODEC_ID_HDMV_PGS_SUBTITLE*/)\n {\n if (sub.num_rects < 1)\n {\n // Support for special format bitmap subtitles.\n // In the case of bitmap subtitles, num_rects = 0 and 1 may alternate.\n // In this case sub->start_display_time and sub->end_display_time are always fixed at 0 and\n // AVPacket->duration is also always 0.\n // This indicates the end of the previous subtitle, and the time in pts is the end time of the previous subtitle.\n\n // Note that not all bitmap subtitles have this behavior.\n\n // Assign pts as the end time of the previous subtitle\n prevSub.EndTime = new TimeSpan(pts - _demuxer.StartTime);\n addSub(prevSub);\n prevSub = null;\n\n avsubtitle_free(&sub);\n continue;\n }\n\n // There are cases where num_rects = 1 is consecutive.\n // In this case, the previous subtitle end time is corrected by pts, and a new subtitle is started with the same pts.\n if (prevSub.Bitmap?.Sub.end_display_time == uint.MaxValue) // 4294967295\n {\n prevSub.EndTime = new TimeSpan(pts - _demuxer.StartTime);\n addSub(prevSub);\n prevSub = null;\n }\n }\n\n subData.StartTime = new TimeSpan(pts - _demuxer.StartTime);\n subData.EndTime = subData.StartTime.Add(TimeSpan.FromMilliseconds(sub.end_display_time));\n\n switch (sub.rects[0]->type)\n {\n case AVSubtitleType.Text:\n subData.Text = Utils.BytePtrToStringUTF8(sub.rects[0]->text).Trim();\n avsubtitle_free(&sub);\n\n if (string.IsNullOrEmpty(subData.Text))\n {\n continue;\n }\n\n break;\n case AVSubtitleType.Ass:\n string text = Utils.BytePtrToStringUTF8(sub.rects[0]->ass).Trim();\n avsubtitle_free(&sub);\n\n subData.Text = ParseSubtitles.SSAtoSubStyles(text, out var subStyles).Trim();\n subData.SubStyles = subStyles;\n\n if (string.IsNullOrEmpty(subData.Text))\n {\n continue;\n }\n\n break;\n\n case AVSubtitleType.Bitmap:\n subData.IsBitmap = true;\n\n if (useBitmap)\n {\n // Save subtitle data for (OCR or subtitle cache)\n subData.Bitmap = new SubtitleBitmapData(sub);\n }\n else\n {\n // Only subtitle timestamp information is used, so bitmap is released\n avsubtitle_free(&sub);\n }\n\n break;\n }\n\n if (prevSub != null)\n {\n addSub(prevSub);\n }\n\n prevSub = subData;\n }\n\n if (token.IsCancellationRequested)\n {\n prevSub?.Dispose();\n token.ThrowIfCancellationRequested();\n }\n\n // Process last\n if (prevSub != null)\n {\n addSub(prevSub);\n }\n }\n\n private bool _isDisposed;\n public void Dispose()\n {\n if (_isDisposed)\n return;\n\n // av_packet_alloc\n if (_packet != null)\n {\n fixed (AVPacket** ptr = &_packet)\n {\n av_packet_free(ptr);\n }\n }\n\n _decoder?.Dispose();\n if (_demuxer != null)\n {\n _demuxer.Interrupter.ForceInterrupt = 0;\n _demuxer.Dispose();\n }\n\n _isDisposed = true;\n }\n}\n\npublic class SubtitleBitmapData : IDisposable\n{\n public SubtitleBitmapData(AVSubtitle sub)\n {\n Sub = sub;\n }\n\n private readonly ReaderWriterLockSlim _rwLock = new();\n private bool _isDisposed;\n\n public AVSubtitle Sub;\n\n public WriteableBitmap SubToWritableBitmap(bool isGrey)\n {\n (byte[] data, AVSubtitleRect rect) = SubToBitmap(isGrey);\n\n WriteableBitmap wb = new(\n rect.w, rect.h,\n Utils.NativeMethods.DpiXSource, Utils.NativeMethods.DpiYSource,\n PixelFormats.Bgra32, null\n );\n Int32Rect dirtyRect = new(0, 0, rect.w, rect.h);\n wb.Lock();\n\n Marshal.Copy(data, 0, wb.BackBuffer, data.Length);\n\n wb.AddDirtyRect(dirtyRect);\n wb.Unlock();\n wb.Freeze();\n\n return wb;\n }\n\n public unsafe (byte[] data, AVSubtitleRect rect) SubToBitmap(bool isGrey)\n {\n if (_isDisposed)\n throw new InvalidOperationException(\"already disposed\");\n\n try\n {\n // Prevent from disposing\n _rwLock.EnterReadLock();\n\n AVSubtitleRect rect = *Sub.rects[0];\n byte[] data = Renderer.ConvertBitmapSub(Sub, isGrey);\n\n return (data, rect);\n }\n finally\n {\n _rwLock.ExitReadLock();\n }\n }\n\n public void Dispose()\n {\n if (_isDisposed)\n return;\n\n _rwLock.EnterWriteLock();\n\n if (Sub.num_rects > 0)\n {\n unsafe\n {\n fixed (AVSubtitle* subPtr = &Sub)\n {\n avsubtitle_free(subPtr);\n }\n }\n }\n\n _isDisposed = true;\n _rwLock.ExitWriteLock();\n\n#if DEBUG\n GC.SuppressFinalize(this);\n#endif\n }\n\n#if DEBUG\n ~SubtitleBitmapData()\n {\n System.Diagnostics.Debug.Fail(\"Dispose is not called\");\n }\n#endif\n}\n\npublic class SubtitleData : IDisposable, INotifyPropertyChanged\n{\n public int Index { get; set; }\n\n public string? Text\n {\n get;\n set\n {\n var prevIsText = IsText;\n if (Set(ref field, value))\n {\n if (prevIsText != IsText)\n OnPropertyChanged(nameof(IsText));\n OnPropertyChanged(nameof(DisplayText));\n }\n }\n }\n\n public string? TranslatedText\n {\n get;\n set\n {\n var prevUseTranslated = UseTranslated;\n if (Set(ref field, value))\n {\n if (prevUseTranslated != UseTranslated)\n {\n OnPropertyChanged(nameof(UseTranslated));\n }\n OnPropertyChanged(nameof(DisplayText));\n }\n }\n }\n\n public bool IsText => !string.IsNullOrEmpty(Text);\n\n public bool IsTranslated => TranslatedText != null;\n public bool UseTranslated => EnabledTranslated && IsTranslated;\n\n public bool EnabledTranslated = true;\n\n public string? DisplayText => UseTranslated ? TranslatedText : Text;\n\n public List? SubStyles;\n public TimeSpan StartTime { get; set; }\n public TimeSpan EndTime { get; set; }\n#if DEBUG\n public int ChunkNo { get; set => Set(ref field, value); }\n public TimeSpan StartTimeChunk { get; set => Set(ref field, value); }\n public TimeSpan EndTimeChunk { get; set => Set(ref field, value); }\n#endif\n public TimeSpan Duration => EndTime - StartTime;\n\n public SubtitleBitmapData? Bitmap { get; set; }\n\n public bool IsBitmap { get; set; }\n\n private bool _isDisposed;\n\n public void Dispose()\n {\n if (_isDisposed)\n return;\n\n if (IsBitmap && Bitmap != null)\n {\n Bitmap.Dispose();\n Bitmap = null;\n }\n\n _isDisposed = true;\n }\n\n public SubtitleData Clone()\n {\n return new SubtitleData()\n {\n Index = Index,\n Text = Text,\n TranslatedText = TranslatedText,\n EnabledTranslated = EnabledTranslated,\n StartTime = StartTime,\n EndTime = EndTime,\n#if DEBUG\n ChunkNo = ChunkNo,\n StartTimeChunk = StartTimeChunk,\n EndTimeChunk = EndTimeChunk,\n#endif\n IsBitmap = IsBitmap,\n Bitmap = null,\n };\n }\n\n #region INotifyPropertyChanged\n public event PropertyChangedEventHandler? PropertyChanged;\n protected virtual void OnPropertyChanged([CallerMemberName] string? propertyName = null)\n {\n PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));\n }\n\n protected bool Set(ref T field, T value, [CallerMemberName] string? propertyName = null)\n {\n if (EqualityComparer.Default.Equals(field, value))\n return false;\n field = value;\n OnPropertyChanged(propertyName);\n return true;\n }\n #endregion\n}\n\npublic class SubtitleTimeStartComparer : Comparer\n{\n public static SubtitleTimeStartComparer Instance { get; } = new();\n private SubtitleTimeStartComparer() { }\n static SubtitleTimeStartComparer() { }\n\n public override int Compare(SubtitleData? x, SubtitleData? y)\n {\n if (object.Equals(x, y)) return 0;\n if (x == null) return -1;\n if (y == null) return 1;\n\n return x.StartTime.CompareTo(y.StartTime);\n }\n}\n\npublic class SubtitleTimeEndComparer : Comparer\n{\n public override int Compare(SubtitleData? x, SubtitleData? y)\n {\n if (object.Equals(x, y)) return 0;\n if (x == null) return -1;\n if (y == null) return 1;\n\n return x.EndTime.CompareTo(y.EndTime);\n }\n}\n\ninternal static class WrapperHelper\n{\n public static int ThrowExceptionIfError(this int error, string message)\n {\n if (error < 0)\n {\n string errStr = AvErrorStr(error);\n throw new InvalidOperationException($\"{message}: {errStr} ({error})\");\n }\n\n return error;\n }\n\n public static unsafe string AvErrorStr(this int error)\n {\n int bufSize = 1024;\n byte* buf = stackalloc byte[bufSize];\n\n if (av_strerror(error, buf, (nuint)bufSize) == 0)\n {\n string errStr = Marshal.PtrToStringAnsi((IntPtr)buf)!;\n return errStr;\n }\n\n return \"unknown error\";\n }\n}\n\npublic static class ObservableCollectionExtensions\n{\n public static int FindIndex(this ObservableCollection collection, Predicate match)\n {\n ArgumentNullException.ThrowIfNull(collection);\n ArgumentNullException.ThrowIfNull(match);\n\n for (int i = 0; i < collection.Count; i++)\n {\n if (match(collection[i]))\n return i;\n }\n return -1;\n }\n\n public static int BinarySearch(this ObservableCollection collection, T item, IComparer comparer)\n {\n ArgumentNullException.ThrowIfNull(collection);\n\n //comparer ??= Comparer.Default;\n int low = 0;\n int high = collection.Count - 1;\n\n while (low <= high)\n {\n int mid = low + ((high - low) / 2);\n int comparison = comparer.Compare(collection[mid], item);\n\n if (comparison == 0)\n return mid;\n if (comparison < 0)\n low = mid + 1;\n else\n high = mid - 1;\n }\n\n return ~low;\n }\n\n public static IEnumerable GetRange(this ObservableCollection collection, int index, int count)\n {\n ArgumentNullException.ThrowIfNull(collection);\n if (index < 0 || count < 0 || (index + count) > collection.Count)\n throw new ArgumentOutOfRangeException();\n\n return collection.Skip(index).Take(count);\n }\n\n public static void Sort(this ObservableCollection collection, IComparer comparer)\n {\n ArgumentNullException.ThrowIfNull(collection);\n ArgumentNullException.ThrowIfNull(comparer);\n\n List sortedList = collection.ToList();\n sortedList.Sort(comparer);\n\n collection.Clear();\n foreach (var item in sortedList)\n {\n collection.Add(item);\n }\n }\n}\n\npublic class BulkObservableCollection : ObservableCollection\n{\n private bool _suppressNotification;\n\n protected override void OnCollectionChanged(NotifyCollectionChangedEventArgs e)\n {\n if (!_suppressNotification)\n base.OnCollectionChanged(e);\n }\n\n public void AddRange(IEnumerable list)\n {\n ArgumentNullException.ThrowIfNull(list);\n\n _suppressNotification = true;\n\n foreach (T item in list)\n {\n Add(item);\n }\n _suppressNotification = false;\n\n OnCollectionChanged(new NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction.Reset));\n }\n}\n"], ["/LLPlayer/FlyleafLib/Plugins/OpenSubtitles.cs", "using System.Collections.Generic;\nusing System.IO;\nusing System.Linq;\nusing System.Text;\nusing FlyleafLib.MediaFramework.MediaStream;\nusing Lingua;\n\nnamespace FlyleafLib.Plugins;\n\npublic class OpenSubtitles : PluginBase, IOpenSubtitles, ISearchLocalSubtitles\n{\n public new int Priority { get; set; } = 3000;\n\n private static readonly Lazy LanguageDetector = new(() =>\n {\n LanguageDetector detector = LanguageDetectorBuilder\n .FromAllLanguages()\n .Build();\n\n return detector;\n }, true);\n\n private static readonly HashSet ExtSet = new(Utils.ExtensionsSubtitles, StringComparer.OrdinalIgnoreCase);\n\n public OpenSubtitlesResults Open(string url)\n {\n foreach (var extStream in Selected.ExternalSubtitlesStreamsAll)\n if (extStream.Url == url)\n return new(extStream);\n\n string title;\n\n if (File.Exists(url))\n {\n Selected.FillMediaParts();\n\n FileInfo fi = new(url);\n title = fi.Name;\n }\n else\n {\n try\n {\n Uri uri = new(url);\n title = Path.GetFileName(uri.LocalPath);\n\n if (title == null || title.Trim().Length == 0)\n title = url;\n\n } catch\n {\n title = url;\n }\n }\n\n ExternalSubtitlesStream newExtStream = new()\n {\n Url = url,\n Title = title,\n Downloaded = true,\n IsBitmap = IsSubtitleBitmap(url),\n };\n\n if (Config.Subtitles.LanguageAutoDetect && !newExtStream.IsBitmap)\n {\n newExtStream.Language = DetectLanguage(url);\n newExtStream.LanguageDetected = true;\n }\n\n AddExternalStream(newExtStream);\n\n return new(newExtStream);\n }\n\n public OpenSubtitlesResults Open(Stream iostream) => null;\n\n public void SearchLocalSubtitles()\n {\n try\n {\n string mediaDir = Path.GetDirectoryName(Playlist.Url);\n string mediaName = Path.GetFileNameWithoutExtension(Playlist.Url);\n\n OrderedDictionary result = new(StringComparer.OrdinalIgnoreCase);\n\n CollectFromDirectory(mediaDir, mediaName, result);\n\n // also search in subdirectories\n string paths = Config.Subtitles.SearchLocalPaths;\n if (!string.IsNullOrWhiteSpace(paths))\n {\n foreach (Range seg in paths.AsSpan().Split(';'))\n {\n var path = paths.AsSpan(seg).Trim();\n if (path.IsEmpty) continue;\n\n string searchDir = !Path.IsPathRooted(path)\n ? Path.Join(mediaDir, path)\n : path.ToString();\n\n if (Directory.Exists(searchDir))\n {\n CollectFromDirectory(searchDir, mediaName, result);\n }\n }\n }\n\n if (result.Count == 0)\n {\n return;\n }\n\n Selected.FillMediaParts();\n\n foreach (var (path, lang) in result)\n {\n if (Selected.ExternalSubtitlesStreamsAll.Any(s => s.Url == path))\n {\n continue;\n }\n\n FileInfo fi = new(path);\n string title = fi.Name;\n\n ExternalSubtitlesStream sub = new()\n {\n Url = path,\n Title = title,\n Downloaded = true,\n IsBitmap = IsSubtitleBitmap(path),\n Language = lang\n };\n\n if (Config.Subtitles.LanguageAutoDetect && !sub.IsBitmap && lang == Language.Unknown)\n {\n sub.Language = DetectLanguage(path);\n sub.LanguageDetected = true;\n }\n\n Log.Debug($\"Adding [{sub.Language.TopEnglishName}] {path}\");\n\n AddExternalStream(sub);\n }\n }\n catch (Exception e)\n {\n Log.Error($\"SearchLocalSubtitles failed ({e.Message})\");\n }\n }\n\n private static void CollectFromDirectory(string searchDir, string filename, IDictionary result)\n {\n HashSet added = null;\n\n // Get files starting with the same filename\n List fileList;\n try\n {\n fileList = Directory.GetFiles(searchDir, $\"{filename}.*\", new EnumerationOptions { MatchCasing = MatchCasing.CaseInsensitive })\n .ToList();\n }\n catch\n {\n return;\n }\n\n if (fileList.Count == 0)\n {\n return;\n }\n\n var files = fileList.Select(f => new\n {\n FullPath = f,\n FileName = Path.GetFileName(f)\n }).ToList();\n\n // full match with top priority (video.srt, video.ass)\n foreach (string ext in ExtSet)\n {\n string expect = $\"{filename}.{ext}\";\n int match = files.FindIndex(x => string.Equals(x.FileName, expect, StringComparison.OrdinalIgnoreCase));\n if (match != -1)\n {\n result.TryAdd(files[match].FullPath, Language.Unknown);\n added ??= new HashSet();\n added.Add(match);\n }\n }\n\n // head match (video.*.srt, video.*.ass)\n var extSetLookup = ExtSet.GetAlternateLookup>();\n foreach (var (i, x) in files.Index())\n {\n // skip full match\n if (added != null && added.Contains(i))\n {\n continue;\n }\n\n var span = x.FileName.AsSpan();\n var fileExt = Path.GetExtension(span).TrimStart('.');\n\n // Check if the file is a subtitle file by its extension\n if (extSetLookup.Contains(fileExt))\n {\n var name = Path.GetFileNameWithoutExtension(span);\n\n if (!name.StartsWith(filename + '.', StringComparison.OrdinalIgnoreCase))\n {\n continue;\n }\n\n Language lang = Language.Unknown;\n\n var extraPart = name.Slice(filename.Length + 1); // Skip file name and dot\n if (extraPart.Length > 0)\n {\n foreach (var codeSeg in extraPart.Split('.'))\n {\n var code = extraPart[codeSeg];\n if (code.Length > 0)\n {\n Language parsed = Language.Get(code.ToString());\n if (!string.IsNullOrEmpty(parsed.IdSubLanguage) && parsed.IdSubLanguage != \"und\")\n {\n lang = parsed;\n break;\n }\n }\n }\n }\n\n result.TryAdd(x.FullPath, lang);\n }\n }\n }\n\n // TODO: L: To check the contents of a file by determining the bitmap.\n private static bool IsSubtitleBitmap(string path)\n {\n try\n {\n FileInfo fi = new(path);\n\n return Utils.ExtensionsSubtitlesBitmap.Contains(fi.Extension.TrimStart('.').ToLower());\n }\n catch\n {\n return false;\n }\n }\n\n // TODO: L: Would it be better to check with SubtitlesManager for network subtitles?\n private static Language DetectLanguage(string path)\n {\n if (!File.Exists(path))\n {\n return Language.Unknown;\n }\n\n Encoding encoding = Encoding.Default;\n Encoding detected = TextEncodings.DetectEncoding(path);\n\n if (detected != null)\n {\n encoding = detected;\n }\n\n // TODO: L: refactor: use the code for reading subtitles in Demuxer\n byte[] data = new byte[100 * 1024];\n\n try\n {\n using FileStream fs = new(path, FileMode.Open, FileAccess.Read);\n int bytesRead = fs.Read(data, 0, data.Length);\n Array.Resize(ref data, bytesRead);\n }\n catch\n {\n return Language.Unknown;\n }\n\n string content = encoding.GetString(data);\n\n var detectedLanguage = LanguageDetector.Value.DetectLanguageOf(content);\n\n if (detectedLanguage == Lingua.Language.Unknown)\n {\n return Language.Unknown;\n }\n\n return Language.Get(detectedLanguage.IsoCode6391().ToString().ToLower());\n }\n}\n"], ["/LLPlayer/FlyleafLib/Plugins/PluginBase.cs", "using System.Collections.Generic;\nusing System.Collections.ObjectModel;\nusing System.IO;\n\nusing FlyleafLib.MediaFramework.MediaContext;\nusing FlyleafLib.MediaFramework.MediaPlaylist;\nusing FlyleafLib.MediaFramework.MediaStream;\n\nusing static FlyleafLib.Utils;\n\nnamespace FlyleafLib.Plugins;\n\npublic abstract class PluginBase : PluginType, IPlugin\n{\n public ObservableDictionary\n Options => Config?.Plugins[Name];\n public Config Config => Handler.Config;\n\n public Playlist Playlist => Handler.Playlist;\n public PlaylistItem Selected => Handler.Playlist.Selected;\n\n public DecoderContext decoder => (DecoderContext) Handler;\n\n public PluginHandler Handler { get; internal set; }\n public LogHandler Log { get; internal set; }\n public bool Disposed { get; protected set;} = true;\n public int Priority { get; set; } = 1000;\n\n public virtual void OnLoaded() { }\n public virtual void OnInitializing() { }\n public virtual void OnInitialized() { }\n\n public virtual void OnInitializingSwitch() { }\n public virtual void OnInitializedSwitch() { }\n\n public virtual void OnBuffering() { }\n public virtual void OnBufferingCompleted() { }\n\n public virtual void OnOpen() { }\n public virtual void OnOpenExternalAudio() { }\n public virtual void OnOpenExternalVideo() { }\n public virtual void OnOpenExternalSubtitles() { }\n\n public virtual void Dispose() { }\n\n public void AddExternalStream(ExternalStream extStream, object tag = null, PlaylistItem item = null)\n {\n item ??= Playlist.Selected;\n\n if (item != null)\n PlaylistItem.AddExternalStream(extStream, item, Name, tag);\n }\n\n public void AddPlaylistItem(PlaylistItem item, object tag = null)\n => Playlist.AddItem(item, Name, tag);\n\n public void AddTag(object tag, PlaylistItem item = null)\n {\n item ??= Playlist.Selected;\n\n item?.AddTag(tag, Name);\n }\n\n public object GetTag(ExternalStream extStream)\n => extStream?.GetTag(Name);\n\n public object GetTag(PlaylistItem item)\n => item?.GetTag(Name);\n\n public virtual Dictionary GetDefaultOptions() => new();\n}\npublic class PluginType\n{\n public Type Type { get; internal set; }\n public string Name { get; internal set; }\n public Version Version { get; internal set; }\n}\npublic class OpenResults\n{\n public string Error;\n public bool Success => Error == null;\n\n public OpenResults() { }\n public OpenResults(string error) => Error = error;\n}\n\npublic class OpenSubtitlesResults : OpenResults\n{\n public ExternalSubtitlesStream ExternalSubtitlesStream;\n public OpenSubtitlesResults(ExternalSubtitlesStream extStream, string error = null) : base(error) => ExternalSubtitlesStream = extStream;\n}\n\npublic interface IPlugin : IDisposable\n{\n string Name { get; }\n Version Version { get; }\n PluginHandler Handler { get; }\n int Priority { get; }\n\n void OnLoaded();\n void OnInitializing();\n void OnInitialized();\n void OnInitializingSwitch();\n void OnInitializedSwitch();\n\n void OnBuffering();\n void OnBufferingCompleted();\n\n void OnOpenExternalAudio();\n void OnOpenExternalVideo();\n void OnOpenExternalSubtitles();\n}\n\npublic interface IOpen : IPlugin\n{\n bool CanOpen();\n OpenResults Open();\n OpenResults OpenItem();\n}\npublic interface IOpenSubtitles : IPlugin\n{\n OpenSubtitlesResults Open(string url);\n OpenSubtitlesResults Open(Stream iostream);\n}\n\npublic interface IScrapeItem : IPlugin\n{\n void ScrapeItem(PlaylistItem item);\n}\n\npublic interface ISuggestPlaylistItem : IPlugin\n{\n PlaylistItem SuggestItem();\n}\n\npublic interface ISuggestExternalAudio : IPlugin\n{\n ExternalAudioStream SuggestExternalAudio();\n}\npublic interface ISuggestExternalVideo : IPlugin\n{\n ExternalVideoStream SuggestExternalVideo();\n}\n\npublic interface ISuggestAudioStream : IPlugin\n{\n AudioStream SuggestAudio(ObservableCollection streams);\n}\npublic interface ISuggestVideoStream : IPlugin\n{\n VideoStream SuggestVideo(ObservableCollection streams);\n}\n\npublic interface ISuggestSubtitlesStream : IPlugin\n{\n SubtitlesStream SuggestSubtitles(ObservableCollection streams, List langs);\n}\n\npublic interface ISuggestSubtitles : IPlugin\n{\n /// \n /// Suggests from all the available subtitles\n /// \n /// Embedded stream\n /// External stream\n void SuggestSubtitles(out SubtitlesStream stream, out ExternalSubtitlesStream extStream);\n}\n\npublic interface ISuggestBestExternalSubtitles : IPlugin\n{\n /// \n /// Suggests only if best match exists (to avoid search local/online)\n /// \n /// \n ExternalSubtitlesStream SuggestBestExternalSubtitles();\n}\n\npublic interface ISearchLocalSubtitles : IPlugin\n{\n void SearchLocalSubtitles();\n}\n\npublic interface ISearchOnlineSubtitles : IPlugin\n{\n void SearchOnlineSubtitles();\n}\n\npublic interface IDownloadSubtitles : IPlugin\n{\n bool DownloadSubtitles(ExternalSubtitlesStream extStream);\n}\n"], ["/LLPlayer/FlyleafLib/MediaFramework/MediaContext/Downloader.cs", "using System.IO;\nusing System.Threading;\nusing System.Threading.Tasks;\n\nusing FlyleafLib.MediaFramework.MediaDemuxer;\nusing FlyleafLib.MediaFramework.MediaRemuxer;\n\nusing static FlyleafLib.Logger;\n\n/* TODO\n * Don't let audio go further than video (because of large duration without video)?\n *\n */\n\nnamespace FlyleafLib.MediaFramework.MediaContext;\n\n/// \n/// Downloads or remuxes to different format any ffmpeg valid input url\n/// \npublic unsafe class Downloader : RunThreadBase\n{\n /// \n /// The backend demuxer. Access this to enable the required streams for downloading\n /// \n //public Demuxer Demuxer { get; private set; }\n\n public DecoderContext DecCtx { get; private set; }\n internal Demuxer AudioDemuxer => DecCtx.AudioDemuxer;\n\n /// \n /// The backend remuxer. Normally you shouldn't access this\n /// \n public Remuxer Remuxer { get; private set; }\n\n /// \n /// The current timestamp of the frame starting from 0 (Ticks)\n /// \n public long CurTime { get => _CurTime; private set => Set(ref _CurTime, value); }\n long _CurTime;\n\n /// \n /// The total duration of the input (Ticks)\n /// \n public long Duration { get => _Duration; private set => Set(ref _Duration, value); }\n long _Duration;\n\n /// \n /// The percentage of the current download process (0 for live streams)\n /// \n public double DownloadPercentage { get => _DownloadPercentage; set => Set(ref _DownloadPercentage, value); }\n double _DownloadPercentage;\n double downPercentageFactor;\n\n public Downloader(Config config, int uniqueId = -1) : base(uniqueId)\n {\n DecCtx = new DecoderContext(config, UniqueId, false);\n DecCtx.AudioDemuxer.Config = config.Demuxer.Clone(); // We change buffer duration and we need to avoid changing video demuxer's config\n\n //DecCtx.VideoInputOpened += (o, e) => { if (!e.Success) OnDownloadCompleted(false); };\n Remuxer = new Remuxer(UniqueId);\n threadName = \"Downloader\";\n }\n\n /// \n /// Fires on download completed or failed\n /// \n public event EventHandler DownloadCompleted;\n protected virtual void OnDownloadCompleted(bool success)\n => Task.Run(() => { Dispose(); DownloadCompleted?.Invoke(this, success); });\n\n /// \n /// Opens a new media file (audio/video) and prepares it for download (blocking)\n /// \n /// Media file's url\n /// Whether to open the default input (in case of multiple inputs eg. from bitswarm/youtube-dl, you might want to choose yours)\n /// Whether to open the default video stream from plugin suggestions\n /// Whether to open the default audio stream from plugin suggestions\n /// \n public string Open(string url, bool defaultPlaylistItem = true, bool defaultVideo = true, bool defaultAudio = true) => Open((object) url, defaultPlaylistItem, defaultVideo, defaultAudio);\n\n /// \n /// Opens a new media file (audio/video) and prepares it for download (blocking)\n /// \n /// Media Stream\n /// Whether to open the default input (in case of multiple inputs eg. from bitswarm/youtube-dl, you might want to choose yours)\n /// Whether to open the default video stream from plugin suggestions\n /// Whether to open the default audio stream from plugin suggestions\n /// \n public string Open(Stream stream, bool defaultPlaylistItem = true, bool defaultVideo = true, bool defaultAudio = true) => Open((object) stream, defaultPlaylistItem, defaultVideo, defaultAudio);\n\n internal string Open(object url, bool defaultPlaylistItem = true, bool defaultVideo = true, bool defaultAudio = true)\n {\n lock (lockActions)\n {\n Dispose();\n\n Disposed= false;\n Status = Status.Opening;\n var ret = DecCtx.Open(url, defaultPlaylistItem, defaultVideo, defaultAudio, false);\n if (ret != null && ret.Error != null) return ret.Error;\n\n CurTime = 0;\n DownloadPercentage = 0;\n\n var Demuxer = !DecCtx.VideoDemuxer.Disposed ? DecCtx.VideoDemuxer : DecCtx.AudioDemuxer;\n Duration = Demuxer.IsLive ? 0 : Demuxer.Duration;\n downPercentageFactor = Duration / 100.0;\n\n return null;\n }\n }\n\n /// \n /// Downloads the currently configured AVS streams\n /// \n /// The filename for the downloaded video. The file extension will let the demuxer to choose the output format (eg. mp4). If you useRecommendedExtension will be updated with the extension.\n /// Will try to match the output container with the input container\n public void Download(ref string filename, bool useRecommendedExtension = true)\n {\n lock (lockActions)\n {\n if (Status != Status.Opening || Disposed)\n { OnDownloadCompleted(false); return; }\n\n if (useRecommendedExtension)\n filename = $\"{filename}.{(!DecCtx.VideoDemuxer.Disposed ? DecCtx.VideoDemuxer.Extension : DecCtx.AudioDemuxer.Extension)}\";\n\n int ret = Remuxer.Open(filename);\n if (ret != 0)\n { OnDownloadCompleted(false); return; }\n\n AddStreams(DecCtx.VideoDemuxer);\n AddStreams(DecCtx.AudioDemuxer);\n\n if (!Remuxer.HasStreams || Remuxer.WriteHeader() != 0)\n { OnDownloadCompleted(false); return; }\n\n Start();\n }\n }\n\n private void AddStreams(Demuxer demuxer)\n {\n for(int i=0; i\n /// Stops and disposes the downloader\n /// \n public void Dispose()\n {\n if (Disposed) return;\n\n lock (lockActions)\n {\n if (Disposed) return;\n\n Stop();\n\n DecCtx.Dispose();\n Remuxer.Dispose();\n\n Status = Status.Stopped;\n Disposed = true;\n }\n }\n\n protected override void RunInternal()\n {\n if (!Remuxer.HasStreams) { OnDownloadCompleted(false); return; }\n\n // Don't allow audio to change our duration without video (TBR: requires timestamp of videodemuxer to wait)\n long resetBufferDuration = -1;\n bool hasAVDemuxers = !DecCtx.VideoDemuxer.Disposed && !DecCtx.AudioDemuxer.Disposed;\n if (hasAVDemuxers)\n {\n resetBufferDuration = DecCtx.AudioDemuxer.Config.BufferDuration;\n DecCtx.AudioDemuxer.Config.BufferDuration = 100 * 10000;\n }\n\n DecCtx.Start();\n\n var Demuxer = !DecCtx.VideoDemuxer.Disposed ? DecCtx.VideoDemuxer : DecCtx.AudioDemuxer;\n long startTime = Demuxer.hlsCtx == null ? Demuxer.StartTime : Demuxer.hlsCtx->first_timestamp * 10;\n Duration = Demuxer.IsLive ? 0 : Demuxer.Duration;\n downPercentageFactor = Duration / 100.0;\n\n long startedAt = DateTime.UtcNow.Ticks;\n long secondTicks = startedAt;\n bool isAudioDemuxer = DecCtx.VideoDemuxer.Disposed && !DecCtx.AudioDemuxer.Disposed;\n IntPtr pktPtr = IntPtr.Zero;\n AVPacket* packet = null;\n AVPacket* packet2 = null;\n\n do\n {\n if ((Demuxer.Packets.Count == 0 && AudioDemuxer.Packets.Count == 0) || (hasAVDemuxers && (Demuxer.Packets.Count == 0 || AudioDemuxer.Packets.Count == 0)))\n {\n lock (lockStatus)\n if (Status == Status.Running) Status = Status.QueueEmpty;\n\n while (Demuxer.Packets.Count == 0 && Status == Status.QueueEmpty)\n {\n if (Demuxer.Status == Status.Ended)\n {\n Status = Status.Ended;\n if (Demuxer.Interrupter.Interrupted == 0)\n {\n CurTime = _Duration;\n DownloadPercentage = 100;\n }\n break;\n }\n else if (!Demuxer.IsRunning)\n {\n if (CanDebug) Log.Debug($\"Demuxer is not running [Demuxer Status: {Demuxer.Status}]\");\n\n lock (Demuxer.lockStatus)\n lock (lockStatus)\n {\n if (Demuxer.Status == Status.Pausing || Demuxer.Status == Status.Paused)\n Status = Status.Pausing;\n else if (Demuxer.Status != Status.Ended)\n Status = Status.Stopping;\n else\n continue;\n }\n\n break;\n }\n\n Thread.Sleep(20);\n }\n\n if (hasAVDemuxers && Status == Status.QueueEmpty && AudioDemuxer.Packets.Count == 0)\n {\n while (AudioDemuxer.Packets.Count == 0 && Status == Status.QueueEmpty && AudioDemuxer.IsRunning)\n Thread.Sleep(20);\n }\n\n lock (lockStatus)\n {\n if (Status != Status.QueueEmpty) break;\n Status = Status.Running;\n }\n }\n\n if (hasAVDemuxers)\n {\n if (AudioDemuxer.Packets.Count == 0)\n {\n packet = Demuxer.Packets.Dequeue();\n isAudioDemuxer = false;\n }\n else if (Demuxer.Packets.Count == 0)\n {\n packet = AudioDemuxer.Packets.Dequeue();\n isAudioDemuxer = true;\n }\n else\n {\n packet = Demuxer.Packets.Peek();\n packet2 = AudioDemuxer.Packets.Peek();\n\n long ts1 = (long) ((packet->dts * Demuxer.AVStreamToStream[packet->stream_index].Timebase) - Demuxer.StartTime);\n long ts2 = (long) ((packet2->dts * AudioDemuxer.AVStreamToStream[packet2->stream_index].Timebase) - AudioDemuxer.StartTime);\n\n if (ts2 <= ts1)\n {\n AudioDemuxer.Packets.Dequeue();\n isAudioDemuxer = true;\n packet = packet2;\n }\n else\n {\n Demuxer.Packets.Dequeue();\n isAudioDemuxer = false;\n }\n\n //Log($\"[{isAudioDemuxer}] {Utils.TicksToTime(ts1)} | {Utils.TicksToTime(ts2)}\");\n }\n }\n else\n {\n packet = Demuxer.Packets.Dequeue();\n }\n\n long curDT = DateTime.UtcNow.Ticks;\n if (curDT - secondTicks > 1000 * 10000 && (!isAudioDemuxer || DecCtx.VideoDemuxer.Disposed))\n {\n secondTicks = curDT;\n\n CurTime = Demuxer.hlsCtx != null\n ? (long) ((packet->dts * Demuxer.AVStreamToStream[packet->stream_index].Timebase) - startTime)\n : Demuxer.CurTime + Demuxer.BufferedDuration;\n\n if (_Duration > 0) DownloadPercentage = CurTime / downPercentageFactor;\n }\n\n Remuxer.Write(packet, isAudioDemuxer);\n\n } while (Status == Status.Running);\n\n if (resetBufferDuration != -1) DecCtx.AudioDemuxer.Config.BufferDuration = resetBufferDuration;\n\n if (Status != Status.Pausing && Status != Status.Paused)\n OnDownloadCompleted(Remuxer.WriteTrailer() == 0);\n else\n Demuxer.Pause();\n }\n}\n"], ["/LLPlayer/FlyleafLib/Engine/Config.cs", "using System.Collections.Generic;\nusing System.IO;\nusing System.Linq;\nusing System.Text.Json;\nusing System.Text.Json.Serialization;\nusing System.Threading;\nusing System.Threading.Tasks;\n\nusing FlyleafLib.Controls.WPF;\nusing FlyleafLib.MediaFramework.MediaDecoder;\nusing FlyleafLib.MediaFramework.MediaFrame;\nusing FlyleafLib.MediaFramework.MediaRenderer;\nusing FlyleafLib.MediaPlayer;\nusing FlyleafLib.MediaPlayer.Translation;\nusing FlyleafLib.MediaPlayer.Translation.Services;\nusing FlyleafLib.Plugins;\nusing static FlyleafLib.Utils;\n\nnamespace FlyleafLib;\n\n/// \n/// Player's configuration\n/// \npublic class Config : NotifyPropertyChanged\n{\n static JsonSerializerOptions jsonOpts = new() { WriteIndented = true };\n\n public Config()\n {\n // Parse default plugin options to Config.Plugins (Creates instances until fix with statics in interfaces)\n foreach (var plugin in Engine.Plugins.Types.Values)\n {\n var tmpPlugin = PluginHandler.CreatePluginInstance(plugin);\n var defaultOptions = tmpPlugin.GetDefaultOptions();\n tmpPlugin.Dispose();\n\n if (defaultOptions == null || defaultOptions.Count == 0) continue;\n\n Plugins.Add(plugin.Name, new ObservableDictionary());\n foreach (var opt in defaultOptions)\n Plugins[plugin.Name].Add(opt.Key, opt.Value);\n }\n // save default plugin options for later\n _PluginsDefault = Plugins;\n\n Player.config = this;\n Demuxer.config = this;\n }\n\n public Config(bool test) { }\n\n public Config Clone()\n {\n Config config = new()\n {\n Audio = Audio.Clone(),\n Video = Video.Clone(),\n Subtitles = Subtitles.Clone(),\n Demuxer = Demuxer.Clone(),\n Decoder = Decoder.Clone(),\n Player = Player.Clone()\n };\n\n config.Player.config = config;\n config.Demuxer.config = config;\n\n return config;\n }\n public static Config Load(string path, JsonSerializerOptions jsonOptions = null)\n {\n Config config = JsonSerializer.Deserialize(File.ReadAllText(path), jsonOptions);\n config.Loaded = true;\n config.LoadedPath = path;\n\n if (config.Audio.FiltersEnabled && Engine.Config.FFmpegLoadProfile == LoadProfile.Main)\n config.Audio.FiltersEnabled = false;\n\n // TODO: L: refactor\n config.Player.config = config;\n config.Demuxer.config = config;\n\n config.Subtitles.SetChildren();\n\n // Restore the plugin options initialized by the constructor, as they are overwritten during deserialization.\n\n // Remove removed plugin options\n foreach (var plugin in config.Plugins)\n {\n // plugin deleted\n if (!config._PluginsDefault.ContainsKey(plugin.Key))\n {\n config.Plugins.Remove(plugin.Key);\n continue;\n }\n\n // plugin option deleted\n foreach (var opt in plugin.Value)\n {\n if (!config._PluginsDefault[plugin.Key].ContainsKey(opt.Key))\n {\n config.Plugins[plugin.Key].Remove(opt.Key);\n }\n }\n }\n\n // Restore added plugin options\n foreach (var plugin in config._PluginsDefault)\n {\n // plugin added\n if (!config.Plugins.ContainsKey(plugin.Key))\n {\n config.Plugins[plugin.Key] = plugin.Value;\n continue;\n }\n\n // plugin option added\n foreach (var opt in plugin.Value)\n {\n if (!config.Plugins[plugin.Key].ContainsKey(opt.Key))\n {\n config.Plugins[plugin.Key][opt.Key] = opt.Value;\n }\n }\n }\n\n config.UpdateDefault();\n\n return config;\n }\n public void Save(string path = null, JsonSerializerOptions jsonOptions = null)\n {\n if (path == null)\n {\n if (string.IsNullOrEmpty(LoadedPath))\n return;\n\n path = LoadedPath;\n }\n\n jsonOptions ??= jsonOpts;\n\n File.WriteAllText(path, JsonSerializer.Serialize(this, jsonOptions));\n }\n\n private void UpdateDefault()\n {\n bool parsed = System.Version.TryParse(Version, out var loadedVer);\n\n if (!parsed || loadedVer <= System.Version.Parse(\"0.2.1\"))\n {\n // for FlyleafLib v3.8.3, Ensure extension_picky is set\n Demuxer.FormatOpt = DemuxerConfig.DefaultVideoFormatOpt();\n Demuxer.AudioFormatOpt = DemuxerConfig.DefaultVideoFormatOpt();\n Demuxer.SubtitlesFormatOpt = DemuxerConfig.DefaultVideoFormatOpt();\n\n\n // for subtitles search #91\n int ctrlFBindingIdx = Player.KeyBindings.Keys\n .FindIndex(k => k.Key == System.Windows.Input.Key.F &&\n k.Ctrl && !k.Alt && !k.Shift);\n if (ctrlFBindingIdx != -1)\n {\n // remove existing binding\n Player.KeyBindings.Keys.RemoveAt(ctrlFBindingIdx);\n }\n // set CTRL+F to subtitles search\n Player.KeyBindings.Keys.Add(new KeyBinding { Ctrl = true, Key = System.Windows.Input.Key.F, IsKeyUp = true, Action = KeyBindingAction.Custom, ActionName = \"ActivateSubsSearch\" });\n\n // Toggle always on top\n int ctrlTBindingIdx = Player.KeyBindings.Keys\n .FindIndex(k => k.Key == System.Windows.Input.Key.T &&\n k.Ctrl && !k.Alt && !k.Shift);\n if (ctrlTBindingIdx == -1)\n {\n Player.KeyBindings.Keys.Add(new KeyBinding { Ctrl = true, Key = System.Windows.Input.Key.T, IsKeyUp = true, Action = KeyBindingAction.Custom, ActionName = \"ToggleAlwaysOnTop\" });\n }\n\n // Set Ctrl+A for ToggleSubsAutoTextCopy (previous Alt+A)\n int ctrlABindingIdx = Player.KeyBindings.Keys\n .FindIndex(k => k.Key == System.Windows.Input.Key.A &&\n k.Ctrl && !k.Alt && !k.Shift);\n if (ctrlABindingIdx == -1)\n {\n Player.KeyBindings.Keys.Add(new KeyBinding { Ctrl = true, Key = System.Windows.Input.Key.A, IsKeyUp = true, Action = KeyBindingAction.Custom, ActionName = \"ToggleSubsAutoTextCopy\" });\n }\n }\n }\n\n internal void SetPlayer(Player player)\n {\n Player.player = player;\n Player.KeyBindings.SetPlayer(player);\n Demuxer.player = player;\n Decoder.player = player;\n Audio.player = player;\n Video.player = player;\n Subtitles.SetPlayer(player);\n }\n\n public string Version { get; set; }\n\n /// \n /// Whether configuration has been loaded from file\n /// \n [JsonIgnore]\n public bool Loaded { get; private set; }\n\n /// \n /// The path that this configuration has been loaded from\n /// \n [JsonIgnore]\n public string LoadedPath { get; private set; }\n\n public PlayerConfig Player { get; set; } = new PlayerConfig();\n public DemuxerConfig Demuxer { get; set; } = new DemuxerConfig();\n public DecoderConfig Decoder { get; set; } = new DecoderConfig();\n public VideoConfig Video { get; set; } = new VideoConfig();\n public AudioConfig Audio { get; set; } = new AudioConfig();\n public SubtitlesConfig Subtitles { get; set; } = new SubtitlesConfig();\n public DataConfig Data { get; set; } = new DataConfig();\n\n public Dictionary>\n Plugins { get; set; } = new();\n private\n Dictionary>\n _PluginsDefault;\n public class PlayerConfig : NotifyPropertyChanged\n {\n public PlayerConfig Clone()\n {\n PlayerConfig player = (PlayerConfig) MemberwiseClone();\n player.player = null;\n player.config = null;\n player.KeyBindings = KeyBindings.Clone();\n return player;\n }\n\n internal Player player;\n internal Config config;\n\n /// \n /// It will automatically start playing after open or seek after ended\n /// \n public bool AutoPlay { get; set; } = true;\n\n /// \n /// Required buffered duration ticks before playing\n /// \n public long MinBufferDuration {\n get => _MinBufferDuration;\n set\n {\n if (!Set(ref _MinBufferDuration, value)) return;\n if (config != null && value > config.Demuxer.BufferDuration)\n config.Demuxer.BufferDuration = value;\n }\n }\n long _MinBufferDuration = 500 * 10000;\n\n /// \n /// Key bindings configuration\n /// \n public KeysConfig\n KeyBindings { get; set; } = new KeysConfig();\n\n /// \n /// Fps while the player is not playing\n /// \n public double IdleFps { get; set; } = 60.0;\n\n /// \n /// Max Latency (ticks) forces playback (with speed x1+) to stay at the end of the live network stream (default: 0 - disabled)\n /// \n public long MaxLatency {\n get => _MaxLatency;\n set\n {\n if (value < 0)\n value = 0;\n\n if (!Set(ref _MaxLatency, value)) return;\n\n if (value == 0)\n {\n if (player != null)\n player.Speed = 1;\n\n if (config != null)\n config.Decoder.LowDelay = false;\n\n return;\n }\n\n // Large max buffer so we ensure the actual latency distance\n if (config != null)\n {\n if (config.Demuxer.BufferDuration < value * 2)\n config.Demuxer.BufferDuration = value * 2;\n\n config.Decoder.LowDelay = true;\n }\n\n // Small min buffer to avoid enabling latency speed directly\n if (_MinBufferDuration > value / 10)\n MinBufferDuration = value / 10;\n }\n }\n long _MaxLatency = 0;\n\n /// \n /// Min Latency (ticks) prevents MaxLatency to go (with speed x1) less than this limit (default: 0 - as low as possible)\n /// \n public long MinLatency { get => _MinLatency; set => Set(ref _MinLatency, value); }\n long _MinLatency = 0;\n\n /// \n /// Prevents frequent speed changes when MaxLatency is enabled (to avoid audio/video gaps and desyncs)\n /// \n public long LatencySpeedChangeInterval { get; set; } = TimeSpan.FromMilliseconds(700).Ticks;\n\n /// \n /// Folder to save recordings (when filename is not specified)\n /// \n public string FolderRecordings { get; set; } = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, \"Recordings\");\n\n /// \n /// Folder to save snapshots (when filename is not specified)\n /// \n\n public string FolderSnapshots { get; set; } = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, \"Snapshots\");\n\n /// \n /// Forces CurTime/SeekBackward/SeekForward to seek accurate on video\n /// \n public bool SeekAccurate { get => _SeekAccurate; set => Set(ref _SeekAccurate, value); }\n bool _SeekAccurate;\n\n /// \n /// Margin time to move back forward when doing an exact seek (ticks)\n /// \n public long SeekAccurateFixMargin { get; set => Set(ref field, value); } = TimeSpan.FromMilliseconds(0).Ticks;\n\n /// \n /// Margin time to move back forward when getting frame (ticks)\n /// \n public long SeekGetFrameFixMargin { get; set => Set(ref field, value); } = TimeSpan.FromMilliseconds(3000).Ticks;\n\n /// \n /// Snapshot encoding will be used (valid formats bmp, png, jpg/jpeg)\n /// \n public string SnapshotFormat { get ;set; } = \"bmp\";\n\n /// \n /// Whether to refresh statistics about bitrates/fps/drops etc.\n /// \n public bool Stats { get => _Stats; set => Set(ref _Stats, value); }\n bool _Stats = false;\n\n /// \n /// Sets playback's thread priority\n /// \n public ThreadPriority\n ThreadPriority { get; set; } = ThreadPriority.AboveNormal;\n\n /// \n /// Refreshes CurTime in UI on every frame (can cause performance issues)\n /// \n public bool UICurTimePerFrame { get; set; } = false;\n\n /// \n /// The upper limit of the volume amplifier\n /// \n public int VolumeMax { get => _VolumeMax; set { Set(ref _VolumeMax, value); if (player != null && player.Audio.masteringVoice != null) player.Audio.masteringVoice.Volume = value / 100f; } }\n int _VolumeMax = 150;\n\n /// \n /// The default volume\n /// \n public int VolumeDefault { get; set => Set(ref field, value); } = 75;\n\n /// \n /// The purpose of the player\n /// \n public Usage Usage { get; set; } = Usage.AVS;\n\n // Offsets\n public long AudioDelayOffset { get; set; } = 100 * 10000;\n public long AudioDelayOffset2 { get; set; } = 1000 * 10000;\n public long SubtitlesDelayOffset { get; set; } = 100 * 10000;\n public long SubtitlesDelayOffset2 { get; set; } = 1000 * 10000;\n public long SeekOffset { get; set; } = 1 * (long)1000 * 10000;\n public long SeekOffset2 { get; set; } = 5 * (long)1000 * 10000;\n public long SeekOffset3 { get; set; } = 15 * (long)1000 * 10000;\n public long SeekOffset4 { get; set; } = 30 * (long)1000 * 10000;\n public bool SeekOffsetAccurate { get; set; } = true;\n public bool SeekOffsetAccurate2 { get; set; } = false;\n public bool SeekOffsetAccurate3 { get; set; } = false;\n public bool SeekOffsetAccurate4 { get; set; } = false;\n public double SpeedOffset { get; set; } = 0.10;\n public double SpeedOffset2 { get; set; } = 0.25;\n public int ZoomOffset { get => _ZoomOffset; set { if (Set(ref _ZoomOffset, value)) player?.ResetAll(); } }\n int _ZoomOffset = 10;\n\n public int VolumeOffset { get; set; } = 5;\n }\n public class DemuxerConfig : NotifyPropertyChanged\n {\n public DemuxerConfig Clone()\n {\n DemuxerConfig demuxer = (DemuxerConfig) MemberwiseClone();\n\n demuxer.FormatOpt = new Dictionary();\n demuxer.AudioFormatOpt = new Dictionary();\n demuxer.SubtitlesFormatOpt = new Dictionary();\n\n foreach (var kv in FormatOpt) demuxer.FormatOpt.Add(kv.Key, kv.Value);\n foreach (var kv in AudioFormatOpt) demuxer.AudioFormatOpt.Add(kv.Key, kv.Value);\n foreach (var kv in SubtitlesFormatOpt) demuxer.SubtitlesFormatOpt.Add(kv.Key, kv.Value);\n\n demuxer.player = null;\n demuxer.config = null;\n\n return demuxer;\n }\n\n internal Player player;\n internal Config config;\n\n /// \n /// Whethere to allow avformat_find_stream_info during open (avoiding this can open the input faster but it could cause other issues)\n /// \n public bool AllowFindStreamInfo { get; set; } = true;\n\n /// \n /// Whether to enable demuxer's custom interrupt callback (for timeouts and interrupts)\n /// \n public bool AllowInterrupts { get; set; } = true;\n\n /// \n /// Whether to allow interrupts during av_read_frame\n /// \n public bool AllowReadInterrupts { get; set; } = true;\n\n /// \n /// Whether to allow timeouts checks within the interrupts callback\n /// \n public bool AllowTimeouts { get; set; } = true;\n\n /// \n /// List of FFmpeg formats to be excluded from interrupts\n /// \n public List ExcludeInterruptFmts{ get; set; } = new List() { \"rtsp\" };\n\n /// \n /// Maximum allowed duration ticks for buffering\n /// \n public long BufferDuration {\n get => _BufferDuration;\n set\n {\n if (!Set(ref _BufferDuration, value)) return;\n if (config != null && value < config.Player.MinBufferDuration)\n config.Player.MinBufferDuration = value;\n }\n }\n long _BufferDuration = 30 * (long)1000 * 10000;\n\n /// \n /// Maximuim allowed packets for buffering (as an extra check along with BufferDuration)\n /// \n public long BufferPackets { get; set; }\n\n /// \n /// Maximuim allowed audio packets (when reached it will drop the extra packets and will fire the AudioLimit event)\n /// \n public long MaxAudioPackets { get; set; }\n\n /// \n /// Maximum allowed errors before stopping\n /// \n public int MaxErrors { get; set; } = 30;\n\n /// \n /// Custom IO Stream buffer size (in bytes) for the AVIO Context\n /// \n public int IOStreamBufferSize\n { get; set; } = 0x200000;\n\n /// \n /// avformat_close_input timeout (ticks) for protocols that support interrupts\n /// \n public long CloseTimeout { get => closeTimeout; set { closeTimeout = value; closeTimeoutMs = value / 10000; } }\n private long closeTimeout = 1 * 1000 * 10000;\n internal long closeTimeoutMs = 1 * 1000;\n\n /// \n /// avformat_open_input + avformat_find_stream_info timeout (ticks) for protocols that support interrupts (should be related to probesize/analyzeduration)\n /// \n public long OpenTimeout { get => openTimeout; set { openTimeout = value; openTimeoutMs = value / 10000; } }\n private long openTimeout = 5 * 60 * (long)1000 * 10000;\n internal long openTimeoutMs = 5 * 60 * 1000;\n\n /// \n /// av_read_frame timeout (ticks) for protocols that support interrupts\n /// \n public long ReadTimeout { get => readTimeout; set { readTimeout = value; readTimeoutMs = value / 10000; } }\n private long readTimeout = 10 * 1000 * 10000;\n internal long readTimeoutMs = 10 * 1000;\n\n /// \n /// av_read_frame timeout (ticks) for protocols that support interrupts (for Live streams)\n /// \n public long ReadLiveTimeout { get => readLiveTimeout; set { readLiveTimeout = value; readLiveTimeoutMs = value / 10000; } }\n private long readLiveTimeout = 20 * 1000 * 10000;\n internal long readLiveTimeoutMs = 20 * 1000;\n\n /// \n /// av_seek_frame timeout (ticks) for protocols that support interrupts\n /// \n public long SeekTimeout { get => seekTimeout; set { seekTimeout = value; seekTimeoutMs = value / 10000; } }\n private long seekTimeout = 8 * 1000 * 10000;\n internal long seekTimeoutMs = 8 * 1000;\n\n /// \n /// Forces Input Format\n /// \n public string ForceFormat { get; set; }\n\n /// \n /// Forces FPS for NoTimestamp formats (such as h264/hevc)\n /// \n public double ForceFPS { get; set; }\n\n /// \n /// FFmpeg's format flags for demuxer (see https://ffmpeg.org/doxygen/trunk/avformat_8h.html)\n /// eg. FormatFlags |= 0x40; // For AVFMT_FLAG_NOBUFFER\n /// \n public DemuxerFlags FormatFlags { get; set; } = DemuxerFlags.DiscardCorrupt;// FFmpeg.AutoGen.ffmpeg.AVFMT_FLAG_DISCARD_CORRUPT;\n\n /// \n /// Certain muxers and demuxers do nesting (they open one or more additional internal format contexts). This will pass the FormatOpt and HTTPQuery params to the underlying contexts)\n /// \n public bool FormatOptToUnderlying\n { get; set; }\n\n /// \n /// Passes original's Url HTTP Query String parameters to underlying\n /// \n public bool DefaultHTTPQueryToUnderlying\n { get; set; } = true;\n\n /// \n /// HTTP Query String parameters to pass to underlying\n /// \n public Dictionary\n ExtraHTTPQueryParamsToUnderlying\n { get; set; } = new();\n\n /// \n /// FFmpeg's format options for demuxer\n /// \n public Dictionary\n FormatOpt { get; set; } = DefaultVideoFormatOpt();\n public Dictionary\n AudioFormatOpt { get; set; } = DefaultVideoFormatOpt();\n\n public Dictionary\n SubtitlesFormatOpt { get; set; } = DefaultVideoFormatOpt();\n\n public static Dictionary DefaultVideoFormatOpt()\n {\n // TODO: Those should be set based on the demuxer format/protocol (to avoid false warnings about invalid options and best fit for the input, eg. live stream)\n\n Dictionary defaults = new()\n {\n // General\n { \"probesize\", (50 * (long)1024 * 1024).ToString() }, // (Bytes) Default 5MB | Higher for weird formats (such as .ts?) and 4K/Hevc\n { \"analyzeduration\", (10 * (long)1000 * 1000).ToString() }, // (Microseconds) Default 5 seconds | Higher for network streams\n\n // HTTP\n { \"reconnect\", \"1\" }, // auto reconnect after disconnect before EOF\n { \"reconnect_streamed\", \"1\" }, // auto reconnect streamed / non seekable streams (this can cause issues with HLS ts segments - disable this or http_persistent)\n { \"reconnect_delay_max\",\"7\" }, // max reconnect delay in seconds after which to give up\n { \"user_agent\", \"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/92.0.4515.159 Safari/537.36\" },\n\n { \"extension_picky\", \"0\" }, // Added in ffmpeg v7.1.1 and causes issues when enabled with allowed extentions #577\n\n // HLS\n { \"http_persistent\", \"0\" }, // Disables keep alive for HLS - mainly when use reconnect_streamed and non-live HLS streams\n\n // RTSP\n { \"rtsp_transport\", \"tcp\" }, // Seems UDP causing issues\n };\n\n //defaults.Add(\"live_start_index\", \"-1\");\n //defaults.Add(\"timeout\", (2 * (long)1000 * 1000).ToString()); // (Bytes) Default 5MB | Higher for weird formats (such as .ts?)\n //defaults.Add(\"rw_timeout\", (2 * (long)1000 * 1000).ToString()); // (Microseconds) Default 5 seconds | Higher for network streams\n\n return defaults;\n }\n\n public Dictionary GetFormatOptPtr(MediaType type)\n => type == MediaType.Video ? FormatOpt : type == MediaType.Audio ? AudioFormatOpt : SubtitlesFormatOpt;\n }\n public class DecoderConfig : NotifyPropertyChanged\n {\n internal Player player;\n\n public DecoderConfig Clone()\n {\n DecoderConfig decoder = (DecoderConfig) MemberwiseClone();\n decoder.player = null;\n\n return decoder;\n }\n\n /// \n /// Threads that will be used from the decoder\n /// \n public int VideoThreads { get; set; } = Environment.ProcessorCount;\n\n /// \n /// Maximum video frames to be decoded and processed for rendering\n /// \n public int MaxVideoFrames { get => _MaxVideoFrames; set { if (Set(ref _MaxVideoFrames, value)) { player?.RefreshMaxVideoFrames(); } } }\n int _MaxVideoFrames = 4;\n\n /// \n /// Maximum audio frames to be decoded and processed for playback\n /// \n public int MaxAudioFrames { get; set; } = 10;\n\n /// \n /// Maximum subtitle frames to be decoded\n /// \n public int MaxSubsFrames { get; set; } = 1;\n\n /// \n /// Maximum data frames to be decoded\n /// \n public int MaxDataFrames { get; set; } = 100;\n\n /// \n /// Maximum allowed errors before stopping\n /// \n public int MaxErrors { get; set; } = 200;\n\n /// \n /// Whether or not to use decoder's textures directly as shader resources\n /// (TBR: Better performance but might need to be disabled while video input has padding or not supported by older Direct3D versions)\n /// \n public ZeroCopy ZeroCopy { get => _ZeroCopy; set { if (SetUI(ref _ZeroCopy, value) && player != null && player.Video.isOpened) player.VideoDecoder?.RecalculateZeroCopy(); } }\n ZeroCopy _ZeroCopy = ZeroCopy.Auto;\n\n /// \n /// Allows video accceleration even in codec's profile mismatch\n /// \n public bool AllowProfileMismatch\n { get => _AllowProfileMismatch; set => SetUI(ref _AllowProfileMismatch, value); }\n bool _AllowProfileMismatch;\n\n /// \n /// Allows corrupted frames (Parses AV_CODEC_FLAG_OUTPUT_CORRUPT to AVCodecContext)\n /// \n public bool ShowCorrupted { get => _ShowCorrupted; set => SetUI(ref _ShowCorrupted, value); }\n bool _ShowCorrupted;\n\n /// \n /// Forces low delay (Parses AV_CODEC_FLAG_LOW_DELAY to AVCodecContext) (auto-enabled with MaxLatency)\n /// \n public bool LowDelay { get => _LowDelay; set => SetUI(ref _LowDelay, value); }\n bool _LowDelay;\n\n public Dictionary\n AudioCodecOpt { get; set; } = new();\n public Dictionary\n VideoCodecOpt { get; set; } = new();\n public Dictionary\n SubtitlesCodecOpt { get; set; } = new();\n\n public Dictionary GetCodecOptPtr(MediaType type)\n => type == MediaType.Video ? VideoCodecOpt : type == MediaType.Audio ? AudioCodecOpt : SubtitlesCodecOpt;\n }\n public class VideoConfig : NotifyPropertyChanged\n {\n public VideoConfig Clone()\n {\n VideoConfig video = (VideoConfig) MemberwiseClone();\n video.player = null;\n\n return video;\n }\n\n internal Player player;\n\n /// \n /// Forces a specific GPU Adapter to be used by the renderer\n /// GPUAdapter must match with the description of the adapter eg. rx 580 (available adapters can be found in Engine.Video.GPUAdapters)\n /// \n public string GPUAdapter { get; set; }\n\n /// \n /// Video aspect ratio\n /// \n public AspectRatio AspectRatio { get => _AspectRatio; set { if (Set(ref _AspectRatio, value) && player != null && player.renderer != null && !player.renderer.SCDisposed) lock(player.renderer.lockDevice) { player.renderer.SetViewport(); if (player.renderer.child != null) player.renderer.child.SetViewport(); } } }\n AspectRatio _AspectRatio = AspectRatio.Keep;\n\n /// \n /// Custom aspect ratio (AspectRatio must be set to Custom to have an effect)\n /// \n public AspectRatio CustomAspectRatio { get => _CustomAspectRatio; set { if (Set(ref _CustomAspectRatio, value) && AspectRatio == AspectRatio.Custom) { _AspectRatio = AspectRatio.Fill; AspectRatio = AspectRatio.Custom; } } }\n AspectRatio _CustomAspectRatio = new(16, 9);\n\n /// \n /// Background color of the player's control\n /// \n public System.Windows.Media.Color\n BackgroundColor { get => VorticeToWPFColor(_BackgroundColor); set { Set(ref _BackgroundColor, WPFToVorticeColor(value)); player?.renderer?.UpdateBackgroundColor(); } }\n internal Vortice.Mathematics.Color _BackgroundColor = (Vortice.Mathematics.Color)Vortice.Mathematics.Colors.Black;\n\n /// \n /// Clears the screen on stop/close/open\n /// \n public bool ClearScreen { get; set; } = true;\n\n /// \n /// Whether video should be allowed\n /// \n public bool Enabled { get => _Enabled; set { if (Set(ref _Enabled, value)) if (value) player?.Video.Enable(); else player?.Video.Disable(); } }\n bool _Enabled = true;\n internal void SetEnabled(bool enabled) => Set(ref _Enabled, enabled, true, nameof(Enabled));\n\n /// \n /// Used to limit the number of frames rendered, particularly at increased speed\n /// \n public double MaxOutputFps { get; set; } = 60;\n\n /// \n /// DXGI Maximum Frame Latency (1 - 16)\n /// \n public uint MaxFrameLatency { get; set; } = 1;\n\n /// \n /// The max resolution that the current system can achieve and will be used from the input/stream suggester plugins\n /// \n [JsonIgnore]\n public int MaxVerticalResolutionAuto { get; internal set; }\n\n /// \n /// Custom max vertical resolution that will be used from the input/stream suggester plugins\n /// \n public int MaxVerticalResolutionCustom { get => _MaxVerticalResolutionCustom; set => Set(ref _MaxVerticalResolutionCustom, value); }\n int _MaxVerticalResolutionCustom;\n\n /// \n /// The max resolution that is currently used (based on Auto/Custom)\n /// \n [JsonIgnore]\n public int MaxVerticalResolution => MaxVerticalResolutionCustom == 0 ? (MaxVerticalResolutionAuto != 0 ? MaxVerticalResolutionAuto : 1080) : MaxVerticalResolutionCustom;\n\n /// \n /// In case of no hardware accelerated or post process accelerated pixel formats will use FFmpeg's SwsScale\n /// \n public bool SwsHighQuality { get; set; } = false;\n\n /// \n /// Forces SwsScale instead of FlyleafVP for non HW decoded frames\n /// \n public bool SwsForce { get; set; } = false;\n\n /// \n /// Activates Direct3D video acceleration (decoding)\n /// \n public bool VideoAcceleration { get; set => Set(ref field, value); } = true;\n\n /// \n /// Whether to use embedded video processor with custom pixel shaders or D3D11
\n /// (Currently D3D11 works only on video accelerated / hardware surfaces)
\n /// * FLVP supports HDR to SDR, D3D11 does not
\n /// * FLVP supports Pan Move/Zoom, D3D11 does not
\n /// * D3D11 possible performs better with color conversion and filters, FLVP supports only brightness/contrast filters
\n /// * D3D11 supports deinterlace (bob)\n ///
\n public VideoProcessors VideoProcessor { get => _VideoProcessor; set { if (Set(ref _VideoProcessor, value)) player?.renderer?.UpdateVideoProcessor(); } }\n VideoProcessors _VideoProcessor = VideoProcessors.Auto;\n\n /// \n /// Whether Vsync should be enabled (0: Disabled, 1: Enabled)\n /// \n public uint VSync { get; set; }\n\n /// \n /// Swap chain's present flags (mainly for waitable -None- or non-waitable -DoNotWait) (default: non-waitable)
\n /// Non-waitable swap chain will reduce re-buffering and audio/video desyncs\n ///
\n public Vortice.DXGI.PresentFlags\n PresentFlags { get; set; } = Vortice.DXGI.PresentFlags.DoNotWait;\n\n /// \n /// Enables the video processor to perform post process deinterlacing\n /// (D3D11 video processor should be enabled and support bob deinterlace method)\n /// \n public bool Deinterlace { get=> _Deinterlace; set { if (Set(ref _Deinterlace, value)) player?.renderer?.UpdateDeinterlace(); } }\n bool _Deinterlace;\n\n public bool DeinterlaceBottomFirst { get=> _DeinterlaceBottomFirst; set { if (Set(ref _DeinterlaceBottomFirst, value)) player?.renderer?.UpdateDeinterlace(); } }\n bool _DeinterlaceBottomFirst;\n\n /// \n /// The HDR to SDR method that will be used by the pixel shader\n /// \n public unsafe HDRtoSDRMethod\n HDRtoSDRMethod { get => _HDRtoSDRMethod; set { if (Set(ref _HDRtoSDRMethod, value) && player != null && player.VideoDecoder.VideoStream != null && player.VideoDecoder.VideoStream.ColorSpace == ColorSpace.BT2020) player.renderer.UpdateHDRtoSDR(); }}\n HDRtoSDRMethod _HDRtoSDRMethod = HDRtoSDRMethod.Hable;\n\n /// \n /// The HDR to SDR Tone float correnction (not used by Reinhard)\n /// \n public unsafe float HDRtoSDRTone { get => _HDRtoSDRTone; set { if (Set(ref _HDRtoSDRTone, value) && player != null && player.VideoDecoder.VideoStream != null && player.VideoDecoder.VideoStream.ColorSpace == ColorSpace.BT2020) player.renderer.UpdateHDRtoSDR(); } }\n float _HDRtoSDRTone = 1.4f;\n\n /// \n /// Whether the renderer will use 10-bit swap chaing or 8-bit output\n /// \n public bool Swap10Bit { get; set; }\n\n /// \n /// The number of buffers to use for the renderer's swap chain\n /// \n public uint SwapBuffers { get; set; } = 2;\n\n /// \n /// \n /// Whether the renderer will use R8G8B8A8_UNorm instead of B8G8R8A8_UNorm format for the swap chain (experimental)
\n /// (TBR: causes slightly different colors with D3D11VP)\n ///
\n ///
\n public bool SwapForceR8G8B8A8 { get; set; }\n\n public Dictionary Filters {get ; set; } = DefaultFilters();\n\n public static Dictionary DefaultFilters()\n {\n Dictionary filters = new();\n\n var available = Enum.GetValues(typeof(VideoFilters));\n\n foreach(object filter in available)\n filters.Add((VideoFilters)filter, new VideoFilter((VideoFilters)filter));\n\n return filters;\n }\n }\n public class AudioConfig : NotifyPropertyChanged\n {\n public AudioConfig Clone()\n {\n AudioConfig audio = (AudioConfig) MemberwiseClone();\n audio.player = null;\n\n return audio;\n }\n\n internal Player player;\n\n /// \n /// Audio delay ticks (will be reseted to 0 for every new audio stream)\n /// \n public long Delay { get => _Delay; set { if (player != null && !player.Audio.IsOpened) return; if (Set(ref _Delay, value)) player?.ReSync(player.decoder.AudioStream); } }\n long _Delay;\n internal void SetDelay(long delay) => Set(ref _Delay, delay, true, nameof(Delay));\n\n /// \n /// Whether audio should allowed\n /// \n public bool Enabled { get => _Enabled; set { if (Set(ref _Enabled, value)) if (value) player?.Audio.Enable(); else player?.Audio.Disable(); } }\n bool _Enabled = true;\n internal void SetEnabled(bool enabled) => Set(ref _Enabled, enabled, true, nameof(Enabled));\n\n /// \n /// Whether to process samples with Filters or SWR (experimental)
\n /// 1. Requires FFmpeg avfilter lib
\n /// 2. Currently SWR performs better if you dont need filters
\n ///
\n public bool FiltersEnabled { get => _FiltersEnabled; set { if (Set(ref _FiltersEnabled, value && Engine.Config.FFmpegLoadProfile != LoadProfile.Main)) player?.AudioDecoder.SetupFiltersOrSwr(); } }\n bool _FiltersEnabled = false;\n\n /// \n /// List of filters for post processing the audio samples (experimental)
\n /// (Requires FiltersEnabled)\n ///
\n public List Filters { get; set; }\n\n /// \n /// Audio languages preference by priority\n /// \n public List Languages\n {\n get\n {\n field ??= GetSystemLanguages();\n return field;\n }\n set => Set(ref field, value);\n }\n\n }\n\n public class SubConfig : NotifyPropertyChanged\n {\n internal Player player;\n\n public SubConfig()\n {\n }\n\n public SubConfig(int subIndex)\n {\n SubIndex = subIndex;\n }\n\n [JsonIgnore]\n public int SubIndex { get; set => Set(ref field, value); }\n\n [JsonIgnore]\n public bool EnabledTranslated\n {\n get;\n set\n {\n if (Set(ref field, value))\n {\n if (player == null)\n {\n return;\n }\n\n // Clear once to update the subtitle being displayed.\n player.sFramesPrev[SubIndex] = null;\n player.SubtitleClear(SubIndex);\n\n // Switching the display while leaving the translated text itself\n foreach (SubtitleData sub in player.SubtitlesManager[SubIndex].Subs)\n {\n sub.EnabledTranslated = field;\n }\n\n // Update text in sidebar\n player.SubtitlesManager[SubIndex].Refresh();\n }\n }\n } = false;\n\n /// \n /// Subtitle delay ticks (will be reset to 0 for every new subtitle stream)\n /// \n public long Delay\n {\n get => _delay;\n set\n {\n if (player == null || !player.Subtitles[SubIndex].Enabled)\n {\n return;\n }\n if (Set(ref _delay, value))\n {\n player.SubtitlesManager[SubIndex].SetCurrentTime(new TimeSpan(player.CurTime));\n player.ReSync(player.decoder.SubtitlesStreams[SubIndex]);\n }\n }\n }\n private long _delay;\n\n internal void SetDelay(long delay) => Set(ref _delay, delay, true, nameof(Delay));\n\n /// \n /// Whether subtitle should be visible\n /// TODO: L: should move to AppConfig?\n /// \n [JsonIgnore]\n public bool Visible { get; set => Set(ref field, value); } = true;\n\n /// \n /// OCR Engine Type\n /// \n public SubOCREngineType OCREngine { get; set => Set(ref field, value); } = SubOCREngineType.Tesseract;\n }\n\n public class SubtitlesConfig : NotifyPropertyChanged\n {\n public SubConfig[] SubConfigs { get; set; }\n\n public SubConfig this[int subIndex] => SubConfigs[subIndex];\n\n public SubtitlesConfig()\n {\n int subNum = 2;\n SubConfigs = new SubConfig[subNum];\n for (int i = 0; i < subNum; i++)\n {\n SubConfigs[i] = new SubConfig(i);\n }\n }\n\n internal void SetChildren()\n {\n for (int i = 0; i < SubConfigs.Length; i++)\n {\n SubConfigs[i].SubIndex = i;\n }\n }\n\n public SubtitlesConfig Clone()\n {\n SubtitlesConfig subs = new();\n subs = (SubtitlesConfig) MemberwiseClone();\n\n subs.Languages = new List();\n if (Languages != null) foreach(var lang in Languages) subs.Languages.Add(lang);\n\n subs.player = null;\n\n return subs;\n }\n\n internal Player player;\n internal void SetPlayer(Player player)\n {\n this.player = player;\n\n foreach (SubConfig conf in SubConfigs)\n {\n conf.player = player;\n }\n }\n\n /// \n /// Whether subtitles should be allowed\n /// \n public bool Enabled { get => _Enabled; set { if(Set(ref _Enabled, value)) if (value) player?.Subtitles.Enable(); else player?.Subtitles.Disable(); } }\n bool _Enabled = true;\n internal void SetEnabled(bool enabled) => Set(ref _Enabled, enabled, true, nameof(Enabled));\n\n /// \n /// Max number of subtitles (currently not configurable)\n /// \n public int Max { get; set => Set(ref field, value); } = 2;\n\n /// \n /// Whether to cache internal bitmap subtitles on memory\n /// Memory usage is larger since all bitmap are read on memory, but has the following advantages\n /// 1. Internal bitmap subtitles can be displayed in the sidebar\n /// 2. Can display bitmap subtitles during playback when seeking (mpv: can, VLC: cannot)\n /// \n public bool EnabledCached { get; set => Set(ref field, value); } = true;\n\n public bool OpenAutomaticSubs { get; set => Set(ref field, value); }\n\n /// \n /// Subtitle languages preference by priority\n /// \n public List Languages\n {\n get\n {\n field ??= GetSystemLanguages();\n return field;\n }\n set => Set(ref field, value);\n }\n\n /// \n /// Whether to use automatic language detection\n /// \n public bool LanguageAutoDetect { get; set => Set(ref field, value); } = true;\n\n /// \n /// Language to be used when source language was unknown (primary)\n /// \n public Language LanguageFallbackPrimary\n {\n get\n {\n field ??= Languages.FirstOrDefault();\n return field;\n }\n set => Set(ref field, value);\n }\n\n /// \n /// Language to be used when source language was unknown (secondary)\n /// \n public Language LanguageFallbackSecondary\n {\n get\n {\n if (LanguageFallbackSecondarySame)\n {\n return LanguageFallbackPrimary;\n }\n\n field ??= LanguageFallbackPrimary;\n\n return field;\n }\n set => Set(ref field, value);\n }\n\n /// \n /// Whether to use LanguageFallbackPrimary for secondary subtitles\n /// \n public bool LanguageFallbackSecondarySame\n {\n get;\n set\n {\n if (Set(ref field, value))\n {\n Raise(nameof(LanguageFallbackSecondary));\n }\n }\n } = true;\n\n /// \n /// Whether to use local search plugins (see also )\n /// \n public bool SearchLocal { get => _SearchLocal; set => Set(ref _SearchLocal, value); }\n bool _SearchLocal = false;\n\n public const string DefaultSearchLocalPaths = \"subs; subtitles\";\n\n public string SearchLocalPaths\n {\n get;\n set\n {\n if (Set(ref field, value))\n {\n CmdResetSearchLocalPaths.OnCanExecuteChanged();\n }\n }\n } = DefaultSearchLocalPaths;\n\n [JsonIgnore]\n public RelayCommand CmdResetSearchLocalPaths => field ??= new((_) =>\n {\n SearchLocalPaths = DefaultSearchLocalPaths;\n }, (_) => SearchLocalPaths != DefaultSearchLocalPaths);\n\n /// \n /// Allowed input types to be searched locally for subtitles (empty list allows all types)\n /// \n public List SearchLocalOnInputType\n { get; set; } = new List() { InputType.File, InputType.UNC, InputType.Torrent };\n\n /// \n /// Whether to use online search plugins (see also )\n /// \n public bool SearchOnline { get => _SearchOnline; set { Set(ref _SearchOnline, value); if (player != null && player.Video.isOpened) Task.Run(() => { if (player != null && player.Video.isOpened) player.decoder.SearchOnlineSubtitles(); }); } }\n bool _SearchOnline = false;\n\n /// \n /// Allowed input types to be searched online for subtitles (empty list allows all types)\n /// \n public List SearchOnlineOnInputType\n { get; set; } = new List() { InputType.File, InputType.Torrent };\n\n /// \n /// Subtitles parser (can be used for custom parsing)\n /// \n [JsonIgnore]\n public Action\n Parser { get; set; } = ParseSubtitles.Parse;\n\n #region ASR\n /// \n /// ASR Engine Type (Currently only supports OpenAI Whisper)\n /// \n public SubASREngineType ASREngine { get; set => Set(ref field, value); } = SubASREngineType.WhisperCpp;\n\n /// \n /// ASR OpenAI Whisper common config\n /// \n public WhisperConfig WhisperConfig { get; set => Set(ref field, value); } = new();\n\n /// \n /// ASR whisper.cpp config\n /// \n public WhisperCppConfig WhisperCppConfig { get; set => Set(ref field, value); } = new();\n\n /// \n /// ASR Faster-Whisper config\n /// \n public FasterWhisperConfig FasterWhisperConfig { get; set => Set(ref field, value); } = new();\n\n /// \n /// Chunk size (MB) when processing ASR with audio stream\n /// Increasing size will increase memory usage but may result in more natural subtitle breaks\n /// \n public int ASRChunkSizeMB\n {\n get;\n set\n {\n if (Set(ref field, value))\n {\n Raise(nameof(ASRChunkSize));\n }\n }\n } = 20;\n\n [JsonIgnore]\n public long ASRChunkSize => ASRChunkSizeMB * 1024 * 1024;\n\n /// \n /// Chunk seconds when processing ASR with audio stream\n /// In the case of network streams, etc., the size is small and can be divided by specifying the number of seconds.\n /// \n public int ASRChunkSeconds { get; set => Set(ref field, value); } = 20;\n #endregion\n\n #region OCR\n /// \n /// OCR Tesseract Region Settings (key: iso6391, value: LangCode)\n /// \n public Dictionary TesseractOcrRegions { get; set => Set(ref field, value); } = new();\n\n /// \n /// OCR Microsoft Region Settings (key: iso6391, value: LanguageTag (BCP-47)\n /// \n public Dictionary MsOcrRegions { get; set => Set(ref field, value); } = new();\n #endregion\n\n #region Translation\n /// \n /// Language to be translated to\n /// \n public TargetLanguage TranslateTargetLanguage\n {\n get;\n set\n {\n if (Set(ref field, value))\n {\n TranslateLanguage = Language.Get(value.ToISO6391());\n }\n }\n } = TargetLanguage.EnglishAmerican;\n\n [JsonIgnore]\n public Language TranslateLanguage { get; private set; }\n\n /// \n /// Translation Service Type\n /// \n public TranslateServiceType TranslateServiceType { get; set => Set(ref field, value); } = TranslateServiceType.GoogleV1;\n\n /// \n /// Translation Word Service Type\n /// \n public TranslateServiceType TranslateWordServiceType { get; set => Set(ref field, value); } = TranslateServiceType.GoogleV1;\n\n /// \n /// Translation Service Type Settings\n /// \n public Dictionary TranslateServiceSettings { get; set => Set(ref field, value); } = new();\n\n /// \n /// Maximum count backward\n /// \n public int TranslateCountBackward { get; set => Set(ref field, value); } = 1;\n\n /// \n /// Maximum count forward\n /// \n public int TranslateCountForward { get; set => Set(ref field, value); } = 12;\n\n /// \n /// Number of concurrent requests to translation services\n /// \n public int TranslateMaxConcurrency {\n get;\n set\n {\n if (value <= 0)\n return;\n\n Set(ref field, value);\n }\n } = 2;\n\n /// \n /// Chat-style LLM API config\n /// \n public TranslateChatConfig TranslateChatConfig { get; set => Set(ref field, value); } = new();\n #endregion\n }\n public class DataConfig : NotifyPropertyChanged\n {\n public DataConfig Clone()\n {\n DataConfig data = new();\n data = (DataConfig)MemberwiseClone();\n\n data.player = null;\n\n return data;\n }\n\n internal Player player;\n\n /// \n /// Whether data should be processed\n /// \n public bool Enabled { get => _Enabled; set { if (Set(ref _Enabled, value)) if (value) player?.Data.Enable(); else player?.Data.Disable(); } }\n bool _Enabled = false;\n internal void SetEnabled(bool enabled) => Set(ref _Enabled, enabled, true, nameof(Enabled));\n }\n}\n\n/// \n/// Engine's configuration\n/// \npublic class EngineConfig\n{\n public string Version { get; set; }\n\n /// \n /// It will not initiallize audio and will be disabled globally\n /// \n public bool DisableAudio { get; set; }\n\n /// \n /// Required to register ffmpeg libraries. Make sure you provide x86 or x64 based on your project.\n /// :<path> for relative path from current folder or any below\n /// <path> for absolute or relative path\n /// \n public string FFmpegPath { get; set; } = \"FFmpeg\";\n\n /// \n /// Can be used to choose which FFmpeg libs to load\n /// All (Devices & Filters)
\n /// Filters
\n /// Main
\n ///
\n public LoadProfile\n FFmpegLoadProfile { get; set; } = LoadProfile.Filters; // change default to disable devices\n\n /// \n /// Whether to allow HLS live seeking (this can cause segmentation faults in case of incompatible ffmpeg version with library's custom structures)\n /// \n public bool FFmpegHLSLiveSeek { get; set; }\n\n /// \n /// Sets FFmpeg logger's level\n /// \n public Flyleaf.FFmpeg.LogLevel\n FFmpegLogLevel { get => _FFmpegLogLevel; set { _FFmpegLogLevel = value; if (Engine.IsLoaded) FFmpegEngine.SetLogLevel(); } }\n Flyleaf.FFmpeg.LogLevel _FFmpegLogLevel = Flyleaf.FFmpeg.LogLevel.Quiet;\n\n /// \n /// Whether configuration has been loaded from file\n /// \n [JsonIgnore]\n public bool Loaded { get; private set; }\n\n /// \n /// The path that this configuration has been loaded from\n /// \n [JsonIgnore]\n public string LoadedPath { get; private set; }\n\n /// \n /// Sets loggers output\n /// :debug -> System.Diagnostics.Debug\n /// :console -> System.Console\n /// <path> -> Absolute or relative file path\n /// \n public string LogOutput { get => _LogOutput; set { _LogOutput = value; if (Engine.IsLoaded) Logger.SetOutput(); } }\n string _LogOutput = \"\";\n\n /// \n /// Sets logger's level\n /// \n public LogLevel LogLevel { get; set; } = LogLevel.Quiet;\n\n /// \n /// When the output is file it will append instead of overwriting\n /// \n public bool LogAppend { get; set; }\n\n /// \n /// Lines to cache before writing them to file\n /// \n public int LogCachedLines { get; set; } = 20;\n\n /// \n /// Sets the logger's datetime string format\n /// \n public string LogDateTimeFormat { get; set; } = \"HH.mm.ss.fff\";\n\n /// \n /// Required to register plugins. Make sure you provide x86 or x64 based on your project and same .NET framework.\n /// :<path> for relative path from current folder or any below\n /// <path> for absolute or relative path\n /// \n public string PluginsPath { get; set; } = \"Plugins\";\n\n /// \n /// Updates Player.CurTime when the second changes otherwise on every UIRefreshInterval\n /// \n public bool UICurTimePerSecond { get; set; } = true;\n\n /// \n /// Activates Master Thread to monitor all the players and perform the required updates\n /// Required for Activity Mode, Stats & Buffered Duration on Pause\n /// \n public bool UIRefresh { get => _UIRefresh; set { _UIRefresh = value; if (value && Engine.IsLoaded) Engine.StartThread(); } }\n static bool _UIRefresh;\n\n /// \n /// How often should update the UI in ms (low values can cause performance issues)\n /// Should UIRefreshInterval < 1000ms and 1000 % UIRefreshInterval == 0 for accurate per second stats\n /// \n public int UIRefreshInterval { get; set; } = 250;\n\n /// \n /// Loads engine's configuration\n /// \n /// Absolute or relative path to load the configuraiton\n /// JSON serializer options\n // \n public static EngineConfig Load(string path, JsonSerializerOptions jsonOptions = null)\n {\n EngineConfig config = JsonSerializer.Deserialize(File.ReadAllText(path), jsonOptions);\n config.Loaded = true;\n config.LoadedPath = path;\n\n return config;\n }\n\n /// \n /// Saves engine's current configuration\n /// \n /// Absolute or relative path to save the configuration\n /// JSON serializer options\n public void Save(string path = null, JsonSerializerOptions jsonOptions = null)\n {\n if (path == null)\n {\n if (string.IsNullOrEmpty(LoadedPath))\n return;\n\n path = LoadedPath;\n }\n\n jsonOptions ??= new JsonSerializerOptions { WriteIndented = true };\n\n File.WriteAllText(path, JsonSerializer.Serialize(this, jsonOptions));\n }\n}\n"], ["/LLPlayer/FlyleafLib/MediaFramework/MediaDecoder/DecoderBase.cs", "using FlyleafLib.MediaFramework.MediaDemuxer;\nusing FlyleafLib.MediaFramework.MediaStream;\n\nnamespace FlyleafLib.MediaFramework.MediaDecoder;\n\npublic abstract unsafe class DecoderBase : RunThreadBase\n{\n public MediaType Type { get; protected set; }\n\n public bool OnVideoDemuxer => demuxer?.Type == MediaType.Video;\n public Demuxer Demuxer => demuxer;\n public StreamBase Stream { get; protected set; }\n public AVCodecContext* CodecCtx => codecCtx;\n public int Width => codecCtx != null ? codecCtx->width : 0; // for subtitle\n public int Height => codecCtx != null ? codecCtx->height : 0; // for subtitle\n\n public Action CodecChanged { get; set; }\n public Config Config { get; protected set; }\n public double Speed { get => speed; set { if (Disposed) { speed = value; return; } if (speed != value) OnSpeedChanged(value); } }\n protected double speed = 1, oldSpeed = 1;\n protected virtual void OnSpeedChanged(double value) { }\n\n internal bool filledFromCodec;\n protected AVFrame* frame;\n protected AVCodecContext* codecCtx;\n internal object lockCodecCtx = new();\n\n protected Demuxer demuxer;\n\n public DecoderBase(Config config, int uniqueId = -1) : base(uniqueId)\n {\n Config = config;\n\n if (this is VideoDecoder)\n Type = MediaType.Video;\n else if (this is AudioDecoder)\n Type = MediaType.Audio;\n else if (this is SubtitlesDecoder)\n Type = MediaType.Subs;\n else if (this is DataDecoder)\n Type = MediaType.Data;\n\n threadName = $\"Decoder: {Type,5}\";\n }\n\n public string Open(StreamBase stream)\n {\n lock (lockActions)\n {\n var prevStream = Stream;\n Dispose();\n Status = Status.Opening;\n string error = Open2(stream, prevStream);\n if (!Disposed)\n frame = av_frame_alloc();\n\n return error;\n }\n }\n protected string Open2(StreamBase stream, StreamBase prevStream, bool openStream = true)\n {\n string error = null;\n\n try\n {\n lock (stream.Demuxer.lockActions)\n {\n if (stream == null || stream.Demuxer.Interrupter.ForceInterrupt == 1 || stream.Demuxer.Disposed)\n return \"Cancelled\";\n\n int ret = -1;\n Disposed= false;\n Stream = stream;\n demuxer = stream.Demuxer;\n\n if (stream is not DataStream) // if we don't open/use a data codec context why not just push the Data Frames directly from the Demuxer? no need to have DataDecoder*\n {\n // avcodec_find_decoder will use libdav1d which does not support hardware decoding (software fallback with openStream = false from av1 to default:libdav1d) [#340]\n var codec = stream.CodecID == AVCodecID.Av1 && openStream && Config.Video.VideoAcceleration ? avcodec_find_decoder_by_name(\"av1\") : avcodec_find_decoder(stream.CodecID);\n if (codec == null)\n return error = $\"[{Type} avcodec_find_decoder] No suitable codec found\";\n\n codecCtx = avcodec_alloc_context3(codec); // Pass codec to use default settings\n if (codecCtx == null)\n return error = $\"[{Type} avcodec_alloc_context3] Failed to allocate context3\";\n\n ret = avcodec_parameters_to_context(codecCtx, stream.AVStream->codecpar);\n if (ret < 0)\n return error = $\"[{Type} avcodec_parameters_to_context] {FFmpegEngine.ErrorCodeToMsg(ret)} ({ret})\";\n\n codecCtx->pkt_timebase = stream.AVStream->time_base;\n codecCtx->codec_id = codec->id; // avcodec_parameters_to_context will change this we need to set Stream's Codec Id (eg we change mp2 to mp3)\n\n if (Config.Decoder.ShowCorrupted)\n codecCtx->flags |= CodecFlags.OutputCorrupt;\n\n if (Config.Decoder.LowDelay)\n codecCtx->flags |= CodecFlags.LowDelay;\n\n try { ret = Setup(codec); } catch(Exception e) { return error = $\"[{Type} Setup] {e.Message}\"; }\n if (ret < 0)\n return error = $\"[{Type} Setup] {ret}\";\n\n var codecOpts = Config.Decoder.GetCodecOptPtr(stream.Type);\n AVDictionary* avopt = null;\n foreach(var optKV in codecOpts)\n av_dict_set(&avopt, optKV.Key, optKV.Value, 0);\n\n ret = avcodec_open2(codecCtx, null, avopt == null ? null : &avopt);\n\n if (avopt != null)\n {\n if (ret >= 0)\n {\n AVDictionaryEntry *t = null;\n\n while ((t = av_dict_get(avopt, \"\", t, DictReadFlags.IgnoreSuffix)) != null)\n Log.Debug($\"Ignoring codec option {Utils.BytePtrToStringUTF8(t->key)}\");\n }\n\n av_dict_free(&avopt);\n }\n\n if (ret < 0)\n return error = $\"[{Type} avcodec_open2] {FFmpegEngine.ErrorCodeToMsg(ret)} ({ret})\";\n }\n\n if (openStream)\n {\n if (prevStream != null)\n {\n if (prevStream.Demuxer.Type == stream.Demuxer.Type)\n stream.Demuxer.SwitchStream(stream);\n else if (!prevStream.Demuxer.Disposed)\n {\n if (prevStream.Demuxer.Type == MediaType.Video)\n prevStream.Demuxer.DisableStream(prevStream);\n else if (prevStream.Demuxer.Type == MediaType.Audio || prevStream.Demuxer.Type == MediaType.Subs)\n prevStream.Demuxer.Dispose();\n\n stream.Demuxer.EnableStream(stream);\n }\n }\n else\n stream.Demuxer.EnableStream(stream);\n\n Status = Status.Stopped;\n CodecChanged?.Invoke(this);\n }\n\n return null;\n }\n }\n finally\n {\n if (error != null)\n Dispose(true);\n }\n }\n protected abstract int Setup(AVCodec* codec);\n\n public void Dispose(bool closeStream = false)\n {\n if (Disposed)\n return;\n\n lock (lockActions)\n {\n if (Disposed)\n return;\n\n Stop();\n DisposeInternal();\n\n if (closeStream && Stream != null && !Stream.Demuxer.Disposed)\n {\n if (Stream.Demuxer.Type == MediaType.Video)\n Stream.Demuxer.DisableStream(Stream);\n else\n Stream.Demuxer.Dispose();\n }\n\n if (frame != null)\n fixed (AVFrame** ptr = &frame)\n av_frame_free(ptr);\n\n if (codecCtx != null)\n fixed (AVCodecContext** ptr = &codecCtx)\n avcodec_free_context(ptr);\n\n codecCtx = null;\n demuxer = null;\n Stream = null;\n Status = Status.Stopped;\n Disposed = true;\n Log.Info(\"Disposed\");\n }\n }\n protected abstract void DisposeInternal();\n}\n"], ["/LLPlayer/LLPlayer/ViewModels/SubtitlesDownloaderDialogVM.cs", "using System.Collections.ObjectModel;\nusing System.ComponentModel;\nusing System.IO;\nusing FlyleafLib;\nusing FlyleafLib.MediaFramework.MediaPlaylist;\nusing FlyleafLib.MediaPlayer;\nusing LLPlayer.Extensions;\nusing LLPlayer.Services;\nusing Microsoft.Win32;\nusing static FlyleafLib.MediaFramework.MediaContext.DecoderContext;\n\nnamespace LLPlayer.ViewModels;\n\npublic class SubtitlesDownloaderDialogVM : Bindable, IDialogAware\n{\n public FlyleafManager FL { get; }\n private readonly OpenSubtitlesProvider _subProvider;\n\n public SubtitlesDownloaderDialogVM(\n FlyleafManager fl,\n OpenSubtitlesProvider subProvider\n )\n {\n FL = fl;\n _subProvider = subProvider;\n }\n\n public ObservableCollection Subs { get; } = new();\n\n public SearchResponse? SelectedSub\n {\n get;\n set\n {\n if (Set(ref field, value))\n {\n OnPropertyChanged(nameof(CanAction));\n }\n }\n } = null;\n\n public string Query\n {\n get;\n set\n {\n if (Set(ref field, value))\n {\n OnPropertyChanged(nameof(CanSearch));\n }\n }\n } = string.Empty;\n\n public bool CanSearch => !string.IsNullOrWhiteSpace(Query);\n public bool CanAction => SelectedSub != null;\n\n public AsyncDelegateCommand? CmdSearch => field ??= new AsyncDelegateCommand(async () =>\n {\n Subs.Clear();\n\n IList result;\n\n try\n {\n result = await _subProvider.Search(Query);\n }\n catch (Exception ex)\n {\n ErrorDialogHelper.ShowUnknownErrorPopup($\"Cannot search subtitles from opensubtitles.org: {ex.Message}\", UnknownErrorType.Network, ex);\n return;\n }\n\n var query = result\n .OrderByDescending(r =>\n {\n // prefer user-configured languages\n return FL.PlayerConfig.Subtitles.Languages.Any(l =>\n l.Equals(Language.Get(r.ISO639)));\n })\n .ThenBy(r => r.LanguageName)\n .ThenByDescending(r => r.SubDownloadsCnt)\n .ThenBy(r => r.SubFileName);\n\n foreach (var record in query)\n {\n Subs.Add(record);\n }\n }).ObservesCanExecute(() => CanSearch);\n\n public AsyncDelegateCommand? CmdLoad => field ??= new AsyncDelegateCommand(async () =>\n {\n var sub = SelectedSub;\n if (sub == null)\n {\n return;\n }\n\n byte[] subData;\n\n try\n {\n (subData, _) = await _subProvider.Download(sub);\n }\n catch (Exception ex)\n {\n ErrorDialogHelper.ShowUnknownErrorPopup($\"Cannot load the subtitle from opensubtitles.org: {ex.Message}\", UnknownErrorType.Network, ex);\n return;\n }\n\n string subDir = Path.Combine(Path.GetTempPath(), App.Name, \"Subs\");\n string subPath = Path.Combine(subDir, sub.SubFileName);\n if (!Directory.Exists(subDir))\n {\n Directory.CreateDirectory(subDir);\n }\n\n var ext = Path.GetExtension(subPath).ToLower();\n if (ext.StartsWith(\".\"))\n {\n ext = ext.Substring(1);\n }\n\n if (!Utils.ExtensionsSubtitles.Contains(ext))\n {\n throw new InvalidOperationException($\"'{ext}' extension is not supported\");\n }\n\n await File.WriteAllBytesAsync(subPath, subData);\n\n // TODO: L: Refactor to pass language directly at Open\n // TODO: L: Allow to load as a secondary subtitle\n FL.Player.decoder.OpenExternalSubtitlesStreamCompleted += DecoderOnOpenExternalSubtitlesStreamCompleted;\n\n void DecoderOnOpenExternalSubtitlesStreamCompleted(object? sender, OpenExternalSubtitlesStreamCompletedArgs e)\n {\n FL.Player.decoder.OpenExternalSubtitlesStreamCompleted -= DecoderOnOpenExternalSubtitlesStreamCompleted;\n\n if (e.Success)\n {\n var stream = e.ExtStream;\n if (stream != null && stream.Url == subPath)\n {\n // Override if different from auto-detected language\n stream.ManualDownloaded = true;\n\n if (stream.Language.ISO6391 != sub.ISO639)\n {\n var lang = Language.Get(sub.ISO639);\n if (!string.IsNullOrEmpty(lang.IdSubLanguage) && lang.IdSubLanguage != \"und\")\n {\n stream.Language = lang;\n FL.Player.SubtitlesManager[0].LanguageSource = stream.Language;\n }\n }\n }\n }\n }\n\n FL.Player.OpenAsync(subPath);\n\n }).ObservesCanExecute(() => CanAction);\n\n public AsyncDelegateCommand? CmdDownload => field ??= new AsyncDelegateCommand(async () =>\n {\n var sub = SelectedSub;\n if (sub == null)\n {\n return;\n }\n\n string fileName = sub.SubFileName;\n\n string? initDir = null;\n if (FL.Player.Playlist.Selected != null)\n {\n var url = FL.Player.Playlist.Selected.DirectUrl;\n if (File.Exists(url))\n {\n initDir = Path.GetDirectoryName(url);\n }\n }\n\n SaveFileDialog dialog = new()\n {\n Title = \"Save subtitles to file\",\n InitialDirectory = initDir,\n FileName = fileName,\n Filter = \"All Files (*.*)|*.*\",\n };\n\n if (dialog.ShowDialog() == true)\n {\n byte[] subData;\n\n try\n {\n (subData, _) = await _subProvider.Download(sub);\n }\n catch (Exception ex)\n {\n ErrorDialogHelper.ShowUnknownErrorPopup($\"Cannot download the subtitle from opensubtitles.org: {ex.Message}\", UnknownErrorType.Network, ex);\n return;\n }\n\n await File.WriteAllBytesAsync(dialog.FileName, subData);\n }\n }).ObservesCanExecute(() => CanAction);\n\n private void Playlist_OnPropertyChanged(object? sender, PropertyChangedEventArgs e)\n {\n if (e.PropertyName == nameof(FL.Player.Playlist.Selected) &&\n FL.Player.Playlist.Selected != null)\n {\n // Update query when video changes\n UpdateQuery(FL.Player.Playlist.Selected);\n }\n }\n\n private void UpdateQuery(PlaylistItem selected)\n {\n string title = selected.Title;\n if (title == selected.OriginalTitle && File.Exists(selected.Url))\n {\n FileInfo fi = new(selected.Url);\n if (!string.IsNullOrEmpty(fi.Extension) && title.EndsWith(fi.Extension))\n {\n // remove extension part\n title = title[..^fi.Extension.Length];\n }\n }\n\n Query = title;\n }\n\n #region IDialogAware\n public string Title { get; set => Set(ref field, value); }\n = $\"Subtitles Downloader - {App.Name}\";\n public double WindowWidth { get; set => Set(ref field, value); } = 900;\n public double WindowHeight { get; set => Set(ref field, value); } = 600;\n\n public DialogCloseListener RequestClose { get; }\n\n public bool CanCloseDialog()\n {\n return true;\n }\n public void OnDialogClosed()\n {\n FL.Player.Playlist.PropertyChanged -= Playlist_OnPropertyChanged;\n }\n public void OnDialogOpened(IDialogParameters parameters)\n {\n // Set query from current video\n var selected = FL.Player.Playlist.Selected;\n if (selected != null)\n {\n UpdateQuery(selected);\n }\n\n // Register update playlist event\n FL.Player.Playlist.PropertyChanged += Playlist_OnPropertyChanged;\n }\n #endregion\n}\n"], ["/LLPlayer/FlyleafLib/MediaPlayer/Player.Screamers.cs", "using System.Diagnostics;\nusing System.Threading;\n\nusing FlyleafLib.MediaFramework.MediaDecoder;\nusing FlyleafLib.MediaFramework.MediaFrame;\nusing FlyleafLib.MediaFramework.MediaStream;\nusing static FlyleafLib.Utils;\nusing static FlyleafLib.Logger;\n\nnamespace FlyleafLib.MediaPlayer;\n\nunsafe partial class Player\n{\n /// \n /// Fires on Data frame when it's supposed to be shown according to the stream\n /// Warning: Uses Invoke and it comes from playback thread so you can't pause/stop etc. You need to use another thread if you have to.\n /// \n public event EventHandler OnDataFrame;\n\n /// \n /// Fires on buffering started\n /// Warning: Uses Invoke and it comes from playback thread so you can't pause/stop etc. You need to use another thread if you have to.\n /// \n public event EventHandler BufferingStarted;\n protected virtual void OnBufferingStarted()\n {\n if (onBufferingStarted != onBufferingCompleted) return;\n BufferingStarted?.Invoke(this, new EventArgs());\n onBufferingStarted++;\n\n if (CanDebug) Log.Debug($\"OnBufferingStarted\");\n }\n\n /// \n /// Fires on buffering completed (will fire also on failed buffering completed)\n /// (BufferDration > Config.Player.MinBufferDuration)\n /// Warning: Uses Invoke and it comes from playback thread so you can't pause/stop etc. You need to use another thread if you have to.\n /// \n public event EventHandler BufferingCompleted;\n protected virtual void OnBufferingCompleted(string error = null)\n {\n if (onBufferingStarted - 1 != onBufferingCompleted) return;\n\n if (error != null && LastError == null)\n {\n lastError = error;\n UI(() => LastError = LastError);\n }\n\n BufferingCompleted?.Invoke(this, new BufferingCompletedArgs(error));\n onBufferingCompleted++;\n if (CanDebug) Log.Debug($\"OnBufferingCompleted{(error != null ? $\" (Error: {error})\" : \"\")}\");\n }\n\n long onBufferingStarted;\n long onBufferingCompleted;\n\n int vDistanceMs;\n int aDistanceMs;\n int[] sDistanceMss;\n int dDistanceMs;\n int sleepMs;\n\n long elapsedTicks;\n long elapsedSec;\n long startTicks;\n long showOneFrameTicks;\n\n int allowedLateAudioDrops;\n long lastSpeedChangeTicks;\n long curLatency;\n internal long curAudioDeviceDelay;\n\n public int subNum => Config.Subtitles.Max;\n\n Stopwatch sw = new();\n\n private void ShowOneFrame()\n {\n for (int i = 0; i < subNum; i++)\n {\n sFrames[i] = null;\n }\n if (VideoDecoder.Frames.IsEmpty || !VideoDecoder.Frames.TryDequeue(out vFrame))\n return;\n\n renderer.Present(vFrame);\n\n if (!seeks.IsEmpty)\n return;\n\n if (!VideoDemuxer.IsHLSLive)\n curTime = vFrame.timestamp;\n\n UI(() => UpdateCurTime());\n\n for (int i = 0; i < subNum; i++)\n {\n // Prevents blinking after seek\n if (sFramesPrev[i] != null)\n {\n var cur = SubtitlesManager[i].GetCurrent();\n if (cur != null)\n {\n if (!string.IsNullOrEmpty(cur.DisplayText) || (cur.IsBitmap && cur.Bitmap != null))\n {\n continue;\n }\n }\n }\n\n // Clear last subtitles text if video timestamp is not within subs timestamp + duration (to prevent clearing current subs on pause/play)\n if (sFramesPrev[i] == null || sFramesPrev[i].timestamp > vFrame.timestamp || (sFramesPrev[i].timestamp + (sFramesPrev[i].duration * (long)10000)) < vFrame.timestamp)\n {\n sFramesPrev[i] = null;\n SubtitleClear(i);\n }\n }\n\n // Required for buffering on paused\n if (decoder.RequiresResync && !IsPlaying && seeks.IsEmpty)\n decoder.Resync(vFrame.timestamp);\n\n vFrame = null;\n }\n\n // !!! NEEDS RECODING (We show one frame, we dispose it, we get another one and we show it also after buffering which can be in 'no time' which can leave us without any more decoded frames so we rebuffer)\n private bool MediaBuffer()\n {\n if (CanTrace) Log.Trace(\"Buffering\");\n\n while (isVideoSwitch && IsPlaying) Thread.Sleep(10);\n\n Audio.ClearBuffer();\n\n VideoDemuxer.Start();\n VideoDecoder.Start();\n\n if (Audio.isOpened && Config.Audio.Enabled)\n {\n curAudioDeviceDelay = Audio.GetDeviceDelay();\n\n if (AudioDecoder.OnVideoDemuxer)\n AudioDecoder.Start();\n else if (!decoder.RequiresResync)\n {\n AudioDemuxer.Start();\n AudioDecoder.Start();\n }\n }\n\n if (Config.Subtitles.Enabled)\n {\n for (int i = 0; i < subNum; i++)\n {\n if (!Subtitles[i].IsOpened)\n {\n continue;\n }\n\n lock (lockSubtitles)\n {\n if (SubtitlesDecoders[i].OnVideoDemuxer)\n {\n SubtitlesDecoders[i].Start();\n }\n //else if (!decoder.RequiresResync)\n //{\n // SubtitlesDemuxers[i].Start();\n // SubtitlesDecoders[i].Start();\n //}\n }\n }\n }\n\n if (Data.isOpened && Config.Data.Enabled)\n {\n if (DataDecoder.OnVideoDemuxer)\n DataDecoder.Start();\n else if (!decoder.RequiresResync)\n {\n DataDemuxer.Start();\n DataDecoder.Start();\n }\n }\n\n VideoDecoder.DisposeFrame(vFrame);\n vFrame = null;\n aFrame = null;\n for (int i = 0; i < subNum; i++)\n {\n sFrames[i] = null;\n }\n dFrame = null;\n\n bool gotAudio = !Audio.IsOpened || Config.Player.MaxLatency != 0;\n bool gotVideo = false;\n bool shouldStop = false;\n bool showOneFrame = true;\n int audioRetries = 4;\n int loops = 0;\n\n if (Config.Player.MaxLatency != 0)\n {\n lastSpeedChangeTicks = DateTime.UtcNow.Ticks;\n showOneFrame = false;\n Speed = 1;\n }\n\n do\n {\n loops++;\n\n if (showOneFrame && !VideoDecoder.Frames.IsEmpty)\n {\n ShowOneFrame();\n showOneFrameTicks = DateTime.UtcNow.Ticks;\n showOneFrame = false;\n }\n\n // We allo few ms to show a frame before cancelling\n if ((!showOneFrame || loops > 8) && !seeks.IsEmpty)\n return false;\n\n if (!gotVideo && !showOneFrame && !VideoDecoder.Frames.IsEmpty)\n {\n VideoDecoder.Frames.TryDequeue(out vFrame);\n if (vFrame != null) gotVideo = true;\n }\n\n if (!gotAudio && aFrame == null && !AudioDecoder.Frames.IsEmpty)\n AudioDecoder.Frames.TryDequeue(out aFrame);\n\n if (gotVideo)\n {\n if (decoder.RequiresResync)\n decoder.Resync(vFrame.timestamp);\n\n if (!gotAudio && aFrame != null)\n {\n for (int i=0; i vFrame.timestamp\n || vFrame.timestamp > Duration)\n {\n gotAudio = true;\n break;\n }\n\n if (CanTrace) Log.Trace($\"Drop aFrame {TicksToTime(aFrame.timestamp)}\");\n AudioDecoder.Frames.TryDequeue(out aFrame);\n }\n\n // Avoid infinite loop in case of all audio timestamps wrong\n if (!gotAudio)\n {\n audioRetries--;\n\n if (audioRetries < 1)\n {\n gotAudio = true;\n aFrame = null;\n Log.Warn($\"Audio Exhausted 1\");\n }\n }\n }\n }\n\n if (!IsPlaying || decoderHasEnded)\n shouldStop = true;\n else\n {\n if (!VideoDecoder.IsRunning && !isVideoSwitch)\n {\n Log.Warn(\"Video Exhausted\");\n shouldStop= true;\n }\n\n if (gotVideo && !gotAudio && audioRetries > 0 && (!AudioDecoder.IsRunning || AudioDecoder.Demuxer.Status == MediaFramework.Status.QueueFull))\n {\n if (CanWarn) Log.Warn($\"Audio Exhausted 2 | {audioRetries}\");\n\n audioRetries--;\n\n if (audioRetries < 1)\n gotAudio = true;\n }\n }\n\n Thread.Sleep(10);\n\n } while (!shouldStop && (!gotVideo || !gotAudio));\n\n if (shouldStop && !(decoderHasEnded && IsPlaying && vFrame != null))\n {\n Log.Info(\"Stopped\");\n return false;\n }\n\n if (vFrame == null)\n {\n Log.Error(\"No Frames!\");\n return false;\n }\n\n // Negative Buffer Duration during codec change (we don't dipose the cached frames or we receive them later) *skip waiting for now\n var bufDuration = GetBufferedDuration();\n if (bufDuration >= 0)\n while(seeks.IsEmpty && bufDuration < Config.Player.MinBufferDuration && IsPlaying && VideoDemuxer.IsRunning && VideoDemuxer.Status != MediaFramework.Status.QueueFull)\n {\n Thread.Sleep(20);\n bufDuration = GetBufferedDuration();\n if (bufDuration < 0)\n break;\n }\n\n if (!seeks.IsEmpty)\n return false;\n\n if (CanInfo) Log.Info($\"Started [V: {TicksToTime(vFrame.timestamp)}]\" + (aFrame == null ? \"\" : $\" [A: {TicksToTime(aFrame.timestamp)}]\"));\n\n decoder.OpenedPlugin.OnBufferingCompleted();\n\n return true;\n }\n private void Screamer()\n {\n long audioBufferedDuration = 0; // We force audio resync with = 0\n\n while (Status == Status.Playing)\n {\n if (seeks.TryPop(out var seekData))\n {\n seeks.Clear();\n requiresBuffering = true;\n\n for (int i = 0; i < subNum; i++)\n {\n // Display subtitles from cache when seeking while playing\n bool display = false;\n var cur = SubtitlesManager[i].GetCurrent();\n if (cur != null)\n {\n if (!string.IsNullOrEmpty(cur.DisplayText))\n {\n SubtitleDisplay(cur.DisplayText, i, cur.UseTranslated);\n display = true;\n }\n else if (cur.IsBitmap && cur.Bitmap != null)\n {\n SubtitleDisplay(cur.Bitmap, i);\n display = true;\n }\n\n if (display)\n {\n sFramesPrev[i] = new SubtitlesFrame\n {\n timestamp = cur.StartTime.Ticks + Config.Subtitles[i].Delay,\n duration = (uint)cur.Duration.TotalMilliseconds,\n isTranslated = cur.UseTranslated\n };\n }\n }\n\n // clear subtitles\n // but do not clear when cache hit\n if (!display && sFramesPrev[i] != null)\n {\n sFramesPrev[i] = null;\n SubtitleClear(i);\n }\n }\n\n decoder.PauseDecoders(); // TBR: Required to avoid gettings packets between Seek and ShowFrame which causes resync issues\n\n if (decoder.Seek(seekData.accurate ? Math.Max(0, seekData.ms - (int)new TimeSpan(Config.Player.SeekAccurateFixMargin).TotalMilliseconds) : seekData.ms, seekData.forward, !seekData.accurate) < 0) // Consider using GetVideoFrame with no timestamp (any) to ensure keyframe packet for faster seek in HEVC\n Log.Warn(\"Seek failed\");\n else if (seekData.accurate)\n decoder.GetVideoFrame(seekData.ms * (long)10000);\n }\n\n if (requiresBuffering)\n {\n if (VideoDemuxer.Interrupter.Timedout)\n break;\n\n OnBufferingStarted();\n MediaBuffer();\n requiresBuffering = false;\n if (!seeks.IsEmpty)\n continue;\n\n if (vFrame == null)\n {\n if (decoderHasEnded)\n OnBufferingCompleted();\n\n Log.Warn(\"[MediaBuffer] No video frame\");\n break;\n }\n\n // Temp fix to ensure we had enough time to decode one more frame\n int retries = 5;\n while (IsPlaying && VideoDecoder.Frames.Count == 0 && retries-- > 0)\n Thread.Sleep(10);\n\n // Give enough time for the 1st frame to be presented\n while (IsPlaying && DateTime.UtcNow.Ticks - showOneFrameTicks < VideoDecoder.VideoStream.FrameDuration)\n Thread.Sleep(4);\n\n OnBufferingCompleted();\n\n audioBufferedDuration = 0;\n allowedLateAudioDrops = 7;\n elapsedSec = 0;\n startTicks = vFrame.timestamp;\n sw.Restart();\n }\n\n if (Status != Status.Playing)\n break;\n\n if (vFrame == null)\n {\n if (VideoDecoder.Status == MediaFramework.Status.Ended)\n {\n if (!MainDemuxer.IsHLSLive)\n {\n if (Math.Abs(MainDemuxer.Duration - curTime) < 2 * VideoDemuxer.VideoStream.FrameDuration)\n curTime = MainDemuxer.Duration;\n else\n curTime += VideoDemuxer.VideoStream.FrameDuration;\n\n UI(() => Set(ref _CurTime, curTime, true, nameof(CurTime)));\n }\n\n break;\n }\n\n Log.Warn(\"No video frames\");\n requiresBuffering = true;\n continue;\n }\n\n if (aFrame == null && !isAudioSwitch)\n AudioDecoder.Frames.TryDequeue(out aFrame);\n\n for (int i = 0; i < subNum; i++)\n {\n if (sFrames[i] == null && !isSubsSwitches[i])\n SubtitlesDecoders[i].Frames.TryPeek(out sFrames[i]);\n }\n\n if (dFrame == null && !isDataSwitch)\n DataDecoder.Frames.TryPeek(out dFrame);\n\n elapsedTicks = (long) (sw.ElapsedTicks * SWFREQ_TO_TICKS); // Do we really need ticks precision?\n\n vDistanceMs =\n (int) ((((vFrame.timestamp - startTicks) / speed) - elapsedTicks) / 10000);\n\n if (aFrame != null)\n {\n curAudioDeviceDelay = Audio.GetDeviceDelay();\n audioBufferedDuration = Audio.GetBufferedDuration();\n aDistanceMs = (int) ((((aFrame.timestamp - startTicks) / speed) - (elapsedTicks - curAudioDeviceDelay)) / 10000);\n\n // Try to keep the audio buffer full enough to avoid audio crackling (up to 50ms)\n while (audioBufferedDuration > 0 && audioBufferedDuration < 50 * 10000 && aDistanceMs > -5 && aDistanceMs < 50)\n {\n Audio.AddSamples(aFrame);\n\n if (isAudioSwitch)\n {\n audioBufferedDuration = 0;\n aDistanceMs = int.MaxValue;\n aFrame = null;\n }\n else\n {\n audioBufferedDuration = Audio.GetBufferedDuration();\n AudioDecoder.Frames.TryDequeue(out aFrame);\n if (aFrame != null)\n aDistanceMs = (int) ((((aFrame.timestamp - startTicks) / speed) - (elapsedTicks - curAudioDeviceDelay)) / 10000);\n else\n aDistanceMs = int.MaxValue;\n }\n }\n }\n else\n aDistanceMs = int.MaxValue;\n\n for (int i = 0; i < subNum; i++)\n {\n sDistanceMss[i] = sFrames[i] != null\n ? (int)((((sFrames[i].timestamp - startTicks) / speed) - elapsedTicks) / 10000)\n : int.MaxValue;\n }\n\n dDistanceMs = dFrame != null\n ? (int)((((dFrame.timestamp - startTicks) / speed) - elapsedTicks) / 10000)\n : int.MaxValue;\n\n sleepMs = Math.Min(vDistanceMs, aDistanceMs) - 1;\n if (sleepMs < 0 || sleepMs == int.MaxValue)\n sleepMs = 0;\n\n if (sleepMs > 2)\n {\n if (vDistanceMs > 2000)\n {\n Log.Warn($\"vDistanceMs = {vDistanceMs} (restarting)\");\n requiresBuffering = true;\n continue;\n }\n\n if (Engine.Config.UICurTimePerSecond && (\n (!MainDemuxer.IsHLSLive && curTime / 10000000 != _CurTime / 10000000) ||\n (MainDemuxer.IsHLSLive && Math.Abs(elapsedTicks - elapsedSec) > 10000000)))\n {\n elapsedSec = elapsedTicks;\n UI(() => UpdateCurTime());\n }\n\n Thread.Sleep(sleepMs);\n }\n\n if (aFrame != null) // Should use different thread for better accurancy (renderer might delay it on high fps) | also on high offset we will have silence between samples\n {\n if (Math.Abs(aDistanceMs - sleepMs) <= 5)\n {\n Audio.AddSamples(aFrame);\n\n // Audio Desync - Large Buffer | ASampleBytes (S16 * 2 Channels = 4) * TimeBase * 2 -frames duration-\n if (Audio.GetBufferedDuration() > Math.Max(50 * 10000, (aFrame.dataLen / 4) * Audio.Timebase * 2))\n {\n if (CanDebug)\n Log.Debug($\"Audio desynced by {(int)(audioBufferedDuration / 10000)}ms, clearing buffers\");\n\n Audio.ClearBuffer();\n audioBufferedDuration = 0;\n }\n\n aFrame = null;\n }\n else if (aDistanceMs > 4000) // Drops few audio frames in case of wrong timestamps (Note this should be lower, until swr has min/max samples for about 20-70ms)\n {\n if (allowedLateAudioDrops > 0)\n {\n Audio.framesDropped++;\n allowedLateAudioDrops--;\n if (CanDebug) Log.Debug($\"aDistanceMs 3 = {aDistanceMs}\");\n aFrame = null;\n audioBufferedDuration = 0;\n }\n }\n else if (aDistanceMs < -5) // Will be transfered back to decoder to drop invalid timestamps\n {\n if (CanTrace) Log.Trace($\"aDistanceMs = {aDistanceMs} | AudioFrames: {AudioDecoder.Frames.Count} AudioPackets: {AudioDecoder.Demuxer.AudioPackets.Count}\");\n\n if (GetBufferedDuration() < Config.Player.MinBufferDuration / 2)\n {\n if (CanInfo)\n Log.Warn($\"Not enough buffer (restarting)\");\n\n requiresBuffering = true;\n continue;\n }\n\n audioBufferedDuration = 0;\n\n if (aDistanceMs < -600)\n {\n if (CanTrace) Log.Trace($\"All audio frames disposed\");\n Audio.framesDropped += AudioDecoder.Frames.Count;\n AudioDecoder.DisposeFrames();\n aFrame = null;\n }\n else\n {\n int maxdrop = Math.Max(Math.Min(vDistanceMs - sleepMs - 1, 20), 3);\n for (int i=0; i 0)\n break;\n\n aFrame = null;\n }\n }\n }\n }\n\n if (Math.Abs(vDistanceMs - sleepMs) <= 2)\n {\n if (CanTrace) Log.Trace($\"[V] Presenting {TicksToTime(vFrame.timestamp)}\");\n\n if (decoder.VideoDecoder.Renderer.Present(vFrame, false))\n Video.framesDisplayed++;\n else\n Video.framesDropped++;\n\n lock (seeks)\n if (seeks.IsEmpty)\n {\n curTime = !MainDemuxer.IsHLSLive ? vFrame.timestamp : VideoDemuxer.CurTime;\n\n if (Config.Player.UICurTimePerFrame)\n UI(() => UpdateCurTime());\n }\n\n VideoDecoder.Frames.TryDequeue(out vFrame);\n if (vFrame != null && Config.Player.MaxLatency != 0)\n CheckLatency();\n }\n else if (vDistanceMs < -2)\n {\n if (vDistanceMs < -10 || GetBufferedDuration() < Config.Player.MinBufferDuration / 2)\n {\n if (CanDebug)\n Log.Debug($\"vDistanceMs = {vDistanceMs} (restarting)\");\n\n requiresBuffering = true;\n continue;\n }\n\n if (CanDebug)\n Log.Debug($\"vDistanceMs = {vDistanceMs}\");\n\n Video.framesDropped++;\n VideoDecoder.DisposeFrame(vFrame);\n VideoDecoder.Frames.TryDequeue(out vFrame);\n }\n\n // Set the current time to SubtitleManager in a loop\n if (Config.Subtitles.Enabled)\n {\n for (int i = 0; i < subNum; i++)\n {\n if (Subtitles[i].Enabled)\n {\n SubtitlesManager[i].SetCurrentTime(new TimeSpan(curTime));\n }\n }\n }\n // Internal subtitles (Text or Bitmap or OCR)\n for (int i = 0; i < subNum; i++)\n {\n if (sFramesPrev[i] != null && ((sFramesPrev[i].timestamp - startTicks + (sFramesPrev[i].duration * (long)10000)) / speed) - (long) (sw.ElapsedTicks * SWFREQ_TO_TICKS) < 0)\n {\n SubtitleClear(i);\n\n sFramesPrev[i] = null;\n }\n\n if (sFrames[i] != null)\n {\n if (Math.Abs(sDistanceMss[i] - sleepMs) < 30 || (sDistanceMss[i] < -30 && sFrames[i].duration + sDistanceMss[i] > 0))\n {\n if (sFrames[i].isBitmap && sFrames[i].sub.num_rects > 0)\n {\n if (SubtitlesSelectedHelper.GetMethod(i) == SelectSubMethod.OCR)\n {\n // Prevent the problem of OCR subtitles not being used in priority by setting\n // the timestamp of the subtitles as they are displayed a little earlier\n SubtitlesManager[i].SetCurrentTime(new TimeSpan(sFrames[i].timestamp));\n }\n\n var cur = SubtitlesManager[i].GetCurrent();\n\n if (cur != null && !string.IsNullOrEmpty(cur.Text))\n {\n // Use OCR text subtitles if available\n SubtitleDisplay(cur.DisplayText, i, cur.UseTranslated);\n }\n else\n {\n // renderer.CreateOverlayTexture(sFrame, SubtitlesDecoder.CodecCtx->width, SubtitlesDecoder.CodecCtx->height);\n SubtitleDisplay(sFrames[i].bitmap, i);\n }\n\n SubtitlesDecoder.DisposeFrame(sFrames[i]); // only rects\n }\n else if (sFrames[i].isBitmap && sFrames[i].sub.num_rects == 0)\n {\n // For Blu-ray subtitles (PGS), clear the previous subtitle\n SubtitleClear(i);\n sFramesPrev[i] = sFrames[i] = null;\n }\n else\n {\n // internal text sub (does not support translate)\n SubtitleDisplay(sFrames[i].text, i, false);\n }\n sFramesPrev[i] = sFrames[i];\n sFrames[i] = null;\n SubtitlesDecoders[i].Frames.TryDequeue(out _);\n }\n else if (sDistanceMss[i] < -30)\n {\n if (CanDebug)\n Log.Debug($\"sDistanceMss[i] = {sDistanceMss[i]}\");\n\n //SubtitleClear(i);\n\n // TODO: L: Here sFrames can be null, occurs when switching subtitles?\n SubtitlesDecoder.DisposeFrame(sFrames[i]);\n sFrames[i] = null;\n SubtitlesDecoders[i].Frames.TryDequeue(out _);\n }\n }\n }\n\n // External or ASR subtitles\n for (int i = 0; i < subNum; i++)\n {\n if (!Config.Subtitles.Enabled || !Subtitles[i].Enabled)\n {\n continue;\n }\n\n SubtitleData cur = SubtitlesManager[i].GetCurrent();\n\n if (cur == null)\n {\n continue;\n }\n\n if (sFramesPrev[i] == null ||\n sFramesPrev[i].timestamp != cur.StartTime.Ticks + Config.Subtitles[i].Delay)\n {\n bool display = false;\n if (!string.IsNullOrEmpty(cur.DisplayText))\n {\n SubtitleDisplay(cur.DisplayText, i, cur.UseTranslated);\n display = true;\n }\n else if (cur.IsBitmap && cur.Bitmap != null)\n {\n SubtitleDisplay(cur.Bitmap, i);\n display = true;\n }\n\n if (display)\n {\n sFramesPrev[i] = new SubtitlesFrame\n {\n timestamp = cur.StartTime.Ticks + Config.Subtitles[i].Delay,\n duration = (uint)cur.Duration.TotalMilliseconds,\n isTranslated = cur.UseTranslated\n };\n }\n }\n else\n {\n // Apply translation to current sub\n if (Config.Subtitles[i].EnabledTranslated) {\n\n // If the subtitle currently playing is not translated, change to the translated for display\n if (sFramesPrev[i] != null &&\n sFramesPrev[i].timestamp == cur.StartTime.Ticks + Config.Subtitles[i].Delay &&\n sFramesPrev[i].isTranslated != cur.UseTranslated)\n {\n SubtitleDisplay(cur.DisplayText, i, cur.UseTranslated);\n sFramesPrev[i].isTranslated = cur.UseTranslated;\n }\n }\n }\n }\n\n if (dFrame != null)\n {\n if (Math.Abs(dDistanceMs - sleepMs) < 30 || (dDistanceMs < -30))\n {\n OnDataFrame?.Invoke(this, dFrame);\n\n dFrame = null;\n DataDecoder.Frames.TryDequeue(out var devnull);\n }\n else if (dDistanceMs < -30)\n {\n if (CanDebug)\n Log.Debug($\"dDistanceMs = {dDistanceMs}\");\n\n dFrame = null;\n DataDecoder.Frames.TryDequeue(out var devnull);\n }\n }\n }\n\n if (CanInfo) Log.Info($\"Finished -> {TicksToTime(CurTime)}\");\n }\n\n private void CheckLatency()\n {\n curLatency = GetBufferedDuration();\n\n if (CanDebug)\n Log.Debug($\"[Latency {curLatency/10000}ms] Frames: {VideoDecoder.Frames.Count} Packets: {VideoDemuxer.VideoPackets.Count} Speed: {speed}\");\n\n if (curLatency <= Config.Player.MinLatency) // We've reached the down limit (back to speed x1)\n {\n ChangeSpeedWithoutBuffering(1);\n return;\n }\n else if (curLatency < Config.Player.MaxLatency)\n return;\n\n var newSpeed = Math.Max(Math.Round((double)curLatency / Config.Player.MaxLatency, 1, MidpointRounding.ToPositiveInfinity), 1.1);\n\n if (newSpeed > 4) // TBR: dispose only as much as required to avoid rebuffering\n {\n decoder.Flush();\n requiresBuffering = true;\n Log.Debug($\"[Latency {curLatency/10000}ms] Clearing queue\");\n return;\n }\n\n ChangeSpeedWithoutBuffering(newSpeed);\n }\n private void ChangeSpeedWithoutBuffering(double newSpeed)\n {\n if (speed == newSpeed)\n return;\n\n long curTicks = DateTime.UtcNow.Ticks;\n\n if (newSpeed != 1 && curTicks - lastSpeedChangeTicks < Config.Player.LatencySpeedChangeInterval)\n return;\n\n lastSpeedChangeTicks = curTicks;\n\n if (CanDebug)\n Log.Debug($\"[Latency {curLatency/10000}ms] Speed changed x{speed} -> x{newSpeed}\");\n\n if (aFrame != null)\n AudioDecoder.FixSample(aFrame, speed, newSpeed);\n\n Speed = newSpeed;\n requiresBuffering\n = false;\n startTicks = curTime;\n elapsedSec = 0;\n sw.Restart();\n }\n private long GetBufferedDuration()\n {\n var decoder = VideoDecoder.Frames.IsEmpty ? 0 : VideoDecoder.Frames.ToArray()[^1].timestamp - vFrame.timestamp;\n var demuxer = VideoDemuxer.VideoPackets.IsEmpty || VideoDemuxer.VideoPackets.LastTimestamp == NoTs\n ? 0 :\n (VideoDemuxer.VideoPackets.LastTimestamp - VideoDemuxer.StartTime) - vFrame.timestamp;\n\n return Math.Max(decoder, demuxer);\n }\n\n private void AudioBuffer()\n {\n if (CanTrace) Log.Trace(\"Buffering\");\n\n while ((isVideoSwitch || isAudioSwitch) && IsPlaying)\n Thread.Sleep(10);\n\n if (!IsPlaying)\n return;\n\n aFrame = null;\n Audio.ClearBuffer();\n decoder.AudioStream.Demuxer.Start();\n AudioDecoder.Start();\n\n while(AudioDecoder.Frames.IsEmpty && IsPlaying && AudioDecoder.IsRunning)\n Thread.Sleep(10);\n\n AudioDecoder.Frames.TryPeek(out aFrame);\n\n if (aFrame == null)\n return;\n\n lock (seeks)\n if (seeks.IsEmpty)\n {\n curTime = !MainDemuxer.IsHLSLive ? aFrame.timestamp : MainDemuxer.CurTime;\n UI(() =>\n {\n Set(ref _CurTime, curTime, true, nameof(CurTime));\n UpdateBufferedDuration();\n });\n }\n\n while(seeks.IsEmpty && decoder.AudioStream.Demuxer.BufferedDuration < Config.Player.MinBufferDuration && AudioDecoder.Frames.Count < Config.Decoder.MaxAudioFrames / 2 && IsPlaying && decoder.AudioStream.Demuxer.IsRunning && decoder.AudioStream.Demuxer.Status != MediaFramework.Status.QueueFull)\n Thread.Sleep(20);\n }\n private void ScreamerAudioOnly()\n {\n long bufferedDuration = 0;\n\n while (IsPlaying)\n {\n if (seeks.TryPop(out var seekData))\n {\n seeks.Clear();\n requiresBuffering = true;\n\n if (AudioDecoder.OnVideoDemuxer)\n {\n if (decoder.Seek(seekData.ms, seekData.forward) < 0)\n Log.Warn(\"Seek failed 1\");\n }\n else\n {\n if (decoder.SeekAudio(seekData.ms, seekData.forward) < 0)\n Log.Warn(\"Seek failed 2\");\n }\n }\n\n if (requiresBuffering)\n {\n OnBufferingStarted();\n AudioBuffer();\n requiresBuffering = false;\n\n if (!seeks.IsEmpty)\n continue;\n\n if (!IsPlaying || AudioDecoder.Frames.IsEmpty)\n break;\n\n OnBufferingCompleted();\n }\n\n if (AudioDecoder.Frames.IsEmpty)\n {\n if (bufferedDuration == 0)\n {\n if (!IsPlaying || AudioDecoder.Status == MediaFramework.Status.Ended)\n break;\n\n Log.Warn(\"No audio frames\");\n requiresBuffering = true;\n }\n else\n {\n Thread.Sleep(50); // waiting for audio buffer to be played before end\n bufferedDuration = Audio.GetBufferedDuration();\n }\n\n continue;\n }\n\n // Support only ASR subtitle for audio\n foreach (int i in SubtitlesASR.SubIndexSet)\n {\n SubtitlesManager[i].SetCurrentTime(new TimeSpan(curTime));\n\n var cur = SubtitlesManager[i].GetCurrent();\n if (cur != null && !string.IsNullOrEmpty(cur.DisplayText))\n {\n SubtitleDisplay(cur.DisplayText, i, cur.UseTranslated);\n }\n else\n {\n SubtitleClear(i);\n }\n }\n\n bufferedDuration = Audio.GetBufferedDuration();\n\n if (bufferedDuration < 300 * 10000)\n {\n do\n {\n AudioDecoder.Frames.TryDequeue(out aFrame);\n if (aFrame == null || !IsPlaying)\n break;\n\n Audio.AddSamples(aFrame);\n bufferedDuration += (long) ((aFrame.dataLen / 4) * Audio.Timebase);\n curTime = !MainDemuxer.IsHLSLive ? aFrame.timestamp : MainDemuxer.CurTime;\n } while (bufferedDuration < 100 * 10000);\n\n lock (seeks)\n if (seeks.IsEmpty)\n {\n if (!Engine.Config.UICurTimePerSecond || curTime / 10000000 != _CurTime / 10000000)\n {\n UI(() =>\n {\n Set(ref _CurTime, curTime, true, nameof(CurTime));\n UpdateBufferedDuration();\n });\n }\n }\n\n Thread.Sleep(20);\n }\n else\n Thread.Sleep(50);\n }\n }\n\n private void ScreamerReverse()\n {\n while (Status == Status.Playing)\n {\n if (seeks.TryPop(out var seekData))\n {\n seeks.Clear();\n if (decoder.Seek(seekData.ms, seekData.forward) < 0)\n Log.Warn(\"Seek failed\");\n }\n\n if (vFrame == null)\n {\n if (VideoDecoder.Status == MediaFramework.Status.Ended)\n break;\n\n OnBufferingStarted();\n if (reversePlaybackResync)\n {\n decoder.Flush();\n VideoDemuxer.EnableReversePlayback(CurTime);\n reversePlaybackResync = false;\n }\n VideoDemuxer.Start();\n VideoDecoder.Start();\n\n while (VideoDecoder.Frames.IsEmpty && Status == Status.Playing && VideoDecoder.IsRunning) Thread.Sleep(15);\n OnBufferingCompleted();\n VideoDecoder.Frames.TryDequeue(out vFrame);\n if (vFrame == null) { Log.Warn(\"No video frame\"); break; }\n vFrame.timestamp = (long) (vFrame.timestamp / Speed);\n\n startTicks = vFrame.timestamp;\n sw.Restart();\n elapsedSec = 0;\n\n if (!MainDemuxer.IsHLSLive && seeks.IsEmpty)\n curTime = (long) (vFrame.timestamp * Speed);\n UI(() => UpdateCurTime());\n }\n\n elapsedTicks = startTicks - (long) (sw.ElapsedTicks * SWFREQ_TO_TICKS);\n vDistanceMs = (int) ((elapsedTicks - vFrame.timestamp) / 10000);\n sleepMs = vDistanceMs - 1;\n\n if (sleepMs < 0) sleepMs = 0;\n\n if (Math.Abs(vDistanceMs - sleepMs) > 5)\n {\n //Log($\"vDistanceMs |-> {vDistanceMs}\");\n VideoDecoder.DisposeFrame(vFrame);\n vFrame = null;\n Thread.Sleep(5);\n continue; // rebuffer\n }\n\n if (sleepMs > 2)\n {\n if (sleepMs > 1000)\n {\n //Log($\"sleepMs -> {sleepMs} , vDistanceMs |-> {vDistanceMs}\");\n VideoDecoder.DisposeFrame(vFrame);\n vFrame = null;\n Thread.Sleep(5);\n continue; // rebuffer\n }\n\n // Every seconds informs the application with CurTime / Bitrates (invokes UI thread to ensure the updates will actually happen)\n if (Engine.Config.UICurTimePerSecond && (\n (!MainDemuxer.IsHLSLive && curTime / 10000000 != _CurTime / 10000000) ||\n (MainDemuxer.IsHLSLive && Math.Abs(elapsedTicks - elapsedSec) > 10000000)))\n {\n elapsedSec = elapsedTicks;\n UI(() => UpdateCurTime());\n }\n\n Thread.Sleep(sleepMs);\n }\n\n decoder.VideoDecoder.Renderer.Present(vFrame, false);\n if (!MainDemuxer.IsHLSLive && seeks.IsEmpty)\n {\n curTime = (long) (vFrame.timestamp * Speed);\n\n if (Config.Player.UICurTimePerFrame)\n UI(() => UpdateCurTime());\n }\n\n VideoDecoder.Frames.TryDequeue(out vFrame);\n if (vFrame != null)\n vFrame.timestamp = (long) (vFrame.timestamp / Speed);\n }\n }\n}\n\npublic class BufferingCompletedArgs : EventArgs\n{\n public string Error { get; }\n public bool Success { get; }\n\n public BufferingCompletedArgs(string error)\n {\n Error = error;\n Success = Error == null;\n }\n}\n"], ["/LLPlayer/FlyleafLib/MediaFramework/MediaPlaylist/PlaylistItem.cs", "using System.Collections.Generic;\nusing System.Collections.ObjectModel;\n\nusing FlyleafLib.MediaFramework.MediaDemuxer;\nusing FlyleafLib.MediaFramework.MediaStream;\n\nnamespace FlyleafLib.MediaFramework.MediaPlaylist;\n\npublic class PlaylistItem : DemuxerInput\n{\n public int Index { get; set; } = -1; // if we need it we need to ensure we fix it in case of removing an item\n\n /// \n /// While the Url can expire or be null DirectUrl can be used as a new input for re-opening\n /// \n public string DirectUrl { get; set; }\n\n /// \n /// Relative folder to playlist's folder base (can be empty, not null)\n /// Use Path.Combine(Playlist.FolderBase, Folder) to get absolute path for saving related files with the current selection item (such as subtitles)\n /// \n public string Folder { get; set; } = \"\";\n\n public long FileSize { get; set; }\n\n /// \n /// Usually just the filename part of the provided Url\n /// \n public string OriginalTitle { get => _OriginalTitle;set => SetUI(ref _OriginalTitle, value ?? \"\", false); }\n string _OriginalTitle = \"\";\n\n /// \n /// Movie/TVShow Title\n /// \n public string MediaTitle { get => _MediaTitle; set => SetUI(ref _MediaTitle, value ?? \"\", false); }\n string _MediaTitle = \"\";\n\n /// \n /// Movie/TVShow Title including Movie's Year or TVShow's Season/Episode\n /// \n public string Title { get => _Title; set { if (_Title == \"\") OriginalTitle = value; SetUI(ref _Title, value ?? \"\", false);} }\n string _Title = \"\";\n\n public List\n Chapters { get; set; } = new();\n\n public int Season { get; set; }\n public int Episode { get; set; }\n public int Year { get; set; }\n\n public Dictionary\n Tag { get; set; } = [];\n public void AddTag(object tag, string pluginName)\n {\n if (!Tag.TryAdd(pluginName, tag))\n Tag[pluginName] = tag;\n }\n\n public object GetTag(string pluginName)\n => Tag.TryGetValue(pluginName, out object value) ? value : null;\n\n public bool SearchedLocal { get; set; }\n public bool SearchedOnline { get; set; }\n\n /// \n /// Whether the item is currently enabled or not\n /// \n public bool Enabled { get => _Enabled; set { if (SetUI(ref _Enabled, value) && value == true) OpenedCounter++; } }\n bool _Enabled;\n public int OpenedCounter { get; set; }\n\n public ExternalVideoStream\n ExternalVideoStream { get; set; }\n public ExternalAudioStream\n ExternalAudioStream { get; set; }\n public ExternalSubtitlesStream[]\n ExternalSubtitlesStreams\n { get; set; } = new ExternalSubtitlesStream[2];\n\n public ObservableCollection\n ExternalVideoStreams { get; set; } = [];\n public ObservableCollection\n ExternalAudioStreams { get; set; } = [];\n public ObservableCollection\n ExternalSubtitlesStreamsAll\n { get; set; } = [];\n internal object lockExternalStreams = new();\n\n bool filled;\n public void FillMediaParts() // Called during OpenScrape (if file) & Open/Search Subtitles (to be able to search online and compare tvshow/movie properly)\n {\n if (filled)\n return;\n\n filled = true;\n var mp = Utils.GetMediaParts(OriginalTitle);\n Year = mp.Year;\n Season = mp.Season;\n Episode = mp.Episode;\n MediaTitle = mp.Title; // safe title to check with online subs\n\n if (mp.Season > 0 && mp.Episode > 0) // tvshow\n {\n var title = \"S\";\n title += Season > 9 ? Season : $\"0{Season}\";\n title += \"E\";\n title += Episode > 9 ? Episode : $\"0{Episode}\";\n\n Title = mp.Title == \"\" ? title : mp.Title + \" (\" + title + \")\";\n }\n else if (mp.Year > 0) // movie\n Title = mp.Title + \" (\" + mp.Year + \")\";\n }\n\n public static void AddExternalStream(ExternalStream extStream, PlaylistItem item, string pluginName, object tag = null)\n {\n lock (item.lockExternalStreams)\n {\n extStream.PlaylistItem = item;\n extStream.PluginName = pluginName;\n\n if (extStream is ExternalAudioStream astream)\n {\n item.ExternalAudioStreams.Add(astream);\n extStream.Index = item.ExternalAudioStreams.Count - 1;\n }\n else if (extStream is ExternalVideoStream vstream)\n {\n item.ExternalVideoStreams.Add(vstream);\n extStream.Index = item.ExternalVideoStreams.Count - 1;\n }\n else if (extStream is ExternalSubtitlesStream sstream)\n {\n item.ExternalSubtitlesStreamsAll.Add(sstream);\n extStream.Index = item.ExternalSubtitlesStreamsAll.Count - 1;\n }\n\n if (tag != null)\n extStream.AddTag(tag, pluginName);\n };\n }\n}\n"], ["/LLPlayer/FlyleafLib/MediaFramework/MediaDecoder/SubtitlesDecoder.cs", "using System.Collections.Concurrent;\nusing System.Diagnostics;\nusing System.Threading;\nusing FlyleafLib.MediaFramework.MediaDemuxer;\nusing FlyleafLib.MediaFramework.MediaStream;\nusing FlyleafLib.MediaFramework.MediaFrame;\nusing FlyleafLib.MediaFramework.MediaRenderer;\nusing static FlyleafLib.Logger;\n\nnamespace FlyleafLib.MediaFramework.MediaDecoder;\n\npublic unsafe class SubtitlesDecoder : DecoderBase\n{\n public SubtitlesStream SubtitlesStream => (SubtitlesStream) Stream;\n\n public ConcurrentQueue\n Frames { get; protected set; } = new ConcurrentQueue();\n\n public PacketQueue SubtitlesPackets;\n\n public SubtitlesDecoder(Config config, int uniqueId = -1, int subIndex = 0) : base(config, uniqueId)\n {\n this.subIndex = subIndex;\n }\n\n private readonly int subIndex;\n protected override int Setup(AVCodec* codec)\n {\n lock (lockCodecCtx)\n {\n if (demuxer.avioCtx != null)\n {\n // Disable check since already converted to UTF-8\n codecCtx->sub_charenc_mode = SubCharencModeFlags.Ignore;\n }\n }\n\n return 0;\n }\n\n protected override void DisposeInternal()\n => DisposeFrames();\n\n public void Flush()\n {\n lock (lockActions)\n lock (lockCodecCtx)\n {\n if (Disposed) return;\n\n if (Status == Status.Ended) Status = Status.Stopped;\n //else if (Status == Status.Draining) Status = Status.Stopping;\n\n DisposeFrames();\n avcodec_flush_buffers(codecCtx);\n }\n }\n\n protected override void RunInternal()\n {\n int ret = 0;\n int allowedErrors = Config.Decoder.MaxErrors;\n AVPacket *packet;\n\n SubtitlesPackets = demuxer.SubtitlesPackets[subIndex];\n\n do\n {\n // Wait until Queue not Full or Stopped\n if (Frames.Count >= Config.Decoder.MaxSubsFrames)\n {\n lock (lockStatus)\n if (Status == Status.Running) Status = Status.QueueFull;\n\n while (Frames.Count >= Config.Decoder.MaxSubsFrames && Status == Status.QueueFull) Thread.Sleep(20);\n\n lock (lockStatus)\n {\n if (Status != Status.QueueFull) break;\n Status = Status.Running;\n }\n }\n\n // While Packets Queue Empty (Ended | Quit if Demuxer stopped | Wait until we get packets)\n if (SubtitlesPackets.Count == 0)\n {\n CriticalArea = true;\n\n lock (lockStatus)\n if (Status == Status.Running) Status = Status.QueueEmpty;\n\n while (SubtitlesPackets.Count == 0 && Status == Status.QueueEmpty)\n {\n if (demuxer.Status == Status.Ended)\n {\n Status = Status.Ended;\n break;\n }\n else if (!demuxer.IsRunning)\n {\n if (CanDebug) Log.Debug($\"Demuxer is not running [Demuxer Status: {demuxer.Status}]\");\n\n int retries = 5;\n\n while (retries > 0)\n {\n retries--;\n Thread.Sleep(10);\n if (demuxer.IsRunning) break;\n }\n\n lock (demuxer.lockStatus)\n lock (lockStatus)\n {\n if (demuxer.Status == Status.Pausing || demuxer.Status == Status.Paused)\n Status = Status.Pausing;\n else if (demuxer.Status != Status.Ended)\n Status = Status.Stopping;\n else\n continue;\n }\n\n break;\n }\n\n Thread.Sleep(20);\n }\n\n lock (lockStatus)\n {\n CriticalArea = false;\n if (Status != Status.QueueEmpty) break;\n Status = Status.Running;\n }\n }\n\n lock (lockCodecCtx)\n {\n if (Status == Status.Stopped || SubtitlesPackets.Count == 0) continue;\n packet = SubtitlesPackets.Dequeue();\n\n int gotFrame = 0;\n SubtitlesFrame subFrame = new();\n\n fixed(AVSubtitle* subPtr = &subFrame.sub)\n ret = avcodec_decode_subtitle2(codecCtx, subPtr, &gotFrame, packet);\n\n if (ret < 0)\n {\n allowedErrors--;\n if (CanWarn) Log.Warn($\"{FFmpegEngine.ErrorCodeToMsg(ret)} ({ret})\");\n\n if (allowedErrors == 0) { Log.Error(\"Too many errors!\"); Status = Status.Stopping; break; }\n\n continue;\n }\n\n if (gotFrame == 0)\n {\n av_packet_free(&packet);\n continue;\n }\n\n long pts = subFrame.sub.pts != AV_NOPTS_VALUE ? subFrame.sub.pts /*mcs*/ * 10 : (packet->pts != AV_NOPTS_VALUE ? (long)(packet->pts * SubtitlesStream.Timebase) : AV_NOPTS_VALUE);\n av_packet_free(&packet);\n\n if (pts == AV_NOPTS_VALUE)\n continue;\n\n pts += subFrame.sub.start_display_time /*ms*/ * 10000L;\n\n if (!filledFromCodec) // TODO: CodecChanged? And when findstreaminfo is disabled as it is an external demuxer will not know the main demuxer's start time\n {\n filledFromCodec = true;\n avcodec_parameters_from_context(Stream.AVStream->codecpar, codecCtx);\n SubtitlesStream.Refresh();\n\n CodecChanged?.Invoke(this);\n }\n\n if (subFrame.sub.num_rects < 1)\n {\n if (SubtitlesStream.IsBitmap) // clear prev subs frame\n {\n subFrame.duration = uint.MaxValue;\n subFrame.timestamp = pts - demuxer.StartTime + Config.Subtitles[subIndex].Delay;\n subFrame.isBitmap = true;\n Frames.Enqueue(subFrame);\n }\n\n fixed(AVSubtitle* subPtr = &subFrame.sub)\n avsubtitle_free(subPtr);\n\n continue;\n }\n\n subFrame.duration = subFrame.sub.end_display_time;\n subFrame.timestamp = pts - demuxer.StartTime + Config.Subtitles[subIndex].Delay;\n\n if (subFrame.sub.rects[0]->type == AVSubtitleType.Ass)\n {\n subFrame.text = Utils.BytePtrToStringUTF8(subFrame.sub.rects[0]->ass).Trim();\n Config.Subtitles.Parser(subFrame);\n\n fixed(AVSubtitle* subPtr = &subFrame.sub)\n avsubtitle_free(subPtr);\n\n if (string.IsNullOrEmpty(subFrame.text))\n continue;\n }\n else if (subFrame.sub.rects[0]->type == AVSubtitleType.Text)\n {\n subFrame.text = Utils.BytePtrToStringUTF8(subFrame.sub.rects[0]->text).Trim();\n\n fixed(AVSubtitle* subPtr = &subFrame.sub)\n avsubtitle_free(subPtr);\n\n if (string.IsNullOrEmpty(subFrame.text))\n continue;\n }\n else if (subFrame.sub.rects[0]->type == AVSubtitleType.Bitmap)\n {\n var rect = subFrame.sub.rects[0];\n byte[] data = Renderer.ConvertBitmapSub(subFrame.sub, false);\n\n subFrame.isBitmap = true;\n subFrame.bitmap = new SubtitlesFrameBitmap()\n {\n data = data,\n width = rect->w,\n height = rect->h,\n x = rect->x,\n y = rect->y,\n };\n }\n\n if (CanTrace) Log.Trace($\"Processes {Utils.TicksToTime(subFrame.timestamp)}\");\n\n Frames.Enqueue(subFrame);\n }\n } while (Status == Status.Running);\n }\n\n public static void DisposeFrame(SubtitlesFrame frame)\n {\n Debug.Assert(frame != null, \"frame is already disposed (race condition)\");\n if (frame != null && frame.sub.num_rects > 0)\n fixed(AVSubtitle* ptr = &frame.sub)\n avsubtitle_free(ptr);\n }\n\n public void DisposeFrames()\n {\n if (!SubtitlesStream.IsBitmap)\n Frames = new ConcurrentQueue();\n else\n {\n while (!Frames.IsEmpty)\n {\n Frames.TryDequeue(out var frame);\n DisposeFrame(frame);\n }\n }\n }\n}\n"], ["/LLPlayer/FlyleafLib/MediaPlayer/Commands.cs", "using System.Threading.Tasks;\nusing System.Windows.Input;\n\nusing FlyleafLib.Controls.WPF;\nusing FlyleafLib.MediaFramework.MediaPlaylist;\nusing FlyleafLib.MediaFramework.MediaStream;\n\nnamespace FlyleafLib.MediaPlayer;\n\npublic class Commands\n{\n public ICommand AudioDelaySet { get; set; }\n public ICommand AudioDelaySet2 { get; set; }\n public ICommand AudioDelayAdd { get; set; }\n public ICommand AudioDelayAdd2 { get; set; }\n public ICommand AudioDelayRemove { get; set; }\n public ICommand AudioDelayRemove2 { get; set; }\n\n public ICommand SubtitlesDelaySetPrimary { get; set; }\n public ICommand SubtitlesDelaySet2Primary { get; set; }\n public ICommand SubtitlesDelayAddPrimary { get; set; }\n public ICommand SubtitlesDelayAdd2Primary { get; set; }\n public ICommand SubtitlesDelayRemovePrimary { get; set; }\n public ICommand SubtitlesDelayRemove2Primary { get; set; }\n\n public ICommand SubtitlesDelaySetSecondary { get; set; }\n public ICommand SubtitlesDelaySet2Secondary { get; set; }\n public ICommand SubtitlesDelayAddSecondary { get; set; }\n public ICommand SubtitlesDelayAdd2Secondary { get; set; }\n public ICommand SubtitlesDelayRemoveSecondary { get; set; }\n public ICommand SubtitlesDelayRemove2Secondary { get; set; }\n\n public ICommand OpenSubtitles { get; set; }\n public ICommand OpenSubtitlesASR { get; set; }\n public ICommand SubtitlesOff { get; set; }\n\n public ICommand Open { get; set; }\n public ICommand OpenFromClipboard { get; set; }\n public ICommand OpenFromFileDialog { get; set; }\n public ICommand Reopen { get; set; }\n public ICommand CopyToClipboard { get; set; }\n public ICommand CopyItemToClipboard { get; set; }\n\n public ICommand Play { get; set; }\n public ICommand Pause { get; set; }\n public ICommand Stop { get; set; }\n public ICommand TogglePlayPause { get; set; }\n\n public ICommand SeekBackward { get; set; }\n public ICommand SeekBackward2 { get; set; }\n public ICommand SeekBackward3 { get; set; }\n public ICommand SeekBackward4 { get; set; }\n public ICommand SeekForward { get; set; }\n public ICommand SeekForward2 { get; set; }\n public ICommand SeekForward3 { get; set; }\n public ICommand SeekForward4 { get; set; }\n public ICommand SeekToChapter { get; set; }\n\n public ICommand ShowFramePrev { get; set; }\n public ICommand ShowFrameNext { get; set; }\n\n public ICommand NormalScreen { get; set; }\n public ICommand FullScreen { get; set; }\n public ICommand ToggleFullScreen { get; set; }\n\n public ICommand ToggleReversePlayback { get; set; }\n public ICommand ToggleLoopPlayback { get; set; }\n public ICommand StartRecording { get; set; }\n public ICommand StopRecording { get; set; }\n public ICommand ToggleRecording { get; set; }\n\n public ICommand TakeSnapshot { get; set; }\n public ICommand ZoomIn { get; set; }\n public ICommand ZoomOut { get; set; }\n public ICommand RotationSet { get; set; }\n public ICommand RotateLeft { get; set; }\n public ICommand RotateRight { get; set; }\n public ICommand ResetAll { get; set; }\n public ICommand ResetSpeed { get; set; }\n public ICommand ResetRotation { get; set; }\n public ICommand ResetZoom { get; set; }\n\n public ICommand SpeedSet { get; set; }\n public ICommand SpeedUp { get; set; }\n public ICommand SpeedUp2 { get; set; }\n public ICommand SpeedDown { get; set; }\n public ICommand SpeedDown2 { get; set; }\n\n public ICommand VolumeUp { get; set; }\n public ICommand VolumeDown { get; set; }\n public ICommand ToggleMute { get; set; }\n\n public ICommand ForceIdle { get; set; }\n public ICommand ForceActive { get; set; }\n public ICommand ForceFullActive { get; set; }\n public ICommand RefreshActive { get; set; }\n public ICommand RefreshFullActive { get; set; }\n\n public ICommand ResetFilter { get; set; }\n\n Player player;\n\n public Commands(Player player)\n {\n this.player = player;\n\n Open = new RelayCommand(OpenAction);\n OpenFromClipboard = new RelayCommandSimple(player.OpenFromClipboard);\n OpenFromFileDialog = new RelayCommandSimple(player.OpenFromFileDialog);\n Reopen = new RelayCommand(ReopenAction);\n CopyToClipboard = new RelayCommandSimple(player.CopyToClipboard);\n CopyItemToClipboard = new RelayCommandSimple(player.CopyItemToClipboard);\n\n Play = new RelayCommandSimple(player.Play);\n Pause = new RelayCommandSimple(player.Pause);\n TogglePlayPause = new RelayCommandSimple(player.TogglePlayPause);\n Stop = new RelayCommandSimple(player.Stop);\n\n SeekBackward = new RelayCommandSimple(player.SeekBackward);\n SeekBackward2 = new RelayCommandSimple(player.SeekBackward2);\n SeekBackward3 = new RelayCommandSimple(player.SeekBackward3);\n SeekBackward4 = new RelayCommandSimple(player.SeekBackward4);\n SeekForward = new RelayCommandSimple(player.SeekForward);\n SeekForward2 = new RelayCommandSimple(player.SeekForward2);\n SeekForward3 = new RelayCommandSimple(player.SeekForward3);\n SeekForward4 = new RelayCommandSimple(player.SeekForward4);\n SeekToChapter = new RelayCommand(SeekToChapterAction);\n\n ShowFrameNext = new RelayCommandSimple(player.ShowFrameNext);\n ShowFramePrev = new RelayCommandSimple(player.ShowFramePrev);\n\n NormalScreen = new RelayCommandSimple(player.NormalScreen);\n FullScreen = new RelayCommandSimple(player.FullScreen);\n ToggleFullScreen = new RelayCommandSimple(player.ToggleFullScreen);\n\n ToggleReversePlayback = new RelayCommandSimple(player.ToggleReversePlayback);\n ToggleLoopPlayback = new RelayCommandSimple(player.ToggleLoopPlayback);\n StartRecording = new RelayCommandSimple(player.StartRecording);\n StopRecording = new RelayCommandSimple(player.StopRecording);\n ToggleRecording = new RelayCommandSimple(player.ToggleRecording);\n\n TakeSnapshot = new RelayCommandSimple(TakeSnapshotAction);\n ZoomIn = new RelayCommandSimple(player.ZoomIn);\n ZoomOut = new RelayCommandSimple(player.ZoomOut);\n RotationSet = new RelayCommand(RotationSetAction);\n RotateLeft = new RelayCommandSimple(player.RotateLeft);\n RotateRight = new RelayCommandSimple(player.RotateRight);\n ResetAll = new RelayCommandSimple(player.ResetAll);\n ResetSpeed = new RelayCommandSimple(player.ResetSpeed);\n ResetRotation = new RelayCommandSimple(player.ResetRotation);\n ResetZoom = new RelayCommandSimple(player.ResetZoom);\n\n SpeedSet = new RelayCommand(SpeedSetAction);\n SpeedUp = new RelayCommandSimple(player.SpeedUp);\n SpeedDown = new RelayCommandSimple(player.SpeedDown);\n SpeedUp2 = new RelayCommandSimple(player.SpeedUp2);\n SpeedDown2 = new RelayCommandSimple(player.SpeedDown2);\n\n VolumeUp = new RelayCommandSimple(player.Audio.VolumeUp);\n VolumeDown = new RelayCommandSimple(player.Audio.VolumeDown);\n ToggleMute = new RelayCommandSimple(player.Audio.ToggleMute);\n\n AudioDelaySet = new RelayCommand(AudioDelaySetAction);\n AudioDelaySet2 = new RelayCommand(AudioDelaySetAction2);\n AudioDelayAdd = new RelayCommandSimple(player.Audio.DelayAdd);\n AudioDelayAdd2 = new RelayCommandSimple(player.Audio.DelayAdd2);\n AudioDelayRemove = new RelayCommandSimple(player.Audio.DelayRemove);\n AudioDelayRemove2 = new RelayCommandSimple(player.Audio.DelayRemove2);\n\n SubtitlesDelaySetPrimary = new RelayCommand(SubtitlesDelaySetActionPrimary);\n SubtitlesDelaySet2Primary = new RelayCommand(SubtitlesDelaySetAction2Primary);\n SubtitlesDelayAddPrimary = new RelayCommandSimple(player.Subtitles.DelayAddPrimary);\n SubtitlesDelayAdd2Primary = new RelayCommandSimple(player.Subtitles.DelayAdd2Primary);\n SubtitlesDelayRemovePrimary = new RelayCommandSimple(player.Subtitles.DelayRemovePrimary);\n SubtitlesDelayRemove2Primary = new RelayCommandSimple(player.Subtitles.DelayRemove2Primary);\n\n SubtitlesDelaySetSecondary = new RelayCommand(SubtitlesDelaySetActionSecondary);\n SubtitlesDelaySet2Secondary = new RelayCommand(SubtitlesDelaySetAction2Secondary);\n SubtitlesDelayAddSecondary = new RelayCommandSimple(player.Subtitles.DelayAddSecondary);\n SubtitlesDelayAdd2Secondary = new RelayCommandSimple(player.Subtitles.DelayAdd2Secondary);\n SubtitlesDelayRemoveSecondary = new RelayCommandSimple(player.Subtitles.DelayRemoveSecondary);\n SubtitlesDelayRemove2Secondary = new RelayCommandSimple(player.Subtitles.DelayRemove2Secondary);\n\n OpenSubtitles = new RelayCommand(OpenSubtitlesAction);\n OpenSubtitlesASR = new RelayCommand(OpenSubtitlesASRAction);\n SubtitlesOff = new RelayCommand(SubtitlesOffAction);\n\n ForceIdle = new RelayCommandSimple(player.Activity.ForceIdle);\n ForceActive = new RelayCommandSimple(player.Activity.ForceActive);\n ForceFullActive = new RelayCommandSimple(player.Activity.ForceFullActive);\n RefreshActive = new RelayCommandSimple(player.Activity.RefreshActive);\n RefreshFullActive = new RelayCommandSimple(player.Activity.RefreshFullActive);\n\n ResetFilter = new RelayCommand(ResetFilterAction);\n }\n\n private void RotationSetAction(object obj)\n => player.Rotation = uint.Parse(obj.ToString());\n\n private void ResetFilterAction(object filter)\n => player.Config.Video.Filters[(VideoFilters)filter].Value = player.Config.Video.Filters[(VideoFilters)filter].DefaultValue;\n\n public void SpeedSetAction(object speed)\n {\n string speedstr = speed.ToString().Replace(',', '.');\n if (double.TryParse(speedstr, System.Globalization.NumberStyles.Any, System.Globalization.CultureInfo.InvariantCulture, out double value))\n player.Speed = value;\n }\n\n public void AudioDelaySetAction(object delay)\n => player.Config.Audio.Delay = int.Parse(delay.ToString()) * (long)10000;\n public void AudioDelaySetAction2(object delay)\n => player.Config.Audio.Delay += int.Parse(delay.ToString()) * (long)10000;\n\n public void SubtitlesDelaySetActionPrimary(object delay)\n => player.Config.Subtitles[0].Delay = int.Parse(delay.ToString()) * (long)10000;\n public void SubtitlesDelaySetAction2Primary(object delay)\n => player.Config.Subtitles[0].Delay += int.Parse(delay.ToString()) * (long)10000;\n\n // TODO: L: refactor\n public void SubtitlesDelaySetActionSecondary(object delay)\n => player.Config.Subtitles[1].Delay = int.Parse(delay.ToString()) * (long)10000;\n public void SubtitlesDelaySetAction2Secondary(object delay)\n => player.Config.Subtitles[1].Delay += int.Parse(delay.ToString()) * (long)10000;\n\n\n public void TakeSnapshotAction() => Task.Run(() => { try { player.TakeSnapshotToFile(); } catch { } });\n\n public void SeekToChapterAction(object chapter)\n {\n if (player.Chapters == null || player.Chapters.Count == 0)\n return;\n\n if (chapter is MediaFramework.MediaDemuxer.Demuxer.Chapter)\n player.SeekToChapter((MediaFramework.MediaDemuxer.Demuxer.Chapter)chapter);\n else if (int.TryParse(chapter.ToString(), out int chapterId) && chapterId < player.Chapters.Count)\n player.SeekToChapter(player.Chapters[chapterId]);\n }\n\n public void OpenSubtitlesAction(object input)\n {\n if (input is not ValueTuple tuple)\n {\n return;\n }\n\n if (tuple is { Item1: string, Item2: SubtitlesStream, Item3: SelectSubMethod })\n {\n var subIndex = int.Parse((string)tuple.Item1);\n var stream = (SubtitlesStream)tuple.Item2;\n var selectSubMethod = (SelectSubMethod)tuple.Item3;\n\n if (selectSubMethod == SelectSubMethod.OCR)\n {\n if (!TryInitializeOCR(subIndex, stream.Language))\n {\n return;\n }\n }\n\n SubtitlesSelectedHelper.Set(subIndex, (stream.StreamIndex, null));\n SubtitlesSelectedHelper.SetMethod(subIndex, selectSubMethod);\n SubtitlesSelectedHelper.CurIndex = subIndex;\n }\n else if (tuple is { Item1: string, Item2: ExternalSubtitlesStream, Item3: SelectSubMethod })\n {\n var subIndex = int.Parse((string)tuple.Item1);\n var stream = (ExternalSubtitlesStream)tuple.Item2;\n var selectSubMethod = (SelectSubMethod)tuple.Item3;\n\n if (selectSubMethod == SelectSubMethod.OCR)\n {\n if (!TryInitializeOCR(subIndex, stream.Language))\n {\n return;\n }\n }\n\n SubtitlesSelectedHelper.Set(subIndex, (null, stream));\n SubtitlesSelectedHelper.SetMethod(subIndex, selectSubMethod);\n SubtitlesSelectedHelper.CurIndex = subIndex;\n }\n\n OpenAction(tuple.Item2);\n return;\n\n bool TryInitializeOCR(int subIndex, Language lang)\n {\n if (!player.SubtitlesOCR.TryInitialize(subIndex, lang, out string err))\n {\n player.RaiseKnownErrorOccurred(err, KnownErrorType.Configuration);\n return false;\n }\n\n return true;\n }\n }\n\n public void OpenSubtitlesASRAction(object input)\n {\n if (!int.TryParse(input.ToString(), out var subIndex))\n {\n return;\n }\n\n if (!player.Audio.IsOpened)\n {\n // not opened\n return;\n }\n\n if (!player.SubtitlesASR.CanExecute(out string err))\n {\n player.RaiseKnownErrorOccurred(err, KnownErrorType.Configuration);\n return;\n }\n\n if (player.IsLive)\n {\n player.RaiseKnownErrorOccurred(\"Currently ASR is not available for live streams.\", KnownErrorType.ASR);\n return;\n }\n\n SubtitlesSelectedHelper.CurIndex = subIndex;\n\n // First, turn off existing subtitles (if not ASR)\n if (!player.Subtitles[subIndex].EnabledASR)\n {\n player.Subtitles[subIndex].Disable();\n }\n\n player.Subtitles[subIndex].EnableASR();\n }\n\n public void SubtitlesOffAction(object input)\n {\n if (int.TryParse(input.ToString(), out var subIndex))\n {\n SubtitlesSelectedHelper.CurIndex = subIndex;\n player.Subtitles[subIndex].Disable();\n }\n }\n\n public void OpenAction(object input)\n {\n if (input == null)\n return;\n\n if (input is StreamBase)\n player.OpenAsync((StreamBase)input);\n else if (input is PlaylistItem)\n player.OpenAsync((PlaylistItem)input);\n else if (input is ExternalStream)\n player.OpenAsync((ExternalStream)input);\n else if (input is System.IO.Stream)\n player.OpenAsync((System.IO.Stream)input);\n else\n player.OpenAsync(input.ToString());\n }\n\n public void ReopenAction(object playlistItem)\n {\n if (playlistItem == null)\n return;\n\n PlaylistItem item = (PlaylistItem)playlistItem;\n if (item.OpenedCounter > 0)\n {\n var session = player.GetSession(item);\n session.isReopen = true;\n session.CurTime = 0;\n\n // TBR: in case of disabled audio/video/subs it will save the session with them to be disabled\n\n // TBR: This can cause issues and it might not useful either\n //if (session.CurTime < 60 * (long)1000 * 10000)\n // session.CurTime = 0;\n\n player.OpenAsync(session);\n }\n else\n player.OpenAsync(item);\n }\n}\n"], ["/LLPlayer/FlyleafLib/MediaFramework/MediaProgram/Program.cs", "using System.Collections.Generic;\nusing System.Linq;\n\nusing FlyleafLib.MediaFramework.MediaDemuxer;\nusing FlyleafLib.MediaFramework.MediaStream;\n\nnamespace FlyleafLib.MediaFramework.MediaProgram;\n\npublic class Program\n{\n public int ProgramNumber { get; internal set; }\n\n public int ProgramId { get; internal set; }\n\n public IReadOnlyDictionary\n Metadata { get; internal set; }\n\n public IReadOnlyList\n Streams { get; internal set; }\n\n public string Name => Metadata.ContainsKey(\"name\") ? Metadata[\"name\"] : string.Empty;\n\n public unsafe Program(AVProgram* program, Demuxer demuxer)\n {\n ProgramNumber = program->program_num;\n ProgramId = program->id;\n\n // Load stream info\n List streams = new(3);\n for(int s = 0; snb_stream_indexes; s++)\n {\n uint streamIndex = program->stream_index[s];\n StreamBase stream = null;\n stream = demuxer.AudioStreams.FirstOrDefault(it=>it.StreamIndex == streamIndex);\n\n if (stream == null)\n {\n stream = demuxer.VideoStreams.FirstOrDefault(it => it.StreamIndex == streamIndex);\n stream ??= demuxer.SubtitlesStreamsAll.FirstOrDefault(it => it.StreamIndex == streamIndex);\n }\n if (stream!=null)\n {\n streams.Add(stream);\n }\n }\n Streams = streams;\n\n // Load metadata\n Dictionary metadata = new();\n AVDictionaryEntry* b = null;\n while (true)\n {\n b = av_dict_get(program->metadata, \"\", b, DictReadFlags.IgnoreSuffix);\n if (b == null) break;\n metadata.Add(Utils.BytePtrToStringUTF8(b->key), Utils.BytePtrToStringUTF8(b->value));\n }\n Metadata = metadata;\n }\n}\n"], ["/LLPlayer/FlyleafLib/MediaFramework/MediaRemuxer/Remuxer.cs", "using System.Collections.Generic;\nusing System.Diagnostics;\n\nnamespace FlyleafLib.MediaFramework.MediaRemuxer;\n\npublic unsafe class Remuxer\n{\n public int UniqueId { get; set; }\n public bool Disposed { get; private set; } = true;\n public string Filename { get; private set; }\n public bool HasStreams => mapInOutStreams2.Count > 0 || mapInOutStreams.Count > 0;\n public bool HeaderWritten { get; private set; }\n\n Dictionary mapInOutStreams = new();\n Dictionary mapInInStream = new();\n Dictionary mapInStreamToDts = new();\n Dictionary mapInOutStreams2 = new();\n Dictionary mapInInStream2 = new();\n Dictionary mapInStreamToDts2 = new();\n\n AVFormatContext* fmtCtx;\n AVOutputFormat* fmt;\n\n public Remuxer(int uniqueId = -1)\n => UniqueId = uniqueId == -1 ? Utils.GetUniqueId() : uniqueId;\n\n public int Open(string filename)\n {\n int ret;\n Filename = filename;\n\n fixed (AVFormatContext** ptr = &fmtCtx)\n ret = avformat_alloc_output_context2(ptr, null, null, Filename);\n\n if (ret < 0) return ret;\n\n fmt = fmtCtx->oformat;\n mapInStreamToDts = new Dictionary();\n Disposed = false;\n\n return 0;\n }\n\n public int AddStream(AVStream* in_stream, bool isAudioDemuxer = false)\n {\n int ret = -1;\n\n if (in_stream == null || (in_stream->codecpar->codec_type != AVMediaType.Video && in_stream->codecpar->codec_type != AVMediaType.Audio)) return ret;\n\n AVStream *out_stream;\n var in_codecpar = in_stream->codecpar;\n\n out_stream = avformat_new_stream(fmtCtx, null);\n if (out_stream == null) return -1;\n\n ret = avcodec_parameters_copy(out_stream->codecpar, in_codecpar);\n if (ret < 0) return ret;\n\n // Copy metadata (currently only language)\n AVDictionaryEntry* b = null;\n while (true)\n {\n b = av_dict_get(in_stream->metadata, \"\", b, DictReadFlags.IgnoreSuffix);\n if (b == null) break;\n\n if (Utils.BytePtrToStringUTF8(b->key).ToLower() == \"language\" || Utils.BytePtrToStringUTF8(b->key).ToLower() == \"lang\")\n av_dict_set(&out_stream->metadata, Utils.BytePtrToStringUTF8(b->key), Utils.BytePtrToStringUTF8(b->value), 0);\n }\n\n out_stream->codecpar->codec_tag = 0;\n\n // TODO:\n // validate that the output format container supports the codecs (if not change the container?)\n // check whether we remux from mp4 to mpegts (requires bitstream filter h264_mp4toannexb)\n\n //if (av_codec_get_tag(fmtCtx->oformat->codec_tag, in_stream->codecpar->codec_id) == 0)\n // Log(\"Not Found\");\n //else\n // Log(\"Found\");\n\n if (isAudioDemuxer)\n {\n mapInOutStreams2.Add((IntPtr)in_stream, (IntPtr)out_stream);\n mapInInStream2.Add(in_stream->index, (IntPtr)in_stream);\n }\n else\n {\n mapInOutStreams.Add((IntPtr)in_stream, (IntPtr)out_stream);\n mapInInStream.Add(in_stream->index, (IntPtr)in_stream);\n }\n\n return 0;\n }\n\n public int WriteHeader()\n {\n if (!HasStreams) throw new Exception(\"No streams have been configured for the remuxer\");\n\n int ret;\n\n ret = avio_open(&fmtCtx->pb, Filename, IOFlags.Write);\n if (ret < 0) { Dispose(); return ret; }\n\n ret = avformat_write_header(fmtCtx, null);\n\n if (ret < 0) { Dispose(); return ret; }\n\n HeaderWritten = true;\n\n return 0;\n }\n\n public int Write(AVPacket* packet, bool isAudioDemuxer = false)\n {\n lock (this)\n {\n var mapInInStream = !isAudioDemuxer? this.mapInInStream : mapInInStream2;\n var mapInOutStreams = !isAudioDemuxer? this.mapInOutStreams : mapInOutStreams2;\n var mapInStreamToDts = !isAudioDemuxer? this.mapInStreamToDts: mapInStreamToDts2;\n\n AVStream* in_stream = (AVStream*) mapInInStream[packet->stream_index];\n AVStream* out_stream = (AVStream*) mapInOutStreams[(IntPtr)in_stream];\n\n if (packet->dts != AV_NOPTS_VALUE)\n {\n\n if (!mapInStreamToDts.ContainsKey(in_stream->index))\n {\n // TODO: In case of AudioDemuxer calculate the diff with the VideoDemuxer and add it in one of them - all stream - (in a way to have positive)\n mapInStreamToDts.Add(in_stream->index, packet->dts);\n }\n\n packet->pts = packet->pts == AV_NOPTS_VALUE ? AV_NOPTS_VALUE : av_rescale_q_rnd(packet->pts - mapInStreamToDts[in_stream->index], in_stream->time_base, out_stream->time_base, AVRounding.NearInf | AVRounding.PassMinmax);\n packet->dts = av_rescale_q_rnd(packet->dts - mapInStreamToDts[in_stream->index], in_stream->time_base, out_stream->time_base, AVRounding.NearInf | AVRounding.PassMinmax);\n }\n else\n {\n packet->pts = packet->pts == AV_NOPTS_VALUE ? AV_NOPTS_VALUE : av_rescale_q_rnd(packet->pts, in_stream->time_base, out_stream->time_base, AVRounding.NearInf | AVRounding.PassMinmax);\n packet->dts = AV_NOPTS_VALUE;\n }\n\n packet->duration = av_rescale_q(packet->duration,in_stream->time_base, out_stream->time_base);\n packet->stream_index = out_stream->index;\n packet->pos = -1;\n\n int ret = av_interleaved_write_frame(fmtCtx, packet);\n av_packet_free(&packet);\n\n return ret;\n }\n }\n\n public int WriteTrailer() => Dispose();\n public int Dispose()\n {\n if (Disposed) return -1;\n\n int ret = 0;\n\n if (fmtCtx != null)\n {\n if (HeaderWritten)\n {\n ret = av_write_trailer(fmtCtx);\n avio_closep(&fmtCtx->pb);\n }\n\n avformat_free_context(fmtCtx);\n }\n\n fmtCtx = null;\n Filename = null;\n Disposed = true;\n HeaderWritten = false;\n mapInOutStreams.Clear();\n mapInInStream.Clear();\n mapInOutStreams2.Clear();\n mapInInStream2.Clear();\n\n return ret;\n }\n\n private void Log(string msg)\n => Debug.WriteLine($\"[{DateTime.Now:hh.mm.ss.fff}] [#{UniqueId}] [Remuxer] {msg}\");\n}\n"], ["/LLPlayer/FlyleafLib/MediaPlayer/Player.Playback.cs", "using System;\nusing System.Runtime.InteropServices;\nusing System.Threading;\nusing System.Threading.Tasks;\nusing System.Windows;\nusing System.Windows.Media;\nusing System.Windows.Media.Imaging;\nusing FlyleafLib.MediaFramework.MediaDecoder;\nusing FlyleafLib.MediaFramework.MediaFrame;\nusing static FlyleafLib.Utils;\nusing static FlyleafLib.Logger;\n\nnamespace FlyleafLib.MediaPlayer;\n\npartial class Player\n{\n string stoppedWithError = null;\n\n /// \n /// Fires on playback stopped by an error or completed / ended successfully \n /// Warning: Uses Invoke and it comes from playback thread so you can't pause/stop etc. You need to use another thread if you have to.\n /// \n public event EventHandler PlaybackStopped;\n protected virtual void OnPlaybackStopped(string error = null)\n {\n if (error != null && LastError == null)\n {\n lastError = error;\n UI(() => LastError = LastError);\n }\n\n PlaybackStopped?.Invoke(this, new PlaybackStoppedArgs(error));\n }\n\n /// \n /// Fires on seek completed for the specified ms (ms will be -1 on failure)\n /// \n public event EventHandler SeekCompleted;\n\n /// \n /// Plays AVS streams\n /// \n public void Play()\n {\n lock (lockActions)\n {\n if (!CanPlay || Status == Status.Playing || Status == Status.Ended)\n return;\n\n status = Status.Playing;\n UI(() => Status = Status);\n }\n\n while (taskPlayRuns || taskSeekRuns) Thread.Sleep(5);\n taskPlayRuns = true;\n\n Thread t = new(() =>\n {\n try\n {\n Engine.TimeBeginPeriod1();\n NativeMethods.SetThreadExecutionState(NativeMethods.EXECUTION_STATE.ES_CONTINUOUS | NativeMethods.EXECUTION_STATE.ES_SYSTEM_REQUIRED | NativeMethods.EXECUTION_STATE.ES_DISPLAY_REQUIRED);\n\n onBufferingStarted = 0;\n onBufferingCompleted = 0;\n requiresBuffering = true;\n\n if (LastError != null)\n {\n lastError = null;\n UI(() => LastError = LastError);\n }\n\n if (Config.Player.Usage == Usage.Audio || !Video.IsOpened)\n ScreamerAudioOnly();\n else\n {\n if (ReversePlayback)\n {\n shouldFlushNext = true;\n ScreamerReverse();\n }\n else\n {\n shouldFlushPrev = true;\n Screamer();\n }\n\n }\n\n }\n catch (Exception ex)\n {\n Log.Error($\"Playback failed ({ex.Message})\");\n RaiseUnknownErrorOccurred($\"Playback failed: {ex.Message}\", UnknownErrorType.Playback, ex);\n }\n finally\n {\n VideoDecoder.DisposeFrame(vFrame);\n vFrame = null;\n for (int i = 0; i < subNum; i++)\n {\n sFrames[i] = null;\n }\n\n if (Status == Status.Stopped)\n decoder?.Initialize();\n else if (decoder != null)\n {\n decoder.PauseOnQueueFull();\n decoder.PauseDecoders();\n }\n\n Audio.ClearBuffer();\n Engine.TimeEndPeriod1();\n NativeMethods.SetThreadExecutionState(NativeMethods.EXECUTION_STATE.ES_CONTINUOUS);\n stoppedWithError = null;\n\n if (IsPlaying)\n {\n if (decoderHasEnded)\n status = Status.Ended;\n else\n {\n if (Video.IsOpened && VideoDemuxer.Interrupter.Timedout)\n stoppedWithError = \"Timeout\";\n else if (onBufferingStarted - 1 == onBufferingCompleted)\n {\n stoppedWithError = \"Playback stopped unexpectedly\";\n OnBufferingCompleted(\"Buffering failed\");\n }\n else\n {\n if (!ReversePlayback)\n {\n if (isLive || Math.Abs(Duration - CurTime) > 3 * 1000 * 10000)\n stoppedWithError = \"Playback stopped unexpectedly\";\n }\n else if (CurTime > 3 * 1000 * 10000)\n stoppedWithError = \"Playback stopped unexpectedly\";\n }\n\n status = Status.Paused;\n }\n }\n\n OnPlaybackStopped(stoppedWithError);\n if (CanDebug) Log.Debug($\"[SCREAMER] Finished (Status: {Status}, Error: {stoppedWithError})\");\n\n UI(() =>\n {\n Status = Status;\n UpdateCurTime();\n });\n\n taskPlayRuns = false;\n }\n });\n t.Priority = Config.Player.ThreadPriority;\n t.Name = $\"[#{PlayerId}] Playback\";\n t.IsBackground = true;\n t.Start();\n }\n\n /// \n /// Pauses AVS streams\n /// \n public void Pause()\n {\n lock (lockActions)\n {\n if (!CanPlay || Status == Status.Ended)\n return;\n\n status = Status.Paused;\n UI(() => Status = Status);\n\n while (taskPlayRuns) Thread.Sleep(5);\n }\n }\n\n public void TogglePlayPause()\n {\n if (IsPlaying)\n Pause();\n else\n Play();\n }\n\n public void ToggleReversePlayback()\n => ReversePlayback = !ReversePlayback;\n\n public void ToggleLoopPlayback()\n => LoopPlayback = !LoopPlayback;\n\n /// \n /// Seeks backwards or forwards based on the specified ms to the nearest keyframe\n /// \n /// \n /// \n public void Seek(int ms, bool forward = false) => Seek(ms, forward, false);\n\n /// \n /// Seeks at the exact timestamp (with half frame distance accuracy)\n /// \n /// \n /// \n public void SeekAccurate(TimeSpan time, int subIndex = -1)\n {\n int ms = (int)time.TotalMilliseconds;\n if (subIndex != -1 && time.Microseconds > 0)\n {\n // When seeking subtitles, rounding down the milliseconds or less will cause the previous subtitle\n // ASR subtitles are in microseconds, so if you truncate, you'll end up one before the current subtitle.\n ms += 1;\n }\n\n SeekAccurate(ms, subIndex);\n }\n\n /// \n /// Seeks at the exact timestamp (with half frame distance accuracy)\n /// \n /// \n /// \n public void SeekAccurate(int ms, int subIndex = -1)\n {\n if (subIndex >= 0)\n {\n ms += (int)(Config.Subtitles[subIndex].Delay / 10000);\n }\n\n Seek(ms, false, !IsLive);\n }\n\n public void ToggleSeekAccurate()\n => Config.Player.SeekAccurate = !Config.Player.SeekAccurate;\n\n private void Seek(int ms, bool forward, bool accurate)\n {\n if (!CanPlay)\n return;\n\n lock (seeks)\n {\n _CurTime = curTime = ms * (long)10000;\n seeks.Push(new SeekData(ms, forward, accurate));\n }\n\n // Set timestamp to Manager immediately after seek to enable continuous seek\n // (Without this, seek is called with the same timestamp on successive calls, so it will seek to the same subtitle.)\n SubtitlesManager.SetCurrentTime(new TimeSpan(curTime));\n\n Raise(nameof(CurTime));\n Raise(nameof(RemainingDuration));\n\n if (Status == Status.Playing)\n return;\n\n lock (seeks)\n {\n if (taskSeekRuns)\n return;\n\n taskSeekRuns = true;\n }\n\n Task.Run(() =>\n {\n int ret;\n bool wasEnded = false;\n SeekData seekData = null;\n\n try\n {\n Engine.TimeBeginPeriod1();\n\n while (true)\n {\n lock (seeks)\n {\n if (!(seeks.TryPop(out seekData) && CanPlay && !IsPlaying))\n {\n taskSeekRuns = false;\n break;\n }\n\n seeks.Clear();\n }\n\n if (Status == Status.Ended)\n {\n wasEnded = true;\n status = Status.Paused;\n UI(() => Status = Status);\n }\n\n for (int i = 0; i < subNum; i++)\n {\n // Display subtitles from cache when seeking while paused\n bool display = false;\n var cur = SubtitlesManager[i].GetCurrent();\n if (cur != null)\n {\n if (!string.IsNullOrEmpty(cur.DisplayText))\n {\n SubtitleDisplay(cur.DisplayText, i, cur.UseTranslated);\n display = true;\n }\n else if (cur.IsBitmap && cur.Bitmap != null)\n {\n SubtitleDisplay(cur.Bitmap, i);\n display = true;\n }\n\n if (display)\n {\n sFramesPrev[i] = new SubtitlesFrame\n {\n timestamp = cur.StartTime.Ticks + Config.Subtitles[i].Delay,\n duration = (uint)cur.Duration.TotalMilliseconds,\n isTranslated = cur.UseTranslated\n };\n }\n }\n\n // clear subtitles\n // but do not clear when cache hit\n if (!display && sFramesPrev[i] != null)\n {\n sFramesPrev[i] = null;\n SubtitleClear(i);\n }\n }\n\n if (!Video.IsOpened)\n {\n if (AudioDecoder.OnVideoDemuxer)\n {\n ret = decoder.Seek(seekData.ms, seekData.forward);\n if (CanWarn && ret < 0)\n Log.Warn(\"Seek failed 2\");\n\n VideoDemuxer.Start();\n SeekCompleted?.Invoke(this, -1);\n }\n else\n {\n ret = decoder.SeekAudio(seekData.ms, seekData.forward);\n if (CanWarn && ret < 0)\n Log.Warn(\"Seek failed 3\");\n\n AudioDemuxer.Start();\n SeekCompleted?.Invoke(this, -1);\n }\n\n decoder.PauseOnQueueFull();\n SeekCompleted?.Invoke(this, seekData.ms);\n }\n else\n {\n decoder.PauseDecoders();\n ret = decoder.Seek(seekData.accurate ? Math.Max(0, seekData.ms - (int) new TimeSpan(Config.Player.SeekAccurateFixMargin).TotalMilliseconds) : seekData.ms, seekData.forward, !seekData.accurate); // 3sec ffmpeg bug for seek accurate when fails to seek backwards (see videodecoder getframe)\n if (ret < 0)\n {\n if (CanWarn) Log.Warn(\"Seek failed\");\n SeekCompleted?.Invoke(this, -1);\n }\n else if (!ReversePlayback && CanPlay)\n {\n decoder.GetVideoFrame(seekData.accurate ? seekData.ms * (long)10000 : -1);\n ShowOneFrame();\n VideoDemuxer.Start();\n AudioDemuxer.Start();\n //for (int i = 0; i < subNum; i++)\n //{\n // SubtitlesDemuxers[i].Start();\n //}\n DataDemuxer.Start();\n decoder.PauseOnQueueFull();\n SeekCompleted?.Invoke(this, seekData.ms);\n }\n }\n\n Thread.Sleep(20);\n }\n }\n catch (Exception e)\n {\n lock (seeks) taskSeekRuns = false;\n Log.Error($\"Seek failed ({e.Message})\");\n }\n finally\n {\n decoder.OpenedPlugin?.OnBufferingCompleted();\n Engine.TimeEndPeriod1();\n if ((wasEnded && Config.Player.AutoPlay) || stoppedWithError != null) // TBR: Possible race condition with if (Status == Status.Playing)\n Play();\n }\n });\n }\n\n /// \n /// Flushes the buffer (demuxers (packets) and decoders (frames))\n /// This is useful mainly for live streams to push the playback at very end (low latency)\n /// \n public void Flush()\n {\n decoder.Flush();\n OSDMessage = \"Buffer Flushed\";\n }\n\n /// \n /// Stops and Closes AVS streams\n /// \n public void Stop()\n {\n lock (lockActions)\n {\n Initialize();\n renderer?.Flush();\n }\n }\n public void SubtitleClear()\n {\n for (int i = 0; i < subNum; i++)\n {\n SubtitleClear(i);\n }\n }\n\n public void SubtitleClear(int subIndex)\n {\n Subtitles[subIndex].Data.Clear();\n //renderer.ClearOverlayTexture();\n }\n\n /// \n /// Updated text format subtitle display\n /// \n /// \n /// \n /// \n public void SubtitleDisplay(string text, int subIndex, bool isTranslated)\n {\n UI(() =>\n {\n Subtitles[subIndex].Data.IsTranslated = isTranslated;\n Subtitles[subIndex].Data.Language = isTranslated\n ? Config.Subtitles.TranslateLanguage\n : SubtitlesManager[subIndex].Language;\n\n Subtitles[subIndex].Data.Text = text;\n Subtitles[subIndex].Data.Bitmap = null;\n });\n }\n\n public void SubtitleDisplay(SubtitleBitmapData bitmapData, int subIndex)\n {\n if (bitmapData.Sub.num_rects == 0)\n {\n return;\n }\n\n (byte[] data, AVSubtitleRect rect) = bitmapData.SubToBitmap(false);\n\n SubtitlesFrameBitmap bitmap = new()\n {\n data = data,\n width = rect.w,\n height = rect.h,\n x = rect.x,\n y = rect.y,\n };\n\n SubtitleDisplay(bitmap, subIndex);\n }\n\n /// \n /// Update bitmap format subtitle display\n /// \n /// \n /// \n public void SubtitleDisplay(SubtitlesFrameBitmap bitmap, int subIndex)\n {\n // TODO: L: refactor\n\n // Each subtitle has a different size and needs to be generated each time.\n WriteableBitmap wb = new(\n bitmap.width, bitmap.height,\n NativeMethods.DpiXSource, NativeMethods.DpiYSource,\n PixelFormats.Bgra32, null\n );\n Int32Rect rect = new(0, 0, bitmap.width, bitmap.height);\n wb.Lock();\n\n Marshal.Copy(bitmap.data, 0, wb.BackBuffer, bitmap.data.Length);\n\n wb.AddDirtyRect(rect);\n wb.Unlock();\n // Note that you will get a UI thread error if you don't call\n wb.Freeze();\n\n int x = bitmap.x;\n int y = bitmap.y;\n int w = bitmap.width;\n int h = bitmap.height;\n\n SubsBitmap subsBitmap = new()\n {\n X = x,\n Y = y,\n Width = w,\n Height = h,\n Source = wb,\n };\n\n UI(() =>\n {\n Subtitles[subIndex].Data.Bitmap = subsBitmap;\n Subtitles[subIndex].Data.Text = \"\";\n });\n }\n}\n\npublic class PlaybackStoppedArgs : EventArgs\n{\n public string Error { get; }\n public bool Success { get; }\n\n public PlaybackStoppedArgs(string error)\n {\n Error = error;\n Success = Error == null;\n }\n}\n\nclass SeekData\n{\n public int ms;\n public bool forward;\n public bool accurate;\n public SeekData(int ms, bool forward, bool accurate)\n { this.ms = ms; this.forward = forward && !accurate; this.accurate = accurate; }\n}\n"], ["/LLPlayer/FlyleafLib/MediaPlayer/Player.cs", "using System;\nusing System.Collections.Concurrent;\nusing System.Collections.Generic;\nusing System.Collections.ObjectModel;\nusing System.Threading;\n\nusing FlyleafLib.Controls;\nusing FlyleafLib.MediaFramework.MediaContext;\nusing FlyleafLib.MediaFramework.MediaDecoder;\nusing FlyleafLib.MediaFramework.MediaFrame;\nusing FlyleafLib.MediaFramework.MediaRenderer;\nusing FlyleafLib.MediaFramework.MediaPlaylist;\nusing FlyleafLib.MediaFramework.MediaDemuxer;\n\nusing static FlyleafLib.Utils;\nusing static FlyleafLib.Logger;\n\nnamespace FlyleafLib.MediaPlayer;\n\npublic unsafe partial class Player : NotifyPropertyChanged, IDisposable\n{\n #region Properties\n public bool IsDisposed { get; private set; }\n\n /// \n /// FlyleafHost (WinForms, WPF or WinUI)\n /// \n public IHostPlayer Host { get => _Host; set => Set(ref _Host, value); }\n IHostPlayer _Host;\n\n /// \n /// Player's Activity (Idle/Active/FullActive)\n /// \n public Activity Activity { get; private set; }\n\n /// \n /// Helper ICommands for WPF MVVM\n /// \n public Commands Commands { get; private set; }\n\n public Playlist Playlist => decoder.Playlist;\n\n /// \n /// Player's Audio (In/Out)\n /// \n public Audio Audio { get; private set; }\n\n /// \n /// Player's Video\n /// \n public Video Video { get; private set; }\n\n /// \n /// Player's Subtitles\n /// \n public Subtitles Subtitles { get; private set; }\n\n /// \n /// Player's Data\n /// \n public Data Data { get; private set; }\n\n /// \n /// Player's Renderer\n /// (Normally you should not access this directly)\n /// \n public Renderer renderer => decoder.VideoDecoder.Renderer;\n\n /// \n /// Player's Decoder Context\n /// (Normally you should not access this directly)\n /// \n public DecoderContext decoder { get; private set; }\n\n /// \n /// Audio Decoder\n /// (Normally you should not access this directly)\n /// \n public AudioDecoder AudioDecoder => decoder.AudioDecoder;\n\n /// \n /// Video Decoder\n /// (Normally you should not access this directly)\n /// \n public VideoDecoder VideoDecoder => decoder.VideoDecoder;\n\n /// \n /// Subtitles Decoder\n /// (Normally you should not access this directly)\n /// \n public SubtitlesDecoder[] SubtitlesDecoders => decoder.SubtitlesDecoders;\n\n /// \n /// Data Decoder\n /// (Normally you should not access this directly)\n /// \n public DataDecoder DataDecoder => decoder.DataDecoder;\n\n /// \n /// Main Demuxer (if video disabled or audio only can be AudioDemuxer instead of VideoDemuxer)\n /// (Normally you should not access this directly)\n /// \n public Demuxer MainDemuxer => decoder.MainDemuxer;\n\n /// \n /// Audio Demuxer\n /// (Normally you should not access this directly)\n /// \n public Demuxer AudioDemuxer => decoder.AudioDemuxer;\n\n /// \n /// Video Demuxer\n /// (Normally you should not access this directly)\n /// \n public Demuxer VideoDemuxer => decoder.VideoDemuxer;\n\n /// \n /// Subtitles Demuxer\n /// (Normally you should not access this directly)\n /// \n public Demuxer[] SubtitlesDemuxers => decoder.SubtitlesDemuxers;\n\n /// \n /// Subtitles Manager\n /// \n public SubtitlesManager SubtitlesManager => decoder.SubtitlesManager;\n\n /// \n /// Subtitles OCR\n /// \n public SubtitlesOCR SubtitlesOCR => decoder.SubtitlesOCR;\n\n /// \n /// Subtitles ASR\n /// \n public SubtitlesASR SubtitlesASR => decoder.SubtitlesASR;\n\n /// \n /// Data Demuxer\n /// (Normally you should not access this directly)\n /// \n public Demuxer DataDemuxer => decoder.DataDemuxer;\n\n\n /// \n /// Player's incremental unique id\n /// \n public int PlayerId { get; private set; }\n\n /// \n /// Player's configuration (set once in the constructor)\n /// \n public Config Config { get; protected set; }\n\n /// \n /// Player's Status\n /// \n public Status Status\n {\n get => status;\n private set\n {\n var prev = _Status;\n\n if (Set(ref _Status, value))\n {\n // Loop Playback\n if (value == Status.Ended)\n {\n if (LoopPlayback && !ReversePlayback)\n {\n int seekMs = (int)(MainDemuxer.StartTime == 0 ? 0 : MainDemuxer.StartTime / 10000);\n Seek(seekMs);\n }\n }\n\n if (prev == Status.Opening || value == Status.Opening)\n {\n Raise(nameof(IsOpening));\n }\n }\n }\n }\n\n Status _Status = Status.Stopped, status = Status.Stopped;\n public bool IsPlaying => status == Status.Playing;\n public bool IsOpening => status == Status.Opening;\n\n /// \n /// Whether the player's status is capable of accepting playback commands\n /// \n public bool CanPlay { get => canPlay; internal set => Set(ref _CanPlay, value); }\n internal bool _CanPlay, canPlay;\n\n /// \n /// The list of chapters\n /// \n public ObservableCollection\n Chapters => VideoDemuxer?.Chapters;\n\n /// \n /// Player's current time or user's current seek time (uses backward direction or accurate seek based on Config.Player.SeekAccurate)\n /// \n public long CurTime { get => curTime; set { if (Config.Player.SeekAccurate) SeekAccurate((int) (value/10000)); else Seek((int) (value/10000), false); } } // Note: forward seeking casues issues to some formats and can have serious delays (eg. dash with h264, dash with vp9 works fine)\n long _CurTime, curTime;\n internal void UpdateCurTime()\n {\n lock (seeks)\n {\n if (MainDemuxer == null || !seeks.IsEmpty)\n return;\n\n if (MainDemuxer.IsHLSLive)\n {\n curTime = MainDemuxer.CurTime; // *speed ?\n duration = MainDemuxer.Duration;\n Duration = Duration;\n }\n }\n\n if (Set(ref _CurTime, curTime, true, nameof(CurTime)))\n {\n Raise(nameof(RemainingDuration));\n }\n\n UpdateBufferedDuration();\n }\n internal void UpdateBufferedDuration()\n {\n if (_BufferedDuration != MainDemuxer.BufferedDuration)\n {\n _BufferedDuration = MainDemuxer.BufferedDuration;\n Raise(nameof(BufferedDuration));\n }\n }\n\n public long RemainingDuration => Duration - CurTime;\n\n /// \n /// Input's duration\n /// \n public long Duration\n {\n get => duration;\n private set\n {\n if (Set(ref _Duration, value))\n {\n Raise(nameof(RemainingDuration));\n }\n }\n }\n long _Duration, duration;\n\n /// \n /// Forces Player's and Demuxer's Duration to allow Seek\n /// \n /// Duration (Ticks)\n /// Demuxer must be opened before forcing the duration\n public void ForceDuration(long duration)\n {\n if (MainDemuxer == null)\n throw new ArgumentNullException(nameof(MainDemuxer));\n\n this.duration = duration;\n MainDemuxer.ForceDuration(duration);\n isLive = MainDemuxer.IsLive;\n UI(() =>\n {\n Duration= Duration;\n IsLive = IsLive;\n });\n }\n\n /// \n /// The current buffered duration in the demuxer\n /// \n public long BufferedDuration { get => MainDemuxer == null ? 0 : MainDemuxer.BufferedDuration;\n internal set => Set(ref _BufferedDuration, value); }\n long _BufferedDuration;\n\n /// \n /// Whether the input is live (duration might not be 0 on live sessions to allow live seek, eg. hls)\n /// \n public bool IsLive { get => isLive; private set => Set(ref _IsLive, value); }\n bool _IsLive, isLive;\n\n ///// \n ///// Total bitrate (Kbps)\n ///// \n public double BitRate { get => bitRate; internal set => Set(ref _BitRate, value); }\n internal double _BitRate, bitRate;\n\n /// \n /// Whether the player is recording\n /// \n public bool IsRecording\n {\n get => decoder != null && decoder.IsRecording;\n private set { if (_IsRecording == value) return; _IsRecording = value; UI(() => Set(ref _IsRecording, value, false)); }\n }\n bool _IsRecording;\n\n /// \n /// Pan X Offset to change the X location\n /// \n public int PanXOffset { get => renderer.PanXOffset; set { renderer.PanXOffset = value; Raise(nameof(PanXOffset)); } }\n\n /// \n /// Pan Y Offset to change the Y location\n /// \n public int PanYOffset { get => renderer.PanYOffset; set { renderer.PanYOffset = value; Raise(nameof(PanYOffset)); } }\n\n /// \n /// Playback's speed (x1 - x4)\n /// \n public double Speed {\n get => speed;\n set\n {\n double newValue = Math.Round(value, 3);\n if (value < 0.125)\n newValue = 0.125;\n else if (value > 16)\n newValue = 16;\n\n if (newValue == speed)\n return;\n\n AudioDecoder.Speed = newValue;\n VideoDecoder.Speed = newValue;\n speed = newValue;\n decoder.RequiresResync = true;\n requiresBuffering = true;\n for (int i = 0; i < subNum; i++)\n {\n sFramesPrev[i] = null;\n }\n SubtitleClear();\n UI(() =>\n {\n Raise(nameof(Speed));\n });\n }\n }\n double speed = 1;\n\n /// \n /// Pan zoom percentage (100 for 100%)\n /// \n public int Zoom\n {\n get => (int)(renderer.Zoom * 100);\n set { renderer.SetZoom(renderer.Zoom = value / 100.0); RaiseUI(nameof(Zoom)); }\n //set { renderer.SetZoomAndCenter(renderer.Zoom = value / 100.0, Renderer.ZoomCenterPoint); RaiseUI(nameof(Zoom)); } // should reset the zoom center point?\n }\n\n /// \n /// Pan rotation angle (for D3D11 VP allowed values are 0, 90, 180, 270 only)\n /// \n public uint Rotation { get => renderer.Rotation;\n set\n {\n renderer.Rotation = value;\n RaiseUI(nameof(Rotation));\n }\n }\n\n /// \n /// Pan Horizontal Flip (FlyleafVP only)\n /// \n public bool HFlip { get => renderer.HFlip; set => renderer.HFlip = value; }\n\n /// \n /// Pan Vertical Flip (FlyleafVP only)\n /// \n public bool VFlip { get => renderer.VFlip; set => renderer.VFlip = value; }\n\n /// \n /// Whether to use reverse playback mode\n /// \n public bool ReversePlayback\n {\n get => _ReversePlayback;\n\n set\n {\n if (_ReversePlayback == value)\n return;\n\n _ReversePlayback = value;\n UI(() => Set(ref _ReversePlayback, value, false));\n\n if (!Video.IsOpened || !CanPlay | IsLive)\n return;\n\n lock (lockActions)\n {\n bool shouldPlay = IsPlaying || (Status == Status.Ended && Config.Player.AutoPlay);\n Pause();\n dFrame = null;\n\n for (int i = 0; i < subNum; i++)\n {\n sFrames[i] = null;\n SubtitleClear(i);\n }\n\n decoder.StopThreads();\n decoder.Flush();\n\n if (Status == Status.Ended)\n {\n status = Status.Paused;\n UI(() => Status = Status);\n }\n\n if (value)\n {\n Speed = 1;\n VideoDemuxer.EnableReversePlayback(CurTime);\n }\n else\n {\n VideoDemuxer.DisableReversePlayback();\n\n var vFrame = VideoDecoder.GetFrame(VideoDecoder.GetFrameNumber(CurTime));\n VideoDecoder.DisposeFrame(vFrame);\n vFrame = null;\n decoder.RequiresResync = true;\n }\n\n reversePlaybackResync = false;\n if (shouldPlay) Play();\n }\n }\n }\n bool _ReversePlayback;\n\n public bool LoopPlayback { get; set => Set(ref field, value); }\n\n public object Tag { get => tag; set => Set(ref tag, value); }\n object tag;\n\n public string LastError { get => lastError; set => Set(ref _LastError, value); }\n string _LastError, lastError;\n\n public string OSDMessage { get; set => Set(ref field, value, false); }\n\n public event EventHandler KnownErrorOccurred;\n public event EventHandler UnknownErrorOccurred;\n\n bool decoderHasEnded => decoder != null && (VideoDecoder.Status == MediaFramework.Status.Ended || (VideoDecoder.Disposed && AudioDecoder.Status == MediaFramework.Status.Ended));\n #endregion\n\n #region Properties Internal\n readonly object lockActions = new();\n readonly object lockSubtitles= new();\n\n bool taskSeekRuns;\n bool taskPlayRuns;\n bool taskOpenAsyncRuns;\n\n readonly ConcurrentStack seeks = new();\n readonly ConcurrentQueue UIActions = new();\n\n internal AudioFrame aFrame;\n internal VideoFrame vFrame;\n internal SubtitlesFrame[] sFrames, sFramesPrev;\n internal DataFrame dFrame;\n internal PlayerStats stats = new();\n internal LogHandler Log;\n\n internal bool requiresBuffering;\n bool reversePlaybackResync;\n\n bool isVideoSwitch;\n bool isAudioSwitch;\n bool[] isSubsSwitches;\n bool isDataSwitch;\n #endregion\n\n public Player(Config config = null)\n {\n if (config != null)\n {\n if (config.Player.player != null)\n throw new Exception(\"Player's configuration is already assigned to another player\");\n\n Config = config;\n }\n else\n Config = new Config();\n\n PlayerId = GetUniqueId();\n Log = new LogHandler((\"[#\" + PlayerId + \"]\").PadRight(8, ' ') + \" [Player ] \");\n Log.Debug($\"Creating Player (Usage = {Config.Player.Usage})\");\n\n Activity = new Activity(this);\n Audio = new Audio(this);\n Video = new Video(this);\n Subtitles = new Subtitles(this);\n Data = new Data(this);\n Commands = new Commands(this);\n\n Config.SetPlayer(this);\n\n if (Config.Player.Usage == Usage.Audio)\n {\n Config.Video.Enabled = false;\n Config.Subtitles.Enabled = false;\n }\n\n decoder = new DecoderContext(Config, PlayerId) { Tag = this };\n Engine.AddPlayer(this);\n\n if (decoder.VideoDecoder.Renderer != null)\n decoder.VideoDecoder.Renderer.forceNotExtractor = true;\n\n //decoder.OpenPlaylistItemCompleted += Decoder_OnOpenExternalSubtitlesStreamCompleted;\n\n decoder.OpenAudioStreamCompleted += Decoder_OpenAudioStreamCompleted;\n decoder.OpenVideoStreamCompleted += Decoder_OpenVideoStreamCompleted;\n decoder.OpenSubtitlesStreamCompleted += Decoder_OpenSubtitlesStreamCompleted;\n decoder.OpenDataStreamCompleted += Decoder_OpenDataStreamCompleted;\n\n decoder.OpenExternalAudioStreamCompleted += Decoder_OpenExternalAudioStreamCompleted;\n decoder.OpenExternalVideoStreamCompleted += Decoder_OpenExternalVideoStreamCompleted;\n decoder.OpenExternalSubtitlesStreamCompleted += Decoder_OpenExternalSubtitlesStreamCompleted;\n\n AudioDecoder.CBufAlloc = () => { if (aFrame != null) aFrame.dataPtr = IntPtr.Zero; aFrame = null; Audio.ClearBuffer(); aFrame = null; };\n AudioDecoder.CodecChanged = Decoder_AudioCodecChanged;\n VideoDecoder.CodecChanged = Decoder_VideoCodecChanged;\n decoder.RecordingCompleted += (o, e) => { IsRecording = false; };\n Chapters.CollectionChanged += (o, e) => { RaiseUI(nameof(Chapters)); };\n\n // second subtitles\n sFrames = new SubtitlesFrame[subNum];\n sFramesPrev = new SubtitlesFrame[subNum];\n sDistanceMss = new int[subNum];\n isSubsSwitches = new bool[subNum];\n\n status = Status.Stopped;\n Reset();\n Log.Debug(\"Created\");\n }\n\n /// \n /// Disposes the Player and de-assigns it from FlyleafHost\n /// \n public void Dispose() => Engine.DisposePlayer(this);\n internal void DisposeInternal()\n {\n lock (lockActions)\n {\n if (IsDisposed)\n return;\n\n try\n {\n Initialize();\n Audio.Dispose();\n decoder.Dispose();\n Host?.Player_Disposed();\n Log.Info(\"Disposed\");\n } catch (Exception e) { Log.Warn($\"Disposed ({e.Message})\"); }\n\n IsDisposed = true;\n }\n }\n internal void RefreshMaxVideoFrames()\n {\n lock (lockActions)\n {\n if (!Video.isOpened)\n return;\n\n bool wasPlaying = IsPlaying;\n Pause();\n VideoDecoder.RefreshMaxVideoFrames();\n ReSync(decoder.VideoStream, (int) (CurTime / 10000), true);\n\n if (wasPlaying)\n Play();\n }\n }\n\n private void ResetMe()\n {\n canPlay = false;\n bitRate = 0;\n curTime = 0;\n duration = 0;\n isLive = false;\n lastError = null;\n\n UIAdd(() =>\n {\n BitRate = BitRate;\n Duration = Duration;\n IsLive = IsLive;\n Status = Status;\n CanPlay = CanPlay;\n LastError = LastError;\n BufferedDuration = 0;\n Set(ref _CurTime, curTime, true, nameof(CurTime));\n });\n }\n private void Reset()\n {\n ResetMe();\n Video.Reset();\n Audio.Reset();\n Subtitles.Reset();\n UIAll();\n }\n private void Initialize(Status status = Status.Stopped, bool andDecoder = true, bool isSwitch = false)\n {\n if (CanDebug) Log.Debug($\"Initializing\");\n\n lock (lockActions) // Required in case of OpenAsync and Stop requests\n {\n try\n {\n Engine.TimeBeginPeriod1();\n\n this.status = status;\n canPlay = false;\n isVideoSwitch = false;\n seeks.Clear();\n\n while (taskPlayRuns || taskSeekRuns) Thread.Sleep(5);\n\n if (andDecoder)\n {\n if (isSwitch)\n decoder.InitializeSwitch();\n else\n decoder.Initialize();\n }\n\n Reset();\n VideoDemuxer.DisableReversePlayback();\n ReversePlayback = false;\n\n if (CanDebug) Log.Debug($\"Initialized\");\n\n } catch (Exception e)\n {\n Log.Error($\"Initialize() Error: {e.Message}\");\n\n } finally\n {\n Engine.TimeEndPeriod1();\n }\n }\n }\n\n internal void UIAdd(Action action) => UIActions.Enqueue(action);\n internal void UIAll()\n {\n while (!UIActions.IsEmpty)\n if (UIActions.TryDequeue(out var action))\n UI(action);\n }\n\n public override bool Equals(object obj)\n => obj == null || !(obj is Player) ? false : ((Player)obj).PlayerId == PlayerId;\n public override int GetHashCode() => PlayerId.GetHashCode();\n\n // Avoid having this code in OnPaintBackground as it can cause designer issues (renderer will try to load FFmpeg.Autogen assembly because of HDR Data)\n internal bool WFPresent() { if (renderer == null || renderer.SCDisposed) return false; renderer?.Present(); return true; }\n\n internal void RaiseKnownErrorOccurred(string message, KnownErrorType errorType)\n {\n KnownErrorOccurred?.Invoke(this, new KnownErrorOccurredEventArgs\n {\n Message = message,\n ErrorType = errorType\n });\n }\n\n internal void RaiseUnknownErrorOccurred(string message, UnknownErrorType errorType, Exception exception = null)\n {\n UnknownErrorOccurred?.Invoke(this, new UnknownErrorOccurredEventArgs\n {\n Message = message,\n ErrorType = errorType,\n Exception = exception\n });\n }\n}\n\npublic enum KnownErrorType\n{\n Configuration,\n ASR\n}\n\npublic class KnownErrorOccurredEventArgs : EventArgs\n{\n public required string Message { get; init; }\n public required KnownErrorType ErrorType { get; init; }\n}\n\npublic enum UnknownErrorType\n{\n Translation,\n Subtitles,\n ASR,\n Playback,\n Network\n}\n\npublic class UnknownErrorOccurredEventArgs : EventArgs\n{\n public required string Message { get; init; }\n public required UnknownErrorType ErrorType { get; init; }\n public Exception Exception { get; init; }\n}\n\npublic enum Status\n{\n Opening,\n Failed,\n Stopped,\n Paused,\n Playing,\n Ended\n}\npublic enum Usage\n{\n AVS,\n Audio\n}\n"], ["/LLPlayer/FlyleafLib/MediaFramework/MediaDevice/VideoDeviceStream.cs", "using System.Collections.Generic;\nusing System.Linq;\nusing System.Reflection;\n\nusing Vortice.MediaFoundation;\n\nnamespace FlyleafLib.MediaFramework.MediaDevice;\n\npublic class VideoDeviceStream : DeviceStreamBase\n{\n public string MajorType { get; }\n public string SubType { get; }\n public int FrameSizeWidth { get; }\n public int FrameSizeHeight { get; }\n public int FrameRate { get; }\n private string FFmpegFormat { get; }\n\n public VideoDeviceStream(string deviceName, Guid majorType, Guid subType, int frameSizeWidth, int frameSizeHeight, int frameRate, int frameRateDenominator) : base(deviceName)\n {\n MajorType = MediaTypeGuids.Video == majorType ? \"Video\" : \"Unknown\";\n SubType = GetPropertyName(subType);\n FrameSizeWidth = frameSizeWidth;\n FrameSizeHeight = frameSizeHeight;\n FrameRate = frameRate / frameRateDenominator;\n FFmpegFormat = GetFFmpegFormat(SubType);\n Url = $\"fmt://dshow?video={DeviceFriendlyName}&video_size={FrameSizeWidth}x{FrameSizeHeight}&framerate={FrameRate}&{FFmpegFormat}\";\n }\n\n private static string GetPropertyName(Guid guid)\n {\n var type = typeof(VideoFormatGuids);\n foreach (var property in type.GetFields(BindingFlags.Public | BindingFlags.Static))\n if (property.FieldType == typeof(Guid))\n {\n object temp = property.GetValue(null);\n if (temp is Guid value)\n if (value == guid)\n return property.Name.ToUpper();\n }\n\n return null;\n }\n private static unsafe string GetFFmpegFormat(string subType)\n {\n switch (subType)\n {\n case \"MJPG\":\n var descriptorPtr = avcodec_descriptor_get(AVCodecID.Mjpeg);\n return $\"vcodec={Utils.BytePtrToStringUTF8(descriptorPtr->name)}\";\n case \"YUY2\":\n return $\"pixel_format={av_get_pix_fmt_name(AVPixelFormat.Yuyv422)}\";\n case \"NV12\":\n return $\"pixel_format={av_get_pix_fmt_name(AVPixelFormat.Nv12)}\";\n default:\n return \"\";\n }\n }\n public override string ToString() => $\"{SubType}, {FrameSizeWidth}x{FrameSizeHeight}, {FrameRate}FPS\";\n\n #region VideoFormatsViaMediaSource\n public static IList GetVideoFormatsForVideoDevice(string friendlyName, string symbolicLink)\n {\n List formatList = new();\n\n using (var mediaSource = GetMediaSourceFromVideoDevice(symbolicLink))\n {\n if (mediaSource == null)\n return null;\n\n using var sourcePresentationDescriptor = mediaSource.CreatePresentationDescriptor();\n int sourceStreamCount = sourcePresentationDescriptor.StreamDescriptorCount;\n\n for (int i = 0; i < sourceStreamCount; i++)\n {\n var guidMajorType = GetMajorMediaTypeFromPresentationDescriptor(sourcePresentationDescriptor, i);\n if (guidMajorType != MediaTypeGuids.Video)\n continue;\n\n sourcePresentationDescriptor.GetStreamDescriptorByIndex(i, out var streamIsSelected, out var videoStreamDescriptor);\n\n using (videoStreamDescriptor)\n {\n if (streamIsSelected == false)\n continue;\n\n using var typeHandler = videoStreamDescriptor.MediaTypeHandler;\n int mediaTypeCount = typeHandler.MediaTypeCount;\n\n for (int mediaTypeId = 0; mediaTypeId < mediaTypeCount; mediaTypeId++)\n using (var workingMediaType = typeHandler.GetMediaTypeByIndex(mediaTypeId))\n {\n var videoFormat = GetVideoFormatFromMediaType(friendlyName, workingMediaType);\n\n if (videoFormat.SubType != \"NV12\") // NV12 is not playable TODO check support for video formats\n formatList.Add(videoFormat);\n }\n }\n }\n }\n\n return formatList.OrderBy(format => format.SubType).ThenBy(format => format.FrameSizeHeight).ThenBy(format => format.FrameRate).ToList();\n }\n\n private static IMFMediaSource GetMediaSourceFromVideoDevice(string symbolicLink)\n {\n using var attributeContainer = MediaFactory.MFCreateAttributes(2);\n attributeContainer.Set(CaptureDeviceAttributeKeys.SourceType, CaptureDeviceAttributeKeys.SourceTypeVidcap);\n attributeContainer.Set(CaptureDeviceAttributeKeys.SourceTypeVidcapSymbolicLink, symbolicLink);\n\n IMFMediaSource ret = null;\n try\n { ret = MediaFactory.MFCreateDeviceSource(attributeContainer); }\n catch (Exception) { }\n\n return ret;\n }\n\n private static Guid GetMajorMediaTypeFromPresentationDescriptor(IMFPresentationDescriptor presentationDescriptor, int streamIndex)\n {\n presentationDescriptor.GetStreamDescriptorByIndex(streamIndex, out _, out var streamDescriptor);\n\n using (streamDescriptor)\n return GetMajorMediaTypeFromStreamDescriptor(streamDescriptor);\n }\n\n private static Guid GetMajorMediaTypeFromStreamDescriptor(IMFStreamDescriptor streamDescriptor)\n {\n using var pHandler = streamDescriptor.MediaTypeHandler;\n var guidMajorType = pHandler.MajorType;\n\n return guidMajorType;\n }\n\n private static VideoDeviceStream GetVideoFormatFromMediaType(string videoDeviceName, IMFMediaType mediaType)\n {\n // MF_MT_MAJOR_TYPE\n // Major type GUID, we return this as human readable text\n var majorType = mediaType.MajorType;\n\n // MF_MT_SUBTYPE\n // Subtype GUID which describes the basic media type, we return this as human readable text\n var subType = mediaType.GetGUID(MediaTypeAttributeKeys.Subtype);\n\n // MF_MT_FRAME_SIZE\n // the Width and height of a video frame, in pixels\n MediaFactory.MFGetAttributeSize(mediaType, MediaTypeAttributeKeys.FrameSize, out uint frameSizeWidth, out uint frameSizeHeight);\n\n // MF_MT_FRAME_RATE\n // The frame rate is expressed as a ratio.The upper 32 bits of the attribute value contain the numerator and the lower 32 bits contain the denominator.\n // For example, if the frame rate is 30 frames per second(fps), the ratio is 30 / 1.If the frame rate is 29.97 fps, the ratio is 30,000 / 1001.\n // we report this back to the user as a decimal\n MediaFactory.MFGetAttributeRatio(mediaType, MediaTypeAttributeKeys.FrameRate, out uint frameRate, out uint frameRateDenominator);\n\n VideoDeviceStream videoFormat = new(videoDeviceName, majorType, subType, (int)frameSizeWidth,\n (int)frameSizeHeight,\n (int)frameRate,\n (int)frameRateDenominator);\n\n return videoFormat;\n }\n #endregion\n}\n"], ["/LLPlayer/FlyleafLib/MediaPlayer/SubtitlesOCR.cs", "using System.Collections.Generic;\nusing System.Drawing;\nusing System.Drawing.Drawing2D;\nusing System.Drawing.Imaging;\nusing System.IO;\nusing System.Linq;\nusing System.Runtime.InteropServices;\nusing System.Threading;\nusing System.Threading.Tasks;\nusing Windows.Graphics.Imaging;\nusing Windows.Media.Ocr;\nusing Windows.Storage.Streams;\nusing Color = System.Drawing.Color;\nusing ImageFormat = System.Drawing.Imaging.ImageFormat;\nusing PixelFormat = System.Drawing.Imaging.PixelFormat;\n\nnamespace FlyleafLib.MediaPlayer;\n\n#nullable enable\n\npublic unsafe class SubtitlesOCR\n{\n private readonly Config.SubtitlesConfig _config;\n private int _subNum;\n\n private readonly CancellationTokenSource?[] _ctss;\n private readonly object[] _lockers;\n private IOCRService? _ocrService;\n\n public SubtitlesOCR(Config.SubtitlesConfig config, int subNum)\n {\n _config = config;\n _subNum = subNum;\n\n _lockers = new object[subNum];\n _ctss = new CancellationTokenSource[subNum];\n for (int i = 0; i < subNum; i++)\n {\n _lockers[i] = new object();\n _ctss[i] = new CancellationTokenSource();\n }\n }\n\n /// \n /// Try to initialize OCR Engine\n /// \n /// OCR Language\n /// expected initialize error\n /// whether to success to initialize\n public bool TryInitialize(int subIndex, Language lang, out string err)\n {\n lang = GetLanguageWithFallback(subIndex, lang);\n\n // Retaining engines will increase memory usage, so they are created and discarded on the fly.\n IOCRService ocrService = _config[subIndex].OCREngine switch\n {\n SubOCREngineType.Tesseract => new TesseractOCRService(_config),\n SubOCREngineType.MicrosoftOCR => new MicrosoftOCRService(_config),\n _ => throw new InvalidOperationException(),\n };\n\n if (!ocrService.TryInitialize(lang, out err))\n {\n return false;\n }\n\n _ocrService = ocrService;\n\n err = \"\";\n return true;\n }\n\n /// \n /// Do OCR\n /// \n /// 0: Primary, 1: Secondary\n /// List of subtitle data for OCR\n /// Timestamp to start OCR\n public void Do(int subIndex, List subs, TimeSpan? startTime = null)\n {\n if (_ocrService == null)\n throw new InvalidOperationException(\"ocrService is not initialized. you must call TryInitialize() first\");\n\n if (subs.Count == 0 || !subs[0].IsBitmap)\n return;\n\n // Cancel preceding OCR\n TryCancelWait(subIndex);\n\n lock (_lockers[subIndex])\n {\n // NOTE: important to dispose inside lock\n using IOCRService ocrService = _ocrService;\n\n _ctss[subIndex] = new CancellationTokenSource();\n\n int startIndex = 0;\n // Start OCR from the current playback point\n if (startTime.HasValue)\n {\n int match = subs.FindIndex(s => s.StartTime >= startTime);\n if (match != -1)\n {\n // Do from 5 previous subtitles\n startIndex = Math.Max(0, match - 5);\n }\n }\n\n for (int i = 0; i < subs.Count; i++)\n {\n if (_ctss[subIndex]!.Token.IsCancellationRequested)\n {\n foreach (var sub in subs)\n {\n sub.Dispose();\n }\n\n break;\n }\n\n int index = (startIndex + i) % subs.Count;\n\n SubtitleBitmapData? bitmap = subs[index].Bitmap;\n if (bitmap == null)\n continue;\n\n // TODO: L: If it's disposed, do I need to cancel it later?\n subs[index].Text = Process(ocrService, subIndex, bitmap);\n if (!string.IsNullOrEmpty(subs[index].Text))\n {\n // If OCR succeeds, dispose of it (if it fails, leave it so that it can be displayed in the sidebar).\n subs[index].Dispose();\n }\n }\n\n if (!_ctss[subIndex]!.Token.IsCancellationRequested)\n {\n // TODO: L: Notify, express completion in some way\n Utils.PlayCompletionSound();\n }\n }\n }\n\n private Language GetLanguageWithFallback(int subIndex, Language lang)\n {\n if (lang == Language.Unknown)\n {\n // fallback to user set language\n lang = subIndex == 0 ? _config.LanguageFallbackPrimary : _config.LanguageFallbackSecondary;\n }\n\n return lang;\n }\n\n public void TryCancelWait(int subIndex)\n {\n if (_ctss[subIndex] != null)\n {\n // Cancel if preceding OCR is running\n _ctss[subIndex]!.Cancel();\n\n // Wait until it is canceled by taking a lock\n lock (_lockers[subIndex])\n {\n _ctss[subIndex]?.Dispose();\n _ctss[subIndex] = null;\n }\n }\n }\n\n public static string Process(IOCRService ocrService, int subIndex, SubtitleBitmapData sub)\n {\n (byte[] data, AVSubtitleRect rect) = sub.SubToBitmap(true);\n\n int width = rect.w;\n int height = rect.h;\n\n fixed (byte* ptr = data)\n {\n // TODO: L: Make it possible to set true here in config (should the bitmap itself have an invert function automatically?)\n Binarize(width, height, ptr, 4, true);\n }\n\n using Bitmap bitmap = new(width, height, PixelFormat.Format32bppArgb);\n BitmapData bitmapData = bitmap.LockBits(\n new Rectangle(0, 0, width, height),\n ImageLockMode.WriteOnly, bitmap.PixelFormat);\n Marshal.Copy(data, 0, bitmapData.Scan0, data.Length);\n bitmap.UnlockBits(bitmapData);\n\n // Perform preprocessing to improve accuracy before OCR (common processing independent of OCR method)\n using Bitmap ocrBitmap = Preprocess(bitmap);\n\n string ocrText = ocrService.RecognizeTextAsync(ocrBitmap).GetAwaiter().GetResult();\n string processedText = ocrService.PostProcess(ocrText);\n\n return processedText;\n }\n\n private static Bitmap Preprocess(Bitmap bitmap)\n {\n using Bitmap blackText = ImageProcessor.BlackText(bitmap);\n Bitmap padded = ImageProcessor.AddPadding(blackText, 20);\n\n return padded;\n }\n\n /// \n /// Perform binarization on bitmaps\n /// \n /// \n /// \n /// \n /// \n /// \n private static void Binarize(int width, int height, byte* buffer, int pixelByte, bool srcTextWhite)\n {\n // Black text on white background\n byte white = 255;\n byte black = 0;\n if (srcTextWhite)\n {\n // The text is white on a black background, so invert it to black text.\n white = 0;\n black = 255;\n }\n\n for (int y = 0; y < height; y++)\n {\n for (int x = 0; x < width; x++)\n {\n byte* pixel = buffer + (y * width + x) * pixelByte;\n // Take out the first R bits since they are already in grayscale\n int grayscale = pixel[0];\n byte binaryValue = grayscale < 128 ? black : white;\n pixel[0] = pixel[1] = pixel[2] = binaryValue;\n }\n }\n }\n\n public void Reset(int subIndex)\n {\n TryCancelWait(subIndex);\n }\n}\n\npublic interface IOCRService : IDisposable\n{\n bool TryInitialize(Language lang, out string err);\n Task RecognizeTextAsync(Bitmap bitmap);\n string PostProcess(string text);\n}\n\npublic class TesseractOCRService : IOCRService\n{\n private readonly Config.SubtitlesConfig _config;\n private TesseractOCR.Engine? _ocrEngine;\n private bool _disposed;\n private Language? _lang;\n\n public TesseractOCRService(Config.SubtitlesConfig config)\n {\n _config = config;\n }\n\n public bool TryInitialize(Language lang, out string err)\n {\n _lang = lang;\n\n string iso6391 = lang.ISO6391;\n\n if (iso6391 == \"nb\")\n {\n // Norwegian Bokmål to Norwegian\n iso6391 = \"no\";\n }\n\n Dictionary> tesseractModels = TesseractModelLoader.GetAvailableModels();\n\n if (!tesseractModels.TryGetValue(iso6391, out List? models))\n {\n err = $\"Language:{lang.TopEnglishName} ({iso6391}) is not available in Tesseract OCR, Please download a model in settings if available language.\";\n\n return false;\n }\n\n TesseractModel model = models.First();\n if (_config.TesseractOcrRegions != null && models.Count >= 2)\n {\n // choose zh-CN or zh-TW (for Chinese)\n if (_config.TesseractOcrRegions.TryGetValue(iso6391, out string? langCode))\n {\n TesseractModel? m = models.FirstOrDefault(m => m.LangCode == langCode);\n if (m != null)\n {\n model = m;\n }\n }\n }\n\n _ocrEngine = new TesseractOCR.Engine(\n TesseractModel.ModelsDirectory,\n model.Lang);\n\n bool isCJK = model.Lang is\n TesseractOCR.Enums.Language.Japanese or\n TesseractOCR.Enums.Language.Korean or\n TesseractOCR.Enums.Language.ChineseSimplified or\n TesseractOCR.Enums.Language.ChineseTraditional;\n\n if (isCJK)\n {\n // remove whitespace around word if CJK\n _ocrEngine.SetVariable(\"preserve_interword_spaces\", 1);\n }\n\n err = string.Empty;\n return true;\n }\n\n public Task RecognizeTextAsync(Bitmap bitmap)\n {\n if (_ocrEngine == null)\n throw new InvalidOperationException(\"ocrEngine is not initialized\");\n\n using MemoryStream stream = new();\n\n // 32bit -> 24bit conversion\n Bitmap converted = new Bitmap(bitmap.Width, bitmap.Height, PixelFormat.Format24bppRgb);\n using (Graphics g = Graphics.FromImage(converted))\n {\n g.DrawImage(bitmap, 0, 0);\n }\n\n converted.Save(stream, ImageFormat.Bmp);\n\n stream.Position = 0;\n\n using var img = TesseractOCR.Pix.Image.LoadFromMemory(stream);\n\n using var page = _ocrEngine.Process(img);\n return Task.FromResult(page.Text);\n }\n\n public string PostProcess(string text)\n {\n var processedText = text;\n\n if (_lang == Language.English)\n {\n processedText = processedText\n .Replace(\"|\", \"I\")\n .Replace(\"I1t's\", \"It's\")\n .Replace(\"’'\", \"'\");\n }\n\n // common\n processedText = processedText\n .Trim();\n\n return processedText;\n }\n\n public void Dispose()\n {\n if (_disposed)\n return;\n\n _ocrEngine?.Dispose();\n _disposed = true;\n }\n}\n\npublic class MicrosoftOCRService : IOCRService\n{\n private readonly Config.SubtitlesConfig _config;\n private OcrEngine? _ocrEngine;\n private bool _isCJK;\n private bool _disposed;\n\n public MicrosoftOCRService(Config.SubtitlesConfig config)\n {\n _config = config;\n }\n\n public bool TryInitialize(Language lang, out string err)\n {\n string iso6391 = lang.ISO6391;\n\n string? langTag = null;\n\n if (_config.MsOcrRegions.TryGetValue(iso6391, out string? tag))\n {\n // If there is a preferred language region in the settings, it is given priority.\n langTag = tag;\n }\n else\n {\n var availableLangs = OcrEngine.AvailableRecognizerLanguages.ToList();\n\n // full match\n var match = availableLangs.FirstOrDefault(l => l.LanguageTag == iso6391);\n\n if (match == null)\n {\n // left match\n match = availableLangs.FirstOrDefault(l => l.LanguageTag.StartsWith($\"{iso6391}-\"));\n }\n\n if (match != null)\n {\n langTag = match.LanguageTag;\n }\n }\n\n if (langTag == null)\n {\n err = $\"Language:{lang.TopEnglishName} ({iso6391}) is not available in Microsoft OCR, Please install an OCR engine if available language.\";\n return false;\n }\n\n var language = new Windows.Globalization.Language(langTag);\n\n OcrEngine ocrEngine = OcrEngine.TryCreateFromLanguage(language);\n if (ocrEngine == null)\n {\n err = $\"Language:{lang.TopEnglishName} ({iso6391}) is not available in Microsoft OCR (TryCreateFromLanguage), Please install an OCR engine if available language.\";\n return false;\n }\n\n _ocrEngine = ocrEngine;\n _isCJK = langTag.StartsWith(\"zh\", StringComparison.OrdinalIgnoreCase) || // Chinese\n langTag.StartsWith(\"ja\", StringComparison.OrdinalIgnoreCase); // Japanese\n\n err = string.Empty;\n return true;\n }\n\n public async Task RecognizeTextAsync(Bitmap bitmap)\n {\n if (_ocrEngine == null)\n throw new InvalidOperationException(\"ocrEngine is not initialized\");\n\n using MemoryStream ms = new();\n\n bitmap.Save(ms, ImageFormat.Bmp);\n ms.Position = 0;\n\n using IRandomAccessStream randomAccessStream = ms.AsRandomAccessStream();\n BitmapDecoder decoder = await BitmapDecoder.CreateAsync(randomAccessStream);\n using SoftwareBitmap softwareBitmap = await decoder.GetSoftwareBitmapAsync();\n\n OcrResult ocrResult = await _ocrEngine.RecognizeAsync(softwareBitmap);\n\n if (_isCJK)\n {\n // remove whitespace around word if CJK\n return string.Join(Environment.NewLine,\n ocrResult.Lines.Select(line => string.Concat(line.Words.Select(word => word.Text))));\n }\n\n return string.Join(Environment.NewLine, ocrResult.Lines.Select(l => l.Text));\n }\n\n public string PostProcess(string text)\n {\n return text;\n }\n\n public void Dispose()\n {\n if (_disposed)\n return;\n\n // do nothing\n _disposed = true;\n }\n}\n\npublic static class ImageProcessor\n{\n /// \n /// Converts to black text on a white background\n /// \n /// original bitmap\n /// processed bitmap\n public static Bitmap BlackText(Bitmap original)\n {\n Bitmap converted = new(original.Width, original.Height, original.PixelFormat);\n\n using (Graphics g = Graphics.FromImage(converted))\n {\n // Convert to black text on a white background\n g.Clear(Color.White);\n\n // Drawing images with alpha blending enabled\n g.CompositingMode = System.Drawing.Drawing2D.CompositingMode.SourceOver;\n\n g.DrawImage(original, 0, 0);\n }\n\n return converted;\n }\n\n /// \n /// Add white padding around the bitmap\n /// \n /// original bitmap\n /// Size of padding to be added (in pixels)\n /// padded bitmap\n public static Bitmap AddPadding(Bitmap original, int padding)\n {\n int newWidth = original.Width + padding * 2;\n int newHeight = original.Height + padding * 2;\n\n Bitmap paddedBitmap = new(newWidth, newHeight, original.PixelFormat);\n\n using (Graphics graphics = Graphics.FromImage(paddedBitmap))\n {\n // White background\n graphics.Clear(Color.White);\n\n graphics.InterpolationMode = InterpolationMode.HighQualityBicubic;\n graphics.CompositingQuality = CompositingQuality.HighQuality;\n graphics.SmoothingMode = SmoothingMode.HighQuality;\n graphics.PixelOffsetMode = PixelOffsetMode.HighQuality;\n\n // Draw the original image in the center\n graphics.DrawImage(original, padding, padding, original.Width, original.Height);\n }\n\n return paddedBitmap;\n }\n\n /// \n /// Enlarge the size of the bitmap while maintaining the aspect ratio.\n /// \n /// source bitmap\n /// processed bitmap\n private static Bitmap ResizeBitmap(Bitmap original, double scaleFactor)\n {\n // Calculate new size\n int newWidth = (int)(original.Width * scaleFactor);\n int newHeight = (int)(original.Height * scaleFactor);\n\n Bitmap resizedBitmap = new(newWidth, newHeight);\n\n using (Graphics graphics = Graphics.FromImage(resizedBitmap))\n {\n graphics.InterpolationMode = InterpolationMode.HighQualityBicubic;\n graphics.CompositingQuality = CompositingQuality.HighQuality;\n graphics.SmoothingMode = SmoothingMode.HighQuality;\n graphics.PixelOffsetMode = PixelOffsetMode.HighQuality;\n\n // resize\n graphics.DrawImage(original, 0, 0, newWidth, newHeight);\n }\n\n return resizedBitmap;\n }\n}\n"], ["/LLPlayer/FlyleafLib/MediaFramework/MediaStream/SubtitlesStream.cs", "using System.IO;\nusing System.Linq;\nusing FlyleafLib.MediaFramework.MediaDemuxer;\nusing FlyleafLib.MediaPlayer;\n\nnamespace FlyleafLib.MediaFramework.MediaStream;\n\npublic enum SelectSubMethod\n{\n Original,\n OCR\n}\n\n// Both external and internal subtitles implement this interface and use it with PopMenu.\npublic interface ISubtitlesStream\n{\n public bool EnabledPrimarySubtitle { get; }\n public bool EnabledSecondarySubtitle { get; }\n}\n\npublic class SelectedSubMethod\n{\n private readonly ISubtitlesStream _stream;\n\n public SelectedSubMethod(ISubtitlesStream stream, SelectSubMethod method)\n {\n _stream = stream;\n SelectSubMethod = method;\n }\n\n public SelectSubMethod SelectSubMethod { get; }\n\n public bool IsPrimaryEnabled => _stream.EnabledPrimarySubtitle\n && SelectSubMethod == SubtitlesSelectedHelper.PrimaryMethod;\n\n public bool IsSecondaryEnabled => _stream.EnabledSecondarySubtitle\n && SelectSubMethod == SubtitlesSelectedHelper.SecondaryMethod;\n}\n\npublic unsafe class SubtitlesStream : StreamBase, ISubtitlesStream\n{\n public bool IsBitmap { get; set; }\n\n public SelectedSubMethod[] SelectedSubMethods {\n get\n {\n var methods = (SelectSubMethod[])Enum.GetValues(typeof(SelectSubMethod));\n if (!IsBitmap)\n {\n // delete OCR if text sub\n methods = methods.Where(m => m != SelectSubMethod.OCR).ToArray();\n }\n\n return methods.\n Select(m => new SelectedSubMethod(this, m)).ToArray();\n }\n }\n\n public string DisplayMember => $\"[#{StreamIndex}] {Language} ({(IsBitmap ? \"BMP\" : \"TXT\")})\";\n\n public override string GetDump()\n => $\"[{Type} #{StreamIndex}-{Language.IdSubLanguage}{(Title != null ? \"(\" + Title + \")\" : \"\")}] {Codec} | [BR: {BitRate}] | {Utils.TicksToTime((long)(AVStream->start_time * Timebase))}/{Utils.TicksToTime((long)(AVStream->duration * Timebase))} | {Utils.TicksToTime(StartTime)}/{Utils.TicksToTime(Duration)}\";\n\n public SubtitlesStream() { }\n public SubtitlesStream(Demuxer demuxer, AVStream* st) : base(demuxer, st) => Refresh();\n\n public override void Refresh()\n {\n base.Refresh();\n\n var codecDescr = avcodec_descriptor_get(CodecID);\n IsBitmap = codecDescr != null && (codecDescr->props & CodecPropFlags.BitmapSub) != 0;\n\n if (Demuxer.FormatContext->nb_streams == 1) // External Streams (mainly for .sub will have as start time the first subs timestamp)\n StartTime = 0;\n }\n\n public void ExternalStreamAdded()\n {\n // VobSub (parse .idx data to extradata - based on .sub url)\n if (CodecID == AVCodecID.DvdSubtitle && ExternalStream != null && ExternalStream.Url.EndsWith(\".sub\", StringComparison.OrdinalIgnoreCase))\n {\n var idxFile = ExternalStream.Url.Substring(0, ExternalStream.Url.Length - 3) + \"idx\";\n if (File.Exists(idxFile))\n {\n var bytes = File.ReadAllBytes(idxFile);\n AVStream->codecpar->extradata = (byte*)av_malloc((nuint)bytes.Length);\n AVStream->codecpar->extradata_size = bytes.Length;\n Span src = new(bytes);\n Span dst = new(AVStream->codecpar->extradata, bytes.Length);\n src.CopyTo(dst);\n }\n }\n }\n}\n"], ["/LLPlayer/FlyleafLib/MediaFramework/MediaStream/StreamBase.cs", "using System.Collections.Generic;\n\nusing FlyleafLib.MediaFramework.MediaDemuxer;\nusing FlyleafLib.MediaPlayer;\n\nnamespace FlyleafLib.MediaFramework.MediaStream;\n\npublic abstract unsafe class StreamBase : NotifyPropertyChanged\n{\n public ExternalStream ExternalStream { get; set; }\n\n public Demuxer Demuxer { get; internal set; }\n public AVStream* AVStream { get; internal set; }\n internal playlist* HLSPlaylist { get; set; }\n public int StreamIndex { get; internal set; } = -1;\n public double Timebase { get; internal set; }\n\n // TBR: To update Pop-up menu's (Player.Audio/Player.Video ... should inherit this?)\n public bool Enabled\n {\n get => _Enabled;\n internal set\n {\n Utils.UI(() =>\n {\n Set(ref _Enabled, value);\n\n Raise(nameof(EnabledPrimarySubtitle));\n Raise(nameof(EnabledSecondarySubtitle));\n Raise(nameof(SubtitlesStream.SelectedSubMethods));\n });\n }\n }\n\n bool _Enabled;\n\n public long BitRate { get; internal set; }\n public Language Language { get; internal set; }\n public string Title { get; internal set; }\n public string Codec { get; internal set; }\n\n public AVCodecID CodecID { get; internal set; }\n public long StartTime { get; internal set; }\n public long StartTimePts { get; internal set; }\n public long Duration { get; internal set; }\n public Dictionary Metadata { get; internal set; } = new Dictionary();\n public MediaType Type { get; internal set; }\n\n #region Subtitles\n // TODO: L: Used for subtitle streams only, but defined in the base class\n public bool EnabledPrimarySubtitle => Enabled && this.GetSubEnabled(0);\n public bool EnabledSecondarySubtitle => Enabled && this.GetSubEnabled(1);\n #endregion\n\n public abstract string GetDump();\n public StreamBase() { }\n public StreamBase(Demuxer demuxer, AVStream* st)\n {\n Demuxer = demuxer;\n AVStream = st;\n }\n\n public virtual void Refresh()\n {\n BitRate = AVStream->codecpar->bit_rate;\n CodecID = AVStream->codecpar->codec_id;\n Codec = avcodec_get_name(AVStream->codecpar->codec_id);\n StreamIndex = AVStream->index;\n Timebase = av_q2d(AVStream->time_base) * 10000.0 * 1000.0;\n StartTime = AVStream->start_time != AV_NOPTS_VALUE && Demuxer.hlsCtx == null ? (long)(AVStream->start_time * Timebase) : Demuxer.StartTime;\n StartTimePts= AVStream->start_time != AV_NOPTS_VALUE ? AVStream->start_time : av_rescale_q(StartTime/10, Engine.FFmpeg.AV_TIMEBASE_Q, AVStream->time_base);\n Duration = AVStream->duration != AV_NOPTS_VALUE ? (long)(AVStream->duration * Timebase) : Demuxer.Duration;\n Type = this is VideoStream ? MediaType.Video : (this is AudioStream ? MediaType.Audio : (this is SubtitlesStream ? MediaType.Subs : MediaType.Data));\n\n if (Demuxer.hlsCtx != null)\n {\n for (int i=0; in_playlists; i++)\n {\n playlist** playlists = Demuxer.hlsCtx->playlists;\n for (int l=0; ln_main_streams; l++)\n if (playlists[i]->main_streams[l]->index == StreamIndex)\n {\n Demuxer.Log.Debug($\"Stream #{StreamIndex} Found in playlist {i}\");\n HLSPlaylist = playlists[i];\n break;\n }\n }\n }\n\n Metadata.Clear();\n\n AVDictionaryEntry* b = null;\n while (true)\n {\n b = av_dict_get(AVStream->metadata, \"\", b, DictReadFlags.IgnoreSuffix);\n if (b == null) break;\n Metadata.Add(Utils.BytePtrToStringUTF8(b->key), Utils.BytePtrToStringUTF8(b->value));\n }\n\n foreach (var kv in Metadata)\n {\n string keyLower = kv.Key.ToLower();\n\n if (Language == null && (keyLower == \"language\" || keyLower == \"lang\"))\n Language = Language.Get(kv.Value);\n else if (keyLower == \"title\")\n Title = kv.Value;\n }\n\n if (Language == null)\n Language = Language.Unknown;\n }\n}\n"], ["/LLPlayer/FlyleafLib/MediaFramework/MediaDecoder/VideoDecoder.cs", "using System.Collections.Concurrent;\nusing System.Collections.Generic;\nusing System.Runtime.InteropServices;\nusing System.Threading;\n\nusing Vortice.DXGI;\nusing Vortice.Direct3D11;\n\nusing ID3D11Texture2D = Vortice.Direct3D11.ID3D11Texture2D;\n\nusing FlyleafLib.MediaFramework.MediaStream;\nusing FlyleafLib.MediaFramework.MediaFrame;\nusing FlyleafLib.MediaFramework.MediaRenderer;\nusing FlyleafLib.MediaFramework.MediaRemuxer;\n\nusing static FlyleafLib.Logger;\n\nnamespace FlyleafLib.MediaFramework.MediaDecoder;\n\npublic unsafe class VideoDecoder : DecoderBase\n{\n public ConcurrentQueue\n Frames { get; protected set; } = new ConcurrentQueue();\n public Renderer Renderer { get; private set; }\n public bool VideoAccelerated { get; internal set; }\n public bool ZeroCopy { get; internal set; }\n\n public VideoStream VideoStream => (VideoStream) Stream;\n\n public long StartTime { get; internal set; } = AV_NOPTS_VALUE;\n public long StartRecordTime { get; internal set; } = AV_NOPTS_VALUE;\n\n const AVPixelFormat PIX_FMT_HWACCEL = AVPixelFormat.D3d11;\n const SwsFlags SCALING_HQ = SwsFlags.AccurateRnd | SwsFlags.Bitexact | SwsFlags.Lanczos | SwsFlags.FullChrHInt | SwsFlags.FullChrHInp;\n const SwsFlags SCALING_LQ = SwsFlags.Bicublin;\n\n internal SwsContext* swsCtx;\n IntPtr swsBufferPtr;\n internal byte_ptrArray4 swsData;\n internal int_array4 swsLineSize;\n\n internal bool swFallback;\n internal bool keyPacketRequired;\n internal long lastFixedPts;\n\n bool checkExtraFrames; // DecodeFrameNext\n\n // Reverse Playback\n ConcurrentStack>\n curReverseVideoStack = new();\n List curReverseVideoPackets = new();\n List curReverseVideoFrames = new();\n int curReversePacketPos = 0;\n\n // Drop frames if FPS is higher than allowed\n int curSpeedFrame = 9999; // don't skip first frame (on start/after seek-flush)\n double skipSpeedFrames = 0;\n\n public VideoDecoder(Config config, int uniqueId = -1) : base(config, uniqueId)\n => getHWformat = new AVCodecContext_get_format(get_format);\n\n protected override void OnSpeedChanged(double value)\n {\n if (VideoStream == null) return;\n speed = value;\n skipSpeedFrames = speed * VideoStream.FPS / Config.Video.MaxOutputFps;\n }\n\n /// \n /// Prevents to get the first frame after seek/flush\n /// \n public void ResetSpeedFrame()\n => curSpeedFrame = 0;\n\n public void CreateRenderer() // TBR: It should be in the constructor but DecoderContext will not work with null VideoDecoder for AudioOnly\n {\n if (Renderer == null)\n Renderer = new Renderer(this, IntPtr.Zero, UniqueId);\n else if (Renderer.Disposed)\n Renderer.Initialize();\n }\n public void DestroyRenderer() => Renderer?.Dispose();\n public void CreateSwapChain(IntPtr handle)\n {\n CreateRenderer();\n Renderer.InitializeSwapChain(handle);\n }\n public void CreateSwapChain(Action swapChainWinUIClbk)\n {\n Renderer.SwapChainWinUIClbk = swapChainWinUIClbk;\n if (Renderer.SwapChainWinUIClbk != null)\n Renderer.InitializeWinUISwapChain();\n\n }\n public void DestroySwapChain() => Renderer?.DisposeSwapChain();\n\n #region Video Acceleration (Should be disposed seperately)\n const int AV_CODEC_HW_CONFIG_METHOD_HW_DEVICE_CTX = 0x01;\n const AVHWDeviceType HW_DEVICE = AVHWDeviceType.D3d11va;\n\n internal ID3D11Texture2D\n textureFFmpeg;\n AVCodecContext_get_format\n getHWformat;\n AVBufferRef* hwframes;\n AVBufferRef* hw_device_ctx;\n\n internal static bool CheckCodecSupport(AVCodec* codec)\n {\n for (int i = 0; ; i++)\n {\n var config = avcodec_get_hw_config(codec, i);\n if (config == null) break;\n if ((config->methods & AVCodecHwConfigMethod.HwDeviceCtx) == 0 || config->pix_fmt == AVPixelFormat.None) continue;\n\n if (config->device_type == HW_DEVICE && config->pix_fmt == PIX_FMT_HWACCEL) return true;\n }\n\n return false;\n }\n internal int InitVA()\n {\n int ret;\n AVHWDeviceContext* device_ctx;\n AVD3D11VADeviceContext* d3d11va_device_ctx;\n\n if (Renderer.Device == null || hw_device_ctx != null) return -1;\n\n hw_device_ctx = av_hwdevice_ctx_alloc(HW_DEVICE);\n\n device_ctx = (AVHWDeviceContext*) hw_device_ctx->data;\n d3d11va_device_ctx = (AVD3D11VADeviceContext*) device_ctx->hwctx;\n d3d11va_device_ctx->device\n = (Flyleaf.FFmpeg.ID3D11Device*) Renderer.Device.NativePointer;\n\n ret = av_hwdevice_ctx_init(hw_device_ctx);\n if (ret != 0)\n {\n Log.Error($\"VA Failed - {FFmpegEngine.ErrorCodeToMsg(ret)} ({ret})\");\n\n fixed(AVBufferRef** ptr = &hw_device_ctx)\n av_buffer_unref(ptr);\n\n hw_device_ctx = null;\n }\n\n Renderer.Device.AddRef(); // Important to give another reference for FFmpeg so we can dispose without issues\n\n return ret;\n }\n\n private AVPixelFormat get_format(AVCodecContext* avctx, AVPixelFormat* pix_fmts)\n {\n if (CanDebug)\n {\n Log.Debug($\"Codec profile '{VideoStream.Codec} {avcodec_profile_name(codecCtx->codec_id, codecCtx->profile)}'\");\n\n if (CanTrace)\n {\n var save = pix_fmts;\n while (*pix_fmts != AVPixelFormat.None)\n {\n Log.Trace($\"{*pix_fmts}\");\n pix_fmts++;\n }\n pix_fmts = save;\n }\n }\n\n bool foundHWformat = false;\n\n while (*pix_fmts != AVPixelFormat.None)\n {\n if ((*pix_fmts) == PIX_FMT_HWACCEL)\n {\n foundHWformat = true;\n break;\n }\n\n pix_fmts++;\n }\n\n int ret = ShouldAllocateNew();\n\n if (foundHWformat && ret == 0)\n {\n if (codecCtx->hw_frames_ctx == null && hwframes != null)\n codecCtx->hw_frames_ctx = av_buffer_ref(hwframes);\n\n return PIX_FMT_HWACCEL;\n }\n\n lock (lockCodecCtx)\n {\n if (!foundHWformat || !VideoAccelerated || AllocateHWFrames() != 0)\n {\n if (CanWarn)\n Log.Warn(\"HW format not found. Fallback to sw format\");\n\n swFallback = true;\n return avcodec_default_get_format(avctx, pix_fmts);\n }\n\n if (CanDebug)\n Log.Debug(\"HW frame allocation completed\");\n\n // TBR: Catch codec changed on live streams (check codec/profiles and check even on sw frames)\n if (ret == 2)\n {\n Log.Warn($\"Codec changed {VideoStream.CodecID} {VideoStream.Width}x{VideoStream.Height} => {codecCtx->codec_id} {codecCtx->width}x{codecCtx->height}\");\n filledFromCodec = false;\n }\n\n return PIX_FMT_HWACCEL;\n }\n }\n private int ShouldAllocateNew() // 0: No, 1: Yes, 2: Yes+Codec Changed\n {\n if (hwframes == null)\n return 1;\n\n AVHWFramesContext* t2 = (AVHWFramesContext*) hwframes->data;\n\n if (codecCtx->coded_width != t2->width)\n return 2;\n\n if (codecCtx->coded_height != t2->height)\n return 2;\n\n // TBR: Codec changed (seems ffmpeg changes codecCtx by itself\n //if (codecCtx->codec_id != VideoStream.CodecID)\n // return 2;\n\n //var fmt = codecCtx->sw_pix_fmt == (AVPixelFormat)AV_PIX_FMT_YUV420P10LE ? (AVPixelFormat)AV_PIX_FMT_P010LE : (codecCtx->sw_pix_fmt == (AVPixelFormat)AV_PIX_FMT_P010BE ? (AVPixelFormat)AV_PIX_FMT_P010BE : AVPixelFormat.AV_PIX_FMT_NV12);\n //if (fmt != t2->sw_format)\n // return 2;\n\n return 0;\n }\n\n private int AllocateHWFrames()\n {\n if (hwframes != null)\n fixed(AVBufferRef** ptr = &hwframes)\n av_buffer_unref(ptr);\n\n hwframes = null;\n\n if (codecCtx->hw_frames_ctx != null)\n av_buffer_unref(&codecCtx->hw_frames_ctx);\n\n if (avcodec_get_hw_frames_parameters(codecCtx, codecCtx->hw_device_ctx, PIX_FMT_HWACCEL, &codecCtx->hw_frames_ctx) != 0)\n return -1;\n\n AVHWFramesContext* hw_frames_ctx = (AVHWFramesContext*)codecCtx->hw_frames_ctx->data;\n //hw_frames_ctx->initial_pool_size += Config.Decoder.MaxVideoFrames; // TBR: Texture 2D Array seems to have up limit to 128 (total=17+MaxVideoFrames)? (should use extra hw frames instead**)\n\n AVD3D11VAFramesContext *va_frames_ctx = (AVD3D11VAFramesContext *)hw_frames_ctx->hwctx;\n va_frames_ctx->BindFlags |= (uint)BindFlags.Decoder | (uint)BindFlags.ShaderResource;\n\n hwframes = av_buffer_ref(codecCtx->hw_frames_ctx);\n\n int ret = av_hwframe_ctx_init(codecCtx->hw_frames_ctx);\n if (ret == 0)\n {\n lock (Renderer.lockDevice)\n {\n textureFFmpeg = new ID3D11Texture2D((IntPtr) va_frames_ctx->texture);\n ZeroCopy = Config.Decoder.ZeroCopy == FlyleafLib.ZeroCopy.Enabled || (Config.Decoder.ZeroCopy == FlyleafLib.ZeroCopy.Auto && codecCtx->width == textureFFmpeg.Description.Width && codecCtx->height == textureFFmpeg.Description.Height);\n filledFromCodec = false;\n }\n }\n\n return ret;\n }\n internal void RecalculateZeroCopy()\n {\n lock (Renderer.lockDevice)\n {\n bool save = ZeroCopy;\n ZeroCopy = VideoAccelerated && (Config.Decoder.ZeroCopy == FlyleafLib.ZeroCopy.Enabled || (Config.Decoder.ZeroCopy == FlyleafLib.ZeroCopy.Auto && codecCtx->width == textureFFmpeg.Description.Width && codecCtx->height == textureFFmpeg.Description.Height));\n if (save != ZeroCopy)\n {\n Renderer?.ConfigPlanes();\n CodecChanged?.Invoke(this);\n }\n }\n }\n #endregion\n\n protected override int Setup(AVCodec* codec)\n {\n // Ensures we have a renderer (no swap chain is required)\n CreateRenderer();\n\n VideoAccelerated = false;\n\n if (!swFallback && Config.Video.VideoAcceleration && Renderer.Device.FeatureLevel >= Vortice.Direct3D.FeatureLevel.Level_10_0)\n {\n if (CheckCodecSupport(codec))\n {\n if (InitVA() == 0)\n {\n codecCtx->hw_device_ctx = av_buffer_ref(hw_device_ctx);\n VideoAccelerated = true;\n Log.Debug(\"VA Success\");\n }\n }\n else\n Log.Info($\"VA {codec->id} not supported\");\n }\n else\n Log.Debug(\"VA Disabled\");\n\n // Can't get data from here?\n //var t1 = av_stream_get_side_data(VideoStream.AVStream, AVPacketSideDataType.AV_PKT_DATA_MASTERING_DISPLAY_METADATA, null);\n //var t2 = av_stream_get_side_data(VideoStream.AVStream, AVPacketSideDataType.AV_PKT_DATA_CONTENT_LIGHT_LEVEL, null);\n\n // TBR: during swFallback (keyFrameRequiredPacket should not reset, currenlty saved in SWFallback)\n keyPacketRequired = false; // allow no key packet after open (lot of videos missing this)\n ZeroCopy = false;\n filledFromCodec = false;\n\n lastFixedPts = 0; // TBR: might need to set this to first known pts/dts\n\n if (VideoAccelerated)\n {\n codecCtx->thread_count = 1;\n codecCtx->hwaccel_flags |= HWAccelFlags.IgnoreLevel;\n if (Config.Decoder.AllowProfileMismatch)\n codecCtx->hwaccel_flags|= HWAccelFlags.AllowProfileMismatch;\n\n codecCtx->get_format = getHWformat;\n codecCtx->extra_hw_frames = Config.Decoder.MaxVideoFrames;\n }\n else\n codecCtx->thread_count = Math.Min(Config.Decoder.VideoThreads, codecCtx->codec_id == AVCodecID.Hevc ? 32 : 16);\n\n return 0;\n }\n internal bool SetupSws()\n {\n Marshal.FreeHGlobal(swsBufferPtr);\n var fmt = AVPixelFormat.Rgba;\n swsData = new byte_ptrArray4();\n swsLineSize = new int_array4();\n int outBufferSize\n = av_image_get_buffer_size(fmt, codecCtx->width, codecCtx->height, 1);\n swsBufferPtr = Marshal.AllocHGlobal(outBufferSize);\n av_image_fill_arrays(ref swsData, ref swsLineSize, (byte*) swsBufferPtr, fmt, codecCtx->width, codecCtx->height, 1);\n swsCtx = sws_getContext(codecCtx->coded_width, codecCtx->coded_height, codecCtx->pix_fmt, codecCtx->width, codecCtx->height, fmt, Config.Video.SwsHighQuality ? SCALING_HQ : SCALING_LQ, null, null, null);\n\n if (swsCtx == null)\n {\n Log.Error($\"Failed to allocate SwsContext\");\n return false;\n }\n\n return true;\n }\n internal void Flush()\n {\n lock (lockActions)\n lock (lockCodecCtx)\n {\n if (Disposed) return;\n\n if (Status == Status.Ended)\n Status = Status.Stopped;\n else if (Status == Status.Draining)\n Status = Status.Stopping;\n\n DisposeFrames();\n avcodec_flush_buffers(codecCtx);\n\n keyPacketRequired\n = true;\n StartTime = AV_NOPTS_VALUE;\n curSpeedFrame = 9999;\n }\n }\n\n protected override void RunInternal()\n {\n if (demuxer.IsReversePlayback)\n {\n RunInternalReverse();\n return;\n }\n\n int ret = 0;\n int allowedErrors = Config.Decoder.MaxErrors;\n int sleepMs = Config.Decoder.MaxVideoFrames > 2 && Config.Player.MaxLatency == 0 ? 10 : 2;\n AVPacket *packet;\n\n do\n {\n // Wait until Queue not Full or Stopped\n if (Frames.Count >= Config.Decoder.MaxVideoFrames)\n {\n lock (lockStatus)\n if (Status == Status.Running) Status = Status.QueueFull;\n\n while (Frames.Count >= Config.Decoder.MaxVideoFrames && Status == Status.QueueFull)\n Thread.Sleep(sleepMs);\n\n lock (lockStatus)\n {\n if (Status != Status.QueueFull) break;\n Status = Status.Running;\n }\n }\n\n // While Packets Queue Empty (Drain | Quit if Demuxer stopped | Wait until we get packets)\n if (demuxer.VideoPackets.Count == 0)\n {\n CriticalArea = true;\n\n lock (lockStatus)\n if (Status == Status.Running) Status = Status.QueueEmpty;\n\n while (demuxer.VideoPackets.Count == 0 && Status == Status.QueueEmpty)\n {\n if (demuxer.Status == Status.Ended)\n {\n lock (lockStatus)\n {\n // TODO: let the demuxer push the draining packet\n Log.Debug(\"Draining\");\n Status = Status.Draining;\n var drainPacket = av_packet_alloc();\n drainPacket->data = null;\n drainPacket->size = 0;\n demuxer.VideoPackets.Enqueue(drainPacket);\n }\n\n break;\n }\n else if (!demuxer.IsRunning)\n {\n if (CanDebug) Log.Debug($\"Demuxer is not running [Demuxer Status: {demuxer.Status}]\");\n\n int retries = 5;\n\n while (retries > 0)\n {\n retries--;\n Thread.Sleep(10);\n if (demuxer.IsRunning) break;\n }\n\n lock (demuxer.lockStatus)\n lock (lockStatus)\n {\n if (demuxer.Status == Status.Pausing || demuxer.Status == Status.Paused)\n Status = Status.Pausing;\n else if (demuxer.Status != Status.Ended)\n Status = Status.Stopping;\n else\n continue;\n }\n\n break;\n }\n\n Thread.Sleep(sleepMs);\n }\n\n lock (lockStatus)\n {\n CriticalArea = false;\n if (Status != Status.QueueEmpty && Status != Status.Draining) break;\n if (Status != Status.Draining) Status = Status.Running;\n }\n }\n\n lock (lockCodecCtx)\n {\n if (Status == Status.Stopped)\n continue;\n\n packet = demuxer.VideoPackets.Dequeue();\n\n if (packet == null)\n continue;\n\n if (isRecording)\n {\n if (!recKeyPacketRequired && (packet->flags & PktFlags.Key) != 0)\n {\n recKeyPacketRequired = true;\n StartRecordTime = (long)(packet->pts * VideoStream.Timebase) - demuxer.StartTime;\n }\n\n if (recKeyPacketRequired)\n curRecorder.Write(av_packet_clone(packet));\n }\n\n if (keyPacketRequired)\n {\n if (packet->flags.HasFlag(PktFlags.Key))\n keyPacketRequired = false;\n else\n {\n if (CanWarn) Log.Warn(\"Ignoring non-key packet\");\n av_packet_unref(packet);\n continue;\n }\n }\n\n // TBR: AVERROR(EAGAIN) means avcodec_receive_frame but after resend the same packet\n ret = avcodec_send_packet(codecCtx, packet);\n\n if (swFallback) // Should use 'global' packet to reset it in get_format (same packet should use also from DecoderContext)\n {\n SWFallback();\n ret = avcodec_send_packet(codecCtx, packet);\n }\n\n if (ret != 0 && ret != AVERROR(EAGAIN))\n {\n // TBR: Possible check for VA failed here (normally this will happen during get_format)\n av_packet_free(&packet);\n\n if (ret == AVERROR_EOF)\n {\n if (demuxer.VideoPackets.Count > 0) { avcodec_flush_buffers(codecCtx); continue; } // TBR: Happens on HLS while switching video streams\n Status = Status.Ended;\n break;\n }\n else\n {\n allowedErrors--;\n if (CanWarn) Log.Warn($\"{FFmpegEngine.ErrorCodeToMsg(ret)} ({ret})\");\n\n if (allowedErrors == 0) { Log.Error(\"Too many errors!\"); Status = Status.Stopping; break; }\n\n continue;\n }\n }\n\n while (true)\n {\n ret = avcodec_receive_frame(codecCtx, frame);\n if (ret != 0) { av_frame_unref(frame); break; }\n\n // GetFormat checks already for this but only for hardware accelerated (should also check for codec/fps* and possible reset sws if required)\n // Might use AVERROR_INPUT_CHANGED to let ffmpeg check for those (requires a flag to be set*)\n if (frame->height != VideoStream.Height || frame->width != VideoStream.Width)\n {\n // THIS IS Wrong and can cause filledFromCodec all the time. comparing frame<->videostream dimensions but we update the videostream from codecparam dimensions (which we pass from codecCtx w/h)\n // Related with display dimensions / coded dimensions / frame-crop dimensions (and apply_cropping) - it could happen when frame->crop... are not 0\n Log.Warn($\"Codec changed {VideoStream.CodecID} {VideoStream.Width}x{VideoStream.Height} => {codecCtx->codec_id} {frame->width}x{frame->height}\");\n filledFromCodec = false;\n }\n\n if (frame->best_effort_timestamp != AV_NOPTS_VALUE)\n frame->pts = frame->best_effort_timestamp;\n\n else if (frame->pts == AV_NOPTS_VALUE)\n {\n if (!VideoStream.FixTimestamps && VideoStream.Duration > TimeSpan.FromSeconds(1).Ticks)\n {\n // TBR: it is possible to have a single frame / image with no dts/pts which actually means pts = 0 ? (ticket_3449.264) - GenPts will not affect it\n // TBR: first frame might no have dts/pts which probably means pts = 0 (and not start time!)\n av_frame_unref(frame);\n continue;\n }\n\n // Create timestamps for h264/hevc raw streams (Needs also to handle this with the remuxer / no recording currently supported!)\n frame->pts = lastFixedPts + VideoStream.StartTimePts;\n lastFixedPts += av_rescale_q(VideoStream.FrameDuration / 10, Engine.FFmpeg.AV_TIMEBASE_Q, VideoStream.AVStream->time_base);\n }\n\n if (StartTime == NoTs)\n StartTime = (long)(frame->pts * VideoStream.Timebase) - demuxer.StartTime;\n\n if (!filledFromCodec) // Ensures we have a proper frame before filling from codec\n {\n ret = FillFromCodec(frame);\n if (ret == -1234)\n {\n Status = Status.Stopping;\n break;\n }\n }\n\n if (skipSpeedFrames > 1)\n {\n curSpeedFrame++;\n if (curSpeedFrame < skipSpeedFrames)\n {\n av_frame_unref(frame);\n continue;\n }\n curSpeedFrame = 0;\n }\n\n var mFrame = Renderer.FillPlanes(frame);\n if (mFrame != null) Frames.Enqueue(mFrame); // TBR: Does not respect Config.Decoder.MaxVideoFrames\n\n if (!Config.Video.PresentFlags.HasFlag(PresentFlags.DoNotWait) && Frames.Count > 2)\n Thread.Sleep(10);\n }\n\n av_packet_free(&packet);\n }\n\n } while (Status == Status.Running);\n\n checkExtraFrames = true;\n\n if (isRecording) { StopRecording(); recCompleted(MediaType.Video); }\n\n if (Status == Status.Draining) Status = Status.Ended;\n }\n\n internal int FillFromCodec(AVFrame* frame)\n {\n lock (Renderer.lockDevice)\n {\n int ret = 0;\n\n filledFromCodec = true;\n\n avcodec_parameters_from_context(Stream.AVStream->codecpar, codecCtx);\n VideoStream.AVStream->time_base = codecCtx->pkt_timebase;\n VideoStream.Refresh(VideoAccelerated && codecCtx->sw_pix_fmt != AVPixelFormat.None ? codecCtx->sw_pix_fmt : codecCtx->pix_fmt, frame);\n\n if (!(VideoStream.FPS > 0)) // NaN\n {\n VideoStream.FPS = av_q2d(codecCtx->framerate) > 0 ? av_q2d(codecCtx->framerate) : 0;\n VideoStream.FrameDuration = VideoStream.FPS > 0 ? (long) (10000000 / VideoStream.FPS) : 0;\n if (VideoStream.FrameDuration > 0)\n VideoStream.Demuxer.VideoPackets.frameDuration = VideoStream.FrameDuration;\n }\n\n skipSpeedFrames = speed * VideoStream.FPS / Config.Video.MaxOutputFps;\n CodecChanged?.Invoke(this);\n\n if (VideoStream.PixelFormat == AVPixelFormat.None || !Renderer.ConfigPlanes())\n {\n Log.Error(\"[Pixel Format] Unknown\");\n return -1234;\n }\n\n return ret;\n }\n }\n\n internal string SWFallback()\n {\n lock (Renderer.lockDevice)\n {\n string ret;\n\n DisposeInternal();\n if (codecCtx != null)\n fixed (AVCodecContext** ptr = &codecCtx)\n avcodec_free_context(ptr);\n\n codecCtx = null;\n swFallback = true;\n bool oldKeyFrameRequiredPacket\n = keyPacketRequired;\n ret = Open2(Stream, null, false); // TBR: Dispose() on failure could cause a deadlock\n keyPacketRequired\n = oldKeyFrameRequiredPacket;\n swFallback = false;\n filledFromCodec = false;\n\n return ret;\n }\n }\n\n private void RunInternalReverse()\n {\n // Bug with B-frames, we should not remove the ref packets (we miss frames each time we restart decoding the gop)\n\n int ret = 0;\n int allowedErrors = Config.Decoder.MaxErrors;\n AVPacket *packet;\n\n do\n {\n // While Packets Queue Empty (Drain | Quit if Demuxer stopped | Wait until we get packets)\n if (demuxer.VideoPacketsReverse.IsEmpty && curReverseVideoStack.IsEmpty && curReverseVideoPackets.Count == 0)\n {\n CriticalArea = true;\n\n lock (lockStatus)\n if (Status == Status.Running) Status = Status.QueueEmpty;\n\n while (demuxer.VideoPacketsReverse.IsEmpty && Status == Status.QueueEmpty)\n {\n if (demuxer.Status == Status.Ended) // TODO\n {\n lock (lockStatus) Status = Status.Ended;\n\n break;\n }\n else if (!demuxer.IsRunning)\n {\n if (CanDebug) Log.Debug($\"Demuxer is not running [Demuxer Status: {demuxer.Status}]\");\n\n int retries = 5;\n\n while (retries > 0)\n {\n retries--;\n Thread.Sleep(10);\n if (demuxer.IsRunning) break;\n }\n\n lock (demuxer.lockStatus)\n lock (lockStatus)\n {\n if (demuxer.Status == Status.Pausing || demuxer.Status == Status.Paused)\n Status = Status.Pausing;\n else if (demuxer.Status != Status.Ended)\n Status = Status.Stopping;\n else\n continue;\n }\n\n break;\n }\n\n Thread.Sleep(20);\n }\n\n lock (lockStatus)\n {\n CriticalArea = false;\n if (Status != Status.QueueEmpty) break;\n Status = Status.Running;\n }\n }\n\n if (curReverseVideoPackets.Count == 0)\n {\n if (curReverseVideoStack.IsEmpty)\n demuxer.VideoPacketsReverse.TryDequeue(out curReverseVideoStack);\n\n curReverseVideoStack.TryPop(out curReverseVideoPackets);\n curReversePacketPos = 0;\n }\n\n while (curReverseVideoPackets.Count > 0 && Status == Status.Running)\n {\n // Wait until Queue not Full or Stopped\n if (Frames.Count + curReverseVideoFrames.Count >= Config.Decoder.MaxVideoFrames)\n {\n lock (lockStatus)\n if (Status == Status.Running) Status = Status.QueueFull;\n\n while (Frames.Count + curReverseVideoFrames.Count >= Config.Decoder.MaxVideoFrames && Status == Status.QueueFull) Thread.Sleep(20);\n\n lock (lockStatus)\n {\n if (Status != Status.QueueFull) break;\n Status = Status.Running;\n }\n }\n\n lock (lockCodecCtx)\n {\n if (keyPacketRequired == true)\n {\n keyPacketRequired = false;\n curReversePacketPos = 0;\n break;\n }\n\n packet = (AVPacket*)curReverseVideoPackets[curReversePacketPos++];\n ret = avcodec_send_packet(codecCtx, packet);\n\n if (ret != 0 && ret != AVERROR(EAGAIN))\n {\n if (ret == AVERROR_EOF) { Status = Status.Ended; break; }\n\n if (CanWarn) Log.Warn($\"{FFmpegEngine.ErrorCodeToMsg(ret)} ({ret})\");\n\n allowedErrors--;\n if (allowedErrors == 0) { Log.Error(\"Too many errors!\"); Status = Status.Stopping; break; }\n\n for (int i=curReverseVideoPackets.Count-1; i>=curReversePacketPos-1; i--)\n {\n packet = (AVPacket*)curReverseVideoPackets[i];\n av_packet_free(&packet);\n curReverseVideoPackets[curReversePacketPos - 1] = IntPtr.Zero;\n curReverseVideoPackets.RemoveAt(i);\n }\n\n avcodec_flush_buffers(codecCtx);\n curReversePacketPos = 0;\n\n for (int i=curReverseVideoFrames.Count -1; i>=0; i--)\n Frames.Enqueue(curReverseVideoFrames[i]);\n\n curReverseVideoFrames.Clear();\n\n continue;\n }\n\n while (true)\n {\n ret = avcodec_receive_frame(codecCtx, frame);\n if (ret != 0) { av_frame_unref(frame); break; }\n\n if (frame->best_effort_timestamp != AV_NOPTS_VALUE)\n frame->pts = frame->best_effort_timestamp;\n else if (frame->pts == AV_NOPTS_VALUE)\n { av_frame_unref(frame); continue; }\n\n bool shouldProcess = curReverseVideoPackets.Count - curReversePacketPos < Config.Decoder.MaxVideoFrames;\n\n if (shouldProcess)\n {\n av_packet_free(&packet);\n curReverseVideoPackets[curReversePacketPos - 1] = IntPtr.Zero;\n var mFrame = Renderer.FillPlanes(frame);\n if (mFrame != null) curReverseVideoFrames.Add(mFrame);\n }\n else\n av_frame_unref(frame);\n }\n\n if (curReversePacketPos == curReverseVideoPackets.Count)\n {\n curReverseVideoPackets.RemoveRange(Math.Max(0, curReverseVideoPackets.Count - Config.Decoder.MaxVideoFrames), Math.Min(curReverseVideoPackets.Count, Config.Decoder.MaxVideoFrames) );\n avcodec_flush_buffers(codecCtx);\n curReversePacketPos = 0;\n\n for (int i=curReverseVideoFrames.Count -1; i>=0; i--)\n Frames.Enqueue(curReverseVideoFrames[i]);\n\n curReverseVideoFrames.Clear();\n\n break; // force recheck for max queues etc...\n }\n\n } // Lock CodecCtx\n\n // Import Sleep required to prevent delay during Renderer.Present for waitable swap chains\n if (!Config.Video.PresentFlags.HasFlag(PresentFlags.DoNotWait) && Frames.Count > 2)\n Thread.Sleep(10);\n\n } // while curReverseVideoPackets.Count > 0\n\n } while (Status == Status.Running);\n\n if (Status != Status.Pausing && Status != Status.Paused)\n curReversePacketPos = 0;\n }\n\n public void RefreshMaxVideoFrames()\n {\n lock (lockActions)\n {\n if (VideoStream == null)\n return;\n\n bool wasRunning = IsRunning;\n\n var stream = Stream;\n\n Dispose();\n Open(stream);\n\n if (wasRunning)\n Start();\n }\n }\n\n public int GetFrameNumber(long timestamp)\n {\n // Incoming timestamps are zero-base from demuxer start time (not from video stream start time)\n timestamp -= VideoStream.StartTime - demuxer.StartTime;\n\n if (timestamp < 1)\n return 0;\n\n // offset 2ms\n return (int) ((timestamp + 20000) / VideoStream.FrameDuration);\n }\n\n /// \n /// Performs accurate seeking to the requested VideoFrame and returns it\n /// \n /// Zero based frame index\n /// The requested VideoFrame or null on failure\n public VideoFrame GetFrame(int index)\n {\n int ret;\n\n // Calculation of FrameX timestamp (based on fps/avgFrameDuration) | offset 2ms\n long frameTimestamp = VideoStream.StartTime + (index * VideoStream.FrameDuration) - 20000;\n //Log.Debug($\"Searching for {Utils.TicksToTime(frameTimestamp)}\");\n\n demuxer.Pause();\n Pause();\n\n // TBR\n //if (demuxer.FormatContext->pb != null)\n // avio_flush(demuxer.FormatContext->pb);\n //avformat_flush(demuxer.FormatContext);\n\n // Seeking at frameTimestamp or previous I/Key frame and flushing codec | Temp fix (max I/distance 3sec) for ffmpeg bug that fails to seek on keyframe with HEVC\n // More issues with mpegts seeking backwards (those should be used also in the reverse playback in the demuxer)\n demuxer.Interrupter.SeekRequest();\n ret = codecCtx->codec_id == AVCodecID.Hevc|| (demuxer.FormatContext->iformat != null) // TBR: this is on FFInputFormat now -> && demuxer.FormatContext->iformat-> read_seek.Pointer == IntPtr.Zero)\n ? av_seek_frame(demuxer.FormatContext, -1, Math.Max(0, frameTimestamp - Config.Player.SeekGetFrameFixMargin) / 10, SeekFlags.Any)\n : av_seek_frame(demuxer.FormatContext, -1, frameTimestamp / 10, SeekFlags.Frame | SeekFlags.Backward);\n\n demuxer.DisposePackets();\n\n if (demuxer.Status == Status.Ended) demuxer.Status = Status.Stopped;\n if (ret < 0) return null; // handle seek error\n Flush();\n checkExtraFrames = false;\n\n while (DecodeFrameNext() == 0)\n {\n // Skip frames before our actual requested frame\n if ((long)(frame->pts * VideoStream.Timebase) < frameTimestamp)\n {\n //Log.Debug($\"[Skip] [pts: {frame->pts}] [time: {Utils.TicksToTime((long)(frame->pts * VideoStream.Timebase))}] | [fltime: {Utils.TicksToTime(((long)(frame->pts * VideoStream.Timebase) - demuxer.StartTime))}]\");\n av_frame_unref(frame);\n continue;\n }\n\n //Log.Debug($\"[Found] [pts: {frame->pts}] [time: {Utils.TicksToTime((long)(frame->pts * VideoStream.Timebase))}] | {Utils.TicksToTime(VideoStream.StartTime + (index * VideoStream.FrameDuration))} | [fltime: {Utils.TicksToTime(((long)(frame->pts * VideoStream.Timebase) - demuxer.StartTime))}]\");\n return Renderer.FillPlanes(frame);\n }\n\n return null;\n }\n\n /// \n /// Gets next VideoFrame (Decoder/Demuxer must not be running)\n /// \n /// The next VideoFrame\n public VideoFrame GetFrameNext()\n => DecodeFrameNext() == 0 ? Renderer.FillPlanes(frame) : null;\n\n /// \n /// Pushes the decoder to the next available VideoFrame (Decoder/Demuxer must not be running)\n /// \n /// \n public int DecodeFrameNext()\n {\n int ret;\n int allowedErrors = Config.Decoder.MaxErrors;\n\n if (checkExtraFrames)\n {\n if (Status == Status.Ended)\n return AVERROR_EOF;\n\n if (DecodeFrameNextInternal() == 0)\n return 0;\n\n if (Demuxer.Status == Status.Ended && demuxer.VideoPackets.Count == 0 && Frames.IsEmpty)\n {\n Stop();\n Status = Status.Ended;\n return AVERROR_EOF;\n }\n\n checkExtraFrames = false;\n }\n\n while (true)\n {\n ret = demuxer.GetNextVideoPacket();\n if (ret != 0)\n {\n if (demuxer.Status != Status.Ended)\n return ret;\n\n // Drain\n ret = avcodec_send_packet(codecCtx, demuxer.packet);\n av_packet_unref(demuxer.packet);\n\n if (ret != 0)\n return AVERROR_EOF;\n\n checkExtraFrames = true;\n return DecodeFrameNext();\n }\n\n if (keyPacketRequired)\n {\n if (demuxer.packet->flags.HasFlag(PktFlags.Key))\n keyPacketRequired = false;\n else\n {\n if (CanWarn) Log.Warn(\"Ignoring non-key packet\");\n av_packet_unref(demuxer.packet);\n continue;\n }\n }\n\n ret = avcodec_send_packet(codecCtx, demuxer.packet);\n\n if (swFallback) // Should use 'global' packet to reset it in get_format (same packet should use also from DecoderContext)\n {\n SWFallback();\n ret = avcodec_send_packet(codecCtx, demuxer.packet);\n }\n\n av_packet_unref(demuxer.packet);\n\n if (ret != 0 && ret != AVERROR(EAGAIN))\n {\n if (CanWarn) Log.Warn($\"{FFmpegEngine.ErrorCodeToMsg(ret)} ({ret})\");\n\n if (allowedErrors-- < 1)\n { Log.Error(\"Too many errors!\"); return ret; }\n\n continue;\n }\n\n if (DecodeFrameNextInternal() == 0)\n {\n checkExtraFrames = true;\n return 0;\n }\n }\n\n }\n private int DecodeFrameNextInternal()\n {\n int ret = avcodec_receive_frame(codecCtx, frame);\n if (ret != 0) { av_frame_unref(frame); return ret; }\n\n if (frame->best_effort_timestamp != AV_NOPTS_VALUE)\n frame->pts = frame->best_effort_timestamp;\n\n else if (frame->pts == AV_NOPTS_VALUE)\n {\n if (!VideoStream.FixTimestamps)\n {\n av_frame_unref(frame);\n\n return DecodeFrameNextInternal();\n }\n\n frame->pts = lastFixedPts + VideoStream.StartTimePts;\n lastFixedPts += av_rescale_q(VideoStream.FrameDuration / 10, Engine.FFmpeg.AV_TIMEBASE_Q, VideoStream.AVStream->time_base);\n }\n\n if (StartTime == NoTs)\n StartTime = (long)(frame->pts * VideoStream.Timebase) - demuxer.StartTime;\n\n if (!filledFromCodec) // Ensures we have a proper frame before filling from codec\n {\n ret = FillFromCodec(frame);\n if (ret == -1234)\n return -1;\n }\n\n return 0;\n }\n\n #region Dispose\n public void DisposeFrames()\n {\n while (!Frames.IsEmpty)\n {\n Frames.TryDequeue(out var frame);\n DisposeFrame(frame);\n }\n\n DisposeFramesReverse();\n }\n private void DisposeFramesReverse()\n {\n while (!curReverseVideoStack.IsEmpty)\n {\n curReverseVideoStack.TryPop(out var t2);\n for (int i = 0; i recCompleted;\n Remuxer curRecorder;\n bool recKeyPacketRequired;\n internal bool isRecording;\n\n internal void StartRecording(Remuxer remuxer)\n {\n if (Disposed || isRecording) return;\n\n StartRecordTime = AV_NOPTS_VALUE;\n curRecorder = remuxer;\n recKeyPacketRequired= false;\n isRecording = true;\n }\n internal void StopRecording() => isRecording = false;\n #endregion\n\n #region TODO Decoder Profiles\n\n /* Use the same as FFmpeg\n * https://github.com/FFmpeg/FFmpeg/blob/master/libavcodec/dxva2.c\n * https://github.com/FFmpeg/FFmpeg/blob/master/libavcodec/avcodec.h\n */\n\n //internal enum DecoderProfiles\n //{\n // DXVA_ModeMPEG2and1_VLD,\n // DXVA_ModeMPEG1_VLD,\n // DXVA2_ModeMPEG2_VLD,\n // DXVA2_ModeMPEG2_IDCT,\n // DXVA2_ModeMPEG2_MoComp,\n // DXVA_ModeH264_A,\n // DXVA_ModeH264_B,\n // DXVA_ModeH264_C,\n // DXVA_ModeH264_D,\n // DXVA_ModeH264_E,\n // DXVA_ModeH264_F,\n // DXVA_ModeH264_VLD_Stereo_Progressive_NoFGT,\n // DXVA_ModeH264_VLD_Stereo_NoFGT,\n // DXVA_ModeH264_VLD_Multiview_NoFGT,\n // DXVA_ModeWMV8_A,\n // DXVA_ModeWMV8_B,\n // DXVA_ModeWMV9_A,\n // DXVA_ModeWMV9_B,\n // DXVA_ModeWMV9_C,\n // DXVA_ModeVC1_A,\n // DXVA_ModeVC1_B,\n // DXVA_ModeVC1_C,\n // DXVA_ModeVC1_D,\n // DXVA_ModeVC1_D2010,\n // DXVA_ModeMPEG4pt2_VLD_Simple,\n // DXVA_ModeMPEG4pt2_VLD_AdvSimple_NoGMC,\n // DXVA_ModeMPEG4pt2_VLD_AdvSimple_GMC,\n // DXVA_ModeHEVC_VLD_Main,\n // DXVA_ModeHEVC_VLD_Main10,\n // DXVA_ModeVP8_VLD,\n // DXVA_ModeVP9_VLD_Profile0,\n // DXVA_ModeVP9_VLD_10bit_Profile2,\n // DXVA_ModeMPEG1_A,\n // DXVA_ModeMPEG2_A,\n // DXVA_ModeMPEG2_B,\n // DXVA_ModeMPEG2_C,\n // DXVA_ModeMPEG2_D,\n // DXVA_ModeH261_A,\n // DXVA_ModeH261_B,\n // DXVA_ModeH263_A,\n // DXVA_ModeH263_B,\n // DXVA_ModeH263_C,\n // DXVA_ModeH263_D,\n // DXVA_ModeH263_E,\n // DXVA_ModeH263_F,\n // DXVA_ModeH264_VLD_WithFMOASO_NoFGT,\n // DXVA_ModeH264_VLD_Multiview,\n // DXVADDI_Intel_ModeH264_A,\n // DXVADDI_Intel_ModeH264_C,\n // DXVA_Intel_H264_NoFGT_ClearVideo,\n // DXVA_ModeH264_VLD_NoFGT_Flash,\n // DXVA_Intel_VC1_ClearVideo,\n // DXVA_Intel_VC1_ClearVideo_2,\n // DXVA_nVidia_MPEG4_ASP,\n // DXVA_ModeMPEG4pt2_VLD_AdvSimple_Avivo,\n // DXVA_ModeHEVC_VLD_Main_Intel,\n // DXVA_ModeHEVC_VLD_Main10_Intel,\n // DXVA_ModeHEVC_VLD_Main12_Intel,\n // DXVA_ModeHEVC_VLD_Main422_10_Intel,\n // DXVA_ModeHEVC_VLD_Main422_12_Intel,\n // DXVA_ModeHEVC_VLD_Main444_Intel,\n // DXVA_ModeHEVC_VLD_Main444_10_Intel,\n // DXVA_ModeHEVC_VLD_Main444_12_Intel,\n // DXVA_ModeH264_VLD_SVC_Scalable_Baseline,\n // DXVA_ModeH264_VLD_SVC_Restricted_Scalable_Baseline,\n // DXVA_ModeH264_VLD_SVC_Scalable_High,\n // DXVA_ModeH264_VLD_SVC_Restricted_Scalable_High_Progressive,\n // DXVA_ModeVP9_VLD_Intel,\n // DXVA_ModeAV1_VLD_Profile0,\n // DXVA_ModeAV1_VLD_Profile1,\n // DXVA_ModeAV1_VLD_Profile2,\n // DXVA_ModeAV1_VLD_12bit_Profile2,\n // DXVA_ModeAV1_VLD_12bit_Profile2_420\n //}\n //internal static Dictionary DXVADecoderProfiles = new()\n //{\n // { new(0x86695f12, 0x340e, 0x4f04, 0x9f, 0xd3, 0x92, 0x53, 0xdd, 0x32, 0x74, 0x60), DecoderProfiles.DXVA_ModeMPEG2and1_VLD },\n // { new(0x6f3ec719, 0x3735, 0x42cc, 0x80, 0x63, 0x65, 0xcc, 0x3c, 0xb3, 0x66, 0x16), DecoderProfiles.DXVA_ModeMPEG1_VLD },\n // { new(0xee27417f, 0x5e28,0x4e65, 0xbe, 0xea, 0x1d, 0x26, 0xb5, 0x08, 0xad, 0xc9), DecoderProfiles.DXVA2_ModeMPEG2_VLD },\n // { new(0xbf22ad00, 0x03ea,0x4690, 0x80, 0x77, 0x47, 0x33, 0x46, 0x20, 0x9b, 0x7e), DecoderProfiles.DXVA2_ModeMPEG2_IDCT },\n // { new(0xe6a9f44b, 0x61b0,0x4563, 0x9e, 0xa4, 0x63, 0xd2, 0xa3, 0xc6, 0xfe, 0x66), DecoderProfiles.DXVA2_ModeMPEG2_MoComp },\n // { new(0x1b81be64, 0xa0c7,0x11d3, 0xb9, 0x84, 0x00, 0xc0, 0x4f, 0x2e, 0x73, 0xc5), DecoderProfiles.DXVA_ModeH264_A },\n // { new(0x1b81be65, 0xa0c7,0x11d3, 0xb9, 0x84, 0x00, 0xc0, 0x4f, 0x2e, 0x73, 0xc5), DecoderProfiles.DXVA_ModeH264_B },\n // { new(0x1b81be66, 0xa0c7,0x11d3, 0xb9, 0x84, 0x00, 0xc0, 0x4f, 0x2e, 0x73, 0xc5), DecoderProfiles.DXVA_ModeH264_C },\n // { new(0x1b81be67, 0xa0c7,0x11d3, 0xb9, 0x84, 0x00, 0xc0, 0x4f, 0x2e, 0x73, 0xc5), DecoderProfiles.DXVA_ModeH264_D },\n // { new(0x1b81be68, 0xa0c7,0x11d3, 0xb9, 0x84, 0x00, 0xc0, 0x4f, 0x2e, 0x73, 0xc5), DecoderProfiles.DXVA_ModeH264_E },\n // { new(0x1b81be69, 0xa0c7,0x11d3, 0xb9, 0x84, 0x00, 0xc0, 0x4f, 0x2e, 0x73, 0xc5), DecoderProfiles.DXVA_ModeH264_F },\n // { new(0xd79be8da, 0x0cf1,0x4c81, 0xb8, 0x2a, 0x69, 0xa4, 0xe2, 0x36, 0xf4, 0x3d), DecoderProfiles.DXVA_ModeH264_VLD_Stereo_Progressive_NoFGT },\n // { new(0xf9aaccbb, 0xc2b6,0x4cfc, 0x87, 0x79, 0x57, 0x07, 0xb1, 0x76, 0x05, 0x52), DecoderProfiles.DXVA_ModeH264_VLD_Stereo_NoFGT },\n // { new(0x705b9d82, 0x76cf,0x49d6, 0xb7, 0xe6, 0xac, 0x88, 0x72, 0xdb, 0x01, 0x3c), DecoderProfiles.DXVA_ModeH264_VLD_Multiview_NoFGT },\n // { new(0x1b81be80, 0xa0c7,0x11d3, 0xb9, 0x84, 0x00, 0xc0, 0x4f, 0x2e, 0x73, 0xc5), DecoderProfiles.DXVA_ModeWMV8_A },\n // { new(0x1b81be81, 0xa0c7,0x11d3, 0xb9, 0x84, 0x00, 0xc0, 0x4f, 0x2e, 0x73, 0xc5), DecoderProfiles.DXVA_ModeWMV8_B },\n // { new(0x1b81be90, 0xa0c7,0x11d3, 0xb9, 0x84, 0x00, 0xc0, 0x4f, 0x2e, 0x73, 0xc5), DecoderProfiles.DXVA_ModeWMV9_A },\n // { new(0x1b81be91, 0xa0c7,0x11d3, 0xb9, 0x84, 0x00, 0xc0, 0x4f, 0x2e, 0x73, 0xc5), DecoderProfiles.DXVA_ModeWMV9_B },\n // { new(0x1b81be94, 0xa0c7,0x11d3, 0xb9, 0x84, 0x00, 0xc0, 0x4f, 0x2e, 0x73, 0xc5), DecoderProfiles.DXVA_ModeWMV9_C },\n // { new(0x1b81beA0, 0xa0c7,0x11d3, 0xb9, 0x84, 0x00, 0xc0, 0x4f, 0x2e, 0x73, 0xc5), DecoderProfiles.DXVA_ModeVC1_A },\n // { new(0x1b81beA1, 0xa0c7,0x11d3, 0xb9, 0x84, 0x00, 0xc0, 0x4f, 0x2e, 0x73, 0xc5), DecoderProfiles.DXVA_ModeVC1_B },\n // { new(0x1b81beA2, 0xa0c7,0x11d3, 0xb9, 0x84, 0x00, 0xc0, 0x4f, 0x2e, 0x73, 0xc5), DecoderProfiles.DXVA_ModeVC1_C },\n // { new(0x1b81beA3, 0xa0c7,0x11d3, 0xb9, 0x84, 0x00, 0xc0, 0x4f, 0x2e, 0x73, 0xc5), DecoderProfiles.DXVA_ModeVC1_D },\n // { new(0x1b81bea4, 0xa0c7,0x11d3, 0xb9, 0x84, 0x00, 0xc0, 0x4f, 0x2e, 0x73, 0xc5), DecoderProfiles.DXVA_ModeVC1_D2010 },\n // { new(0xefd64d74, 0xc9e8,0x41d7, 0xa5, 0xe9, 0xe9, 0xb0, 0xe3, 0x9f, 0xa3, 0x19), DecoderProfiles.DXVA_ModeMPEG4pt2_VLD_Simple },\n // { new(0xed418a9f, 0x010d,0x4eda, 0x9a, 0xe3, 0x9a, 0x65, 0x35, 0x8d, 0x8d, 0x2e), DecoderProfiles.DXVA_ModeMPEG4pt2_VLD_AdvSimple_NoGMC },\n // { new(0xab998b5b, 0x4258,0x44a9, 0x9f, 0xeb, 0x94, 0xe5, 0x97, 0xa6, 0xba, 0xae), DecoderProfiles.DXVA_ModeMPEG4pt2_VLD_AdvSimple_GMC },\n // { new(0x5b11d51b, 0x2f4c,0x4452, 0xbc, 0xc3, 0x09, 0xf2, 0xa1, 0x16, 0x0c, 0xc0), DecoderProfiles.DXVA_ModeHEVC_VLD_Main },\n // { new(0x107af0e0, 0xef1a,0x4d19, 0xab, 0xa8, 0x67, 0xa1, 0x63, 0x07, 0x3d, 0x13), DecoderProfiles.DXVA_ModeHEVC_VLD_Main10 },\n // { new(0x90b899ea, 0x3a62,0x4705, 0x88, 0xb3, 0x8d, 0xf0, 0x4b, 0x27, 0x44, 0xe7), DecoderProfiles.DXVA_ModeVP8_VLD },\n // { new(0x463707f8, 0xa1d0,0x4585, 0x87, 0x6d, 0x83, 0xaa, 0x6d, 0x60, 0xb8, 0x9e), DecoderProfiles.DXVA_ModeVP9_VLD_Profile0 },\n // { new(0xa4c749ef, 0x6ecf,0x48aa, 0x84, 0x48, 0x50, 0xa7, 0xa1, 0x16, 0x5f, 0xf7), DecoderProfiles.DXVA_ModeVP9_VLD_10bit_Profile2 },\n // { new(0x1b81be09, 0xa0c7, 0x11d3, 0xb9, 0x84, 0x00, 0xc0, 0x4f, 0x2e, 0x73, 0xc5), DecoderProfiles.DXVA_ModeMPEG1_A },\n // { new(0x1b81be0A, 0xa0c7, 0x11d3, 0xb9, 0x84, 0x00, 0xc0, 0x4f, 0x2e, 0x73, 0xc5), DecoderProfiles.DXVA_ModeMPEG2_A },\n // { new(0x1b81be0B, 0xa0c7, 0x11d3, 0xb9, 0x84, 0x00, 0xc0, 0x4f, 0x2e, 0x73, 0xc5), DecoderProfiles.DXVA_ModeMPEG2_B },\n // { new(0x1b81be0C, 0xa0c7, 0x11d3, 0xb9, 0x84, 0x00, 0xc0, 0x4f, 0x2e, 0x73, 0xc5), DecoderProfiles.DXVA_ModeMPEG2_C },\n // { new(0x1b81be0D, 0xa0c7, 0x11d3, 0xb9, 0x84, 0x00, 0xc0, 0x4f, 0x2e, 0x73, 0xc5), DecoderProfiles.DXVA_ModeMPEG2_D },\n // { new(0x1b81be01, 0xa0c7, 0x11d3, 0xb9, 0x84, 0x00, 0xc0, 0x4f, 0x2e, 0x73, 0xc5), DecoderProfiles.DXVA_ModeH261_A },\n // { new(0x1b81be02, 0xa0c7, 0x11d3, 0xb9, 0x84, 0x00, 0xc0, 0x4f, 0x2e, 0x73, 0xc5), DecoderProfiles.DXVA_ModeH261_B },\n // { new(0x1b81be03, 0xa0c7, 0x11d3, 0xb9, 0x84, 0x00, 0xc0, 0x4f, 0x2e, 0x73, 0xc5), DecoderProfiles.DXVA_ModeH263_A },\n // { new(0x1b81be04, 0xa0c7, 0x11d3, 0xb9, 0x84, 0x00, 0xc0, 0x4f, 0x2e, 0x73, 0xc5), DecoderProfiles.DXVA_ModeH263_B },\n // { new(0x1b81be05, 0xa0c7, 0x11d3, 0xb9, 0x84, 0x00, 0xc0, 0x4f, 0x2e, 0x73, 0xc5), DecoderProfiles.DXVA_ModeH263_C },\n // { new(0x1b81be06, 0xa0c7, 0x11d3, 0xb9, 0x84, 0x00, 0xc0, 0x4f, 0x2e, 0x73, 0xc5), DecoderProfiles.DXVA_ModeH263_D },\n // { new(0x1b81be07, 0xa0c7, 0x11d3, 0xb9, 0x84, 0x00, 0xc0, 0x4f, 0x2e, 0x73, 0xc5), DecoderProfiles.DXVA_ModeH263_E },\n // { new(0x1b81be08, 0xa0c7, 0x11d3, 0xb9, 0x84, 0x00, 0xc0, 0x4f, 0x2e, 0x73, 0xc5), DecoderProfiles.DXVA_ModeH263_F },\n // { new(0xd5f04ff9, 0x3418, 0x45d8, 0x95, 0x61, 0x32, 0xa7, 0x6a, 0xae, 0x2d, 0xdd), DecoderProfiles.DXVA_ModeH264_VLD_WithFMOASO_NoFGT },\n // { new(0x9901CCD3, 0xca12, 0x4b7e, 0x86, 0x7a, 0xe2, 0x22, 0x3d, 0x92, 0x55, 0xc3), DecoderProfiles.DXVA_ModeH264_VLD_Multiview },\n // { new(0x604F8E64, 0x4951, 0x4c54, 0x88, 0xFE, 0xAB, 0xD2, 0x5C, 0x15, 0xB3, 0xD6), DecoderProfiles.DXVADDI_Intel_ModeH264_A },\n // { new(0x604F8E66, 0x4951, 0x4c54, 0x88, 0xFE, 0xAB, 0xD2, 0x5C, 0x15, 0xB3, 0xD6), DecoderProfiles.DXVADDI_Intel_ModeH264_C },\n // { new(0x604F8E68, 0x4951, 0x4c54, 0x88, 0xFE, 0xAB, 0xD2, 0x5C, 0x15, 0xB3, 0xD6), DecoderProfiles.DXVA_Intel_H264_NoFGT_ClearVideo },\n // { new(0x4245F676, 0x2BBC, 0x4166, 0xa0, 0xBB, 0x54, 0xE7, 0xB8, 0x49, 0xC3, 0x80), DecoderProfiles.DXVA_ModeH264_VLD_NoFGT_Flash },\n // { new(0xBCC5DB6D, 0xA2B6, 0x4AF0, 0xAC, 0xE4, 0xAD, 0xB1, 0xF7, 0x87, 0xBC, 0x89), DecoderProfiles.DXVA_Intel_VC1_ClearVideo },\n // { new(0xE07EC519, 0xE651, 0x4CD6, 0xAC, 0x84, 0x13, 0x70, 0xCC, 0xEE, 0xC8, 0x51), DecoderProfiles.DXVA_Intel_VC1_ClearVideo_2 },\n // { new(0x9947EC6F, 0x689B, 0x11DC, 0xA3, 0x20, 0x00, 0x19, 0xDB, 0xBC, 0x41, 0x84), DecoderProfiles.DXVA_nVidia_MPEG4_ASP },\n // { new(0x7C74ADC6, 0xe2ba, 0x4ade, 0x86, 0xde, 0x30, 0xbe, 0xab, 0xb4, 0x0c, 0xc1), DecoderProfiles.DXVA_ModeMPEG4pt2_VLD_AdvSimple_Avivo },\n // { new(0x8c56eb1e, 0x2b47, 0x466f, 0x8d, 0x33, 0x7d, 0xbc, 0xd6, 0x3f, 0x3d, 0xf2), DecoderProfiles.DXVA_ModeHEVC_VLD_Main_Intel },\n // { new(0x75fc75f7, 0xc589, 0x4a07, 0xa2, 0x5b, 0x72, 0xe0, 0x3b, 0x03, 0x83, 0xb3), DecoderProfiles.DXVA_ModeHEVC_VLD_Main10_Intel },\n // { new(0x8ff8a3aa, 0xc456, 0x4132, 0xb6, 0xef, 0x69, 0xd9, 0xdd, 0x72, 0x57, 0x1d), DecoderProfiles.DXVA_ModeHEVC_VLD_Main12_Intel },\n // { new(0xe484dcb8, 0xcac9, 0x4859, 0x99, 0xf5, 0x5c, 0x0d, 0x45, 0x06, 0x90, 0x89), DecoderProfiles.DXVA_ModeHEVC_VLD_Main422_10_Intel },\n // { new(0xc23dd857, 0x874b, 0x423c, 0xb6, 0xe0, 0x82, 0xce, 0xaa, 0x9b, 0x11, 0x8a), DecoderProfiles.DXVA_ModeHEVC_VLD_Main422_12_Intel },\n // { new(0x41a5af96, 0xe415, 0x4b0c, 0x9d, 0x03, 0x90, 0x78, 0x58, 0xe2, 0x3e, 0x78), DecoderProfiles.DXVA_ModeHEVC_VLD_Main444_Intel },\n // { new(0x6a6a81ba, 0x912a, 0x485d, 0xb5, 0x7f, 0xcc, 0xd2, 0xd3, 0x7b, 0x8d, 0x94), DecoderProfiles.DXVA_ModeHEVC_VLD_Main444_10_Intel },\n // { new(0x5b08e35d, 0x0c66, 0x4c51, 0xa6, 0xf1, 0x89, 0xd0, 0x0c, 0xb2, 0xc1, 0x97), DecoderProfiles.DXVA_ModeHEVC_VLD_Main444_12_Intel },\n // { new(0xc30700c4, 0xe384, 0x43e0, 0xb9, 0x82, 0x2d, 0x89, 0xee, 0x7f, 0x77, 0xc4), DecoderProfiles.DXVA_ModeH264_VLD_SVC_Scalable_Baseline },\n // { new(0x9b8175d4, 0xd670, 0x4cf2, 0xa9, 0xf0, 0xfa, 0x56, 0xdf, 0x71, 0xa1, 0xae), DecoderProfiles.DXVA_ModeH264_VLD_SVC_Restricted_Scalable_Baseline },\n // { new(0x728012c9, 0x66a8, 0x422f, 0x97, 0xe9, 0xb5, 0xe3, 0x9b, 0x51, 0xc0, 0x53), DecoderProfiles.DXVA_ModeH264_VLD_SVC_Scalable_High },\n // { new(0x8efa5926, 0xbd9e, 0x4b04, 0x8b, 0x72, 0x8f, 0x97, 0x7d, 0xc4, 0x4c, 0x36), DecoderProfiles.DXVA_ModeH264_VLD_SVC_Restricted_Scalable_High_Progressive },\n // { new(0x76988a52, 0xdf13, 0x419a, 0x8e, 0x64, 0xff, 0xcf, 0x4a, 0x33, 0x6c, 0xf5), DecoderProfiles.DXVA_ModeVP9_VLD_Intel },\n // { new(0xb8be4ccb, 0xcf53, 0x46ba, 0x8d, 0x59, 0xd6, 0xb8, 0xa6, 0xda, 0x5d, 0x2a), DecoderProfiles.DXVA_ModeAV1_VLD_Profile0 },\n // { new(0x6936ff0f, 0x45b1, 0x4163, 0x9c, 0xc1, 0x64, 0x6e, 0xf6, 0x94, 0x61, 0x08), DecoderProfiles.DXVA_ModeAV1_VLD_Profile1 },\n // { new(0x0c5f2aa1, 0xe541, 0x4089, 0xbb, 0x7b, 0x98, 0x11, 0x0a, 0x19, 0xd7, 0xc8), DecoderProfiles.DXVA_ModeAV1_VLD_Profile2 },\n // { new(0x17127009, 0xa00f, 0x4ce1, 0x99, 0x4e, 0xbf, 0x40, 0x81, 0xf6, 0xf3, 0xf0), DecoderProfiles.DXVA_ModeAV1_VLD_12bit_Profile2 },\n // { new(0x2d80bed6, 0x9cac, 0x4835, 0x9e, 0x91, 0x32, 0x7b, 0xbc, 0x4f, 0x9e, 0xe8), DecoderProfiles.DXVA_ModeAV1_VLD_12bit_Profile2_420 },\n\n\n //};\n //internal static Dictionary DXVADecoderProfilesDesc = new()\n //{\n // { DecoderProfiles.DXVA_ModeMPEG1_A, \"MPEG-1 decoder, restricted profile A\" },\n // { DecoderProfiles.DXVA_ModeMPEG2_A, \"MPEG-2 decoder, restricted profile A\" },\n // { DecoderProfiles.DXVA_ModeMPEG2_B, \"MPEG-2 decoder, restricted profile B\" },\n // { DecoderProfiles.DXVA_ModeMPEG2_C, \"MPEG-2 decoder, restricted profile C\" },\n // { DecoderProfiles.DXVA_ModeMPEG2_D, \"MPEG-2 decoder, restricted profile D\" },\n // { DecoderProfiles.DXVA2_ModeMPEG2_VLD, \"MPEG-2 variable-length decoder\" },\n // { DecoderProfiles.DXVA_ModeMPEG2and1_VLD, \"MPEG-2 & MPEG-1 variable-length decoder\" },\n // { DecoderProfiles.DXVA2_ModeMPEG2_MoComp, \"MPEG-2 motion compensation\" },\n // { DecoderProfiles.DXVA2_ModeMPEG2_IDCT, \"MPEG-2 inverse discrete cosine transform\" },\n // { DecoderProfiles.DXVA_ModeMPEG1_VLD, \"MPEG-1 variable-length decoder, no D pictures\" },\n // { DecoderProfiles.DXVA_ModeH264_F, \"H.264 variable-length decoder, film grain technology\" },\n // { DecoderProfiles.DXVA_ModeH264_E, \"H.264 variable-length decoder, no film grain technology\" },\n // { DecoderProfiles.DXVA_Intel_H264_NoFGT_ClearVideo, \"H.264 variable-length decoder, no film grain technology (Intel ClearVideo)\" },\n // { DecoderProfiles.DXVA_ModeH264_VLD_WithFMOASO_NoFGT, \"H.264 variable-length decoder, no film grain technology, FMO/ASO\" },\n // { DecoderProfiles.DXVA_ModeH264_VLD_NoFGT_Flash, \"H.264 variable-length decoder, no film grain technology, Flash\" },\n // { DecoderProfiles.DXVA_ModeH264_D, \"H.264 inverse discrete cosine transform, film grain technology\" },\n // { DecoderProfiles.DXVA_ModeH264_C, \"H.264 inverse discrete cosine transform, no film grain technology\" },\n // { DecoderProfiles.DXVADDI_Intel_ModeH264_C, \"H.264 inverse discrete cosine transform, no film grain technology (Intel)\" },\n // { DecoderProfiles.DXVA_ModeH264_B, \"H.264 motion compensation, film grain technology\" },\n // { DecoderProfiles.DXVA_ModeH264_A, \"H.264 motion compensation, no film grain technology\" },\n // { DecoderProfiles.DXVADDI_Intel_ModeH264_A, \"H.264 motion compensation, no film grain technology (Intel)\" },\n // { DecoderProfiles.DXVA_ModeH264_VLD_Stereo_Progressive_NoFGT, \"H.264 stereo high profile, mbs flag set\" },\n // { DecoderProfiles.DXVA_ModeH264_VLD_Stereo_NoFGT, \"H.264 stereo high profile\" },\n // { DecoderProfiles.DXVA_ModeH264_VLD_Multiview_NoFGT, \"H.264 multiview high profile\" },\n // { DecoderProfiles.DXVA_ModeH264_VLD_SVC_Scalable_Baseline, \"H.264 scalable video coding, Scalable Baseline Profile\" },\n // { DecoderProfiles.DXVA_ModeH264_VLD_SVC_Restricted_Scalable_Baseline, \"H.264 scalable video coding, Scalable Constrained Baseline Profile\" },\n // { DecoderProfiles.DXVA_ModeH264_VLD_SVC_Scalable_High, \"H.264 scalable video coding, Scalable High Profile\" },\n // { DecoderProfiles.DXVA_ModeH264_VLD_SVC_Restricted_Scalable_High_Progressive, \"H.264 scalable video coding, Scalable Constrained High Profile\" },\n // { DecoderProfiles.DXVA_ModeWMV8_B, \"Windows Media Video 8 motion compensation\" },\n // { DecoderProfiles.DXVA_ModeWMV8_A, \"Windows Media Video 8 post processing\" },\n // { DecoderProfiles.DXVA_ModeWMV9_C, \"Windows Media Video 9 IDCT\" },\n // { DecoderProfiles.DXVA_ModeWMV9_B, \"Windows Media Video 9 motion compensation\" },\n // { DecoderProfiles.DXVA_ModeWMV9_A, \"Windows Media Video 9 post processing\" },\n // { DecoderProfiles.DXVA_ModeVC1_D, \"VC-1 variable-length decoder\" },\n // { DecoderProfiles.DXVA_ModeVC1_D2010, \"VC-1 variable-length decoder\" },\n // { DecoderProfiles.DXVA_Intel_VC1_ClearVideo_2, \"VC-1 variable-length decoder 2 (Intel)\" },\n // { DecoderProfiles.DXVA_Intel_VC1_ClearVideo, \"VC-1 variable-length decoder (Intel)\" },\n // { DecoderProfiles.DXVA_ModeVC1_C, \"VC-1 inverse discrete cosine transform\" },\n // { DecoderProfiles.DXVA_ModeVC1_B, \"VC-1 motion compensation\" },\n // { DecoderProfiles.DXVA_ModeVC1_A, \"VC-1 post processing\" },\n // { DecoderProfiles.DXVA_nVidia_MPEG4_ASP, \"MPEG-4 Part 2 nVidia bitstream decoder\" },\n // { DecoderProfiles.DXVA_ModeMPEG4pt2_VLD_Simple, \"MPEG-4 Part 2 variable-length decoder, Simple Profile\" },\n // { DecoderProfiles.DXVA_ModeMPEG4pt2_VLD_AdvSimple_NoGMC, \"MPEG-4 Part 2 variable-length decoder, Simple&Advanced Profile, no GMC\" },\n // { DecoderProfiles.DXVA_ModeMPEG4pt2_VLD_AdvSimple_GMC, \"MPEG-4 Part 2 variable-length decoder, Simple&Advanced Profile, GMC\" },\n // { DecoderProfiles.DXVA_ModeMPEG4pt2_VLD_AdvSimple_Avivo, \"MPEG-4 Part 2 variable-length decoder, Simple&Advanced Profile, Avivo\" },\n // { DecoderProfiles.DXVA_ModeHEVC_VLD_Main_Intel, \"HEVC Main profile (Intel)\" },\n // { DecoderProfiles.DXVA_ModeHEVC_VLD_Main10_Intel, \"HEVC Main 10 profile (Intel)\" },\n // { DecoderProfiles.DXVA_ModeHEVC_VLD_Main12_Intel, \"HEVC Main profile 4:2:2 Range Extension (Intel)\" },\n // { DecoderProfiles.DXVA_ModeHEVC_VLD_Main422_10_Intel, \"HEVC Main 10 profile 4:2:2 Range Extension (Intel)\" },\n // { DecoderProfiles.DXVA_ModeHEVC_VLD_Main422_12_Intel, \"HEVC Main 12 profile 4:2:2 Range Extension (Intel)\" },\n // { DecoderProfiles.DXVA_ModeHEVC_VLD_Main444_Intel, \"HEVC Main profile 4:4:4 Range Extension (Intel)\" },\n // { DecoderProfiles.DXVA_ModeHEVC_VLD_Main444_10_Intel, \"HEVC Main 10 profile 4:4:4 Range Extension (Intel)\" },\n // { DecoderProfiles.DXVA_ModeHEVC_VLD_Main444_12_Intel, \"HEVC Main 12 profile 4:4:4 Range Extension (Intel)\" },\n // { DecoderProfiles.DXVA_ModeHEVC_VLD_Main, \"HEVC Main profile\" },\n // { DecoderProfiles.DXVA_ModeHEVC_VLD_Main10, \"HEVC Main 10 profile\" },\n // { DecoderProfiles.DXVA_ModeH261_A, \"H.261 decoder, restricted profile A\" },\n // { DecoderProfiles.DXVA_ModeH261_B, \"H.261 decoder, restricted profile B\" },\n // { DecoderProfiles.DXVA_ModeH263_A, \"H.263 decoder, restricted profile A\" },\n // { DecoderProfiles.DXVA_ModeH263_B, \"H.263 decoder, restricted profile B\" },\n // { DecoderProfiles.DXVA_ModeH263_C, \"H.263 decoder, restricted profile C\" },\n // { DecoderProfiles.DXVA_ModeH263_D, \"H.263 decoder, restricted profile D\" },\n // { DecoderProfiles.DXVA_ModeH263_E, \"H.263 decoder, restricted profile E\" },\n // { DecoderProfiles.DXVA_ModeH263_F, \"H.263 decoder, restricted profile F\" },\n // { DecoderProfiles.DXVA_ModeVP8_VLD, \"VP8\" },\n // { DecoderProfiles.DXVA_ModeVP9_VLD_Profile0, \"VP9 profile 0\" },\n // { DecoderProfiles.DXVA_ModeVP9_VLD_10bit_Profile2, \"VP9 profile\" },\n // { DecoderProfiles.DXVA_ModeVP9_VLD_Intel, \"VP9 profile Intel\" },\n // { DecoderProfiles.DXVA_ModeAV1_VLD_Profile0, \"AV1 Main profile\" },\n // { DecoderProfiles.DXVA_ModeAV1_VLD_Profile1, \"AV1 High profile\" },\n //};\n #endregion\n}\n"], ["/LLPlayer/FlyleafLib/MediaFramework/MediaDecoder/AudioDecoder.cs", "using System.Collections.Concurrent;\nusing System.Threading;\n\nusing FlyleafLib.MediaFramework.MediaStream;\nusing FlyleafLib.MediaFramework.MediaFrame;\nusing FlyleafLib.MediaFramework.MediaRemuxer;\n\nusing static FlyleafLib.Logger;\n\nnamespace FlyleafLib.MediaFramework.MediaDecoder;\n\n/* TODO\n *\n * Circular Buffer\n * - Safe re-allocation and check also actual frames in queue (as now during draining we can overwrite them)\n * - Locking with Audio.AddSamples during re-allocation and re-write old data to the new buffer and update the pointers in queue\n *\n * Filters\n * - Note: Performance issue (for seek/speed change). We can't drain the buffersrc and re-use the filtergraph without re-initializing it, is not supported\n * - Check if av_buffersrc_get_nb_failed_requests required\n * - Add Config for filter threads?\n * - Review Access Violation issue with dynaudnorm/loudnorm filters in combination with atempo (when changing speed to fast?)\n * - Use multiple atempo for better quality (for < 0.5 and > 2, use eg. 2 of sqrt(X) * sqrt(X) to achive this)\n * - Review locks / recode RunInternal to be able to continue from where it stopped (eg. ProcessFilter)\n *\n * Custom Frames Queue to notify when the queue is not full anymore (to avoid thread sleep which can cause delays)\n * Support more output formats/channels/sampleRates (and currently output to 32-bit, sample rate to 48Khz and not the same as input? - should calculate possible delays)\n */\n\npublic unsafe partial class AudioDecoder : DecoderBase\n{\n public AudioStream AudioStream => (AudioStream) Stream;\n public readonly\n VideoDecoder VideoDecoder;\n public ConcurrentQueue\n Frames { get; protected set; } = new();\n\n static AVSampleFormat AOutSampleFormat = AVSampleFormat.S16;\n static string AOutSampleFormatStr = av_get_sample_fmt_name(AOutSampleFormat);\n static AVChannelLayout AOutChannelLayout = AV_CHANNEL_LAYOUT_STEREO;// new() { order = AVChannelOrder.Native, nb_channels = 2, u = new AVChannelLayout_u() { mask = AVChannel.for AV_CH_FRONT_LEFT | AV_CH_FRONT_RIGHT} };\n static int AOutChannels = AOutChannelLayout.nb_channels;\n static int ASampleBytes = av_get_bytes_per_sample(AOutSampleFormat) * AOutChannels;\n\n public readonly object CircularBufferLocker= new();\n internal Action CBufAlloc; // Informs Audio player to clear buffer pointers to avoid access violation\n static int cBufTimesSize = 4;\n int cBufTimesCur = 1;\n byte[] cBuf;\n int cBufPos;\n int cBufSamples;\n internal bool resyncWithVideoRequired;\n SwrContext* swrCtx;\n\n internal long nextPts;\n double sampleRateTimebase;\n\n public AudioDecoder(Config config, int uniqueId = -1, VideoDecoder syncDecoder = null) : base(config, uniqueId)\n => VideoDecoder = syncDecoder;\n\n protected override int Setup(AVCodec* codec) => 0;\n private int SetupSwr()\n {\n int ret;\n\n DisposeSwr();\n swrCtx = swr_alloc();\n\n av_opt_set_chlayout(swrCtx, \"in_chlayout\", &codecCtx->ch_layout, 0);\n av_opt_set_int(swrCtx, \"in_sample_rate\", codecCtx->sample_rate, 0);\n av_opt_set_sample_fmt(swrCtx, \"in_sample_fmt\", codecCtx->sample_fmt, 0);\n\n fixed(AVChannelLayout* ptr = &AOutChannelLayout)\n av_opt_set_chlayout(swrCtx, \"out_chlayout\", ptr, 0);\n av_opt_set_int(swrCtx, \"out_sample_rate\", codecCtx->sample_rate, 0);\n av_opt_set_sample_fmt(swrCtx, \"out_sample_fmt\", AOutSampleFormat, 0);\n\n ret = swr_init(swrCtx);\n if (ret < 0)\n Log.Error($\"Swr setup failed {FFmpegEngine.ErrorCodeToMsg(ret)} ({ret})\");\n\n return ret;\n }\n private void DisposeSwr()\n {\n if (swrCtx == null)\n return;\n\n swr_close(swrCtx);\n\n fixed(SwrContext** ptr = &swrCtx)\n swr_free(ptr);\n\n swrCtx = null;\n }\n\n protected override void DisposeInternal()\n {\n DisposeFrames();\n DisposeSwr();\n DisposeFilters();\n\n lock (CircularBufferLocker)\n cBuf = null;\n cBufSamples = 0;\n filledFromCodec = false;\n nextPts = AV_NOPTS_VALUE;\n }\n public void DisposeFrames() => Frames = new();\n public void Flush()\n {\n lock (lockActions)\n lock (lockCodecCtx)\n {\n if (Disposed)\n return;\n\n if (Status == Status.Ended)\n Status = Status.Stopped;\n else if (Status == Status.Draining)\n Status = Status.Stopping;\n\n resyncWithVideoRequired = !VideoDecoder.Disposed;\n nextPts = AV_NOPTS_VALUE;\n DisposeFrames();\n avcodec_flush_buffers(codecCtx);\n if (filterGraph != null)\n SetupFilters();\n }\n }\n\n protected override void RunInternal()\n {\n int ret = 0;\n int allowedErrors = Config.Decoder.MaxErrors;\n int sleepMs = Config.Decoder.MaxAudioFrames > 5 && Config.Player.MaxLatency == 0 ? 10 : 4;\n AVPacket *packet;\n\n do\n {\n // Wait until Queue not Full or Stopped\n if (Frames.Count >= Config.Decoder.MaxAudioFrames)\n {\n lock (lockStatus)\n if (Status == Status.Running)\n Status = Status.QueueFull;\n\n while (Frames.Count >= Config.Decoder.MaxAudioFrames && Status == Status.QueueFull)\n Thread.Sleep(sleepMs);\n\n lock (lockStatus)\n {\n if (Status != Status.QueueFull)\n break;\n\n Status = Status.Running;\n }\n }\n\n // While Packets Queue Empty (Ended | Quit if Demuxer stopped | Wait until we get packets)\n if (demuxer.AudioPackets.Count == 0)\n {\n CriticalArea = true;\n\n lock (lockStatus)\n if (Status == Status.Running) Status = Status.QueueEmpty;\n\n while (demuxer.AudioPackets.Count == 0 && Status == Status.QueueEmpty)\n {\n if (demuxer.Status == Status.Ended)\n {\n lock (lockStatus)\n {\n // TODO: let the demuxer push the draining packet\n Log.Debug(\"Draining\");\n Status = Status.Draining;\n var drainPacket = av_packet_alloc();\n drainPacket->data = null;\n drainPacket->size = 0;\n demuxer.AudioPackets.Enqueue(drainPacket);\n }\n\n break;\n }\n else if (!demuxer.IsRunning)\n {\n if (CanDebug) Log.Debug($\"Demuxer is not running [Demuxer Status: {demuxer.Status}]\");\n\n int retries = 5;\n\n while (retries > 0)\n {\n retries--;\n Thread.Sleep(10);\n if (demuxer.IsRunning) break;\n }\n\n lock (demuxer.lockStatus)\n lock (lockStatus)\n {\n if (demuxer.Status == Status.Pausing || demuxer.Status == Status.Paused)\n Status = Status.Pausing;\n else if (demuxer.Status != Status.Ended)\n Status = Status.Stopping;\n else\n continue;\n }\n\n break;\n }\n\n Thread.Sleep(sleepMs);\n }\n\n lock (lockStatus)\n {\n CriticalArea = false;\n if (Status != Status.QueueEmpty && Status != Status.Draining) break;\n if (Status != Status.Draining) Status = Status.Running;\n }\n }\n\n Monitor.Enter(lockCodecCtx); // restore the old lock / add interrupters similar to the demuxer\n try\n {\n if (Status == Status.Stopped)\n { Monitor.Exit(lockCodecCtx); continue; }\n\n packet = demuxer.AudioPackets.Dequeue();\n\n if (packet == null)\n { Monitor.Exit(lockCodecCtx); continue; }\n\n if (isRecording)\n {\n if (!recGotKeyframe && VideoDecoder.StartRecordTime != AV_NOPTS_VALUE && (long)(packet->pts * AudioStream.Timebase) - demuxer.StartTime > VideoDecoder.StartRecordTime)\n recGotKeyframe = true;\n\n if (recGotKeyframe)\n curRecorder.Write(av_packet_clone(packet), !OnVideoDemuxer);\n }\n\n ret = avcodec_send_packet(codecCtx, packet);\n av_packet_free(&packet);\n\n if (ret != 0 && ret != AVERROR(EAGAIN))\n {\n if (ret == AVERROR_EOF)\n {\n Status = Status.Ended;\n break;\n }\n else\n {\n allowedErrors--;\n if (CanWarn) Log.Warn($\"{FFmpegEngine.ErrorCodeToMsg(ret)} ({ret})\");\n\n if (allowedErrors == 0) { Log.Error(\"Too many errors!\"); Status = Status.Stopping; break; }\n\n Monitor.Exit(lockCodecCtx); continue;\n }\n }\n\n while (true)\n {\n ret = avcodec_receive_frame(codecCtx, frame);\n if (ret != 0)\n {\n av_frame_unref(frame);\n\n if (ret == AVERROR_EOF && filterGraph != null)\n {\n lock (lockSpeed)\n {\n DrainFilters();\n Status = Status.Ended;\n }\n }\n\n break;\n }\n\n if (frame->best_effort_timestamp != AV_NOPTS_VALUE)\n frame->pts = frame->best_effort_timestamp;\n else if (frame->pts == AV_NOPTS_VALUE)\n {\n if (nextPts == AV_NOPTS_VALUE && filledFromCodec) // Possible after seek (maybe set based on pkt_pos?)\n {\n av_frame_unref(frame);\n continue;\n }\n\n frame->pts = nextPts;\n }\n\n // We could fix it down to the demuxer based on size?\n if (frame->duration <= 0)\n frame->duration = av_rescale_q((long)(frame->nb_samples * sampleRateTimebase), Engine.FFmpeg.AV_TIMEBASE_Q, Stream.AVStream->time_base);\n\n bool codecChanged = AudioStream.SampleFormat != codecCtx->sample_fmt || AudioStream.SampleRate != codecCtx->sample_rate || AudioStream.ChannelLayout != codecCtx->ch_layout.u.mask;\n\n if (!filledFromCodec || codecChanged)\n {\n if (codecChanged && filledFromCodec)\n {\n byte[] buf = new byte[50];\n fixed (byte* bufPtr = buf)\n {\n av_channel_layout_describe(&codecCtx->ch_layout, bufPtr, (nuint)buf.Length);\n Log.Warn($\"Codec changed {AudioStream.CodecIDOrig} {AudioStream.SampleFormat} {AudioStream.SampleRate} {AudioStream.ChannelLayoutStr} => {codecCtx->codec_id} {codecCtx->sample_fmt} {codecCtx->sample_rate} {Utils.BytePtrToStringUTF8(bufPtr)}\");\n }\n }\n\n DisposeInternal();\n filledFromCodec = true;\n\n avcodec_parameters_from_context(Stream.AVStream->codecpar, codecCtx);\n AudioStream.AVStream->time_base = codecCtx->pkt_timebase;\n AudioStream.Refresh();\n resyncWithVideoRequired = !VideoDecoder.Disposed;\n sampleRateTimebase = 1000 * 1000.0 / codecCtx->sample_rate;\n nextPts = AudioStream.StartTimePts;\n\n if (frame->pts == AV_NOPTS_VALUE)\n frame->pts = nextPts;\n\n ret = SetupFiltersOrSwr();\n\n CodecChanged?.Invoke(this);\n\n if (ret != 0)\n {\n Status = Status.Stopping;\n av_frame_unref(frame);\n break;\n }\n\n if (nextPts == AV_NOPTS_VALUE)\n {\n av_frame_unref(frame);\n continue;\n }\n }\n\n if (resyncWithVideoRequired)\n {\n // TODO: in case of long distance will spin (CPU issue), possible reseek?\n while (VideoDecoder.StartTime == AV_NOPTS_VALUE && VideoDecoder.IsRunning && resyncWithVideoRequired)\n Thread.Sleep(10);\n\n long ts = (long)((frame->pts + frame->duration) * AudioStream.Timebase) - demuxer.StartTime + Config.Audio.Delay;\n\n if (ts < VideoDecoder.StartTime)\n {\n if (CanTrace) Log.Trace($\"Drops {Utils.TicksToTime(ts)} (< V: {Utils.TicksToTime(VideoDecoder.StartTime)})\");\n av_frame_unref(frame);\n continue;\n }\n else\n resyncWithVideoRequired = false;\n }\n\n lock (lockSpeed)\n {\n if (filterGraph != null)\n ProcessFilters();\n else\n Process();\n\n av_frame_unref(frame);\n }\n }\n } catch { }\n\n Monitor.Exit(lockCodecCtx);\n\n } while (Status == Status.Running);\n\n if (isRecording) { StopRecording(); recCompleted(MediaType.Audio); }\n\n if (Status == Status.Draining) Status = Status.Ended;\n }\n private void Process()\n {\n try\n {\n nextPts = frame->pts + frame->duration;\n\n var dataLen = frame->nb_samples * ASampleBytes;\n var speedDataLen= Utils.Align((int)(dataLen / speed), ASampleBytes);\n\n AudioFrame mFrame = new()\n {\n timestamp = (long)(frame->pts * AudioStream.Timebase) - demuxer.StartTime + Config.Audio.Delay,\n dataLen = speedDataLen\n };\n if (CanTrace) Log.Trace($\"Processes {Utils.TicksToTime(mFrame.timestamp)}\");\n\n if (frame->nb_samples > cBufSamples)\n AllocateCircularBuffer(frame->nb_samples);\n else if (cBufPos + Math.Max(dataLen, speedDataLen) >= cBuf.Length)\n cBufPos = 0;\n\n fixed (byte *circularBufferPosPtr = &cBuf[cBufPos])\n {\n int ret = swr_convert(swrCtx, &circularBufferPosPtr, frame->nb_samples, (byte**)&frame->data, frame->nb_samples);\n if (ret < 0)\n return;\n\n mFrame.dataPtr = (IntPtr)circularBufferPosPtr;\n }\n\n // Fill silence\n if (speed < 1)\n for (int p = dataLen; p < speedDataLen; p++)\n cBuf[cBufPos + p] = 0;\n\n cBufPos += Math.Max(dataLen, speedDataLen);\n Frames.Enqueue(mFrame);\n\n // Wait until Queue not Full or Stopped\n if (Frames.Count >= Config.Decoder.MaxAudioFrames * cBufTimesCur)\n {\n Monitor.Exit(lockCodecCtx);\n lock (lockStatus)\n if (Status == Status.Running) Status = Status.QueueFull;\n\n while (Frames.Count >= Config.Decoder.MaxAudioFrames * cBufTimesCur && Status == Status.QueueFull)\n Thread.Sleep(20);\n\n Monitor.Enter(lockCodecCtx);\n\n lock (lockStatus)\n {\n if (Status != Status.QueueFull)\n return;\n\n Status = Status.Running;\n }\n }\n }\n catch (Exception e)\n {\n Log.Error($\"Failed to process frame ({e.Message})\");\n }\n }\n\n private void AllocateCircularBuffer(int samples)\n {\n /* TBR\n * 1. If we change to different in/out sample rates we need to calculate delay\n * 2. By destorying the cBuf can create critical issues while the audio decoder reads the data? (add lock) | we need to copy the lost data and change the pointers\n * 3. Recalculate on Config.Decoder.MaxAudioFrames change (greater)\n * 4. cBufTimesSize cause filters can pass the limit when we need to use lockSpeed\n */\n\n samples = Math.Max(10000, samples); // 10K samples to ensure that currently we will not re-allocate?\n int size = Config.Decoder.MaxAudioFrames * samples * ASampleBytes * cBufTimesSize;\n Log.Debug($\"Re-allocating circular buffer ({samples} > {cBufSamples}) with {size}bytes\");\n\n lock (CircularBufferLocker)\n {\n DisposeFrames(); // TODO: copy data\n CBufAlloc?.Invoke();\n cBuf = new byte[size];\n cBufPos = 0;\n cBufSamples = samples;\n }\n\n }\n\n #region Recording\n internal Action\n recCompleted;\n Remuxer curRecorder;\n bool recGotKeyframe;\n internal bool isRecording;\n internal void StartRecording(Remuxer remuxer)\n {\n if (Disposed || isRecording) return;\n\n curRecorder = remuxer;\n isRecording = true;\n recGotKeyframe = VideoDecoder.Disposed || VideoDecoder.Stream == null;\n }\n internal void StopRecording() => isRecording = false;\n #endregion\n}\n"], ["/LLPlayer/FlyleafLib/MediaFramework/MediaRenderer/Renderer.PixelShader.cs", "using System.Collections.Generic;\nusing System.Threading;\n\nusing Vortice.Direct3D;\nusing Vortice.Direct3D11;\nusing Vortice.DXGI;\nusing Vortice.Mathematics;\nusing Vortice;\n\nusing FlyleafLib.MediaFramework.MediaDecoder;\nusing FlyleafLib.MediaFramework.MediaFrame;\n\nusing static FlyleafLib.Logger;\n\nusing ID3D11Texture2D = Vortice.Direct3D11.ID3D11Texture2D;\n\nnamespace FlyleafLib.MediaFramework.MediaRenderer;\n\nunsafe public partial class Renderer\n{\n static string[] pixelOffsets = new[] { \"r\", \"g\", \"b\", \"a\" };\n enum PSDefines { HDR, HLG, YUV }\n enum PSCase : int\n {\n None,\n HWD3D11VP,\n HWD3D11VPZeroCopy,\n HW,\n HWZeroCopy,\n\n RGBPacked,\n RGBPacked2,\n RGBPlanar,\n\n YUVPacked,\n YUVSemiPlanar,\n YUVPlanar,\n SwsScale\n }\n\n bool checkHDR;\n PSCase curPSCase;\n string curPSUniqueId;\n float curRatio = 1.0f;\n string prevPSUniqueId;\n internal bool forceNotExtractor; // TBR: workaround until we separate the Extractor?\n\n Texture2DDescription[] textDesc= new Texture2DDescription[4];\n ShaderResourceViewDescription[] srvDesc = new ShaderResourceViewDescription[4];\n SubresourceData[] subData = new SubresourceData[1];\n Box cropBox = new(0, 0, 0, 0, 0, 1);\n\n void InitPS()\n {\n for (int i=0; iflags & PixFmtFlags.Be) == 0) // We currently force SwsScale for BE (RGBA64/BGRA64 BE noted that could work as is?*)\n {\n if (videoProcessor == VideoProcessors.D3D11)\n {\n if (oldVP != videoProcessor)\n {\n VideoDecoder.DisposeFrames();\n Config.Video.Filters[VideoFilters.Brightness].Value = Config.Video.Filters[VideoFilters.Brightness].DefaultValue;\n Config.Video.Filters[VideoFilters.Contrast].Value = Config.Video.Filters[VideoFilters.Contrast].DefaultValue;\n }\n\n inputColorSpace = new()\n {\n Usage = 0,\n RGB_Range = VideoStream.AVStream->codecpar->color_range == AVColorRange.Jpeg ? (uint) 0 : 1,\n YCbCr_Matrix = VideoStream.ColorSpace != ColorSpace.BT601 ? (uint) 1 : 0,\n YCbCr_xvYCC = 0,\n Nominal_Range = VideoStream.AVStream->codecpar->color_range == AVColorRange.Jpeg ? (uint) 2 : 1\n };\n\n vpov?.Dispose();\n vd1.CreateVideoProcessorOutputView(backBuffer, vpe, vpovd, out vpov);\n vc.VideoProcessorSetStreamColorSpace(vp, 0, inputColorSpace);\n vc.VideoProcessorSetOutputColorSpace(vp, outputColorSpace);\n\n if (child != null)\n {\n child.vpov?.Dispose();\n vd1.CreateVideoProcessorOutputView(child.backBuffer, vpe, vpovd, out child.vpov);\n }\n\n if (VideoDecoder.ZeroCopy)\n curPSCase = PSCase.HWD3D11VPZeroCopy;\n else\n {\n curPSCase = PSCase.HWD3D11VP;\n\n textDesc[0].BindFlags |= BindFlags.RenderTarget;\n\n cropBox.Right = (int)VideoStream.Width;\n textDesc[0].Width = VideoStream.Width;\n cropBox.Bottom = (int)VideoStream.Height;\n textDesc[0].Height = VideoStream.Height;\n textDesc[0].Format = VideoDecoder.textureFFmpeg.Description.Format;\n }\n }\n else if (!Config.Video.SwsForce || VideoDecoder.VideoAccelerated) // FlyleafVP\n {\n List defines = new();\n\n if (oldVP != videoProcessor)\n {\n VideoDecoder.DisposeFrames();\n Config.Video.Filters[VideoFilters.Brightness].Value = Config.Video.Filters[VideoFilters.Brightness].Minimum + ((Config.Video.Filters[VideoFilters.Brightness].Maximum - Config.Video.Filters[VideoFilters.Brightness].Minimum) / 2);\n Config.Video.Filters[VideoFilters.Contrast].Value = Config.Video.Filters[VideoFilters.Contrast].Minimum + ((Config.Video.Filters[VideoFilters.Contrast].Maximum - Config.Video.Filters[VideoFilters.Contrast].Minimum) / 2);\n }\n\n if (IsHDR)\n {\n // TBR: It currently works better without it\n //if (VideoStream.ColorTransfer == AVColorTransferCharacteristic.AVCOL_TRC_ARIB_STD_B67)\n //{\n // defines.Add(PSDefines.HLG.ToString());\n // curPSUniqueId += \"g\";\n //}\n\n curPSUniqueId += \"h\";\n defines.Add(PSDefines.HDR.ToString());\n psBufferData.coefsIndex = 0;\n UpdateHDRtoSDR(false);\n }\n else\n psBufferData.coefsIndex = VideoStream.ColorSpace == ColorSpace.BT709 ? 1 : 2;\n\n for (int i=0; i 8)\n {\n srvDesc[0].Format = Format.R16_UNorm;\n srvDesc[1].Format = Format.R16G16_UNorm;\n }\n else\n {\n srvDesc[0].Format = Format.R8_UNorm;\n srvDesc[1].Format = Format.R8G8_UNorm;\n }\n\n if (VideoDecoder.ZeroCopy)\n {\n curPSCase = PSCase.HWZeroCopy;\n curPSUniqueId += ((int)curPSCase).ToString();\n\n for (int i=0; i 8)\n {\n curPSUniqueId += \"x\";\n textDesc[0].Format = srvDesc[0].Format = Format.R16G16B16A16_UNorm;\n }\n else if (VideoStream.PixelComp0Depth > 4)\n textDesc[0].Format = srvDesc[0].Format = Format.R8G8B8A8_UNorm; // B8G8R8X8_UNorm for 0[rgb]?\n\n string offsets = \"\";\n for (int i = 0; i < VideoStream.PixelComps.Length; i++)\n offsets += pixelOffsets[(int) (VideoStream.PixelComps[i].offset / Math.Ceiling(VideoStream.PixelComp0Depth / 8.0))];\n\n curPSUniqueId += offsets;\n\n if (VideoStream.PixelComps.Length > 3)\n SetPS(curPSUniqueId, $\"color = Texture1.Sample(Sampler, input.Texture).{offsets};\");\n else\n SetPS(curPSUniqueId, $\"color = float4(Texture1.Sample(Sampler, input.Texture).{offsets}, 1.0);\");\n }\n\n // [BGR/RGB]16\n else if (VideoStream.PixelPlanes == 1 && (\n VideoStream.PixelFormat == AVPixelFormat.Rgb444le||\n VideoStream.PixelFormat == AVPixelFormat.Bgr444le))\n {\n curPSCase = PSCase.RGBPacked2;\n curPSUniqueId += ((int)curPSCase).ToString();\n\n textDesc[0].Width = VideoStream.Width;\n textDesc[0].Height = VideoStream.Height;\n\n textDesc[0].Format = srvDesc[0].Format = Format.B4G4R4A4_UNorm;\n\n if (VideoStream.PixelFormat == AVPixelFormat.Rgb444le)\n {\n curPSUniqueId += \"a\";\n SetPS(curPSUniqueId, $\"color = float4(Texture1.Sample(Sampler, input.Texture).rgb, 1.0);\");\n }\n else\n {\n curPSUniqueId += \"b\";\n SetPS(curPSUniqueId, $\"color = float4(Texture1.Sample(Sampler, input.Texture).bgr, 1.0);\");\n }\n }\n\n // GBR(A) <=16\n else if (VideoStream.PixelPlanes > 2 && VideoStream.PixelComp0Depth <= 16)\n {\n curPSCase = PSCase.RGBPlanar;\n curPSUniqueId += ((int)curPSCase).ToString();\n\n for (int i=0; i 8)\n {\n curPSUniqueId += VideoStream.PixelComp0Depth;\n\n for (int i=0; i> 1);\n textDesc[0].Width = VideoStream.Width;\n textDesc[0].Height = VideoStream.Height;\n\n if (VideoStream.PixelComp0Depth > 8)\n {\n curPSUniqueId += $\"{VideoStream.Width}_\";\n textDesc[0].Format = Format.Y210;\n srvDesc[0].Format = Format.R16G16B16A16_UNorm;\n }\n else\n {\n curPSUniqueId += $\"{VideoStream.Width}\";\n textDesc[0].Format = Format.YUY2;\n srvDesc[0].Format = Format.R8G8B8A8_UNorm;\n }\n\n string header = @\"\n float posx = input.Texture.x - (texWidth * 0.25);\n float fx = frac(posx / texWidth);\n float pos1 = posx + ((0.5 - fx) * texWidth);\n float pos2 = posx + ((1.5 - fx) * texWidth);\n\n float4 c1 = Texture1.Sample(Sampler, float2(pos1, input.Texture.y));\n float4 c2 = Texture1.Sample(Sampler, float2(pos2, input.Texture.y));\n\n \";\n if (VideoStream.PixelFormat == AVPixelFormat.Yuyv422 ||\n VideoStream.PixelFormat == AVPixelFormat.Y210le)\n {\n curPSUniqueId += $\"a\";\n\n SetPS(curPSUniqueId, header + @\"\n float leftY = lerp(c1.r, c1.b, fx * 2);\n float rightY = lerp(c1.b, c2.r, fx * 2 - 1);\n float2 outUV = lerp(c1.ga, c2.ga, fx);\n float outY = lerp(leftY, rightY, step(0.5, fx));\n color = float4(outY, outUV, 1.0);\n \", defines);\n } else if (VideoStream.PixelFormat == AVPixelFormat.Yvyu422)\n {\n curPSUniqueId += $\"b\";\n\n SetPS(curPSUniqueId, header + @\"\n float leftY = lerp(c1.r, c1.b, fx * 2);\n float rightY = lerp(c1.b, c2.r, fx * 2 - 1);\n float2 outUV = lerp(c1.ag, c2.ag, fx);\n float outY = lerp(leftY, rightY, step(0.5, fx));\n color = float4(outY, outUV, 1.0);\n \", defines);\n } else if (VideoStream.PixelFormat == AVPixelFormat.Uyvy422)\n {\n curPSUniqueId += $\"c\";\n\n SetPS(curPSUniqueId, header + @\"\n float leftY = lerp(c1.g, c1.a, fx * 2);\n float rightY = lerp(c1.a, c2.g, fx * 2 - 1);\n float2 outUV = lerp(c1.rb, c2.rb, fx);\n float outY = lerp(leftY, rightY, step(0.5, fx));\n color = float4(outY, outUV, 1.0);\n \", defines);\n }\n }\n\n // Y_UV | nv12,nv21,nv24,nv42,p010le,p016le,p410le,p416le | (log2_chroma_w != log2_chroma_h / Interleaved) (? nv16,nv20le,p210le,p216le)\n // This covers all planes == 2 YUV (Semi-Planar)\n else if (VideoStream.PixelPlanes == 2) // && VideoStream.PixelSameDepth) && !VideoStream.PixelInterleaved)\n {\n curPSCase = PSCase.YUVSemiPlanar;\n curPSUniqueId += ((int)curPSCase).ToString();\n\n textDesc[0].Width = VideoStream.Width;\n textDesc[0].Height = VideoStream.Height;\n textDesc[1].Width = VideoStream.PixelFormatDesc->log2_chroma_w > 0 ? (VideoStream.Width + 1) >> VideoStream.PixelFormatDesc->log2_chroma_w : VideoStream.Width >> VideoStream.PixelFormatDesc->log2_chroma_w;\n textDesc[1].Height = VideoStream.PixelFormatDesc->log2_chroma_h > 0 ? (VideoStream.Height + 1) >> VideoStream.PixelFormatDesc->log2_chroma_h : VideoStream.Height >> VideoStream.PixelFormatDesc->log2_chroma_h;\n\n string offsets = VideoStream.PixelComps[1].offset > VideoStream.PixelComps[2].offset ? \"gr\" : \"rg\";\n\n if (VideoStream.PixelComp0Depth > 8)\n {\n curPSUniqueId += \"x\";\n textDesc[0].Format = srvDesc[0].Format = Format.R16_UNorm;\n textDesc[1].Format = srvDesc[1].Format = Format.R16G16_UNorm;\n }\n else\n {\n textDesc[0].Format = srvDesc[0].Format = Format.R8_UNorm;\n textDesc[1].Format = srvDesc[1].Format = Format.R8G8_UNorm;\n }\n\n SetPS(curPSUniqueId, @\"\n color = float4(\n Texture1.Sample(Sampler, input.Texture).r,\n Texture2.Sample(Sampler, input.Texture).\" + offsets + @\",\n 1.0);\n \", defines);\n }\n\n // Y_U_V\n else if (VideoStream.PixelPlanes > 2)\n {\n curPSCase = PSCase.YUVPlanar;\n curPSUniqueId += ((int)curPSCase).ToString();\n\n textDesc[0].Width = textDesc[3].Width = VideoStream.Width;\n textDesc[0].Height = textDesc[3].Height= VideoStream.Height;\n textDesc[1].Width = textDesc[2].Width = VideoStream.PixelFormatDesc->log2_chroma_w > 0 ? (VideoStream.Width + 1) >> VideoStream.PixelFormatDesc->log2_chroma_w : VideoStream.Width >> VideoStream.PixelFormatDesc->log2_chroma_w;\n textDesc[1].Height = textDesc[2].Height= VideoStream.PixelFormatDesc->log2_chroma_h > 0 ? (VideoStream.Height + 1) >> VideoStream.PixelFormatDesc->log2_chroma_h : VideoStream.Height >> VideoStream.PixelFormatDesc->log2_chroma_h;\n\n string shader = @\"\n color.r = Texture1.Sample(Sampler, input.Texture).r;\n color.g = Texture2.Sample(Sampler, input.Texture).r;\n color.b = Texture3.Sample(Sampler, input.Texture).r;\n \";\n\n if (VideoStream.PixelPlanes == 4)\n {\n curPSUniqueId += \"x\";\n\n shader += @\"\n color.a = Texture4.Sample(Sampler, input.Texture).r;\n \";\n }\n\n if (VideoStream.PixelComp0Depth > 8)\n {\n curPSUniqueId += VideoStream.PixelComp0Depth;\n\n for (int i=0; ipts * VideoStream.Timebase) - VideoDecoder.Demuxer.StartTime;\n if (CanTrace) Log.Trace($\"Processes {Utils.TicksToTime(mFrame.timestamp)}\");\n\n if (checkHDR)\n {\n // TODO Dolpy Vision / Vivid\n //var hdrSideDolpyDynamic = av_frame_get_side_data(frame, AVFrameSideDataType.AV_FRAME_DATA_DOVI_METADATA);\n\n var hdrSideDynamic = av_frame_get_side_data(frame, AVFrameSideDataType.DynamicHdrPlus);\n\n if (hdrSideDynamic != null && hdrSideDynamic->data != null)\n {\n hdrPlusData = (AVDynamicHDRPlus*) hdrSideDynamic->data;\n UpdateHDRtoSDR();\n }\n else\n {\n var lightSide = av_frame_get_side_data(frame, AVFrameSideDataType.ContentLightLevel);\n var displaySide = av_frame_get_side_data(frame, AVFrameSideDataType.MasteringDisplayMetadata);\n\n if (lightSide != null && lightSide->data != null && ((AVContentLightMetadata*)lightSide->data)->MaxCLL != 0)\n {\n lightData = *((AVContentLightMetadata*) lightSide->data);\n checkHDR = false;\n UpdateHDRtoSDR();\n }\n\n if (displaySide != null && displaySide->data != null && ((AVMasteringDisplayMetadata*)displaySide->data)->has_luminance != 0)\n {\n displayData = *((AVMasteringDisplayMetadata*) displaySide->data);\n checkHDR = false;\n UpdateHDRtoSDR();\n }\n }\n }\n\n if (curPSCase == PSCase.HWZeroCopy)\n {\n mFrame.srvs = new ID3D11ShaderResourceView[2];\n srvDesc[0].Texture2DArray.FirstArraySlice = srvDesc[1].Texture2DArray.FirstArraySlice = (uint) frame->data[1];\n\n mFrame.srvs[0] = Device.CreateShaderResourceView(VideoDecoder.textureFFmpeg, srvDesc[0]);\n mFrame.srvs[1] = Device.CreateShaderResourceView(VideoDecoder.textureFFmpeg, srvDesc[1]);\n\n mFrame.avFrame = av_frame_alloc();\n av_frame_move_ref(mFrame.avFrame, frame);\n return mFrame;\n }\n\n else if (curPSCase == PSCase.HW)\n {\n mFrame.textures = new ID3D11Texture2D[1];\n mFrame.srvs = new ID3D11ShaderResourceView[2];\n\n mFrame.textures[0] = Device.CreateTexture2D(textDesc[0]);\n context.CopySubresourceRegion(\n mFrame.textures[0], 0, 0, 0, 0, // dst\n VideoDecoder.textureFFmpeg, (uint) frame->data[1], // src\n cropBox); // crop decoder's padding\n\n mFrame.srvs[0] = Device.CreateShaderResourceView(mFrame.textures[0], srvDesc[0]);\n mFrame.srvs[1] = Device.CreateShaderResourceView(mFrame.textures[0], srvDesc[1]);\n }\n\n else if (curPSCase == PSCase.HWD3D11VPZeroCopy)\n {\n mFrame.avFrame = av_frame_alloc();\n av_frame_move_ref(mFrame.avFrame, frame);\n return mFrame;\n }\n\n else if (curPSCase == PSCase.HWD3D11VP)\n {\n mFrame.textures = new ID3D11Texture2D[1];\n mFrame.textures[0] = Device.CreateTexture2D(textDesc[0]);\n context.CopySubresourceRegion(\n mFrame.textures[0], 0, 0, 0, 0, // dst\n VideoDecoder.textureFFmpeg, (uint) frame->data[1], // src\n cropBox); // crop decoder's padding\n }\n\n else if (curPSCase == PSCase.SwsScale)\n {\n mFrame.textures = new ID3D11Texture2D[1];\n mFrame.srvs = new ID3D11ShaderResourceView[1];\n\n sws_scale(VideoDecoder.swsCtx, frame->data.ToRawArray(), frame->linesize.ToArray(), 0, frame->height, VideoDecoder.swsData.ToRawArray(), VideoDecoder.swsLineSize.ToArray());\n\n subData[0].DataPointer = VideoDecoder.swsData[0];\n subData[0].RowPitch = (uint)VideoDecoder.swsLineSize[0];\n\n mFrame.textures[0] = Device.CreateTexture2D(textDesc[0], subData);\n mFrame.srvs[0] = Device.CreateShaderResourceView(mFrame.textures[0], srvDesc[0]);\n }\n\n else\n {\n mFrame.textures = new ID3D11Texture2D[VideoStream.PixelPlanes];\n mFrame.srvs = new ID3D11ShaderResourceView[VideoStream.PixelPlanes];\n\n bool newRotationLinesize = false;\n for (int i = 0; i < VideoStream.PixelPlanes; i++)\n {\n if (frame->linesize[i] < 0)\n {\n // Negative linesize for vertical flipping [TBR: might required for HW as well? (SwsScale does that)] http://ffmpeg.org/doxygen/trunk/structAVFrame.html#aa52bfc6605f6a3059a0c3226cc0f6567\n newRotationLinesize = true;\n subData[0].RowPitch = (uint)(-1 * frame->linesize[i]);\n subData[0].DataPointer = frame->data[i];\n subData[0].DataPointer -= (nint)((subData[0].RowPitch * (VideoStream.Height - 1)));\n }\n else\n {\n newRotationLinesize = false;\n subData[0].RowPitch = (uint)frame->linesize[i];\n subData[0].DataPointer = frame->data[i];\n }\n\n if (subData[0].RowPitch < textDesc[i].Width) // Prevent reading more than the actual data (Access Violation #424)\n {\n av_frame_unref(frame);\n return null;\n }\n\n mFrame.textures[i] = Device.CreateTexture2D(textDesc[i], subData);\n mFrame.srvs[i] = Device.CreateShaderResourceView(mFrame.textures[i], srvDesc[i]);\n }\n\n if (newRotationLinesize != rotationLinesize)\n {\n rotationLinesize = newRotationLinesize;\n UpdateRotation(_RotationAngle);\n }\n }\n\n av_frame_unref(frame);\n return mFrame;\n }\n catch (Exception e)\n {\n av_frame_unref(frame);\n Log.Error($\"Failed to process frame ({e.Message})\");\n return null;\n }\n }\n\n void SetPS(string uniqueId, string sampleHLSL, List defines = null)\n {\n if (curPSUniqueId == prevPSUniqueId)\n return;\n\n ShaderPS?.Dispose();\n ShaderPS = ShaderCompiler.CompilePS(Device, uniqueId, sampleHLSL, defines);\n context.PSSetShader(ShaderPS);\n }\n}\n"], ["/LLPlayer/FlyleafLib/MediaFramework/MediaRenderer/Renderer.VideoProcessor.cs", "using System.Collections.Generic;\nusing System.Numerics;\nusing System.Text.Json.Serialization;\nusing Vortice.DXGI;\nusing Vortice.Direct3D11;\n\nusing ID3D11VideoContext = Vortice.Direct3D11.ID3D11VideoContext;\n\nusing FlyleafLib.Controls.WPF;\nusing FlyleafLib.MediaPlayer;\n\nusing static FlyleafLib.Logger;\nusing static FlyleafLib.Utils;\n\nnamespace FlyleafLib.MediaFramework.MediaRenderer;\n\nunsafe public partial class Renderer\n{\n /* TODO\n * 1) Try to sync filters between Flyleaf and D3D11 video processors so we will not have to reset on change\n * 2) Filter default values will change when the device/adapter is changed\n */\n\n public static Dictionary VideoProcessorsCapsCache = new();\n\n internal static VideoProcessorFilter ConvertFromVideoProcessorFilterCaps(VideoProcessorFilterCaps filter)\n {\n switch (filter)\n {\n case VideoProcessorFilterCaps.Brightness:\n return VideoProcessorFilter.Brightness;\n case VideoProcessorFilterCaps.Contrast:\n return VideoProcessorFilter.Contrast;\n case VideoProcessorFilterCaps.Hue:\n return VideoProcessorFilter.Hue;\n case VideoProcessorFilterCaps.Saturation:\n return VideoProcessorFilter.Saturation;\n case VideoProcessorFilterCaps.EdgeEnhancement:\n return VideoProcessorFilter.EdgeEnhancement;\n case VideoProcessorFilterCaps.NoiseReduction:\n return VideoProcessorFilter.NoiseReduction;\n case VideoProcessorFilterCaps.AnamorphicScaling:\n return VideoProcessorFilter.AnamorphicScaling;\n case VideoProcessorFilterCaps.StereoAdjustment:\n return VideoProcessorFilter.StereoAdjustment;\n\n default:\n return VideoProcessorFilter.StereoAdjustment;\n }\n }\n internal static VideoProcessorFilterCaps ConvertFromVideoProcessorFilter(VideoProcessorFilter filter)\n {\n switch (filter)\n {\n case VideoProcessorFilter.Brightness:\n return VideoProcessorFilterCaps.Brightness;\n case VideoProcessorFilter.Contrast:\n return VideoProcessorFilterCaps.Contrast;\n case VideoProcessorFilter.Hue:\n return VideoProcessorFilterCaps.Hue;\n case VideoProcessorFilter.Saturation:\n return VideoProcessorFilterCaps.Saturation;\n case VideoProcessorFilter.EdgeEnhancement:\n return VideoProcessorFilterCaps.EdgeEnhancement;\n case VideoProcessorFilter.NoiseReduction:\n return VideoProcessorFilterCaps.NoiseReduction;\n case VideoProcessorFilter.AnamorphicScaling:\n return VideoProcessorFilterCaps.AnamorphicScaling;\n case VideoProcessorFilter.StereoAdjustment:\n return VideoProcessorFilterCaps.StereoAdjustment;\n\n default:\n return VideoProcessorFilterCaps.StereoAdjustment;\n }\n }\n internal static VideoFilter ConvertFromVideoProcessorFilterRange(VideoProcessorFilterRange filter) => new()\n {\n Minimum = filter.Minimum,\n Maximum = filter.Maximum,\n Value = filter.Default,\n Step = filter.Multiplier\n };\n\n VideoColor D3D11VPBackgroundColor;\n ID3D11VideoDevice1 vd1;\n ID3D11VideoProcessor vp;\n ID3D11VideoContext vc;\n ID3D11VideoProcessorEnumerator vpe;\n ID3D11VideoProcessorInputView vpiv;\n ID3D11VideoProcessorOutputView vpov;\n\n VideoProcessorStream[] vpsa = new VideoProcessorStream[] { new VideoProcessorStream() { Enable = true } };\n VideoProcessorContentDescription vpcd = new()\n {\n Usage = VideoUsage.PlaybackNormal,\n InputFrameFormat = VideoFrameFormat.InterlacedTopFieldFirst,\n\n InputFrameRate = new Rational(1, 1),\n OutputFrameRate = new Rational(1, 1),\n };\n VideoProcessorOutputViewDescription vpovd = new() { ViewDimension = VideoProcessorOutputViewDimension.Texture2D };\n VideoProcessorInputViewDescription vpivd = new()\n {\n FourCC = 0,\n ViewDimension = VideoProcessorInputViewDimension.Texture2D,\n Texture2D = new Texture2DVideoProcessorInputView() { MipSlice = 0, ArraySlice = 0 }\n };\n VideoProcessorColorSpace inputColorSpace;\n VideoProcessorColorSpace outputColorSpace;\n\n AVDynamicHDRPlus* hdrPlusData = null;\n AVContentLightMetadata lightData = new();\n AVMasteringDisplayMetadata displayData = new();\n\n uint actualRotation;\n bool actualHFlip, actualVFlip;\n bool configLoadedChecked;\n\n void InitializeVideoProcessor()\n {\n lock (VideoProcessorsCapsCache)\n try\n {\n vpcd.InputWidth = 1;\n vpcd.InputHeight= 1;\n vpcd.OutputWidth = vpcd.InputWidth;\n vpcd.OutputHeight= vpcd.InputHeight;\n\n outputColorSpace = new VideoProcessorColorSpace()\n {\n Usage = 0,\n RGB_Range = 0,\n YCbCr_Matrix = 1,\n YCbCr_xvYCC = 0,\n Nominal_Range = 2\n };\n\n if (VideoProcessorsCapsCache.ContainsKey(Device.Tag.ToString()))\n {\n if (VideoProcessorsCapsCache[Device.Tag.ToString()].Failed)\n {\n InitializeFilters();\n return;\n }\n\n vd1 = Device.QueryInterface();\n vc = context.QueryInterface();\n\n vd1.CreateVideoProcessorEnumerator(ref vpcd, out vpe);\n\n if (vpe == null)\n {\n VPFailed();\n return;\n }\n\n // if (!VideoProcessorsCapsCache[Device.Tag.ToString()].TypeIndex != -1)\n vd1.CreateVideoProcessor(vpe, (uint)VideoProcessorsCapsCache[Device.Tag.ToString()].TypeIndex, out vp);\n InitializeFilters();\n\n return;\n }\n\n VideoProcessorCapsCache cache = new();\n VideoProcessorsCapsCache.Add(Device.Tag.ToString(), cache);\n\n vd1 = Device.QueryInterface();\n vc = context.QueryInterface();\n\n vd1.CreateVideoProcessorEnumerator(ref vpcd, out vpe);\n\n if (vpe == null || Device.FeatureLevel < Vortice.Direct3D.FeatureLevel.Level_10_0)\n {\n VPFailed();\n return;\n }\n\n var vpe1 = vpe.QueryInterface();\n bool supportHLG = vpe1.CheckVideoProcessorFormatConversion(Format.P010, ColorSpaceType.YcbcrStudioGhlgTopLeftP2020, Format.B8G8R8A8_UNorm, ColorSpaceType.RgbFullG22NoneP709);\n bool supportHDR10Limited = vpe1.CheckVideoProcessorFormatConversion(Format.P010, ColorSpaceType.YcbcrStudioG2084TopLeftP2020, Format.B8G8R8A8_UNorm, ColorSpaceType.RgbStudioG2084NoneP2020);\n\n var vpCaps = vpe.VideoProcessorCaps;\n string dump = \"\";\n\n if (CanDebug)\n {\n dump += $\"=====================================================\\r\\n\";\n dump += $\"MaxInputStreams {vpCaps.MaxInputStreams}\\r\\n\";\n dump += $\"MaxStreamStates {vpCaps.MaxStreamStates}\\r\\n\";\n dump += $\"HDR10 Limited {(supportHDR10Limited ? \"yes\" : \"no\")}\\r\\n\";\n dump += $\"HLG {(supportHLG ? \"yes\" : \"no\")}\\r\\n\";\n\n dump += $\"\\n[Video Processor Device Caps]\\r\\n\";\n foreach (VideoProcessorDeviceCaps cap in Enum.GetValues(typeof(VideoProcessorDeviceCaps)))\n dump += $\"{cap,-25} {((vpCaps.DeviceCaps & cap) != 0 ? \"yes\" : \"no\")}\\r\\n\";\n\n dump += $\"\\n[Video Processor Feature Caps]\\r\\n\";\n foreach (VideoProcessorFeatureCaps cap in Enum.GetValues(typeof(VideoProcessorFeatureCaps)))\n dump += $\"{cap,-25} {((vpCaps.FeatureCaps & cap) != 0 ? \"yes\" : \"no\")}\\r\\n\";\n\n dump += $\"\\n[Video Processor Stereo Caps]\\r\\n\";\n foreach (VideoProcessorStereoCaps cap in Enum.GetValues(typeof(VideoProcessorStereoCaps)))\n dump += $\"{cap,-25} {((vpCaps.StereoCaps & cap) != 0 ? \"yes\" : \"no\")}\\r\\n\";\n\n dump += $\"\\n[Video Processor Input Format Caps]\\r\\n\";\n foreach (VideoProcessorFormatCaps cap in Enum.GetValues(typeof(VideoProcessorFormatCaps)))\n dump += $\"{cap,-25} {((vpCaps.InputFormatCaps & cap) != 0 ? \"yes\" : \"no\")}\\r\\n\";\n\n dump += $\"\\n[Video Processor Filter Caps]\\r\\n\";\n }\n\n foreach (VideoProcessorFilterCaps filter in Enum.GetValues(typeof(VideoProcessorFilterCaps)))\n if ((vpCaps.FilterCaps & filter) != 0)\n {\n vpe1.GetVideoProcessorFilterRange(ConvertFromVideoProcessorFilterCaps(filter), out var range);\n if (CanDebug) dump += $\"{filter,-25} [{range.Minimum,6} - {range.Maximum,4}] | x{range.Multiplier,4} | *{range.Default}\\r\\n\";\n var vf = ConvertFromVideoProcessorFilterRange(range);\n vf.Filter = (VideoFilters)filter;\n cache.Filters.Add((VideoFilters)filter, vf);\n }\n else if (CanDebug)\n dump += $\"{filter,-25} no\\r\\n\";\n\n if (CanDebug)\n {\n dump += $\"\\n[Video Processor Input Format Caps]\\r\\n\";\n foreach (VideoProcessorAutoStreamCaps cap in Enum.GetValues(typeof(VideoProcessorAutoStreamCaps)))\n dump += $\"{cap,-25} {((vpCaps.AutoStreamCaps & cap) != 0 ? \"yes\" : \"no\")}\\r\\n\";\n }\n\n uint typeIndex = 0;\n VideoProcessorRateConversionCaps rcCap = new();\n for (uint i = 0; i < vpCaps.RateConversionCapsCount; i++)\n {\n vpe.GetVideoProcessorRateConversionCaps(i, out rcCap);\n VideoProcessorProcessorCaps pCaps = (VideoProcessorProcessorCaps) rcCap.ProcessorCaps;\n\n if (CanDebug)\n {\n dump += $\"\\n[Video Processor Rate Conversion Caps #{i}]\\r\\n\";\n\n dump += $\"\\n\\t[Video Processor Rate Conversion Caps]\\r\\n\";\n var fields = typeof(VideoProcessorRateConversionCaps).GetFields();\n foreach (var field in fields)\n dump += $\"\\t{field.Name,-35} {field.GetValue(rcCap)}\\r\\n\";\n\n dump += $\"\\n\\t[Video Processor Processor Caps]\\r\\n\";\n foreach (VideoProcessorProcessorCaps cap in Enum.GetValues(typeof(VideoProcessorProcessorCaps)))\n dump += $\"\\t{cap,-35} {(((VideoProcessorProcessorCaps)rcCap.ProcessorCaps & cap) != 0 ? \"yes\" : \"no\")}\\r\\n\";\n }\n\n typeIndex = i;\n\n if (((VideoProcessorProcessorCaps)rcCap.ProcessorCaps & VideoProcessorProcessorCaps.DeinterlaceBob) != 0)\n break; // TBR: When we add past/future frames support\n }\n vpe1.Dispose();\n\n if (CanDebug) Log.Debug($\"D3D11 Video Processor\\r\\n{dump}\");\n\n cache.TypeIndex = (int)typeIndex;\n cache.HLG = supportHLG;\n cache.HDR10Limited = supportHDR10Limited;\n cache.VideoProcessorCaps = vpCaps;\n cache.VideoProcessorRateConversionCaps = rcCap;\n\n //if (typeIndex != -1)\n vd1.CreateVideoProcessor(vpe, (uint)typeIndex, out vp);\n if (vp == null)\n {\n VPFailed();\n return;\n }\n\n cache.Failed = false;\n Log.Info($\"D3D11 Video Processor Initialized (Rate Caps #{typeIndex})\");\n\n } catch { DisposeVideoProcessor(); Log.Error($\"D3D11 Video Processor Initialization Failed\"); }\n\n InitializeFilters();\n }\n void VPFailed()\n {\n Log.Error($\"D3D11 Video Processor Initialization Failed\");\n\n if (!VideoProcessorsCapsCache.ContainsKey(Device.Tag.ToString()))\n VideoProcessorsCapsCache.Add(Device.Tag.ToString(), new VideoProcessorCapsCache());\n VideoProcessorsCapsCache[Device.Tag.ToString()].Failed = true;\n\n VideoProcessorsCapsCache[Device.Tag.ToString()].Filters.Add(VideoFilters.Brightness, new VideoFilter() { Filter = VideoFilters.Brightness });\n VideoProcessorsCapsCache[Device.Tag.ToString()].Filters.Add(VideoFilters.Contrast, new VideoFilter() { Filter = VideoFilters.Contrast });\n\n DisposeVideoProcessor();\n InitializeFilters();\n }\n void DisposeVideoProcessor()\n {\n vpiv?.Dispose();\n vpov?.Dispose();\n vp?. Dispose();\n vpe?. Dispose();\n vc?. Dispose();\n vd1?. Dispose();\n\n vc = null;\n }\n void InitializeFilters()\n {\n Filters = VideoProcessorsCapsCache[Device.Tag.ToString()].Filters;\n\n // Add FLVP filters if D3D11VP does not support them\n if (!Filters.ContainsKey(VideoFilters.Brightness))\n Filters.Add(VideoFilters.Brightness, new VideoFilter(VideoFilters.Brightness));\n\n if (!Filters.ContainsKey(VideoFilters.Contrast))\n Filters.Add(VideoFilters.Contrast, new VideoFilter(VideoFilters.Contrast));\n\n foreach(var filter in Filters.Values)\n {\n if (!Config.Video.Filters.ContainsKey(filter.Filter))\n continue;\n\n var cfgFilter = Config.Video.Filters[filter.Filter];\n cfgFilter.Available = true;\n cfgFilter.renderer = this;\n\n if (!configLoadedChecked && !Config.Loaded)\n {\n cfgFilter.Minimum = filter.Minimum;\n cfgFilter.Maximum = filter.Maximum;\n cfgFilter.DefaultValue = filter.Value;\n cfgFilter.Value = filter.Value;\n cfgFilter.Step = filter.Step;\n }\n\n UpdateFilterValue(cfgFilter);\n }\n\n configLoadedChecked = true;\n UpdateBackgroundColor();\n\n if (vc != null)\n {\n vc.VideoProcessorSetStreamAutoProcessingMode(vp, 0, false);\n vc.VideoProcessorSetStreamFrameFormat(vp, 0, !Config.Video.Deinterlace ? VideoFrameFormat.Progressive : (Config.Video.DeinterlaceBottomFirst ? VideoFrameFormat.InterlacedBottomFieldFirst : VideoFrameFormat.InterlacedTopFieldFirst));\n }\n\n // Reset FLVP filters to defaults (can be different from D3D11VP filters scaling)\n if (videoProcessor == VideoProcessors.Flyleaf)\n {\n Config.Video.Filters[VideoFilters.Brightness].Value = Config.Video.Filters[VideoFilters.Brightness].Minimum + ((Config.Video.Filters[VideoFilters.Brightness].Maximum - Config.Video.Filters[VideoFilters.Brightness].Minimum) / 2);\n Config.Video.Filters[VideoFilters.Contrast].Value = Config.Video.Filters[VideoFilters.Contrast].Minimum + ((Config.Video.Filters[VideoFilters.Contrast].Maximum - Config.Video.Filters[VideoFilters.Contrast].Minimum) / 2);\n }\n }\n\n internal void UpdateBackgroundColor()\n {\n D3D11VPBackgroundColor.Rgba.R = Scale(Config.Video.BackgroundColor.R, 0, 255, 0, 100) / 100.0f;\n D3D11VPBackgroundColor.Rgba.G = Scale(Config.Video.BackgroundColor.G, 0, 255, 0, 100) / 100.0f;\n D3D11VPBackgroundColor.Rgba.B = Scale(Config.Video.BackgroundColor.B, 0, 255, 0, 100) / 100.0f;\n\n vc?.VideoProcessorSetOutputBackgroundColor(vp, false, D3D11VPBackgroundColor);\n\n Present();\n }\n internal void UpdateDeinterlace()\n {\n lock (lockDevice)\n {\n if (Disposed)\n return;\n\n vc?.VideoProcessorSetStreamFrameFormat(vp, 0, !Config.Video.Deinterlace ? VideoFrameFormat.Progressive : (Config.Video.DeinterlaceBottomFirst ? VideoFrameFormat.InterlacedBottomFieldFirst : VideoFrameFormat.InterlacedTopFieldFirst));\n\n if (Config.Video.VideoProcessor != VideoProcessors.Auto)\n return;\n\n if (parent != null)\n return;\n\n ConfigPlanes();\n Present();\n }\n }\n internal void UpdateFilterValue(VideoFilter filter)\n {\n // D3D11VP\n if (Filters.ContainsKey(filter.Filter) && vc != null)\n {\n int scaledValue = (int) Scale(filter.Value, filter.Minimum, filter.Maximum, Filters[filter.Filter].Minimum, Filters[filter.Filter].Maximum);\n vc.VideoProcessorSetStreamFilter(vp, 0, ConvertFromVideoProcessorFilterCaps((VideoProcessorFilterCaps)filter.Filter), true, scaledValue);\n }\n\n if (parent != null)\n return;\n\n // FLVP\n switch (filter.Filter)\n {\n case VideoFilters.Brightness:\n int scaledValue = (int) Scale(filter.Value, filter.Minimum, filter.Maximum, 0, 100);\n psBufferData.brightness = scaledValue / 100.0f;\n context.UpdateSubresource(psBufferData, psBuffer);\n\n break;\n\n case VideoFilters.Contrast:\n scaledValue = (int) Scale(filter.Value, filter.Minimum, filter.Maximum, 0, 100);\n psBufferData.contrast = scaledValue / 100.0f;\n context.UpdateSubresource(psBufferData, psBuffer);\n\n break;\n\n default:\n break;\n }\n\n Present();\n }\n internal void UpdateHDRtoSDR(bool updateResource = true)\n {\n if(parent != null)\n return;\n\n float lum1 = 400;\n\n if (hdrPlusData != null)\n {\n lum1 = (float) (av_q2d(hdrPlusData->@params[0].average_maxrgb) * 100000.0);\n\n // this is not accurate more research required\n if (lum1 < 100)\n lum1 *= 10;\n lum1 = Math.Max(lum1, 400);\n }\n else if (Config.Video.HDRtoSDRMethod != HDRtoSDRMethod.Reinhard)\n {\n float lum2 = lum1;\n float lum3 = lum1;\n\n double lum = displayData.has_luminance != 0 ? av_q2d(displayData.max_luminance) : 400;\n\n if (lightData.MaxCLL > 0)\n {\n if (lightData.MaxCLL >= lum)\n {\n lum1 = (float)lum;\n lum2 = lightData.MaxCLL;\n }\n else\n {\n lum1 = lightData.MaxCLL;\n lum2 = (float)lum;\n }\n lum3 = lightData.MaxFALL;\n lum1 = (lum1 * 0.5f) + (lum2 * 0.2f) + (lum3 * 0.3f);\n }\n else\n {\n lum1 = (float)lum;\n }\n }\n else\n {\n if (lightData.MaxCLL > 0)\n lum1 = lightData.MaxCLL;\n else if (displayData.has_luminance != 0)\n lum1 = (float)av_q2d(displayData.max_luminance);\n }\n\n psBufferData.hdrmethod = Config.Video.HDRtoSDRMethod;\n\n if (psBufferData.hdrmethod == HDRtoSDRMethod.Hable)\n {\n psBufferData.g_luminance = lum1 > 1 ? lum1 : 400.0f;\n psBufferData.g_toneP1 = 10000.0f / psBufferData.g_luminance * (2.0f / Config.Video.HDRtoSDRTone);\n psBufferData.g_toneP2 = psBufferData.g_luminance / (100.0f * Config.Video.HDRtoSDRTone);\n }\n else if (psBufferData.hdrmethod == HDRtoSDRMethod.Reinhard)\n {\n psBufferData.g_toneP1 = lum1 > 0 ? (float)(Math.Log10(100) / Math.Log10(lum1)) : 0.72f;\n if (psBufferData.g_toneP1 < 0.1f || psBufferData.g_toneP1 > 5.0f)\n psBufferData.g_toneP1 = 0.72f;\n\n psBufferData.g_toneP1 *= Config.Video.HDRtoSDRTone;\n }\n else if (psBufferData.hdrmethod == HDRtoSDRMethod.Aces)\n {\n psBufferData.g_luminance = lum1 > 1 ? lum1 : 400.0f;\n psBufferData.g_toneP1 = Config.Video.HDRtoSDRTone;\n }\n\n if (updateResource)\n {\n context.UpdateSubresource(psBufferData, psBuffer);\n if (!VideoDecoder.IsRunning)\n Present();\n }\n }\n void UpdateRotation(uint angle, bool refresh = true)\n {\n _RotationAngle = angle;\n\n uint newRotation = _RotationAngle;\n\n if (VideoStream != null)\n newRotation += (uint)VideoStream.Rotation;\n\n if (rotationLinesize)\n newRotation += 180;\n\n newRotation %= 360;\n\n if (Disposed || (actualRotation == newRotation && actualHFlip == _HFlip && actualVFlip == _VFlip))\n return;\n\n bool hvFlipChanged = (actualHFlip || actualVFlip) != (_HFlip || _VFlip);\n\n actualRotation = newRotation;\n actualHFlip = _HFlip;\n actualVFlip = _VFlip;\n\n if (actualRotation < 45 || actualRotation == 360)\n _d3d11vpRotation = VideoProcessorRotation.Identity;\n else if (actualRotation < 135)\n _d3d11vpRotation = VideoProcessorRotation.Rotation90;\n else if (actualRotation < 225)\n _d3d11vpRotation = VideoProcessorRotation.Rotation180;\n else if (actualRotation < 360)\n _d3d11vpRotation = VideoProcessorRotation.Rotation270;\n\n vsBufferData.mat = Matrix4x4.CreateFromYawPitchRoll(0.0f, 0.0f, (float) (Math.PI / 180 * actualRotation));\n\n if (_HFlip || _VFlip)\n {\n vsBufferData.mat *= Matrix4x4.CreateScale(_HFlip ? -1 : 1, _VFlip ? -1 : 1, 1);\n if (hvFlipChanged)\n {\n // Renders both sides required for H-V Flip - TBR: consider for performance changing the vertex buffer / input layout instead?\n rasterizerState?.Dispose();\n rasterizerState = Device.CreateRasterizerState(new(CullMode.None, FillMode.Solid));\n context.RSSetState(rasterizerState);\n }\n }\n else if (hvFlipChanged)\n {\n // Removes back rendering for better performance\n rasterizerState?.Dispose();\n rasterizerState = Device.CreateRasterizerState(new(CullMode.Back, FillMode.Solid));\n context.RSSetState(rasterizerState);\n }\n\n if (parent == null)\n context.UpdateSubresource(vsBufferData, vsBuffer);\n\n if (child != null)\n {\n child.actualRotation = actualRotation;\n child._d3d11vpRotation = _d3d11vpRotation;\n child._RotationAngle = _RotationAngle;\n child.rotationLinesize = rotationLinesize;\n child.SetViewport();\n }\n\n vc?.VideoProcessorSetStreamRotation(vp, 0, true, _d3d11vpRotation);\n\n if (refresh)\n SetViewport();\n }\n internal void UpdateVideoProcessor()\n {\n if(parent != null)\n return;\n\n if (Config.Video.VideoProcessor == videoProcessor || (Config.Video.VideoProcessor == VideoProcessors.D3D11 && D3D11VPFailed))\n return;\n\n ConfigPlanes();\n Present();\n }\n}\n\npublic class VideoFilter : NotifyPropertyChanged\n{\n internal Renderer renderer;\n\n [JsonIgnore]\n public bool Available { get => _Available; set => SetUI(ref _Available, value); }\n bool _Available;\n\n public VideoFilters Filter { get => _Filter; set => SetUI(ref _Filter, value); }\n VideoFilters _Filter = VideoFilters.Brightness;\n\n public int Minimum { get => _Minimum; set => SetUI(ref _Minimum, value); }\n int _Minimum = 0;\n\n public int Maximum { get => _Maximum; set => SetUI(ref _Maximum, value); }\n int _Maximum = 100;\n\n public float Step { get => _Step; set => SetUI(ref _Step, value); }\n float _Step = 1;\n\n public int DefaultValue\n {\n get;\n set\n {\n if (SetUI(ref field, value))\n {\n SetDefaultValue.OnCanExecuteChanged();\n }\n }\n } = 50;\n\n public int Value\n {\n get;\n set\n {\n int v = value;\n v = Math.Min(v, Maximum);\n v = Math.Max(v, Minimum);\n\n if (Set(ref field, v))\n {\n renderer?.UpdateFilterValue(this);\n SetDefaultValue.OnCanExecuteChanged();\n }\n }\n } = 50;\n\n public RelayCommand SetDefaultValue => field ??= new(_ =>\n {\n Value = DefaultValue;\n }, _ => Value != DefaultValue);\n\n //internal void SetValue(int value) => SetUI(ref _Value, value, true, nameof(Value));\n\n public VideoFilter() { }\n public VideoFilter(VideoFilters filter, Player player = null)\n => Filter = filter;\n}\n\npublic class VideoProcessorCapsCache\n{\n public bool Failed = true;\n public int TypeIndex = -1;\n public bool HLG;\n public bool HDR10Limited;\n public VideoProcessorCaps VideoProcessorCaps;\n public VideoProcessorRateConversionCaps VideoProcessorRateConversionCaps;\n\n public Dictionary Filters { get; set; } = new();\n}\n"], ["/LLPlayer/FlyleafLib/MediaFramework/MediaRenderer/Renderer.Present.cs", "using System;\nusing System.Threading;\nusing System.Threading.Tasks;\n\nusing Vortice.DXGI;\nusing Vortice.Direct3D11;\n\nusing FlyleafLib.MediaFramework.MediaDecoder;\nusing FlyleafLib.MediaFramework.MediaFrame;\n\nusing static FlyleafLib.Logger;\n\nnamespace FlyleafLib.MediaFramework.MediaRenderer;\n\npublic unsafe partial class Renderer\n{\n bool isPresenting;\n long lastPresentAt = 0;\n long lastPresentRequestAt= 0;\n object lockPresentTask = new();\n\n public bool Present(VideoFrame frame, bool forceWait = true)\n {\n if (Monitor.TryEnter(lockDevice, frame.timestamp == 0 ? 100 : 5)) // Allow more time for first frame\n {\n try\n {\n PresentInternal(frame, forceWait);\n VideoDecoder.DisposeFrame(LastFrame);\n LastFrame = frame;\n\n if (child != null)\n child.LastFrame = frame;\n\n return true;\n\n }\n catch (Exception e)\n {\n if (CanWarn) Log.Warn($\"Present frame failed {e.Message} | {Device?.DeviceRemovedReason}\");\n VideoDecoder.DisposeFrame(frame);\n\n vpiv?.Dispose();\n\n return false;\n\n }\n finally\n {\n Monitor.Exit(lockDevice);\n }\n }\n\n if (CanDebug) Log.Debug(\"Dropped Frame - Lock timeout \" + (frame != null ? Utils.TicksToTime(frame.timestamp) : \"\"));\n VideoDecoder.DisposeFrame(frame);\n\n return false;\n }\n public void Present()\n {\n if (SCDisposed)\n return;\n\n // NOTE: We don't have TimeBeginPeriod, FpsForIdle will not be accurate\n lock (lockPresentTask)\n {\n if ((Config.Player.player == null || !Config.Player.player.requiresBuffering) && VideoDecoder.IsRunning && (VideoStream == null || VideoStream.FPS > 10)) // With slow FPS we need to refresh as fast as possible\n return;\n\n if (isPresenting)\n {\n lastPresentRequestAt = DateTime.UtcNow.Ticks;\n return;\n }\n\n isPresenting = true;\n }\n\n Task.Run(() =>\n {\n long presentingAt;\n do\n {\n long sleepMs = DateTime.UtcNow.Ticks - lastPresentAt;\n sleepMs = sleepMs < (long)(1.0 / Config.Player.IdleFps * 1000 * 10000) ? (long) (1.0 / Config.Player.IdleFps * 1000) : 0;\n if (sleepMs > 2)\n Thread.Sleep((int)sleepMs);\n\n presentingAt = DateTime.UtcNow.Ticks;\n RefreshLayout();\n lastPresentAt = DateTime.UtcNow.Ticks;\n\n } while (lastPresentRequestAt > presentingAt);\n\n isPresenting = false;\n });\n }\n internal void PresentInternal(VideoFrame frame, bool forceWait = true)\n {\n if (SCDisposed)\n return;\n\n // TBR: Replica performance issue with D3D11 (more zoom more gpu overload)\n if (frame.srvs == null) // videoProcessor can be FlyleafVP but the player can send us a cached frame from prev videoProcessor D3D11VP (check frame.srv instead of videoProcessor)\n {\n if (frame.avFrame != null)\n {\n vpivd.Texture2D.ArraySlice = (uint) frame.avFrame->data[1];\n vd1.CreateVideoProcessorInputView(VideoDecoder.textureFFmpeg, vpe, vpivd, out vpiv);\n }\n else\n {\n vpivd.Texture2D.ArraySlice = 0;\n vd1.CreateVideoProcessorInputView(frame.textures[0], vpe, vpivd, out vpiv);\n }\n\n vpsa[0].InputSurface = vpiv;\n vc.VideoProcessorBlt(vp, vpov, 0, 1, vpsa);\n swapChain.Present(Config.Video.VSync, forceWait ? PresentFlags.None : Config.Video.PresentFlags);\n\n vpiv.Dispose();\n }\n else\n {\n context.OMSetRenderTargets(backBufferRtv);\n context.ClearRenderTargetView(backBufferRtv, Config.Video._BackgroundColor);\n context.RSSetViewport(GetViewport);\n context.PSSetShaderResources(0, frame.srvs);\n context.Draw(6, 0);\n\n if (overlayTexture != null)\n {\n // Don't stretch the overlay (reduce height based on ratiox) | Sub's stream size might be different from video size (fix y based on percentage)\n var ratiox = (double)GetViewport.Width / overlayTextureOriginalWidth;\n var ratioy = (double)overlayTextureOriginalPosY / overlayTextureOriginalHeight;\n\n context.OMSetBlendState(blendStateAlpha);\n context.PSSetShaderResources(0, overlayTextureSRVs);\n context.RSSetViewport((float) (GetViewport.X + (overlayTextureOriginalPosX * ratiox)), (float) (GetViewport.Y + (GetViewport.Height * ratioy)), (float) (overlayTexture.Description.Width * ratiox), (float) (overlayTexture.Description.Height * ratiox));\n context.PSSetShader(ShaderBGRA);\n context.Draw(6, 0);\n\n // restore context\n context.PSSetShader(ShaderPS);\n context.OMSetBlendState(curPSCase == PSCase.RGBPacked ? blendStateAlpha : null);\n }\n\n swapChain.Present(Config.Video.VSync, forceWait ? PresentFlags.None : Config.Video.PresentFlags);\n }\n\n child?.PresentInternal(frame);\n }\n\n public void ClearOverlayTexture()\n {\n if (overlayTexture == null)\n return;\n\n overlayTexture?.Dispose();\n overlayTextureSrv?.Dispose();\n overlayTexture = null;\n overlayTextureSrv = null;\n }\n\n internal void CreateOverlayTexture(SubtitlesFrame frame, int streamWidth, int streamHeight)\n {\n var rect = frame.sub.rects[0];\n var stride = rect->linesize[0] * 4;\n\n overlayTextureOriginalWidth = streamWidth;\n overlayTextureOriginalHeight= streamHeight;\n overlayTextureOriginalPosX = rect->x;\n overlayTextureOriginalPosY = rect->y;\n overlayTextureDesc.Width = (uint)rect->w;\n overlayTextureDesc.Height = (uint)rect->h;\n\n byte[] data = ConvertBitmapSub(frame.sub, false);\n\n fixed(byte* ptr = data)\n {\n SubresourceData subData = new()\n {\n DataPointer = (nint)ptr,\n RowPitch = (uint)stride\n };\n\n overlayTexture?.Dispose();\n overlayTextureSrv?.Dispose();\n overlayTexture = Device.CreateTexture2D(overlayTextureDesc, new SubresourceData[] { subData });\n overlayTextureSrv = Device.CreateShaderResourceView(overlayTexture);\n overlayTextureSRVs[0] = overlayTextureSrv;\n }\n }\n\n public static byte[] ConvertBitmapSub(AVSubtitle sub, bool grey)\n {\n var rect = sub.rects[0];\n var stride = rect->linesize[0] * 4;\n\n byte[] data = new byte[rect->w * rect->h * 4];\n Span colors = stackalloc uint[256];\n\n fixed(byte* ptr = data)\n {\n var colorsData = new Span((byte*)rect->data[1], rect->nb_colors);\n\n for (int i = 0; i < colorsData.Length; i++)\n colors[i] = colorsData[i];\n\n ConvertPal(colors, 256, grey);\n\n for (int y = 0; y < rect->h; y++)\n {\n uint* xout =(uint*) (ptr + y * stride);\n byte* xin = ((byte*)rect->data[0]) + y * rect->linesize[0];\n\n for (int x = 0; x < rect->w; x++)\n *xout++ = colors[*xin++];\n }\n }\n\n return data;\n }\n\n static void ConvertPal(Span colors, int count, bool gray) // subs bitmap (source: mpv)\n {\n for (int n = 0; n < count; n++)\n {\n uint c = colors[n];\n uint b = c & 0xFF;\n uint g = (c >> 8) & 0xFF;\n uint r = (c >> 16) & 0xFF;\n uint a = (c >> 24) & 0xFF;\n\n if (gray)\n r = g = b = (r + g + b) / 3;\n\n // from straight to pre-multiplied alpha\n b = b * a / 255;\n g = g * a / 255;\n r = r * a / 255;\n colors[n] = b | (g << 8) | (r << 16) | (a << 24);\n }\n }\n\n public void RefreshLayout()\n {\n if (Monitor.TryEnter(lockDevice, 5))\n {\n try\n {\n if (SCDisposed)\n return;\n\n if (LastFrame != null && (LastFrame.textures != null || LastFrame.avFrame != null))\n PresentInternal(LastFrame);\n else if (Config.Video.ClearScreen)\n {\n context.ClearRenderTargetView(backBufferRtv, Config.Video._BackgroundColor);\n swapChain.Present(Config.Video.VSync, PresentFlags.None);\n }\n }\n catch (Exception e)\n {\n if (CanWarn) Log.Warn($\"Present idle failed {e.Message} | {Device.DeviceRemovedReason}\");\n }\n finally\n {\n Monitor.Exit(lockDevice);\n }\n }\n }\n public void ClearScreen()\n {\n ClearOverlayTexture();\n VideoDecoder.DisposeFrame(LastFrame);\n Present();\n }\n}\n"], ["/LLPlayer/FlyleafLib/Engine/Engine.cs", "using System.Collections.Generic;\nusing System.Threading.Tasks;\nusing System.Threading;\nusing System.Windows;\n\nusing FlyleafLib.MediaFramework.MediaDevice;\nusing FlyleafLib.MediaPlayer;\n\nnamespace FlyleafLib;\n\n/// \n/// Flyleaf Engine\n/// \npublic static class Engine\n{\n /// \n /// Engine has been loaded and is ready for use\n /// \n public static bool IsLoaded { get; private set; }\n\n /// \n /// Engine's configuration\n /// \n public static EngineConfig Config { get; private set; }\n\n /// \n /// Audio Engine\n /// \n public static AudioEngine Audio { get; private set; }\n\n /// \n /// Video Engine\n /// \n public static VideoEngine Video { get; private set; }\n\n /// \n /// Plugins Engine\n /// \n public static PluginsEngine Plugins { get; private set; }\n\n /// \n /// FFmpeg Engine\n /// \n public static FFmpegEngine FFmpeg { get; private set; }\n\n /// \n /// List of active Players\n /// \n public static List Players { get; private set; }\n\n public static event EventHandler\n Loaded;\n\n internal static LogHandler\n Log;\n\n static Thread tMaster;\n static object lockEngine = new();\n static bool isLoading;\n static int timePeriod;\n\n /// \n /// Initializes Flyleaf's Engine (Must be called from UI thread)\n /// \n /// Engine's configuration\n public static void Start(EngineConfig config = null) => StartInternal(config);\n\n /// \n /// Initializes Flyleaf's Engine Async (Must be called from UI thread)\n /// \n /// Engine's configuration\n public static void StartAsync(EngineConfig config = null) => StartInternal(config, true);\n\n /// \n /// Requests timeBeginPeriod(1) - You should call TimeEndPeriod1 when not required anymore\n /// \n public static void TimeBeginPeriod1()\n {\n lock (lockEngine)\n {\n timePeriod++;\n\n if (timePeriod == 1)\n {\n Log.Trace(\"timeBeginPeriod(1)\");\n Utils.NativeMethods.TimeBeginPeriod(1);\n }\n }\n }\n\n /// \n /// Stops previously requested timeBeginPeriod(1)\n /// \n public static void TimeEndPeriod1()\n {\n lock (lockEngine)\n {\n timePeriod--;\n\n if (timePeriod == 0)\n {\n Log.Trace(\"timeEndPeriod(1)\");\n Utils.NativeMethods.TimeEndPeriod(1);\n }\n }\n }\n\n private static void StartInternal(EngineConfig config = null, bool async = false)\n {\n lock (lockEngine)\n {\n if (isLoading)\n return;\n\n isLoading = true;\n\n Config = config ?? new EngineConfig();\n\n if (Application.Current == null)\n new Application();\n\n StartInternalUI();\n\n if (async)\n Task.Run(() => StartInternalNonUI());\n else\n StartInternalNonUI();\n }\n }\n\n private static void StartInternalUI()\n {\n Application.Current.Exit += (o, e) =>\n {\n Config.UIRefresh = false;\n Config.UIRefreshInterval = 1;\n\n while (Players.Count != 0)\n Players[0].Dispose();\n };\n\n Logger.SetOutput();\n\n Log = new LogHandler(\"[FlyleafEngine] \");\n\n Audio = new AudioEngine();\n if (Config.FFmpegLoadProfile == LoadProfile.All)\n AudioDevice.RefreshDevices();\n }\n\n private static void StartInternalNonUI()\n {\n var version = System.Reflection.Assembly.GetExecutingAssembly().GetName().Version;\n Log.Info($\"FlyleafLib {version.Major }.{version.Minor}.{version.Build}\");\n\n FFmpeg = new FFmpegEngine();\n Video = new VideoEngine();\n if (Config.FFmpegLoadProfile == LoadProfile.All)\n VideoDevice.RefreshDevices();\n Plugins = new PluginsEngine();\n Players = new List();\n\n IsLoaded = true;\n Loaded?.Invoke(null, null);\n\n if (Config.UIRefresh)\n StartThread();\n }\n internal static void AddPlayer(Player player)\n {\n lock (Players)\n Players.Add(player);\n }\n internal static int GetPlayerPos(int playerId)\n {\n for (int i=0; i { MasterThread(); })\n {\n Name = \"FlyleafEngine\",\n IsBackground = true\n };\n tMaster.Start();\n }\n internal static void MasterThread()\n {\n Log.Info(\"Thread started\");\n\n int curLoop = 0;\n int secondLoops = 1000 / Config.UIRefreshInterval;\n long prevTicks = DateTime.UtcNow.Ticks;\n double curSecond= 0;\n\n do\n {\n try\n {\n if (Players.Count == 0)\n {\n Thread.Sleep(Config.UIRefreshInterval);\n continue;\n }\n\n curLoop++;\n if (curLoop == secondLoops)\n {\n long curTicks = DateTime.UtcNow.Ticks;\n curSecond = (curTicks - prevTicks) / 10000000.0;\n prevTicks = curTicks;\n }\n\n lock (Players)\n foreach (var player in Players)\n {\n /* Every UIRefreshInterval */\n player.Activity.RefreshMode();\n\n /* Every Second */\n if (curLoop == secondLoops)\n {\n if (player.Config.Player.Stats)\n {\n var curStats = player.stats;\n // TODO: L: including Subtitles bytes?\n long curTotalBytes = player.VideoDemuxer.TotalBytes + player.AudioDemuxer.TotalBytes;\n long curVideoBytes = player.VideoDemuxer.VideoPackets.Bytes + player.AudioDemuxer.VideoPackets.Bytes;\n long curAudioBytes = player.VideoDemuxer.AudioPackets.Bytes + player.AudioDemuxer.AudioPackets.Bytes;\n\n player.bitRate = (curTotalBytes - curStats.TotalBytes) * 8 / 1000.0;\n player.Video.bitRate= (curVideoBytes - curStats.VideoBytes) * 8 / 1000.0;\n player.Audio.bitRate= (curAudioBytes - curStats.AudioBytes) * 8 / 1000.0;\n\n curStats.TotalBytes = curTotalBytes;\n curStats.VideoBytes = curVideoBytes;\n curStats.AudioBytes = curAudioBytes;\n\n if (player.IsPlaying)\n {\n player.Video.fpsCurrent = (player.Video.FramesDisplayed - curStats.FramesDisplayed) / curSecond;\n curStats.FramesDisplayed = player.Video.FramesDisplayed;\n }\n }\n }\n }\n\n if (curLoop == secondLoops)\n curLoop = 0;\n\n Action action = () =>\n {\n try\n {\n foreach (var player in Players)\n {\n /* Every UIRefreshInterval */\n\n // Activity Mode Refresh & Hide Mouse Cursor (FullScreen only)\n if (player.Activity.mode != player.Activity._Mode)\n player.Activity.SetMode();\n\n // CurTime / Buffered Duration (+Duration for HLS)\n if (!Config.UICurTimePerSecond)\n player.UpdateCurTime();\n else if (player.Status == Status.Paused)\n {\n if (player.MainDemuxer.IsRunning)\n player.UpdateCurTime();\n else\n player.UpdateBufferedDuration();\n }\n\n /* Every Second */\n if (curLoop == 0)\n {\n // Stats Refresh (BitRates / FrameDisplayed / FramesDropped / FPS)\n if (player.Config.Player.Stats)\n {\n player.BitRate = player.BitRate;\n player.Video.BitRate = player.Video.BitRate;\n player.Audio.BitRate = player.Audio.BitRate;\n\n if (player.IsPlaying)\n {\n player.Audio.FramesDisplayed= player.Audio.FramesDisplayed;\n player.Audio.FramesDropped = player.Audio.FramesDropped;\n\n player.Video.FramesDisplayed= player.Video.FramesDisplayed;\n player.Video.FramesDropped = player.Video.FramesDropped;\n player.Video.FPSCurrent = player.Video.FPSCurrent;\n }\n }\n }\n }\n } catch { }\n };\n\n Utils.UI(action);\n Thread.Sleep(Config.UIRefreshInterval);\n\n } catch { curLoop = 0; }\n\n } while (Config.UIRefresh);\n\n Log.Info(\"Thread stopped\");\n }\n}\n"], ["/LLPlayer/FlyleafLib/Utils/Utils.cs", "using System;\nusing System.Collections.Generic;\nusing System.Diagnostics;\nusing System.Globalization;\nusing System.IO;\nusing System.IO.Compression;\nusing System.Linq;\nusing System.Net.Http;\nusing System.Runtime.InteropServices;\nusing System.Text;\nusing System.Text.RegularExpressions;\nusing System.Threading;\nusing System.Threading.Tasks;\nusing System.Windows;\nusing CliWrap;\nusing Microsoft.Win32;\n\nnamespace FlyleafLib;\n\npublic static partial class Utils\n{\n // VLC : https://github.com/videolan/vlc/blob/master/modules/gui/qt/dialogs/preferences/simple_preferences.cpp\n // Kodi: https://github.com/xbmc/xbmc/blob/master/xbmc/settings/AdvancedSettings.cpp\n\n public static List ExtensionsAudio = new()\n {\n // VLC\n \"3ga\" , \"669\" , \"a52\" , \"aac\" , \"ac3\"\n , \"adt\" , \"adts\", \"aif\" , \"aifc\", \"aiff\"\n , \"au\" , \"amr\" , \"aob\" , \"ape\" , \"caf\"\n , \"cda\" , \"dts\" , \"flac\", \"it\" , \"m4a\"\n , \"m4p\" , \"mid\" , \"mka\" , \"mlp\" , \"mod\"\n , \"mp1\" , \"mp2\" , \"mp3\" , \"mpc\" , \"mpga\"\n , \"oga\" , \"oma\" , \"opus\", \"qcp\" , \"ra\"\n , \"rmi\" , \"snd\" , \"s3m\" , \"spx\" , \"tta\"\n , \"voc\" , \"vqf\" , \"w64\" , \"wav\" , \"wma\"\n , \"wv\" , \"xa\" , \"xm\"\n };\n\n public static List ExtensionsPictures = new()\n {\n \"apng\", \"bmp\", \"gif\", \"jpg\", \"jpeg\", \"png\", \"ico\", \"tif\", \"tiff\", \"tga\",\"jfif\"\n };\n\n public static List ExtensionsSubtitlesText = new()\n {\n \"ass\", \"ssa\", \"srt\", \"txt\", \"text\", \"vtt\"\n };\n\n public static List ExtensionsSubtitlesBitmap = new()\n {\n \"sub\", \"sup\"\n };\n\n public static List ExtensionsSubtitles = [..ExtensionsSubtitlesText, ..ExtensionsSubtitlesBitmap];\n\n public static List ExtensionsVideo = new()\n {\n // VLC\n \"3g2\" , \"3gp\" , \"3gp2\", \"3gpp\", \"amrec\"\n , \"amv\" , \"asf\" , \"avi\" , \"bik\" , \"divx\"\n , \"drc\" , \"dv\" , \"f4v\" , \"flv\" , \"gvi\"\n , \"gxf\" , \"m1v\" , \"m2t\" , \"m2v\" , \"m2ts\"\n , \"m4v\" , \"mkv\" , \"mov\" , \"mp2v\", \"mp4\"\n , \"mp4v\", \"mpa\" , \"mpe\" , \"mpeg\", \"mpeg1\"\n , \"mpeg2\",\"mpeg4\",\"mpg\" , \"mpv2\", \"mts\"\n , \"mtv\" , \"mxf\" , \"nsv\" , \"nuv\" , \"ogg\"\n , \"ogm\" , \"ogx\" , \"ogv\" , \"rec\" , \"rm\"\n , \"rmvb\", \"rpl\" , \"thp\" , \"tod\" , \"ts\"\n , \"tts\" , \"vob\" , \"vro\" , \"webm\", \"wmv\"\n , \"xesc\"\n\n // Additional\n , \"dav\"\n };\n\n private static int uniqueId;\n public static int GetUniqueId() { Interlocked.Increment(ref uniqueId); return uniqueId; }\n\n /// \n /// Begin Invokes the UI thread to execute the specified action\n /// \n /// \n public static void UI(Action action)\n {\n#if DEBUG\n if (Application.Current == null)\n return;\n#endif\n\n Application.Current.Dispatcher.BeginInvoke(action, System.Windows.Threading.DispatcherPriority.DataBind);\n }\n\n /// \n /// Begin Invokes the UI thread if required to execute the specified action\n /// \n /// \n public static void UIIfRequired(Action action)\n {\n if (Thread.CurrentThread.ManagedThreadId == Application.Current.Dispatcher.Thread.ManagedThreadId)\n action();\n else\n Application.Current.Dispatcher.BeginInvoke(action);\n }\n\n /// \n /// Invokes the UI thread to execute the specified action\n /// \n /// \n public static void UIInvoke(Action action) => Application.Current.Dispatcher.Invoke(action);\n\n /// \n /// Invokes the UI thread if required to execute the specified action\n /// \n /// \n public static void UIInvokeIfRequired(Action action)\n {\n if (Thread.CurrentThread.ManagedThreadId == Application.Current.Dispatcher.Thread.ManagedThreadId)\n action();\n else\n Application.Current.Dispatcher.Invoke(action);\n }\n\n public static Thread STA(Action action)\n {\n Thread thread = new(() => action());\n thread.SetApartmentState(ApartmentState.STA);\n thread.Start();\n\n return thread;\n }\n\n public static void STAInvoke(Action action)\n {\n Thread thread = STA(action);\n thread.Join();\n }\n\n public static int Align(int num, int align)\n {\n int mod = num % align;\n return mod == 0 ? num : num + (align - mod);\n }\n public static float Scale(float value, float inMin, float inMax, float outMin, float outMax)\n => ((value - inMin) * (outMax - outMin) / (inMax - inMin)) + outMin;\n\n /// \n /// Adds a windows firewall rule if not already exists for the specified program path\n /// \n /// Default value is Flyleaf\n /// Default value is current executable path\n public static void AddFirewallRule(string ruleName = null, string path = null)\n {\n Task.Run(() =>\n {\n try\n {\n if (string.IsNullOrEmpty(ruleName))\n ruleName = \"Flyleaf\";\n\n if (string.IsNullOrEmpty(path))\n path = Process.GetCurrentProcess().MainModule.FileName;\n\n path = $\"\\\"{path}\\\"\";\n\n // Check if rule already exists\n Process proc = new()\n {\n StartInfo = new ProcessStartInfo\n {\n FileName = \"cmd\",\n Arguments = $\"/C netsh advfirewall firewall show rule name={ruleName} verbose | findstr /L {path}\",\n CreateNoWindow = true,\n UseShellExecute = false,\n RedirectStandardOutput\n = true,\n WindowStyle = ProcessWindowStyle.Hidden\n }\n };\n\n proc.Start();\n proc.WaitForExit();\n\n if (proc.StandardOutput.Read() > 0)\n return;\n\n // Add rule with admin rights\n proc = new Process\n {\n StartInfo = new ProcessStartInfo\n {\n FileName = \"cmd\",\n Arguments = $\"/C netsh advfirewall firewall add rule name={ruleName} dir=in action=allow enable=yes program={path} profile=any &\" +\n $\"netsh advfirewall firewall add rule name={ruleName} dir=out action=allow enable=yes program={path} profile=any\",\n Verb = \"runas\",\n CreateNoWindow = true,\n UseShellExecute = true,\n WindowStyle = ProcessWindowStyle.Hidden\n }\n };\n\n proc.Start();\n proc.WaitForExit();\n\n Log($\"Firewall rule \\\"{ruleName}\\\" added for {path}\");\n }\n catch { }\n });\n }\n\n // We can't trust those\n //public static private bool IsDesignMode=> (bool) DesignerProperties.IsInDesignModeProperty.GetMetadata(typeof(DependencyObject)).DefaultValue;\n //public static bool IsDesignMode = LicenseManager.UsageMode == LicenseUsageMode.Designtime; // Will not work properly (need to be called from non-static class constructor)\n\n //public static bool IsWin11 = Regex.IsMatch(Registry.GetValue(@\"HKEY_LOCAL_MACHINE\\SOFTWARE\\Microsoft\\Windows NT\\CurrentVersion\", \"ProductName\", \"\").ToString(), \"Windows 11\");\n //public static bool IsWin10 = Regex.IsMatch(Registry.GetValue(@\"HKEY_LOCAL_MACHINE\\SOFTWARE\\Microsoft\\Windows NT\\CurrentVersion\", \"ProductName\", \"\").ToString(), \"Windows 10\");\n //public static bool IsWin8 = Regex.IsMatch(Registry.GetValue(@\"HKEY_LOCAL_MACHINE\\SOFTWARE\\Microsoft\\Windows NT\\CurrentVersion\", \"ProductName\", \"\").ToString(), \"Windows 8\");\n //public static bool IsWin7 = Regex.IsMatch(Registry.GetValue(@\"HKEY_LOCAL_MACHINE\\SOFTWARE\\Microsoft\\Windows NT\\CurrentVersion\", \"ProductName\", \"\").ToString(), \"Windows 7\");\n\n public static List GetMoviesSorted(List movies)\n {\n List moviesSorted = new();\n\n for (int i = 0; i < movies.Count; i++)\n {\n string ext = Path.GetExtension(movies[i]);\n\n if (ext == null || ext.Trim() == \"\")\n continue;\n\n if (ExtensionsVideo.Contains(ext[1..].ToLower()))\n moviesSorted.Add(movies[i]);\n }\n\n moviesSorted.Sort(new NaturalStringComparer());\n\n return moviesSorted;\n }\n public sealed class NaturalStringComparer : IComparer\n { public int Compare(string a, string b) => NativeMethods.StrCmpLogicalW(a, b); }\n\n public static string GetRecInnerException(Exception e)\n {\n string dump = \"\";\n var cur = e.InnerException;\n\n for (int i = 0; i < 4; i++)\n {\n if (cur == null) break;\n dump += \"\\r\\n - \" + cur.Message;\n cur = cur.InnerException;\n }\n\n return dump;\n }\n public static string GetUrlExtention(string url)\n {\n int index;\n if ((index = url.LastIndexOf('.')) > 0)\n return url[(index + 1)..].ToLower();\n\n return \"\";\n }\n\n public static List GetSystemLanguages()\n {\n List Languages = [ Language.English ];\n\n if (OriginalCulture.ThreeLetterISOLanguageName != \"eng\")\n Languages.Add(Language.Get(OriginalCulture));\n\n foreach (System.Windows.Forms.InputLanguage lang in System.Windows.Forms.InputLanguage.InstalledInputLanguages)\n if (lang.Culture.ThreeLetterISOLanguageName != OriginalCulture.ThreeLetterISOLanguageName && lang.Culture.ThreeLetterISOLanguageName != \"eng\")\n Languages.Add(Language.Get(lang.Culture));\n\n return Languages;\n }\n\n public static CultureInfo OriginalCulture { get; private set; }\n public static CultureInfo OriginalUICulture { get; private set; }\n\n public static void SaveOriginalCulture()\n {\n OriginalCulture = CultureInfo.CurrentCulture;\n OriginalUICulture = CultureInfo.CurrentUICulture;\n }\n\n public class MediaParts\n {\n public string Title { get; set; } = \"\";\n public string Extension { get; set; } = \"\";\n public int Season { get; set; }\n public int Episode { get; set; }\n public int Year { get; set; }\n }\n public static MediaParts GetMediaParts(string title, bool checkSeasonEpisodeOnly = false)\n {\n Match res;\n MediaParts mp = new();\n int index = int.MaxValue; // title end pos\n\n res = RxSeasonEpisode1().Match(title);\n if (!res.Success)\n {\n res = RxSeasonEpisode2().Match(title);\n\n if (!res.Success)\n res = RxEpisodePart().Match(title);\n }\n\n if (res.Groups.Count > 1)\n {\n if (res.Groups[\"season\"].Value != \"\")\n mp.Season = int.Parse(res.Groups[\"season\"].Value);\n\n if (res.Groups[\"episode\"].Value != \"\")\n mp.Episode = int.Parse(res.Groups[\"episode\"].Value);\n\n if (checkSeasonEpisodeOnly || res.Index == 0) // 0: No title just season/episode\n return mp;\n\n index = res.Index;\n }\n\n mp.Extension = GetUrlExtention(title);\n if (mp.Extension.Length > 0 && mp.Extension.Length < 5)\n title = title[..(title.Length - mp.Extension.Length - 1)];\n\n // non-movie words, 1080p, 2015\n if ((res = RxExtended().Match(title)).Index > 0 && res.Index < index)\n index = res.Index;\n\n if ((res = RxDirectorsCut().Match(title)).Index > 0 && res.Index < index)\n index = res.Index;\n\n if ((res = RxBrrip().Match(title)).Index > 0 && res.Index < index)\n index = res.Index;\n\n if ((res = RxResolution().Match(title)).Index > 0 && res.Index < index)\n index = res.Index;\n\n res = RxYear().Match(title);\n Group gc;\n if (res.Success && (gc = res.Groups[\"year\"]).Index > 2)\n {\n mp.Year = int.Parse(gc.Value);\n if (res.Index < index)\n index = res.Index;\n }\n\n if (index != int.MaxValue)\n title = title[..index];\n\n title = title.Replace(\".\", \" \").Replace(\"_\", \" \");\n title = RxSpaces().Replace(title, \" \");\n title = RxNonAlphaNumeric().Replace(title, \"\");\n\n mp.Title = title.Trim();\n\n return mp;\n }\n\n public static string FindNextAvailableFile(string fileName)\n {\n if (!File.Exists(fileName)) return fileName;\n\n string tmp = Path.Combine(Path.GetDirectoryName(fileName), Regex.Replace(Path.GetFileNameWithoutExtension(fileName), @\"(.*) (\\([0-9]+)\\)$\", \"$1\"));\n string newName;\n\n for (int i = 1; i < 101; i++)\n {\n newName = tmp + \" (\" + i + \")\" + Path.GetExtension(fileName);\n if (!File.Exists(newName)) return newName;\n }\n\n return null;\n }\n public static string GetValidFileName(string name) => string.Join(\"_\", name.Split(Path.GetInvalidFileNameChars()));\n\n public static string FindFileBelow(string filename)\n {\n string current = AppDomain.CurrentDomain.BaseDirectory;\n\n while (current != null)\n {\n if (File.Exists(Path.Combine(current, filename)))\n return Path.Combine(current, filename);\n\n current = Directory.GetParent(current)?.FullName;\n }\n\n return null;\n }\n public static string GetFolderPath(string folder)\n {\n if (folder.StartsWith(\":\"))\n {\n folder = folder[1..];\n return FindFolderBelow(folder);\n }\n\n return Path.IsPathRooted(folder) ? folder : Path.GetFullPath(folder);\n }\n\n public static string FindFolderBelow(string folder)\n {\n string current = AppDomain.CurrentDomain.BaseDirectory;\n\n while (current != null)\n {\n if (Directory.Exists(Path.Combine(current, folder)))\n return Path.Combine(current, folder);\n\n current = Directory.GetParent(current)?.FullName;\n }\n\n return null;\n }\n public static string GetUserDownloadPath() { try { return Registry.CurrentUser.OpenSubKey(@\"Software\\Microsoft\\Windows\\CurrentVersion\\Explorer\\User Shell Folders\\\").GetValue(\"{374DE290-123F-4565-9164-39C4925E467B}\").ToString(); } catch (Exception) { return null; } }\n public static string DownloadToString(string url, int timeoutMs = 30000)\n {\n try\n {\n using HttpClient client = new() { Timeout = TimeSpan.FromMilliseconds(timeoutMs) };\n return client.GetAsync(url).Result.Content.ReadAsStringAsync().Result;\n }\n catch (Exception e)\n {\n Log($\"Download failed {e.Message} [Url: {url ?? \"Null\"}]\");\n }\n\n return null;\n }\n\n public static MemoryStream DownloadFile(string url, int timeoutMs = 30000)\n {\n MemoryStream ms = new();\n\n try\n {\n using HttpClient client = new() { Timeout = TimeSpan.FromMilliseconds(timeoutMs) };\n client.GetAsync(url).Result.Content.CopyToAsync(ms).Wait();\n }\n catch (Exception e)\n {\n Log($\"Download failed {e.Message} [Url: {url ?? \"Null\"}]\");\n }\n\n return ms;\n }\n\n public static bool DownloadFile(string url, string filename, int timeoutMs = 30000, bool overwrite = true)\n {\n try\n {\n using HttpClient client = new() { Timeout = TimeSpan.FromMilliseconds(timeoutMs) };\n using FileStream fs = new(filename, overwrite ? FileMode.Create : FileMode.CreateNew);\n client.GetAsync(url).Result.Content.CopyToAsync(fs).Wait();\n\n return true;\n }\n catch (Exception e)\n {\n Log($\"Download failed {e.Message} [Url: {url ?? \"Null\"}, Path: {filename ?? \"Null\"}]\");\n }\n\n return false;\n }\n public static string FixFileUrl(string url)\n {\n try\n {\n if (url == null || url.Length < 5)\n return url;\n\n if (url[..5].ToLower() == \"file:\")\n return new Uri(url).LocalPath;\n }\n catch { }\n\n return url;\n }\n\n /// \n /// Convert Windows lnk file path to target path\n /// \n /// lnk file path\n /// targetPath or null\n public static string GetLnkTargetPath(string filepath)\n {\n try\n {\n // Using dynamic COM\n // ref: https://stackoverflow.com/a/49198242/9070784\n dynamic windowsShell = Activator.CreateInstance(Type.GetTypeFromProgID(\"WScript.Shell\", true)!);\n dynamic shortcut = windowsShell!.CreateShortcut(filepath);\n string targetPath = shortcut.TargetPath;\n\n if (string.IsNullOrEmpty(targetPath))\n {\n throw new InvalidOperationException(\"TargetPath is empty.\");\n }\n\n return targetPath;\n }\n catch (Exception e)\n {\n Log($\"Resolving Windows Link failed {e.Message} [FilePath: {filepath}]\");\n\n return null;\n }\n }\n\n public static string GetBytesReadable(nuint i)\n {\n // Determine the suffix and readable value\n string suffix;\n double readable;\n if (i >= 0x1000000000000000) // Exabyte\n {\n suffix = \"EB\";\n readable = i >> 50;\n }\n else if (i >= 0x4000000000000) // Petabyte\n {\n suffix = \"PB\";\n readable = i >> 40;\n }\n else if (i >= 0x10000000000) // Terabyte\n {\n suffix = \"TB\";\n readable = i >> 30;\n }\n else if (i >= 0x40000000) // Gigabyte\n {\n suffix = \"GB\";\n readable = i >> 20;\n }\n else if (i >= 0x100000) // Megabyte\n {\n suffix = \"MB\";\n readable = i >> 10;\n }\n else if (i >= 0x400) // Kilobyte\n {\n suffix = \"KB\";\n readable = i;\n }\n else\n {\n return i.ToString(\"0 B\"); // Byte\n }\n // Divide by 1024 to get fractional value\n readable /= 1024;\n // Return formatted number with suffix\n return readable.ToString(\"0.## \") + suffix;\n }\n static List gpuCounters;\n public static void GetGPUCounters()\n {\n PerformanceCounterCategory category = new(\"GPU Engine\");\n string[] counterNames = category.GetInstanceNames();\n gpuCounters = new List();\n\n foreach (string counterName in counterNames)\n if (counterName.EndsWith(\"engtype_3D\"))\n foreach (var counter in category.GetCounters(counterName))\n if (counter.CounterName == \"Utilization Percentage\")\n gpuCounters.Add(counter);\n }\n public static float GetGPUUsage()\n {\n float result = 0f;\n\n try\n {\n if (gpuCounters == null) GetGPUCounters();\n\n gpuCounters.ForEach(x => { _ = x.NextValue(); });\n Thread.Sleep(1000);\n gpuCounters.ForEach(x => { result += x.NextValue(); });\n\n }\n catch (Exception e) { Log($\"[GPUUsage] Error {e.Message}\"); result = -1f; GetGPUCounters(); }\n\n return result;\n }\n public static string GZipDecompress(string filename)\n {\n string newFileName = \"\";\n\n FileInfo fileToDecompress = new(filename);\n using (var originalFileStream = fileToDecompress.OpenRead())\n {\n string currentFileName = fileToDecompress.FullName;\n newFileName = currentFileName.Remove(currentFileName.Length - fileToDecompress.Extension.Length);\n\n using var decompressedFileStream = File.Create(newFileName);\n using GZipStream decompressionStream = new(originalFileStream, CompressionMode.Decompress);\n decompressionStream.CopyTo(decompressedFileStream);\n }\n\n return newFileName;\n }\n\n public static Dictionary ParseQueryString(ReadOnlySpan query)\n {\n Dictionary dict = [];\n\n int nameStart = 0;\n int equalPos = -1;\n for (int i = 0; i < query.Length; i++)\n {\n if (query[i] == '=')\n equalPos = i;\n else if (query[i] == '&')\n {\n if (equalPos == -1)\n dict[query[nameStart..i].ToString()] = null;\n else\n dict[query[nameStart..equalPos].ToString()] = query.Slice(equalPos + 1, i - equalPos - 1).ToString();\n\n equalPos = -1;\n nameStart = i + 1;\n }\n }\n\n if (nameStart < query.Length - 1)\n {\n if (equalPos == -1)\n dict[query[nameStart..].ToString()] = null;\n else\n dict[query[nameStart..equalPos].ToString()] = query.Slice(equalPos + 1, query.Length - equalPos - 1).ToString();\n }\n\n return dict;\n }\n\n public unsafe static string BytePtrToStringUTF8(byte* bytePtr)\n => Marshal.PtrToStringUTF8((nint)bytePtr);\n\n public static System.Windows.Media.Color WinFormsToWPFColor(System.Drawing.Color sColor)\n => System.Windows.Media.Color.FromArgb(sColor.A, sColor.R, sColor.G, sColor.B);\n public static System.Drawing.Color WPFToWinFormsColor(System.Windows.Media.Color wColor)\n => System.Drawing.Color.FromArgb(wColor.A, wColor.R, wColor.G, wColor.B);\n\n public static System.Windows.Media.Color VorticeToWPFColor(Vortice.Mathematics.Color sColor)\n => System.Windows.Media.Color.FromArgb(sColor.A, sColor.R, sColor.G, sColor.B);\n public static Vortice.Mathematics.Color WPFToVorticeColor(System.Windows.Media.Color wColor)\n => new Vortice.Mathematics.Color(wColor.R, wColor.G, wColor.B, wColor.A);\n\n public static double SWFREQ_TO_TICKS = 10000000.0 / Stopwatch.Frequency;\n public static string ToHexadecimal(byte[] bytes)\n {\n StringBuilder hexBuilder = new();\n for (int i = 0; i < bytes.Length; i++)\n {\n hexBuilder.Append(bytes[i].ToString(\"x2\"));\n }\n return hexBuilder.ToString();\n }\n public static int GCD(int a, int b) => b == 0 ? a : GCD(b, a % b);\n public static string TicksToTime(long ticks) => new TimeSpan(ticks).ToString();\n public static void Log(string msg) { try { Debug.WriteLine($\"[{DateTime.Now:hh.mm.ss.fff}] {msg}\"); } catch (Exception) { Debug.WriteLine($\"[............] [MediaFramework] {msg}\"); } }\n\n [GeneratedRegex(\"[^a-z0-9]extended\", RegexOptions.IgnoreCase)]\n private static partial Regex RxExtended();\n [GeneratedRegex(\"[^a-z0-9]directors.cut\", RegexOptions.IgnoreCase)]\n private static partial Regex RxDirectorsCut();\n [GeneratedRegex(@\"(^|[^a-z0-9])(s|season)[^a-z0-9]*(?[0-9]{1,2})[^a-z0-9]*(e|episode|part)[^a-z0-9]*(?[0-9]{1,2})($|[^a-z0-9])\", RegexOptions.IgnoreCase)]\n\n // s|season 01 ... e|episode|part 01\n private static partial Regex RxSeasonEpisode1();\n [GeneratedRegex(@\"(^|[^a-z0-9])(?[0-9]{1,2})x(?[0-9]{1,2})($|[^a-z0-9])\", RegexOptions.IgnoreCase)]\n // 01x01\n private static partial Regex RxSeasonEpisode2();\n // TODO: in case of single season should check only for e|episode|part 01\n [GeneratedRegex(@\"(^|[^a-z0-9])(episode|part)[^a-z0-9]*(?[0-9]{1,2})($|[^a-z0-9])\", RegexOptions.IgnoreCase)]\n private static partial Regex RxEpisodePart();\n [GeneratedRegex(\"[^a-z0-9]brrip\", RegexOptions.IgnoreCase)]\n private static partial Regex RxBrrip();\n\n [GeneratedRegex(\"[^a-z0-9][0-9]{3,4}p\", RegexOptions.IgnoreCase)]\n private static partial Regex RxResolution();\n [GeneratedRegex(@\"[^a-z0-9](?(19|20)[0-9][0-9])($|[^a-z0-9])\", RegexOptions.IgnoreCase)]\n private static partial Regex RxYear();\n [GeneratedRegex(@\"\\s{2,}\")]\n private static partial Regex RxSpaces();\n [GeneratedRegex(@\"[^a-z0-9]$\", RegexOptions.IgnoreCase)]\n private static partial Regex RxNonAlphaNumeric();\n\n public static string TruncateString(string str, int maxLength, string suffix = \"...\")\n {\n if (string.IsNullOrEmpty(str))\n return str;\n\n if (str.Length <= maxLength)\n return str;\n\n int availableLength = maxLength - suffix.Length;\n\n if (availableLength <= 0)\n {\n return suffix.Substring(0, Math.Min(maxLength, suffix.Length));\n }\n\n return str.Substring(0, availableLength) + suffix;\n }\n\n // TODO: L: move to app, using event\n public static void PlayCompletionSound()\n {\n string soundPath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, \"Assets/completion.mp3\");\n\n if (!File.Exists(soundPath))\n {\n return;\n }\n\n UI(() =>\n {\n try\n {\n // play completion sound\n System.Windows.Media.MediaPlayer mp = new();\n mp.Open(new Uri(soundPath));\n mp.Play();\n }\n catch\n {\n // ignored\n }\n });\n }\n\n public static string CommandToText(this Command cmd)\n {\n if (cmd.TargetFilePath.Any(char.IsWhiteSpace))\n {\n return $\"& \\\"{cmd.TargetFilePath}\\\" {cmd.Arguments}\";\n }\n\n return cmd.ToString();\n }\n}\n"], ["/LLPlayer/FlyleafLib/MediaPlayer/Player.Extra.cs", "using System;\nusing System.Drawing.Imaging;\nusing System.IO;\nusing System.Windows;\n\nusing FlyleafLib.MediaFramework.MediaDecoder;\nusing FlyleafLib.MediaFramework.MediaDemuxer;\nusing FlyleafLib.MediaFramework.MediaFrame;\nusing FlyleafLib.MediaFramework.MediaRenderer;\n\nusing static FlyleafLib.Utils;\nusing static FlyleafLib.Logger;\n\nnamespace FlyleafLib.MediaPlayer;\n\nunsafe partial class Player\n{\n public bool IsOpenFileDialogOpen { get; private set; }\n\n\n public void SeekBackward() => SeekBackward_(Config.Player.SeekOffset, Config.Player.SeekOffsetAccurate);\n public void SeekBackward2() => SeekBackward_(Config.Player.SeekOffset2, Config.Player.SeekOffsetAccurate2);\n public void SeekBackward3() => SeekBackward_(Config.Player.SeekOffset3, Config.Player.SeekOffsetAccurate3);\n public void SeekBackward4() => SeekBackward_(Config.Player.SeekOffset4, Config.Player.SeekOffsetAccurate4);\n public void SeekBackward_(long offset, bool accurate)\n {\n if (!CanPlay)\n return;\n\n long seekTs = CurTime - (CurTime % offset) - offset;\n\n if (Config.Player.SeekAccurate || accurate)\n SeekAccurate(Math.Max((int) (seekTs / 10000), 0));\n else\n Seek(Math.Max((int) (seekTs / 10000), 0), false);\n }\n\n public void SeekForward() => SeekForward_(Config.Player.SeekOffset, Config.Player.SeekOffsetAccurate);\n public void SeekForward2() => SeekForward_(Config.Player.SeekOffset2, Config.Player.SeekOffsetAccurate2);\n public void SeekForward3() => SeekForward_(Config.Player.SeekOffset3, Config.Player.SeekOffsetAccurate3);\n public void SeekForward4() => SeekForward_(Config.Player.SeekOffset4, Config.Player.SeekOffsetAccurate4);\n public void SeekForward_(long offset, bool accurate)\n {\n if (!CanPlay)\n return;\n\n long seekTs = CurTime - (CurTime % offset) + offset;\n\n if (seekTs > Duration && !isLive)\n return;\n\n if (Config.Player.SeekAccurate || accurate)\n SeekAccurate((int)(seekTs / 10000));\n else\n Seek((int)(seekTs / 10000), true);\n }\n\n public void SeekToChapter(Demuxer.Chapter chapter) =>\n /* TODO\n* Accurate pts required (backward/forward check)\n* Get current chapter implementation + next/prev\n*/\n Seek((int)(chapter.StartTime / 10000.0), true);\n\n public void CopyToClipboard()\n {\n var url = decoder.Playlist.Url;\n if (url == null)\n return;\n\n Clipboard.SetText(url);\n OSDMessage = $\"Copy {url}\";\n }\n public void CopyItemToClipboard()\n {\n if (decoder.Playlist.Selected == null || decoder.Playlist.Selected.DirectUrl == null)\n return;\n\n string url = decoder.Playlist.Selected.DirectUrl;\n\n Clipboard.SetText(url);\n OSDMessage = $\"Copy {url}\";\n }\n public void OpenFromClipboard()\n {\n string text = Clipboard.GetText();\n if (!string.IsNullOrWhiteSpace(text))\n {\n OpenAsync(text);\n }\n }\n\n public void OpenFromClipboardSafe()\n {\n if (decoder.Playlist.Selected != null)\n {\n return;\n }\n\n OpenFromClipboard();\n }\n\n public void OpenFromFileDialog()\n {\n int prevTimeout = Activity.Timeout;\n Activity.IsEnabled = false;\n Activity.Timeout = 0;\n IsOpenFileDialogOpen = true;\n\n System.Windows.Forms.OpenFileDialog openFileDialog = new();\n\n // If there is currently an open file, set that folder as the base folder\n if (decoder.Playlist.Url != null && File.Exists(decoder.Playlist.Url))\n {\n var folder = Path.GetDirectoryName(decoder.Playlist.Url);\n if (folder != null)\n openFileDialog.InitialDirectory = folder;\n }\n\n var res = openFileDialog.ShowDialog();\n\n if (res == System.Windows.Forms.DialogResult.OK)\n OpenAsync(openFileDialog.FileName);\n\n Activity.Timeout = prevTimeout;\n Activity.IsEnabled = true;\n IsOpenFileDialogOpen = false;\n }\n\n public void ShowFrame(int frameIndex)\n {\n if (!Video.IsOpened || !CanPlay || VideoDemuxer.IsHLSLive) return;\n\n lock (lockActions)\n {\n Pause();\n dFrame = null;\n for (int i = 0; i < subNum; i++)\n {\n sFrames[i] = null;\n SubtitleClear(i);\n }\n\n decoder.Flush();\n decoder.RequiresResync = true;\n\n vFrame = VideoDecoder.GetFrame(frameIndex);\n if (vFrame == null) return;\n\n if (CanDebug) Log.Debug($\"SFI: {VideoDecoder.GetFrameNumber(vFrame.timestamp)}\");\n\n curTime = vFrame.timestamp;\n renderer.Present(vFrame);\n reversePlaybackResync = true;\n vFrame = null;\n\n UI(() => UpdateCurTime());\n }\n }\n\n // Whether video queue should be flushed as it could have opposite direction frames\n bool shouldFlushNext;\n bool shouldFlushPrev;\n public void ShowFrameNext()\n {\n if (!Video.IsOpened || !CanPlay || VideoDemuxer.IsHLSLive)\n return;\n\n lock (lockActions)\n {\n Pause();\n\n if (Status == Status.Ended)\n {\n status = Status.Paused;\n UI(() => Status = Status);\n }\n\n shouldFlushPrev = true;\n decoder.RequiresResync = true;\n\n if (shouldFlushNext)\n {\n decoder.StopThreads();\n decoder.Flush();\n shouldFlushNext = false;\n\n var vFrame = VideoDecoder.GetFrame(VideoDecoder.GetFrameNumber(CurTime));\n VideoDecoder.DisposeFrame(vFrame);\n }\n\n for (int i = 0; i < subNum; i++)\n {\n sFrames[i] = null;\n SubtitleClear(i);\n }\n\n if (VideoDecoder.Frames.IsEmpty)\n vFrame = VideoDecoder.GetFrameNext();\n else\n VideoDecoder.Frames.TryDequeue(out vFrame);\n\n if (vFrame == null)\n return;\n\n if (CanDebug) Log.Debug($\"SFN: {VideoDecoder.GetFrameNumber(vFrame.timestamp)}\");\n\n curTime = curTime = vFrame.timestamp;\n renderer.Present(vFrame);\n reversePlaybackResync = true;\n vFrame = null;\n\n UI(() => UpdateCurTime());\n }\n }\n public void ShowFramePrev()\n {\n if (!Video.IsOpened || !CanPlay || VideoDemuxer.IsHLSLive)\n return;\n\n lock (lockActions)\n {\n Pause();\n\n if (Status == Status.Ended)\n {\n status = Status.Paused;\n UI(() => Status = Status);\n }\n\n shouldFlushNext = true;\n decoder.RequiresResync = true;\n\n if (shouldFlushPrev)\n {\n decoder.StopThreads();\n decoder.Flush();\n shouldFlushPrev = false;\n }\n\n for (int i = 0; i < subNum; i++)\n {\n sFrames[i] = null;\n SubtitleClear(i);\n }\n\n if (VideoDecoder.Frames.IsEmpty)\n {\n // Temp fix for previous timestamps until we seperate GetFrame for Extractor and the Player\n reversePlaybackResync = true;\n int askedFrame = VideoDecoder.GetFrameNumber(CurTime) - 1;\n //Log.Debug($\"CurTime1: {TicksToTime(CurTime)}, Asked: {askedFrame}\");\n vFrame = VideoDecoder.GetFrame(askedFrame);\n if (vFrame == null) return;\n\n int recvFrame = VideoDecoder.GetFrameNumber(vFrame.timestamp);\n //Log.Debug($\"CurTime2: {TicksToTime(vFrame.timestamp)}, Got: {recvFrame}\");\n if (askedFrame != recvFrame)\n {\n VideoDecoder.DisposeFrame(vFrame);\n vFrame = null;\n vFrame = askedFrame > recvFrame\n ? VideoDecoder.GetFrame(VideoDecoder.GetFrameNumber(CurTime))\n : VideoDecoder.GetFrame(VideoDecoder.GetFrameNumber(CurTime) - 2);\n }\n }\n else\n VideoDecoder.Frames.TryDequeue(out vFrame);\n\n if (vFrame == null)\n return;\n\n if (CanDebug) Log.Debug($\"SFB: {VideoDecoder.GetFrameNumber(vFrame.timestamp)}\");\n\n curTime = vFrame.timestamp;\n renderer.Present(vFrame);\n vFrame = null;\n UI(() => UpdateCurTime()); // For some strange reason this will not be updated on KeyDown (only on KeyUp) which doesn't happen on ShowFrameNext (GPU overload? / Thread.Sleep underlying in UI thread?)\n }\n }\n\n public void SpeedUp() => Speed += Config.Player.SpeedOffset;\n public void SpeedUp2() => Speed += Config.Player.SpeedOffset2;\n public void SpeedDown() => Speed -= Config.Player.SpeedOffset;\n public void SpeedDown2() => Speed -= Config.Player.SpeedOffset2;\n\n public void RotateRight() => renderer.Rotation = (renderer.Rotation + 90) % 360;\n public void RotateLeft() => renderer.Rotation = renderer.Rotation < 90 ? 360 + renderer.Rotation - 90 : renderer.Rotation - 90;\n\n public void FullScreen() => Host?.Player_SetFullScreen(true);\n public void NormalScreen() => Host?.Player_SetFullScreen(false);\n public void ToggleFullScreen()\n {\n if (Host == null)\n return;\n\n if (Host.Player_GetFullScreen())\n Host.Player_SetFullScreen(false);\n else\n Host.Player_SetFullScreen(true);\n }\n\n /// \n /// Starts recording (uses Config.Player.FolderRecordings and default filename title_curTime)\n /// \n public void StartRecording()\n {\n if (!CanPlay)\n return;\n try\n {\n if (!Directory.Exists(Config.Player.FolderRecordings))\n Directory.CreateDirectory(Config.Player.FolderRecordings);\n\n string filename = GetValidFileName(string.IsNullOrEmpty(Playlist.Selected.Title) ? \"Record\" : Playlist.Selected.Title) + $\"_{new TimeSpan(CurTime):hhmmss}.\" + decoder.Extension;\n filename = FindNextAvailableFile(Path.Combine(Config.Player.FolderRecordings, filename));\n StartRecording(ref filename, false);\n } catch { }\n }\n\n /// \n /// Starts recording\n /// \n /// Path of the new recording file\n /// You can force the output container's format or use the recommended one to avoid incompatibility\n public void StartRecording(ref string filename, bool useRecommendedExtension = true)\n {\n if (!CanPlay)\n return;\n\n OSDMessage = $\"Start recording to {Path.GetFileName(filename)}\";\n decoder.StartRecording(ref filename, useRecommendedExtension);\n IsRecording = decoder.IsRecording;\n }\n\n /// \n /// Stops recording\n /// \n public void StopRecording()\n {\n decoder.StopRecording();\n IsRecording = decoder.IsRecording;\n OSDMessage = \"Stop recording\";\n }\n public void ToggleRecording()\n {\n if (!CanPlay) return;\n\n if (IsRecording)\n StopRecording();\n else\n StartRecording();\n }\n\n /// \n /// Saves the current video frame (encoding based on file extention .bmp, .png, .jpg)\n /// If filename not specified will use Config.Player.FolderSnapshots and with default filename title_frameNumber.ext (ext from Config.Player.SnapshotFormat)\n /// If width/height not specified will use the original size. If one of them will be set, the other one will be set based on original ratio\n /// If frame not specified will use the current/last frame\n /// \n /// Specify the filename (null: will use Config.Player.FolderSnapshots and with default filename title_frameNumber.ext (ext from Config.Player.SnapshotFormat)\n /// Specify the width (-1: will keep the ratio based on height)\n /// Specify the height (-1: will keep the ratio based on width)\n /// Specify the frame (null: will use the current/last frame)\n /// \n public void TakeSnapshotToFile(string filename = null, int width = -1, int height = -1, VideoFrame frame = null)\n {\n if (!CanPlay)\n return;\n\n if (filename == null)\n {\n try\n {\n if (!Directory.Exists(Config.Player.FolderSnapshots))\n Directory.CreateDirectory(Config.Player.FolderSnapshots);\n\n // TBR: if frame is specified we don't know the frame's number\n filename = GetValidFileName(string.IsNullOrEmpty(Playlist.Selected.Title) ? \"Snapshot\" : Playlist.Selected.Title) + $\"_{(frame == null ? VideoDecoder.GetFrameNumber(CurTime).ToString() : \"X\")}.{Config.Player.SnapshotFormat}\";\n filename = FindNextAvailableFile(Path.Combine(Config.Player.FolderSnapshots, filename));\n } catch { return; }\n }\n\n string ext = GetUrlExtention(filename);\n\n ImageFormat imageFormat;\n\n switch (ext)\n {\n case \"bmp\":\n imageFormat = ImageFormat.Bmp;\n break;\n\n case \"png\":\n imageFormat = ImageFormat.Png;\n break;\n\n case \"jpg\":\n case \"jpeg\":\n imageFormat = ImageFormat.Jpeg;\n break;\n\n default:\n throw new Exception($\"Invalid snapshot extention '{ext}' (valid .bmp, .png, .jpeg, .jpg\");\n }\n\n if (renderer == null)\n return;\n\n var snapshotBitmap = renderer.GetBitmap(width, height, frame);\n if (snapshotBitmap == null)\n return;\n\n Exception e = null;\n try\n {\n snapshotBitmap.Save(filename, imageFormat);\n\n UI(() =>\n {\n OSDMessage = $\"Save snapshot to {Path.GetFileName(filename)}\";\n });\n }\n catch (Exception e2)\n {\n e = e2;\n }\n snapshotBitmap.Dispose();\n\n if (e != null)\n throw e;\n }\n\n /// \n /// Returns a bitmap of the current or specified video frame\n /// If width/height not specified will use the original size. If one of them will be set, the other one will be set based on original ratio\n /// If frame not specified will use the current/last frame\n /// \n /// Specify the width (-1: will keep the ratio based on height)\n /// Specify the height (-1: will keep the ratio based on width)\n /// Specify the frame (null: will use the current/last frame)\n /// \n public System.Drawing.Bitmap TakeSnapshotToBitmap(int width = -1, int height = -1, VideoFrame frame = null) => renderer?.GetBitmap(width, height, frame);\n\n public void ZoomIn() => Zoom += Config.Player.ZoomOffset;\n public void ZoomOut() { if (Zoom - Config.Player.ZoomOffset < 1) return; Zoom -= Config.Player.ZoomOffset; }\n\n /// \n /// Pan zoom in with center point\n /// \n /// \n public void ZoomIn(Point p) { renderer.ZoomWithCenterPoint(p, renderer.Zoom + Config.Player.ZoomOffset / 100.0); RaiseUI(nameof(Zoom)); }\n\n /// \n /// Pan zoom out with center point\n /// \n /// \n public void ZoomOut(Point p){ double zoom = renderer.Zoom - Config.Player.ZoomOffset / 100.0; if (zoom < 0.001) return; renderer.ZoomWithCenterPoint(p, zoom); RaiseUI(nameof(Zoom)); }\n\n /// \n /// Pan zoom (no raise)\n /// \n /// \n public void SetZoom(double zoom) => renderer.SetZoom(zoom);\n /// \n /// Pan zoom's center point (no raise, no center point change)\n /// \n /// \n public void SetZoomCenter(Point p) => renderer.SetZoomCenter(p);\n /// \n /// Pan zoom and center point (no raise)\n /// \n /// \n /// \n public void SetZoomAndCenter(double zoom, Point p) => renderer.SetZoomAndCenter(zoom, p);\n\n public void ResetAll()\n {\n ResetSpeed();\n ResetRotation();\n ResetZoom();\n }\n\n public void ResetSpeed()\n {\n Speed = 1;\n }\n\n public void ResetRotation()\n {\n Rotation = 0;\n }\n\n public void ResetZoom()\n {\n bool npx = renderer.PanXOffset != 0;\n bool npy = renderer.PanYOffset != 0;\n bool npz = renderer.Zoom != 1;\n renderer.SetPanAll(0, 0, Rotation, 1, Renderer.ZoomCenterPoint, true); // Pan X/Y, Rotation, Zoom, Zoomcenter, Refresh\n\n UI(() =>\n {\n if (npx) Raise(nameof(PanXOffset));\n if (npy) Raise(nameof(PanYOffset));\n if (npz) Raise(nameof(Zoom));\n });\n }\n}\n"], ["/LLPlayer/FlyleafLib/MediaFramework/MediaRenderer/ShaderCompiler.cs", "using System.Collections.Generic;\nusing System.Text;\nusing System.Threading;\n\nusing Vortice.D3DCompiler;\nusing Vortice.Direct3D;\nusing Vortice.Direct3D11;\n\nusing ID3D11Device = Vortice.Direct3D11.ID3D11Device;\nusing static FlyleafLib.Utils;\n\nnamespace FlyleafLib.MediaFramework.MediaRenderer;\n\ninternal class BlobWrapper\n{\n public Blob blob;\n public BlobWrapper(Blob blob) => this.blob = blob;\n public BlobWrapper() { }\n}\n\ninternal static class ShaderCompiler\n{\n internal static Blob VSBlob = Compile(VS, false); // TODO Embedded?\n\n const int MAXSIZE = 64;\n static Dictionary cache = new();\n\n internal static ID3D11PixelShader CompilePS(ID3D11Device device, string uniqueId, string hlslSample, List defines = null)\n {\n BlobWrapper bw;\n\n lock (cache)\n {\n if (cache.Count > MAXSIZE)\n {\n Engine.Log.Trace($\"[ShaderCompiler] Clears cache\");\n foreach (var bw1 in cache.Values)\n bw1.blob.Dispose();\n\n cache.Clear();\n }\n\n cache.TryGetValue(uniqueId, out var bw2);\n if (bw2 != null)\n {\n Engine.Log.Trace($\"[ShaderCompiler] Found in cache {uniqueId}\");\n lock(bw2)\n return device.CreatePixelShader(bw2.blob);\n }\n\n bw = new();\n Monitor.Enter(bw);\n cache.Add(uniqueId, bw);\n }\n\n var blob = Compile(PS_HEADER + hlslSample + PS_FOOTER, true, defines);\n bw.blob = blob;\n var ps = device.CreatePixelShader(bw.blob);\n Monitor.Exit(bw);\n\n Engine.Log.Trace($\"[ShaderCompiler] Compiled {uniqueId}\");\n return ps;\n }\n internal static Blob Compile(string hlsl, bool isPS = true, List defines = null)\n {\n ShaderMacro[] definesMacro = null;\n\n if (defines != null)\n {\n definesMacro = new ShaderMacro[defines.Count + 1];\n for(int i=0; i GetUrlExtention(x) == \"hlsl\").ToArray();\n\n // foreach (string shader in shaders)\n // using (Stream stream = assembly.GetManifestResourceStream(shader))\n // {\n // string shaderName = shader.Substring(0, shader.Length - 5);\n // shaderName = shaderName.Substring(shaderName.LastIndexOf('.') + 1);\n\n // byte[] bytes = new byte[stream.Length];\n // stream.Read(bytes, 0, bytes.Length);\n\n // CompileShader(bytes, shaderName);\n // }\n //}\n\n //private unsafe static void CompileFileShaders()\n //{\n // List shaders = Directory.EnumerateFiles(EmbeddedShadersFolder, \"*.hlsl\").ToList();\n // foreach (string shader in shaders)\n // {\n // string shaderName = shader.Substring(0, shader.Length - 5);\n // shaderName = shaderName.Substring(shaderName.LastIndexOf('\\\\') + 1);\n\n // CompileShader(File.ReadAllBytes(shader), shaderName);\n // }\n //}\n\n // Loads compiled blob shaders\n //private static void LoadShaders()\n //{\n // Assembly assembly = Assembly.GetExecutingAssembly();\n // string[] shaders = assembly.GetManifestResourceNames().Where(x => GetUrlExtention(x) == \"blob\").ToArray();\n // string tempFile = Path.GetTempFileName();\n\n // foreach (string shader in shaders)\n // {\n // using (Stream stream = assembly.GetManifestResourceStream(shader))\n // {\n // var shaderName = shader.Substring(0, shader.Length - 5);\n // shaderName = shaderName.Substring(shaderName.LastIndexOf('.') + 1);\n\n // byte[] bytes = new byte[stream.Length];\n // stream.Read(bytes, 0, bytes.Length);\n\n // Dictionary curShaders = shaderName.Substring(0, 2).ToLower() == \"vs\" ? VSShaderBlobs : PSShaderBlobs;\n\n // File.WriteAllBytes(tempFile, bytes);\n // curShaders.Add(shaderName, Compiler.ReadFileToBlob(tempFile));\n // }\n // }\n //}\n\n // Should work at least from main Samples => FlyleafPlayer (WPF Control) (WPF)\n //static string EmbeddedShadersFolder = @\"..\\..\\..\\..\\..\\..\\FlyleafLib\\MediaFramework\\MediaRenderer\\Shaders\";\n //static Assembly ASSEMBLY = Assembly.GetExecutingAssembly();\n //static string SHADERS_NS = typeof(Renderer).Namespace + \".Shaders.\";\n\n //static byte[] GetEmbeddedShaderResource(string shaderName)\n //{\n // using (Stream stream = ASSEMBLY.GetManifestResourceStream(SHADERS_NS + shaderName + \".hlsl\"))\n // {\n // byte[] bytes = new byte[stream.Length];\n // stream.Read(bytes, 0, bytes.Length);\n\n // return bytes;\n // }\n //}\n\n const string PS_HEADER = @\"\n#pragma warning( disable: 3571 )\nTexture2D\t\tTexture1\t\t: register(t0);\nTexture2D\t\tTexture2\t\t: register(t1);\nTexture2D\t\tTexture3\t\t: register(t2);\nTexture2D\t\tTexture4\t\t: register(t3);\n\ncbuffer Config : register(b0)\n{\n int coefsIndex;\n int hdrmethod;\n\n float brightness;\n float contrast;\n\n float g_luminance;\n float g_toneP1;\n float g_toneP2;\n\n float texWidth;\n};\n\nSamplerState Sampler : IMMUTABLE\n{\n Filter = MIN_MAG_MIP_LINEAR;\n AddressU = CLAMP;\n AddressV = CLAMP;\n AddressW = CLAMP;\n ComparisonFunc = NEVER;\n MinLOD = 0;\n};\n\n#if defined(YUV)\n// YUV to RGB matrix coefficients\nstatic const float4x4 coefs[] =\n{\n // Limited -> Full\n {\n // BT2020 (srcBits = 10)\n { 1.16438353, 1.16438353, 1.16438353, 0 },\n { 0, -0.187326103, 2.14177227, 0 },\n { 1.67867422, -0.650424361, 0, 0 },\n { -0.915688038, 0.347458541, -1.14814520, 1 }\n },\n\n // BT709\n {\n { 1.16438341, 1.16438341, 1.16438341, 0 },\n { 0, -0.213248596, 2.11240149, 0 },\n { 1.79274082, -0.532909214, 0, 0 },\n { -0.972944975, 0.301482648, -1.13340211, 1 }\n },\n // BT601\n {\n { 1.16438341, 1.16438341, 1.16438341, 0 },\n { 0, -0.391762286, 2.01723194, 0 },\n { 1.59602666, -0.812967658, 0, 0 },\n { -0.874202192, 0.531667829, -1.08563077, 1 },\n }\n};\n#endif\n\n#if defined(HDR)\n// hdrmethod enum\nstatic const int Aces = 1;\nstatic const int Hable = 2;\nstatic const int Reinhard = 3;\n\n// HDR to SDR color convert (Thanks to KODI community https://github.com/thexai/xbmc)\nstatic const float ST2084_m1 = 2610.0f / (4096.0f * 4.0f);\nstatic const float ST2084_m2 = (2523.0f / 4096.0f) * 128.0f;\nstatic const float ST2084_c1 = 3424.0f / 4096.0f;\nstatic const float ST2084_c2 = (2413.0f / 4096.0f) * 32.0f;\nstatic const float ST2084_c3 = (2392.0f / 4096.0f) * 32.0f;\n\nstatic const float4x4 bt2020tobt709color =\n{\n { 1.6604f, -0.1245f, -0.0181f, 0 },\n { -0.5876f, 1.1329f, -0.10057f, 0 },\n { -0.07284f, -0.0083f, 1.1187f, 0 },\n { 0, 0, 0, 0 }\n};\n\nfloat3 inversePQ(float3 x)\n{\n x = pow(max(x, 0.0f), 1.0f / ST2084_m2);\n x = max(x - ST2084_c1, 0.0f) / (ST2084_c2 - ST2084_c3 * x);\n x = pow(x, 1.0f / ST2084_m1);\n return x;\n}\n\n#if defined(HLG)\nfloat3 inverseHLG(float3 x)\n{\n const float B67_a = 0.17883277f;\n const float B67_b = 0.28466892f;\n const float B67_c = 0.55991073f;\n const float B67_inv_r2 = 4.0f;\n x = (x <= 0.5f) ? x * x * B67_inv_r2 : exp((x - B67_c) / B67_a) + B67_b;\n return x;\n}\n\nfloat3 tranferPQ(float3 x)\n{\n x = pow(x / 1000.0f, ST2084_m1);\n x = (ST2084_c1 + ST2084_c2 * x) / (1.0f + ST2084_c3 * x);\n x = pow(x, ST2084_m2);\n return x;\n}\n\n#endif\nfloat3 aces(float3 x)\n{\n const float A = 2.51f;\n const float B = 0.03f;\n const float C = 2.43f;\n const float D = 0.59f;\n const float E = 0.14f;\n return (x * (A * x + B)) / (x * (C * x + D) + E);\n}\n\nfloat3 hable(float3 x)\n{\n const float A = 0.15f;\n const float B = 0.5f;\n const float C = 0.1f;\n const float D = 0.2f;\n const float E = 0.02f;\n const float F = 0.3f;\n return ((x * (A * x + C * B) + D * E) / (x * (A * x + B) + D * F)) - E / F;\n}\n\nstatic const float3 bt709coefs = { 0.2126f, 1.0f - 0.2126f - 0.0722f, 0.0722f };\nfloat reinhard(float x)\n{\n return x * (1.0f + x / (g_toneP1 * g_toneP1)) / (1.0f + x);\n}\n#endif\n\nstruct PSInput\n{\n float4 Position : SV_POSITION;\n float2 Texture : TEXCOORD;\n};\n\nfloat4 main(PSInput input) : SV_TARGET\n{\n float4 color;\n\n // Dynamic Sampling\n\n\";\n\n const string PS_FOOTER = @\"\n\n // YUV to RGB\n#if defined(YUV)\n color = mul(color, coefs[coefsIndex]);\n#endif\n\n\n // HDR\n#if defined(HDR)\n // BT2020 -> BT709\n color.rgb = pow(max(0.0, color.rgb), 2.4f);\n color.rgb = max(0.0, mul(color, bt2020tobt709color).rgb);\n color.rgb = pow(color.rgb, 1.0f / 2.2f);\n\n if (hdrmethod == Aces)\n {\n color.rgb = inversePQ(color.rgb);\n color.rgb *= (10000.0f / g_luminance) * (2.0f / g_toneP1);\n color.rgb = aces(color.rgb);\n color.rgb *= (1.24f / g_toneP1);\n color.rgb = pow(color.rgb, 0.27f);\n }\n else if (hdrmethod == Hable)\n {\n color.rgb = inversePQ(color.rgb);\n color.rgb *= g_toneP1;\n color.rgb = hable(color.rgb * g_toneP2) / hable(g_toneP2);\n color.rgb = pow(color.rgb, 1.0f / 2.2f);\n }\n else if (hdrmethod == Reinhard)\n {\n float luma = dot(color.rgb, bt709coefs);\n color.rgb *= reinhard(luma) / luma;\n }\n #if defined(HLG)\n // HLG\n color.rgb = inverseHLG(color.rgb);\n float3 ootf_2020 = float3(0.2627f, 0.6780f, 0.0593f);\n float ootf_ys = 2000.0f * dot(ootf_2020, color.rgb);\n color.rgb *= pow(ootf_ys, 0.2f);\n color.rgb = tranferPQ(color.rgb);\n #endif\n#endif\n\n // Contrast / Brightness / Saturate / Hue\n color *= contrast * 2.0f;\n color += brightness - 0.5f;\n\n return color;\n}\n\";\n\n const string VS = @\"\ncbuffer cBuf : register(b0)\n{\n matrix mat;\n}\n\nstruct VSInput\n{\n float4 Position : POSITION;\n float2 Texture : TEXCOORD;\n};\n\nstruct PSInput\n{\n float4 Position : SV_POSITION;\n float2 Texture : TEXCOORD;\n};\n\nPSInput main(VSInput vsi)\n{\n PSInput psi;\n\n psi.Position = mul(vsi.Position, mat);\n psi.Texture = vsi.Texture;\n\n return psi;\n}\n\";\n}\n"], ["/LLPlayer/FlyleafLib/MediaFramework/MediaStream/VideoStream.cs", "using System.Runtime.InteropServices;\n\nusing FlyleafLib.MediaFramework.MediaDemuxer;\n\nnamespace FlyleafLib.MediaFramework.MediaStream;\n\npublic unsafe class VideoStream : StreamBase\n{\n public AspectRatio AspectRatio { get; set; }\n public ColorRange ColorRange { get; set; }\n public ColorSpace ColorSpace { get; set; }\n public AVColorTransferCharacteristic\n ColorTransfer { get; set; }\n public double Rotation { get; set; }\n public double FPS { get; set; }\n public long FrameDuration { get ;set; }\n public uint Height { get; set; }\n public bool IsRGB { get; set; }\n public AVComponentDescriptor[] PixelComps { get; set; }\n public int PixelComp0Depth { get; set; }\n public AVPixelFormat PixelFormat { get; set; }\n public AVPixFmtDescriptor* PixelFormatDesc { get; set; }\n public string PixelFormatStr { get; set; }\n public int PixelPlanes { get; set; }\n public bool PixelSameDepth { get; set; }\n public bool PixelInterleaved { get; set; }\n public int TotalFrames { get; set; }\n public uint Width { get; set; }\n public bool FixTimestamps { get; set; } // TBR: For formats such as h264/hevc that have no or invalid pts values\n\n public override string GetDump()\n => $\"[{Type} #{StreamIndex}] {Codec} {PixelFormatStr} {Width}x{Height} @ {FPS:#.###} | [Color: {ColorSpace}] [BR: {BitRate}] | {Utils.TicksToTime((long)(AVStream->start_time * Timebase))}/{Utils.TicksToTime((long)(AVStream->duration * Timebase))} | {Utils.TicksToTime(StartTime)}/{Utils.TicksToTime(Duration)}\";\n\n public VideoStream() { }\n public VideoStream(Demuxer demuxer, AVStream* st) : base(demuxer, st)\n {\n Demuxer = demuxer;\n AVStream = st;\n Refresh();\n }\n\n public void Refresh(AVPixelFormat format = AVPixelFormat.None, AVFrame* frame = null)\n {\n base.Refresh();\n\n PixelFormat = format == AVPixelFormat.None ? (AVPixelFormat)AVStream->codecpar->format : format;\n PixelFormatStr = PixelFormat.ToString().Replace(\"AV_PIX_FMT_\",\"\").ToLower();\n Width = (uint)AVStream->codecpar->width;\n Height = (uint)AVStream->codecpar->height;\n\n // TBR: Maybe required also for input formats with AVFMT_NOTIMESTAMPS (and audio/subs)\n // Possible FFmpeg.Autogen bug with Demuxer.FormatContext->iformat->flags (should be uint?) does not contain AVFMT_NOTIMESTAMPS (256 instead of 384)\n if (Demuxer.Name == \"h264\" || Demuxer.Name == \"hevc\")\n {\n FixTimestamps = true;\n\n if (Demuxer.Config.ForceFPS > 0)\n FPS = Demuxer.Config.ForceFPS;\n else\n FPS = av_q2d(av_guess_frame_rate(Demuxer.FormatContext, AVStream, frame));\n\n if (FPS == 0)\n FPS = 25;\n }\n else\n {\n FixTimestamps = false;\n FPS = av_q2d(av_guess_frame_rate(Demuxer.FormatContext, AVStream, frame));\n }\n\n FrameDuration = FPS > 0 ? (long) (10000000 / FPS) : 0;\n TotalFrames = AVStream->duration > 0 && FrameDuration > 0 ? (int) (AVStream->duration * Timebase / FrameDuration) : (FrameDuration > 0 ? (int) (Demuxer.Duration / FrameDuration) : 0);\n\n int x, y;\n AVRational sar = av_guess_sample_aspect_ratio(null, AVStream, null);\n if (av_cmp_q(sar, av_make_q(0, 1)) <= 0)\n sar = av_make_q(1, 1);\n\n av_reduce(&x, &y, Width * sar.Num, Height * sar.Den, 1024 * 1024);\n AspectRatio = new AspectRatio(x, y);\n\n if (PixelFormat != AVPixelFormat.None)\n {\n ColorRange = AVStream->codecpar->color_range == AVColorRange.Jpeg ? ColorRange.Full : ColorRange.Limited;\n\n if (AVStream->codecpar->color_space == AVColorSpace.Bt470bg)\n ColorSpace = ColorSpace.BT601;\n else if (AVStream->codecpar->color_space == AVColorSpace.Bt709)\n ColorSpace = ColorSpace.BT709;\n else ColorSpace = AVStream->codecpar->color_space == AVColorSpace.Bt2020Cl || AVStream->codecpar->color_space == AVColorSpace.Bt2020Ncl\n ? ColorSpace.BT2020\n : Height > 576 ? ColorSpace.BT709 : ColorSpace.BT601;\n\n // This causes issues\n //if (AVStream->codecpar->color_space == AVColorSpace.AVCOL_SPC_UNSPECIFIED && AVStream->codecpar->color_trc == AVColorTransferCharacteristic.AVCOL_TRC_UNSPECIFIED && Height > 1080)\n //{ // TBR: Handle Dolphy Vision?\n // ColorSpace = ColorSpace.BT2020;\n // ColorTransfer = AVColorTransferCharacteristic.AVCOL_TRC_SMPTE2084;\n //}\n //else\n ColorTransfer = AVStream->codecpar->color_trc;\n\n // We get rotation from frame side data only from 1st frame in case of exif orientation (mainly for jpeg) - TBR if required to check for each frame\n AVFrameSideData* frameSideData;\n AVPacketSideData* pktSideData;\n double rotation = 0;\n if (frame != null && (frameSideData = av_frame_get_side_data(frame, AVFrameSideDataType.Displaymatrix)) != null && frameSideData->data != null)\n rotation = -Math.Round(av_display_rotation_get((int*)frameSideData->data)); //int_array9 displayMatrix = Marshal.PtrToStructure((nint)frameSideData->data); TBR: NaN why?\n else if ((pktSideData = av_packet_side_data_get(AVStream->codecpar->coded_side_data, AVStream->codecpar->nb_coded_side_data, AVPacketSideDataType.Displaymatrix)) != null && pktSideData->data != null)\n rotation = -Math.Round(av_display_rotation_get((int*)pktSideData->data));\n\n Rotation = rotation - (360*Math.Floor(rotation/360 + 0.9/360));\n\n PixelFormatDesc = av_pix_fmt_desc_get(PixelFormat);\n var comps = PixelFormatDesc->comp.ToArray();\n PixelComps = new AVComponentDescriptor[PixelFormatDesc->nb_components];\n for (int i=0; ilog2_chroma_w != PixelFormatDesc->log2_chroma_h;\n IsRGB = (PixelFormatDesc->flags & PixFmtFlags.Rgb) != 0;\n\n PixelSameDepth = true;\n PixelPlanes = 0;\n if (PixelComps.Length > 0)\n {\n PixelComp0Depth = PixelComps[0].depth;\n int prevBit = PixelComp0Depth;\n for (int i=0; i PixelPlanes)\n PixelPlanes = PixelComps[i].plane;\n\n if (prevBit != PixelComps[i].depth)\n PixelSameDepth = false;\n }\n\n PixelPlanes++;\n }\n }\n }\n}\n"], ["/LLPlayer/FlyleafLib/MediaPlayer/Audio.cs", "using System;\nusing System.Collections.ObjectModel;\n\nusing Vortice.Multimedia;\nusing Vortice.XAudio2;\n\nusing static Vortice.XAudio2.XAudio2;\n\nusing FlyleafLib.MediaFramework.MediaContext;\nusing FlyleafLib.MediaFramework.MediaFrame;\nusing FlyleafLib.MediaFramework.MediaStream;\n\nusing static FlyleafLib.Logger;\n\nnamespace FlyleafLib.MediaPlayer;\n\npublic class Audio : NotifyPropertyChanged\n{\n public event EventHandler SamplesAdded;\n\n #region Properties\n /// \n /// Embedded Streams\n /// \n public ObservableCollection\n Streams => decoder?.VideoDemuxer.AudioStreams; // TBR: We miss AudioDemuxer embedded streams\n\n /// \n /// Whether the input has audio and it is configured\n /// \n public bool IsOpened { get => isOpened; internal set => Set(ref _IsOpened, value); }\n internal bool _IsOpened, isOpened;\n\n public string Codec { get => codec; internal set => Set(ref _Codec, value); }\n internal string _Codec, codec;\n\n ///// \n ///// Audio bitrate (Kbps)\n ///// \n public double BitRate { get => bitRate; internal set => Set(ref _BitRate, value); }\n internal double _BitRate, bitRate;\n\n public int Bits { get => bits; internal set => Set(ref _Bits, value); }\n internal int _Bits, bits;\n\n public int Channels { get => channels; internal set => Set(ref _Channels, value); }\n internal int _Channels, channels;\n\n /// \n /// Audio player's channels out (currently 2 channels supported only)\n /// \n public int ChannelsOut { get; } = 2;\n\n public string ChannelLayout { get => channelLayout; internal set => Set(ref _ChannelLayout, value); }\n internal string _ChannelLayout, channelLayout;\n\n ///// \n ///// Total Dropped Frames\n ///// \n public int FramesDropped { get => framesDropped; internal set => Set(ref _FramesDropped, value); }\n internal int _FramesDropped, framesDropped;\n\n public int FramesDisplayed { get => framesDisplayed; internal set => Set(ref _FramesDisplayed, value); }\n internal int _FramesDisplayed, framesDisplayed;\n\n public string SampleFormat { get => sampleFormat; internal set => Set(ref _SampleFormat, value); }\n internal string _SampleFormat, sampleFormat;\n\n /// \n /// Audio sample rate (in/out)\n /// \n public int SampleRate { get => sampleRate; internal set => Set(ref _SampleRate, value); }\n internal int _SampleRate, sampleRate;\n\n /// \n /// Audio player's volume / amplifier (valid values 0 - no upper limit)\n /// \n public int Volume\n {\n get\n {\n lock (locker)\n return sourceVoice == null || Mute ? _Volume : (int) ((decimal)sourceVoice.Volume * 100);\n }\n set\n {\n if (value > Config.Player.VolumeMax || value < 0)\n return;\n\n if (value == 0)\n Mute = true;\n else if (Mute)\n {\n _Volume = value;\n Mute = false;\n }\n else\n {\n if (sourceVoice != null)\n sourceVoice.Volume = Math.Max(0, value / 100.0f);\n }\n\n Set(ref _Volume, value, false);\n }\n }\n int _Volume;\n\n /// \n /// Audio player's mute\n /// \n public bool Mute\n {\n get => mute;\n set\n {\n lock (locker)\n {\n if (sourceVoice == null)\n return;\n\n sourceVoice.Volume = value ? 0 : _Volume / 100.0f;\n }\n\n Set(ref mute, value, false);\n }\n }\n private bool mute = false;\n\n /// \n /// Audio player's current device (available devices can be found on )/>\n /// \n public AudioEngine.AudioEndpoint Device\n {\n get => _Device;\n set\n {\n if ((value == null && _Device == Engine.Audio.DefaultDevice) || value == _Device)\n return;\n\n _Device = value ?? Engine.Audio.DefaultDevice;\n Initialize();\n RaiseUI(nameof(Device));\n }\n }\n internal AudioEngine.AudioEndpoint _Device = Engine.Audio.DefaultDevice;\n #endregion\n\n #region Declaration\n public Player Player => player;\n\n Player player;\n Config Config => player.Config;\n DecoderContext decoder => player?.decoder;\n\n Action uiAction;\n internal readonly object\n locker = new();\n\n IXAudio2 xaudio2;\n internal IXAudio2MasteringVoice\n masteringVoice;\n internal IXAudio2SourceVoice\n sourceVoice;\n WaveFormat waveFormat = new(48000, 16, 2); // Output Audio Device\n AudioBuffer audioBuffer = new();\n internal double Timebase;\n internal ulong submittedSamples;\n #endregion\n\n public Audio(Player player)\n {\n this.player = player;\n\n uiAction = () =>\n {\n IsOpened = IsOpened;\n Codec = Codec;\n BitRate = BitRate;\n Bits = Bits;\n Channels = Channels;\n ChannelLayout = ChannelLayout;\n SampleFormat = SampleFormat;\n SampleRate = SampleRate;\n\n FramesDisplayed = FramesDisplayed;\n FramesDropped = FramesDropped;\n };\n\n // Set default volume\n Volume = Math.Min(Config.Player.VolumeDefault, Config.Player.VolumeMax);\n Initialize();\n }\n\n internal void Initialize()\n {\n lock (locker)\n {\n if (Engine.Audio.Failed)\n {\n Config.Audio.Enabled = false;\n return;\n }\n\n sampleRate = decoder != null && decoder.AudioStream != null && decoder.AudioStream.SampleRate > 0 ? decoder.AudioStream.SampleRate : 48000;\n player.Log.Info($\"Initialiazing audio ({Device.Name} - {Device.Id} @ {SampleRate}Hz)\");\n\n Dispose();\n\n try\n {\n xaudio2 = XAudio2Create();\n\n try\n {\n masteringVoice = xaudio2.CreateMasteringVoice(0, 0, AudioStreamCategory.GameEffects, _Device == Engine.Audio.DefaultDevice ? null : _Device.Id);\n }\n catch (Exception) // Win 7/8 compatibility issue https://social.msdn.microsoft.com/Forums/en-US/4989237b-814c-4a7a-8a35-00714d36b327/xaudio2-how-to-get-device-id-for-mastering-voice?forum=windowspro-audiodevelopment\n {\n masteringVoice = xaudio2.CreateMasteringVoice(0, 0, AudioStreamCategory.GameEffects, _Device == Engine.Audio.DefaultDevice ? null : (@\"\\\\?\\swd#mmdevapi#\" + _Device.Id.ToLower() + @\"#{e6327cad-dcec-4949-ae8a-991e976a79d2}\"));\n }\n\n sourceVoice = xaudio2.CreateSourceVoice(waveFormat, false);\n sourceVoice.SetSourceSampleRate((uint)SampleRate);\n sourceVoice.Start();\n\n submittedSamples = 0;\n Timebase = 1000 * 10000.0 / sampleRate;\n masteringVoice.Volume = Config.Player.VolumeMax / 100.0f;\n sourceVoice.Volume = mute ? 0 : Math.Max(0, _Volume / 100.0f);\n }\n catch (Exception e)\n {\n player.Log.Info($\"Audio initialization failed ({e.Message})\");\n Config.Audio.Enabled = false;\n }\n }\n }\n internal void Dispose()\n {\n lock (locker)\n {\n if (xaudio2 == null)\n return;\n\n xaudio2. Dispose();\n sourceVoice?. Dispose();\n masteringVoice?.Dispose();\n xaudio2 = null;\n sourceVoice = null;\n masteringVoice = null;\n }\n }\n\n // TBR: Very rarely could crash the app on audio device change while playing? Requires two locks (Audio's locker and aFrame)\n // The process was terminated due to an internal error in the .NET Runtime at IP 00007FFA6725DA03 (00007FFA67090000) with exit code c0000005.\n [System.Security.SecurityCritical]\n internal void AddSamples(AudioFrame aFrame)\n {\n lock (locker) // required for submittedSamples only? (ClearBuffer() can be called during audio decocder circular buffer reallocation)\n {\n try\n {\n if (CanTrace)\n player.Log.Trace($\"[A] Presenting {Utils.TicksToTime(player.aFrame.timestamp)}\");\n\n framesDisplayed++;\n\n submittedSamples += (ulong) (aFrame.dataLen / 4); // ASampleBytes\n SamplesAdded?.Invoke(this, aFrame);\n\n audioBuffer.AudioDataPointer= aFrame.dataPtr;\n audioBuffer.AudioBytes = (uint)aFrame.dataLen;\n sourceVoice.SubmitSourceBuffer(audioBuffer);\n }\n catch (Exception e) // Happens on audio device changed/removed\n {\n if (CanDebug)\n player.Log.Debug($\"[Audio] Submitting samples failed ({e.Message})\");\n\n ClearBuffer(); // TBR: Inform player to resync audio?\n }\n }\n }\n internal long GetBufferedDuration() { lock (locker) { return (long) ((submittedSamples - sourceVoice.State.SamplesPlayed) * Timebase); } }\n internal long GetDeviceDelay() { lock (locker) { return (long) ((xaudio2.PerformanceData.CurrentLatencyInSamples * Timebase) - 80000); } } // TODO: VBlack delay (8ms correction for now)\n internal void ClearBuffer()\n {\n lock (locker)\n {\n if (sourceVoice == null)\n return;\n\n sourceVoice.Stop();\n sourceVoice.FlushSourceBuffers();\n sourceVoice.Start();\n submittedSamples = sourceVoice.State.SamplesPlayed;\n }\n }\n\n internal void Reset()\n {\n codec = null;\n bitRate = 0;\n bits = 0;\n channels = 0;\n channelLayout = null;\n sampleFormat = null;\n isOpened = false;\n\n ClearBuffer();\n player.UIAdd(uiAction);\n }\n internal void Refresh()\n {\n if (decoder.AudioStream == null) { Reset(); return; }\n\n codec = decoder.AudioStream.Codec;\n bits = decoder.AudioStream.Bits;\n channels = decoder.AudioStream.Channels;\n channelLayout = decoder.AudioStream.ChannelLayoutStr;\n sampleFormat = decoder.AudioStream.SampleFormatStr;\n isOpened =!decoder.AudioDecoder.Disposed;\n\n framesDisplayed = 0;\n framesDropped = 0;\n\n if (SampleRate!= decoder.AudioStream.SampleRate)\n Initialize();\n\n player.UIAdd(uiAction);\n }\n internal void Enable()\n {\n bool wasPlaying = player.IsPlaying;\n\n decoder.OpenSuggestedAudio();\n\n player.ReSync(decoder.AudioStream, (int) (player.CurTime / 10000), true);\n\n Refresh();\n player.UIAll();\n\n if (wasPlaying || Config.Player.AutoPlay)\n player.Play();\n }\n internal void Disable()\n {\n if (!IsOpened)\n return;\n\n decoder.CloseAudio();\n\n player.aFrame = null;\n\n if (!player.Video.IsOpened)\n {\n player.canPlay = false;\n player.UIAdd(() => player.CanPlay = player.CanPlay);\n }\n\n Reset();\n player.UIAll();\n }\n\n public void DelayAdd() => Config.Audio.Delay += Config.Player.AudioDelayOffset;\n public void DelayAdd2() => Config.Audio.Delay += Config.Player.AudioDelayOffset2;\n public void DelayRemove() => Config.Audio.Delay -= Config.Player.AudioDelayOffset;\n public void DelayRemove2() => Config.Audio.Delay -= Config.Player.AudioDelayOffset2;\n public void Toggle() => Config.Audio.Enabled = !Config.Audio.Enabled;\n public void ToggleMute() => Mute = !Mute;\n public void VolumeUp()\n {\n if (Volume == Config.Player.VolumeMax) return;\n Volume = Math.Min(Volume + Config.Player.VolumeOffset, Config.Player.VolumeMax);\n }\n public void VolumeDown()\n {\n if (Volume == 0) return;\n Volume = Math.Max(Volume - Config.Player.VolumeOffset, 0);\n }\n\n /// \n /// Reloads filters from Config.Audio.Filters (experimental)\n /// \n /// 0 on success\n public int ReloadFilters() => player.AudioDecoder.ReloadFilters();\n\n /// \n /// \n /// Updates filter's property (experimental)\n /// Note: This will not update the property value in Config.Audio.Filters\n /// \n /// \n /// Filter's unique id specified in Config.Audio.Filters\n /// Filter's property to change\n /// Filter's property value\n /// 0 on success\n public int UpdateFilter(string filterId, string key, string value) => player.AudioDecoder.UpdateFilter(filterId, key, value);\n}\n"], ["/LLPlayer/FlyleafLib/MediaFramework/MediaPlaylist/Playlist.cs", "using System.Collections.ObjectModel;\nusing System.IO;\n\nusing FlyleafLib.MediaFramework.MediaContext;\n\nusing static FlyleafLib.Utils;\n\nnamespace FlyleafLib.MediaFramework.MediaPlaylist;\n\npublic class Playlist : NotifyPropertyChanged\n{\n /// \n /// Url provided by user\n /// \n public string Url { get => _Url; set { string fixedUrl = FixFileUrl(value); SetUI(ref _Url, fixedUrl); } }\n string _Url;\n\n /// \n /// IOStream provided by user\n /// \n public Stream IOStream { get; set; }\n\n /// \n /// Playlist's folder base which can be used to save related files\n /// \n public string FolderBase { get; set; }\n\n /// \n /// Playlist's title\n /// \n public string Title { get => _Title; set => SetUI(ref _Title, value); }\n string _Title;\n\n public int ExpectingItems { get => _ExpectingItems; set => SetUI(ref _ExpectingItems, value); }\n int _ExpectingItems;\n\n public bool Completed { get; set; }\n\n /// \n /// Playlist's opened/selected item\n /// \n public PlaylistItem Selected { get => _Selected; internal set { SetUI(ref _Selected, value); UpdatePrevNextItem(); } }\n PlaylistItem _Selected;\n\n public PlaylistItem NextItem { get => _NextItem; internal set => SetUI(ref _NextItem, value); }\n PlaylistItem _NextItem;\n\n public PlaylistItem PrevItem { get => _PrevItem; internal set => SetUI(ref _PrevItem, value); }\n PlaylistItem _PrevItem;\n\n internal void UpdatePrevNextItem()\n {\n if (Selected == null)\n {\n PrevItem = NextItem = null;\n return;\n }\n\n for (int i=0; i < Items.Count; i++)\n {\n if (Items[i] == Selected)\n {\n PrevItem = i > 0 ? Items[i - 1] : null;\n NextItem = i < Items.Count - 1 ? Items[i + 1] : null;\n\n return;\n }\n }\n }\n\n /// \n /// Type of the provided input (such as File, UNC, Torrent, Web, etc.)\n /// \n public InputType InputType { get; set; }\n\n // TODO: MediaType (Music/MusicClip/Movie/TVShow/etc.) probably should go per Playlist Item\n\n public ObservableCollection\n Items { get; set; } = new ObservableCollection();\n object lockItems = new();\n\n long openCounter;\n //long openItemCounter;\n internal DecoderContext decoder;\n LogHandler Log;\n\n public Playlist(int uniqueId)\n {\n Log = new LogHandler((\"[#\" + uniqueId + \"]\").PadRight(8, ' ') + \" [Playlist] \");\n UIInvokeIfRequired(() => System.Windows.Data.BindingOperations.EnableCollectionSynchronization(Items, lockItems));\n }\n\n public void Reset()\n {\n openCounter = decoder.OpenCounter;\n\n lock (lockItems)\n Items.Clear();\n\n bool noupdate = _Url == null && _Title == null && _Selected == null;\n\n _Url = null;\n _Title = null;\n _Selected = null;\n PrevItem = null;\n NextItem = null;\n IOStream = null;\n FolderBase = null;\n Completed = false;\n ExpectingItems = 0;\n\n InputType = InputType.Unknown;\n\n if (!noupdate)\n UI(() =>\n {\n Raise(nameof(Url));\n Raise(nameof(Title));\n Raise(nameof(Selected));\n });\n }\n\n public void AddItem(PlaylistItem item, string pluginName, object tag = null)\n {\n if (openCounter != decoder.OpenCounter)\n {\n Log.Debug(\"AddItem Cancelled\");\n return;\n }\n\n lock (lockItems)\n {\n Items.Add(item);\n Items[^1].Index = Items.Count - 1;\n\n UpdatePrevNextItem();\n\n if (tag != null)\n item.AddTag(tag, pluginName);\n };\n\n decoder.ScrapeItem(item);\n\n UIInvokeIfRequired(() =>\n {\n System.Windows.Data.BindingOperations.EnableCollectionSynchronization(item.ExternalAudioStreams, item.lockExternalStreams);\n System.Windows.Data.BindingOperations.EnableCollectionSynchronization(item.ExternalVideoStreams, item.lockExternalStreams);\n System.Windows.Data.BindingOperations.EnableCollectionSynchronization(item.ExternalSubtitlesStreamsAll, item.lockExternalStreams);\n });\n }\n}\n"], ["/LLPlayer/LLPlayer/Controls/Settings/SettingsSubtitlesOCR.xaml.cs", "using System.Collections.ObjectModel;\nusing System.ComponentModel;\nusing System.Diagnostics.CodeAnalysis;\nusing System.Windows;\nusing System.Windows.Controls;\nusing Windows.Media.Ocr;\nusing FlyleafLib;\nusing LLPlayer.Extensions;\nusing LLPlayer.Services;\nusing LLPlayer.Views;\n\nnamespace LLPlayer.Controls.Settings;\n\npublic partial class SettingsSubtitlesOCR : UserControl\n{\n public SettingsSubtitlesOCR()\n {\n InitializeComponent();\n\n DataContext = ((App)Application.Current).Container.Resolve();\n }\n}\n\npublic class SettingsSubtitlesOCRVM : Bindable\n{\n public FlyleafManager FL { get; }\n private readonly IDialogService _dialogService;\n\n public SettingsSubtitlesOCRVM(FlyleafManager fl, IDialogService dialogService)\n {\n FL = fl;\n _dialogService = dialogService;\n\n LoadDownloadedTessModels();\n LoadAvailableMsModels();\n }\n\n public ObservableCollection DownloadedTessLanguages { get; } = new();\n public ObservableCollection TessLanguageGroups { get; } = new();\n\n public ObservableCollection AvailableMsOcrLanguages { get; } = new();\n public ObservableCollection MsLanguageGroups { get; } = new();\n\n [field: AllowNull, MaybeNull]\n public DelegateCommand CmdDownloadTessModel => field ??= new(() =>\n {\n _dialogService.ShowDialog(nameof(TesseractDownloadDialog));\n\n // reload\n LoadDownloadedTessModels();\n });\n\n private void LoadDownloadedTessModels()\n {\n DownloadedTessLanguages.Clear();\n\n List langs = TesseractModelLoader.LoadDownloadedModels().ToList();\n foreach (var lang in langs)\n {\n DownloadedTessLanguages.Add(lang);\n }\n\n TessLanguageGroups.Clear();\n\n List langGroups = langs\n .GroupBy(l => l.ISO6391)\n .Where(lg => lg.Count() >= 2)\n .Select(lg => new TessOcrLanguageGroup\n {\n ISO6391 = lg.Key,\n Members = new ObservableCollection(\n lg.Select(m => new TessOcrLanguageGroupMember()\n {\n DisplayName = m.Lang.ToString(),\n LangCode = m.LangCode\n })\n )\n }).ToList();\n\n Dictionary? regionConfig = FL.PlayerConfig.Subtitles.TesseractOcrRegions;\n foreach (TessOcrLanguageGroup group in langGroups)\n {\n // Load preferred region settings from config\n if (regionConfig != null && regionConfig.TryGetValue(group.ISO6391, out string? code))\n {\n group.SelectedMember = group.Members.FirstOrDefault(m => m.LangCode == code);\n }\n group.PropertyChanged += TessLanguageGroup_OnPropertyChanged;\n\n TessLanguageGroups.Add(group);\n }\n }\n\n private void LoadAvailableMsModels()\n {\n var langs = OcrEngine.AvailableRecognizerLanguages.ToList();\n foreach (var lang in langs)\n {\n AvailableMsOcrLanguages.Add(lang);\n }\n\n List langGroups = langs\n .GroupBy(l => l.LanguageTag.Split('-').First())\n .Where(lg => lg.Count() >= 2)\n .Select(lg => new MsOcrLanguageGroup\n {\n ISO6391 = lg.Key,\n Members = new ObservableCollection(\n lg.Select(m => new MsOcrLanguageGroupMember()\n {\n DisplayName = m.DisplayName,\n LanguageTag = m.LanguageTag,\n NativeName = m.NativeName\n })\n )\n }).ToList();\n\n Dictionary? regionConfig = FL.PlayerConfig.Subtitles.MsOcrRegions;\n foreach (MsOcrLanguageGroup group in langGroups)\n {\n // Load preferred region settings from config\n if (regionConfig != null && regionConfig.TryGetValue(group.ISO6391, out string? tag))\n {\n group.SelectedMember = group.Members.FirstOrDefault(m => m.LanguageTag == tag);\n }\n group.PropertyChanged += MsLanguageGroup_OnPropertyChanged;\n\n MsLanguageGroups.Add(group);\n }\n }\n\n private void MsLanguageGroup_OnPropertyChanged(object? sender, PropertyChangedEventArgs e)\n {\n if (e.PropertyName == nameof(MsOcrLanguageGroup.SelectedMember))\n {\n Dictionary iso6391ToTag = new();\n\n foreach (MsOcrLanguageGroup group in MsLanguageGroups)\n {\n if (group.SelectedMember != null)\n {\n iso6391ToTag.Add(group.ISO6391, group.SelectedMember.LanguageTag);\n }\n }\n\n FL.PlayerConfig.Subtitles.MsOcrRegions = iso6391ToTag;\n }\n }\n\n private void TessLanguageGroup_OnPropertyChanged(object? sender, PropertyChangedEventArgs e)\n {\n if (e.PropertyName == nameof(TessOcrLanguageGroup.SelectedMember))\n {\n Dictionary iso6391ToCode = new();\n\n foreach (TessOcrLanguageGroup group in TessLanguageGroups)\n {\n if (group.SelectedMember != null)\n {\n iso6391ToCode.Add(group.ISO6391, group.SelectedMember.LangCode);\n }\n }\n\n FL.PlayerConfig.Subtitles.TesseractOcrRegions = iso6391ToCode;\n }\n }\n}\n\n#region Tesseract\npublic class TessOcrLanguageGroupMember : Bindable\n{\n public required string LangCode { get; init; }\n public required string DisplayName { get; init; }\n}\n\npublic class TessOcrLanguageGroup : Bindable\n{\n public required string ISO6391 { get; init; }\n\n public string DisplayName\n {\n get\n {\n var lang = Language.Get(ISO6391);\n return lang.TopEnglishName;\n }\n }\n\n public required ObservableCollection Members { get; init; }\n public TessOcrLanguageGroupMember? SelectedMember { get; set => Set(ref field, value); }\n}\n#endregion\n\n#region Microsoft OCR\npublic class MsOcrLanguageGroupMember : Bindable\n{\n public required string LanguageTag { get; init; }\n public required string DisplayName { get; init; }\n public required string NativeName { get; init; }\n}\n\npublic class MsOcrLanguageGroup : Bindable\n{\n public required string ISO6391 { get; init; }\n\n public string DisplayName\n {\n get\n {\n var lang = Language.Get(ISO6391);\n return lang.TopEnglishName;\n }\n }\n\n public required ObservableCollection Members { get; init; }\n public MsOcrLanguageGroupMember? SelectedMember { get; set => Set(ref field, value); }\n}\n#endregion\n"], ["/LLPlayer/FlyleafLib/MediaFramework/MediaStream/ExternalStream.cs", "using System.Collections.Generic;\n\nusing FlyleafLib.MediaFramework.MediaDemuxer;\nusing FlyleafLib.MediaFramework.MediaPlaylist;\nusing FlyleafLib.MediaPlayer;\n\nnamespace FlyleafLib.MediaFramework.MediaStream;\n\npublic class ExternalStream : DemuxerInput\n{\n public string PluginName { get; set; }\n public PlaylistItem\n PlaylistItem { get; set; }\n public int Index { get; set; } = -1; // if we need it (already used to compare same type streams) we need to ensure we fix it in case of removing an item\n public string Protocol { get; set; }\n public string Codec { get; set; }\n public long BitRate { get; set; }\n public Dictionary\n Tag { get; set; } = new Dictionary();\n public void AddTag(object tag, string pluginName)\n {\n if (Tag.ContainsKey(pluginName))\n Tag[pluginName] = tag;\n else\n Tag.Add(pluginName, tag);\n }\n public object GetTag(string pluginName)\n => Tag.ContainsKey(pluginName) ? Tag[pluginName] : null;\n\n /// \n /// Whether the item is currently enabled or not\n /// \n public bool Enabled\n {\n get => _Enabled;\n set\n {\n Utils.UI(() =>\n {\n if (Set(ref _Enabled, value) && value)\n {\n OpenedCounter++;\n }\n\n Raise(nameof(EnabledPrimarySubtitle));\n Raise(nameof(EnabledSecondarySubtitle));\n Raise(nameof(SubtitlesStream.SelectedSubMethods));\n });\n }\n }\n bool _Enabled;\n\n /// \n /// Times this item has been used/opened\n /// \n public int OpenedCounter { get; set; }\n\n public MediaType\n Type => this is ExternalAudioStream ? MediaType.Audio : this is ExternalVideoStream ? MediaType.Video : MediaType.Subs;\n\n #region Subtitles\n // TODO: L: Used for subtitle streams only, but defined in the base class\n public bool EnabledPrimarySubtitle => Enabled && this.GetSubEnabled(0);\n public bool EnabledSecondarySubtitle => Enabled && this.GetSubEnabled(1);\n #endregion\n}\n"], ["/LLPlayer/FlyleafLib/MediaPlayer/Translation/SubtitlesTranslator.cs", "using System.Collections.Generic;\nusing System.ComponentModel;\nusing System.Diagnostics;\nusing System.Linq;\nusing System.Threading;\nusing System.Threading.Tasks;\nusing FlyleafLib.MediaPlayer.Translation.Services;\nusing static FlyleafLib.Logger;\n\nnamespace FlyleafLib.MediaPlayer.Translation;\n\n#nullable enable\n\npublic class SubTranslator\n{\n private readonly SubManager _subManager;\n private readonly Config.SubtitlesConfig _config;\n private readonly int _subIndex;\n\n private ITranslateService? _translateService;\n private CancellationTokenSource? _translationCancellation;\n private readonly TranslateServiceFactory _translateServiceFactory;\n private Task? _translateTask;\n private bool _isReset;\n private Language? _srcLang;\n\n private bool IsEnabled => _config[_subIndex].EnabledTranslated;\n\n private readonly LogHandler Log;\n\n public SubTranslator(SubManager subManager, Config.SubtitlesConfig config, int subIndex)\n {\n _subManager = subManager;\n _config = config;\n _subIndex = subIndex;\n\n _subManager.PropertyChanged += SubManager_OnPropertyChanged;\n\n // apply config changes\n _config.PropertyChanged += SubtitlesConfig_OnPropertyChanged;\n _config.SubConfigs[subIndex].PropertyChanged += SubConfig_OnPropertyChanged;\n _config.TranslateChatConfig.PropertyChanged += TranslateChatConfig_OnPropertyChanged;\n\n _translateServiceFactory = new TranslateServiceFactory(config);\n\n Log = new LogHandler((\"[#1]\").PadRight(8, ' ') + $\" [Translator{subIndex + 1} ] \");\n }\n\n private int _oldIndex = -1;\n private CancellationTokenSource? _translationStartCancellation;\n\n private void SubManager_OnPropertyChanged(object? sender, PropertyChangedEventArgs e)\n {\n switch (e.PropertyName)\n {\n case nameof(SubManager.CurrentIndex):\n if (!IsEnabled || _subManager.Subs.Count == 0 || _subManager.Language == null)\n return;\n\n if (_translateService == null)\n {\n // capture for later initialization\n _srcLang = _subManager.Language;\n }\n\n if (_translationStartCancellation != null)\n {\n _translationStartCancellation.Cancel();\n _translationStartCancellation.Dispose();\n _translationStartCancellation = null;\n }\n _translationStartCancellation = new CancellationTokenSource();\n _ = UpdateCurrentIndexAsync(_subManager.CurrentIndex, _translationStartCancellation.Token);\n break;\n case nameof(SubManager.Language):\n _ = Reset();\n break;\n }\n }\n\n private void SubtitlesConfig_OnPropertyChanged(object? sender, PropertyChangedEventArgs e)\n {\n string languageFallbackPropName = _subIndex == 0 ?\n nameof(Config.SubtitlesConfig.LanguageFallbackPrimary) :\n nameof(Config.SubtitlesConfig.LanguageFallbackSecondary);\n\n if (e.PropertyName is\n nameof(Config.SubtitlesConfig.TranslateServiceType) or\n nameof(Config.SubtitlesConfig.TranslateTargetLanguage)\n ||\n e.PropertyName == languageFallbackPropName)\n {\n // Apply translating config changes\n _ = Reset();\n }\n }\n\n private void SubConfig_OnPropertyChanged(object? sender, PropertyChangedEventArgs e)\n {\n // Reset when translation is off\n if (e.PropertyName is nameof(Config.SubConfig.EnabledTranslated))\n {\n if (!IsEnabled)\n {\n _ = Reset();\n }\n }\n }\n\n private void TranslateChatConfig_OnPropertyChanged(object? sender, PropertyChangedEventArgs e)\n {\n _ = Reset();\n }\n\n private async Task Reset()\n {\n if (_translateService == null)\n return;\n\n try\n {\n _isReset = true;\n await Cancel();\n\n _translateService?.Dispose();\n _translateService = null;\n _srcLang = null;\n }\n finally\n {\n _isReset = false;\n }\n }\n\n private async Task Cancel()\n {\n _translationCancellation?.Cancel();\n Task? pendingTask = _translateTask;\n if (pendingTask != null)\n {\n await pendingTask;\n }\n _translateTask = null;\n }\n\n private async Task UpdateCurrentIndexAsync(int newIndex, CancellationToken token)\n {\n if (newIndex != -1 && _subManager.Subs.Any())\n {\n int indexDiff = Math.Abs(_oldIndex - newIndex);\n bool isForward = newIndex > _oldIndex;\n _oldIndex = newIndex;\n\n if ((isForward && indexDiff > _config.TranslateCountForward) ||\n (!isForward && indexDiff > _config.TranslateCountBackward))\n {\n // Cancel a running translation request when a large seek is performed\n await Cancel();\n }\n else if (_translateTask != null)\n {\n // for performance\n return;\n }\n\n // Prevent continuous firing when continuously switching subtitles with sub seek\n if (indexDiff == 1)\n {\n if (_subManager.Subs[newIndex].Duration.TotalMilliseconds > 320)\n {\n await Task.Delay(300, token);\n }\n }\n token.ThrowIfCancellationRequested();\n\n if (_translateTask == null && !_isReset)\n {\n // singleton task\n // Ensure that it is not executed in the main thread because it scans all subtitles\n Task task = Task.Run(async () =>\n {\n try\n {\n await TranslateAheadAsync(newIndex, _config.TranslateCountBackward, _config.TranslateCountForward);\n }\n finally\n {\n _translateTask = null;\n }\n });\n _translateTask = task;\n }\n }\n }\n\n private readonly Lock _initLock = new();\n // initialize TranslateService lazily\n private void EnsureTranslationService()\n {\n if (_translateService != null)\n {\n return;\n }\n\n // double-check lock pattern\n lock (_initLock)\n {\n if (_translateService == null)\n {\n var service = _translateServiceFactory.GetService(_config.TranslateServiceType, false);\n service.Initialize(_srcLang!, _config.TranslateTargetLanguage);\n\n Volatile.Write(ref _translateService, service);\n }\n }\n }\n\n private async Task TranslateAheadAsync(int currentIndex, int countBackward, int countForward)\n {\n try\n {\n // Token for canceling translation, releasing previous one to prevent leakage\n _translationCancellation?.Dispose();\n _translationCancellation = new CancellationTokenSource();\n\n var token = _translationCancellation.Token;\n int start = Math.Max(0, currentIndex - countBackward);\n int end = Math.Min(start + countForward - 1, _subManager.Subs.Count - 1);\n\n List translateSubs = new();\n for (int i = start; i <= end; i++)\n {\n if (token.IsCancellationRequested)\n break;\n if (i >= _subManager.Subs.Count)\n break;\n\n var sub = _subManager.Subs[i];\n if (!sub.IsTranslated && !string.IsNullOrEmpty(sub.Text))\n {\n translateSubs.Add(sub);\n }\n }\n\n if (translateSubs.Count == 0)\n return;\n\n int concurrency = _config.TranslateMaxConcurrency;\n\n if (concurrency > 1 && _config.TranslateServiceType.IsLLM() &&\n _config.TranslateChatConfig.TranslateMethod == ChatTranslateMethod.KeepContext)\n {\n // fixed to 1\n // it must be sequential because of maintaining context\n concurrency = 1;\n }\n\n if (concurrency <= 1)\n {\n // sequentially (important to maintain execution order for LLM)\n foreach (var sub in translateSubs)\n {\n await TranslateSubAsync(sub, token);\n }\n }\n else\n {\n // concurrently\n ParallelOptions parallelOptions = new()\n {\n CancellationToken = token,\n MaxDegreeOfParallelism = concurrency\n };\n\n await Parallel.ForEachAsync(\n translateSubs,\n parallelOptions,\n async (sub, ct) =>\n {\n await TranslateSubAsync(sub, ct);\n });\n }\n }\n catch (OperationCanceledException)\n {\n // ignore\n }\n catch (Exception ex)\n {\n Log.Error($\"Translation failed: {ex.Message}\");\n\n bool isConfigError = ex is TranslationConfigException;\n\n // Unable to translate, so turn off the translation and notify\n _config[_subIndex].EnabledTranslated = false;\n _ = Reset().ContinueWith((_) =>\n {\n if (isConfigError)\n {\n _config.player.RaiseKnownErrorOccurred($\"Translation Failed: {ex.Message}\", KnownErrorType.Configuration);\n }\n else\n {\n _config.player.RaiseUnknownErrorOccurred($\"Translation Failed: {ex.Message}\", UnknownErrorType.Translation, ex);\n }\n });\n }\n }\n\n private async Task TranslateSubAsync(SubtitleData sub, CancellationToken token)\n {\n string? text = sub.Text;\n if (string.IsNullOrEmpty(text))\n return;\n\n try\n {\n long start = Stopwatch.GetTimestamp();\n string translateText = SubtitleTextUtil.FlattenText(text);\n if (CanDebug) Log.Debug($\"Translation Start {sub.Index} - {translateText}\");\n EnsureTranslationService();\n string translated = await _translateService!.TranslateAsync(translateText, token);\n sub.TranslatedText = translated;\n\n if (CanDebug)\n {\n TimeSpan elapsed = Stopwatch.GetElapsedTime(start);\n Log.Debug($\"Translation End {sub.Index} in {elapsed.TotalMilliseconds} - {translated}\");\n }\n }\n catch (OperationCanceledException)\n {\n if (CanDebug) Log.Debug($\"Translation Cancel {sub.Index}\");\n throw;\n }\n }\n}\n"], ["/LLPlayer/FlyleafLib/MediaFramework/MediaRenderer/Renderer.Device.cs", "using System.Numerics;\nusing System.Text.RegularExpressions;\n\nusing Vortice;\nusing Vortice.Direct3D;\nusing Vortice.Direct3D11;\nusing Vortice.DXGI;\nusing Vortice.DXGI.Debug;\n\nusing FlyleafLib.MediaFramework.MediaDecoder;\n\nusing static FlyleafLib.Logger;\nusing System.Runtime.InteropServices;\n\nusing ID3D11Device = Vortice.Direct3D11.ID3D11Device;\nusing ID3D11DeviceContext = Vortice.Direct3D11.ID3D11DeviceContext;\n\nnamespace FlyleafLib.MediaFramework.MediaRenderer;\n\npublic unsafe partial class Renderer\n{\n static InputElementDescription[] inputElements =\n {\n new(\"POSITION\", 0, Format.R32G32B32_Float, 0),\n new(\"TEXCOORD\", 0, Format.R32G32_Float, 0),\n };\n\n static BufferDescription vertexBufferDesc = new()\n {\n BindFlags = BindFlags.VertexBuffer\n };\n\n static float[] vertexBufferData = new[]\n {\n -1.0f, -1.0f, 0, 0.0f, 1.0f,\n -1.0f, 1.0f, 0, 0.0f, 0.0f,\n 1.0f, -1.0f, 0, 1.0f, 1.0f,\n\n 1.0f, -1.0f, 0, 1.0f, 1.0f,\n -1.0f, 1.0f, 0, 0.0f, 0.0f,\n 1.0f, 1.0f, 0, 1.0f, 0.0f\n };\n\n static FeatureLevel[] featureLevelsAll = new[]\n {\n FeatureLevel.Level_12_1,\n FeatureLevel.Level_12_0,\n FeatureLevel.Level_11_1,\n FeatureLevel.Level_11_0,\n FeatureLevel.Level_10_1,\n FeatureLevel.Level_10_0,\n FeatureLevel.Level_9_3,\n FeatureLevel.Level_9_2,\n FeatureLevel.Level_9_1\n };\n\n static FeatureLevel[] featureLevels = new[]\n {\n FeatureLevel.Level_11_0,\n FeatureLevel.Level_10_1,\n FeatureLevel.Level_10_0,\n FeatureLevel.Level_9_3,\n FeatureLevel.Level_9_2,\n FeatureLevel.Level_9_1\n };\n\n static BlendDescription blendDesc = new();\n\n static Renderer()\n {\n blendDesc.RenderTarget[0].BlendEnable = true;\n blendDesc.RenderTarget[0].SourceBlend = Blend.SourceAlpha;\n blendDesc.RenderTarget[0].DestinationBlend = Blend.InverseSourceAlpha;\n blendDesc.RenderTarget[0].BlendOperation = BlendOperation.Add;\n blendDesc.RenderTarget[0].SourceBlendAlpha = Blend.Zero;\n blendDesc.RenderTarget[0].DestinationBlendAlpha = Blend.Zero;\n blendDesc.RenderTarget[0].BlendOperationAlpha = BlendOperation.Add;\n blendDesc.RenderTarget[0].RenderTargetWriteMask = ColorWriteEnable.All;\n }\n\n\n ID3D11DeviceContext context;\n\n ID3D11Buffer vertexBuffer;\n ID3D11InputLayout inputLayout;\n ID3D11RasterizerState\n rasterizerState;\n ID3D11BlendState blendStateAlpha;\n\n ID3D11VertexShader ShaderVS;\n ID3D11PixelShader ShaderPS;\n ID3D11PixelShader ShaderBGRA;\n\n ID3D11Buffer psBuffer;\n PSBufferType psBufferData;\n\n ID3D11Buffer vsBuffer;\n VSBufferType vsBufferData;\n\n internal object lockDevice = new();\n bool isFlushing;\n\n public void Initialize(bool swapChain = true)\n {\n lock (lockDevice)\n {\n try\n {\n if (CanDebug) Log.Debug(\"Initializing\");\n\n if (!Disposed)\n Dispose();\n\n Disposed = false;\n\n ID3D11Device tempDevice;\n IDXGIAdapter1 adapter = null;\n var creationFlags = DeviceCreationFlags.BgraSupport /*| DeviceCreationFlags.VideoSupport*/; // Let FFmpeg failed for VA if does not support it\n var creationFlagsWarp = DeviceCreationFlags.None;\n\n #if DEBUG\n if (D3D11.SdkLayersAvailable())\n {\n creationFlags |= DeviceCreationFlags.Debug;\n creationFlagsWarp |= DeviceCreationFlags.Debug;\n }\n #endif\n\n // Finding User Definied adapter\n if (!string.IsNullOrWhiteSpace(Config.Video.GPUAdapter) && Config.Video.GPUAdapter.ToUpper() != \"WARP\")\n {\n for (uint i=0; Engine.Video.Factory.EnumAdapters1(i, out adapter).Success; i++)\n {\n if (adapter.Description1.Description == Config.Video.GPUAdapter)\n break;\n\n if (Regex.IsMatch(adapter.Description1.Description + \" luid=\" + adapter.Description1.Luid, Config.Video.GPUAdapter, RegexOptions.IgnoreCase))\n break;\n\n adapter.Dispose();\n }\n\n if (adapter == null)\n {\n Log.Error($\"GPU Adapter with {Config.Video.GPUAdapter} has not been found. Falling back to default.\");\n Config.Video.GPUAdapter = null;\n }\n }\n\n // Creating WARP (force by user or us after late failure)\n if (!string.IsNullOrWhiteSpace(Config.Video.GPUAdapter) && Config.Video.GPUAdapter.ToUpper() == \"WARP\")\n D3D11.D3D11CreateDevice(null, DriverType.Warp, creationFlagsWarp, featureLevels, out tempDevice).CheckError();\n\n // Creating User Defined or Default\n else\n {\n // Creates the D3D11 Device based on selected adapter or default hardware (highest to lowest features and fall back to the WARP device. see http://go.microsoft.com/fwlink/?LinkId=286690)\n if (D3D11.D3D11CreateDevice(adapter, adapter == null ? DriverType.Hardware : DriverType.Unknown, creationFlags, featureLevelsAll, out tempDevice).Failure)\n if (D3D11.D3D11CreateDevice(adapter, adapter == null ? DriverType.Hardware : DriverType.Unknown, creationFlags, featureLevels, out tempDevice).Failure)\n {\n Config.Video.GPUAdapter = \"WARP\";\n D3D11.D3D11CreateDevice(null, DriverType.Warp, creationFlagsWarp, featureLevels, out tempDevice).CheckError();\n }\n }\n\n Device = tempDevice.QueryInterface();\n context= Device.ImmediateContext;\n\n // Gets the default adapter from the D3D11 Device\n if (adapter == null)\n {\n Device.Tag = new Luid().ToString();\n using var deviceTmp = Device.QueryInterface();\n using var adapterTmp = deviceTmp.GetAdapter();\n adapter = adapterTmp.QueryInterface();\n }\n else\n Device.Tag = adapter.Description.Luid.ToString();\n\n if (Engine.Video.GPUAdapters.ContainsKey(adapter.Description1.Luid))\n {\n GPUAdapter = Engine.Video.GPUAdapters[adapter.Description1.Luid];\n Config.Video.MaxVerticalResolutionAuto = GPUAdapter.MaxHeight;\n\n if (CanDebug)\n {\n string dump = $\"GPU Adapter\\r\\n{GPUAdapter}\\r\\n\";\n\n for (int i=0; i()) mthread.SetMultithreadProtected(true);\n using (var dxgidevice = Device.QueryInterface()) dxgidevice.MaximumFrameLatency = Config.Video.MaxFrameLatency;\n\n // Input Layout\n inputLayout = Device.CreateInputLayout(inputElements, ShaderCompiler.VSBlob);\n context.IASetInputLayout(inputLayout);\n context.IASetPrimitiveTopology(PrimitiveTopology.TriangleList);\n\n // Vertex Shader\n vertexBuffer = Device.CreateBuffer(vertexBufferData, vertexBufferDesc);\n context.IASetVertexBuffer(0, vertexBuffer, sizeof(float) * 5);\n\n ShaderVS = Device.CreateVertexShader(ShaderCompiler.VSBlob);\n context.VSSetShader(ShaderVS);\n\n vsBuffer = Device.CreateBuffer(new()\n {\n Usage = ResourceUsage.Default,\n BindFlags = BindFlags.ConstantBuffer,\n CPUAccessFlags = CpuAccessFlags.None,\n ByteWidth = (uint)(sizeof(VSBufferType) + (16 - (sizeof(VSBufferType) % 16)))\n });\n context.VSSetConstantBuffer(0, vsBuffer);\n\n vsBufferData.mat = Matrix4x4.Identity;\n context.UpdateSubresource(vsBufferData, vsBuffer);\n\n // Pixel Shader\n InitPS();\n psBuffer = Device.CreateBuffer(new()\n {\n Usage = ResourceUsage.Default,\n BindFlags = BindFlags.ConstantBuffer,\n CPUAccessFlags = CpuAccessFlags.None,\n ByteWidth = (uint)(sizeof(PSBufferType) + (16 - (sizeof(PSBufferType) % 16)))\n });\n context.PSSetConstantBuffer(0, psBuffer);\n psBufferData.hdrmethod = HDRtoSDRMethod.None;\n context.UpdateSubresource(psBufferData, psBuffer);\n\n // subs\n ShaderBGRA = ShaderCompiler.CompilePS(Device, \"bgra\", @\"color = float4(Texture1.Sample(Sampler, input.Texture).rgba);\", null);\n\n // Blend State (currently used -mainly- for RGBA images and OverlayTexture)\n blendStateAlpha = Device.CreateBlendState(blendDesc);\n\n // Rasterizer (Will change CullMode to None for H-V Flip)\n rasterizerState = Device.CreateRasterizerState(new(CullMode.Back, FillMode.Solid));\n context.RSSetState(rasterizerState);\n\n InitializeVideoProcessor();\n\n if (CanInfo) Log.Info($\"Initialized with Feature Level {(int)Device.FeatureLevel >> 12}.{((int)Device.FeatureLevel >> 8) & 0xf}\");\n\n } catch (Exception e)\n {\n if (string.IsNullOrWhiteSpace(Config.Video.GPUAdapter) || Config.Video.GPUAdapter.ToUpper() != \"WARP\")\n {\n try { if (Device != null) Log.Warn($\"Device Remove Reason = {Device.DeviceRemovedReason.Description}\"); } catch { } // For troubleshooting\n\n Log.Warn($\"Initialization failed ({e.Message}). Failling back to WARP device.\");\n Config.Video.GPUAdapter = \"WARP\";\n Flush();\n }\n else\n {\n Log.Error($\"Initialization failed ({e.Message})\");\n Dispose();\n return;\n }\n }\n\n if (swapChain)\n {\n if (ControlHandle != IntPtr.Zero)\n InitializeSwapChain(ControlHandle);\n else if (SwapChainWinUIClbk != null)\n InitializeWinUISwapChain();\n }\n\n InitializeChildSwapChain();\n }\n }\n public void InitializeChildSwapChain(bool swapChain = true)\n {\n if (child == null )\n return;\n\n lock (lockDevice)\n {\n child.lockDevice = lockDevice;\n child.VideoDecoder = VideoDecoder;\n child.Device = Device;\n child.context = context;\n child.curRatio = curRatio;\n child.VideoRect = VideoRect;\n child.videoProcessor= videoProcessor;\n child.InitializeVideoProcessor(); // to use the same VP we need to set it's config in each present (means we don't update VP config as is different)\n\n if (swapChain)\n {\n if (child.ControlHandle != IntPtr.Zero)\n child.InitializeSwapChain(child.ControlHandle);\n else if (child.SwapChainWinUIClbk != null)\n child.InitializeWinUISwapChain();\n }\n\n child.Disposed = false;\n child.SetViewport();\n }\n }\n\n public void Dispose()\n {\n lock (lockDevice)\n {\n if (Disposed)\n return;\n\n if (child != null)\n DisposeChild();\n\n Disposed = true;\n\n if (CanDebug) Log.Debug(\"Disposing\");\n\n VideoDecoder.DisposeFrame(LastFrame);\n RefreshLayout();\n\n DisposeVideoProcessor();\n\n ShaderVS?.Dispose();\n ShaderPS?.Dispose();\n prevPSUniqueId = curPSUniqueId = \"\"; // Ensure we re-create ShaderPS for FlyleafVP on ConfigPlanes\n psBuffer?.Dispose();\n vsBuffer?.Dispose();\n inputLayout?.Dispose();\n vertexBuffer?.Dispose();\n rasterizerState?.Dispose();\n blendStateAlpha?.Dispose();\n DisposeSwapChain();\n\n overlayTexture?.Dispose();\n overlayTextureSrv?.Dispose();\n ShaderBGRA?.Dispose();\n\n singleGpu?.Dispose();\n singleStage?.Dispose();\n singleGpuRtv?.Dispose();\n singleStageDesc.Width = 0; // ensures re-allocation\n\n if (rtv2 != null)\n {\n for(int i = 0; i < rtv2.Length; i++)\n rtv2[i].Dispose();\n\n rtv2 = null;\n }\n\n if (backBuffer2 != null)\n {\n for(int i = 0; i < backBuffer2.Length; i++)\n backBuffer2[i]?.Dispose();\n\n backBuffer2 = null;\n }\n\n if (Device != null)\n {\n context.ClearState();\n context.Flush();\n context.Dispose();\n Device.Dispose();\n Device = null;\n }\n\n #if DEBUG\n ReportLiveObjects();\n #endif\n\n curRatio = 1.0f;\n if (CanInfo) Log.Info(\"Disposed\");\n }\n }\n public void DisposeChild()\n {\n if (child == null)\n return;\n\n lock (lockDevice)\n {\n child.DisposeSwapChain();\n child.DisposeVideoProcessor();\n child.Disposed = true;\n\n if (!isFlushing)\n {\n child.Device = null;\n child.context = null;\n child.VideoDecoder = null;\n child.LastFrame = null;\n child = null;\n }\n }\n }\n\n public void Flush()\n {\n lock (lockDevice)\n {\n isFlushing = true;\n var controlHandle = ControlHandle;\n var swapChainClbk = SwapChainWinUIClbk;\n\n IntPtr controlHandleReplica = IntPtr.Zero;\n Action swapChainClbkReplica = null;;\n if (child != null)\n {\n controlHandleReplica = child.ControlHandle;\n swapChainClbkReplica = child.SwapChainWinUIClbk;\n }\n\n Dispose();\n ControlHandle = controlHandle;\n SwapChainWinUIClbk = swapChainClbk;\n if (child != null)\n {\n child.ControlHandle = controlHandleReplica;\n child.SwapChainWinUIClbk = swapChainClbkReplica;\n }\n Initialize();\n isFlushing = false;\n }\n }\n\n #if DEBUG\n public static void ReportLiveObjects()\n {\n try\n {\n if (DXGI.DXGIGetDebugInterface1(out IDXGIDebug1 dxgiDebug).Success)\n {\n dxgiDebug.ReportLiveObjects(DXGI.DebugAll, ReportLiveObjectFlags.Summary | ReportLiveObjectFlags.IgnoreInternal);\n dxgiDebug.Dispose();\n }\n } catch { }\n }\n #endif\n\n [StructLayout(LayoutKind.Sequential)]\n struct PSBufferType\n {\n public int coefsIndex;\n public HDRtoSDRMethod hdrmethod;\n\n public float brightness;\n public float contrast;\n\n public float g_luminance;\n public float g_toneP1;\n public float g_toneP2;\n\n public float texWidth;\n }\n\n [StructLayout(LayoutKind.Sequential)]\n struct VSBufferType\n {\n public Matrix4x4 mat;\n }\n}\n"], ["/LLPlayer/FlyleafLib/MediaFramework/MediaRenderer/Renderer.PresentOffline.cs", "using System.Drawing.Imaging;\nusing System.Drawing;\nusing System.Threading;\nusing System.Windows.Media.Imaging;\n\nusing SharpGen.Runtime;\n\nusing Vortice;\nusing Vortice.Direct3D11;\nusing Vortice.DXGI;\nusing Vortice.Mathematics;\n\nusing FlyleafLib.MediaFramework.MediaDecoder;\nusing FlyleafLib.MediaFramework.MediaFrame;\n\nusing ID3D11Texture2D = Vortice.Direct3D11.ID3D11Texture2D;\n\nnamespace FlyleafLib.MediaFramework.MediaRenderer;\n\npublic partial class Renderer\n{\n // subs\n Texture2DDescription overlayTextureDesc;\n ID3D11Texture2D overlayTexture;\n ID3D11ShaderResourceView overlayTextureSrv;\n int overlayTextureOriginalWidth;\n int overlayTextureOriginalHeight;\n int overlayTextureOriginalPosX;\n int overlayTextureOriginalPosY;\n\n ID3D11ShaderResourceView[] overlayTextureSRVs = new ID3D11ShaderResourceView[1];\n\n // Used for off screen rendering\n Texture2DDescription singleStageDesc, singleGpuDesc;\n ID3D11Texture2D singleStage;\n ID3D11Texture2D singleGpu;\n ID3D11RenderTargetView singleGpuRtv;\n Viewport singleViewport;\n\n // Used for parallel off screen rendering\n ID3D11RenderTargetView[] rtv2;\n ID3D11Texture2D[] backBuffer2;\n bool[] backBuffer2busy;\n\n unsafe internal void PresentOffline(VideoFrame frame, ID3D11RenderTargetView rtv, Viewport viewport)\n {\n if (videoProcessor == VideoProcessors.D3D11)\n {\n var tmpResource = rtv.Resource;\n vd1.CreateVideoProcessorOutputView(tmpResource, vpe, vpovd, out var vpov);\n\n RawRect rect = new((int)viewport.X, (int)viewport.Y, (int)(viewport.Width + viewport.X), (int)(viewport.Height + viewport.Y));\n vc.VideoProcessorSetStreamSourceRect(vp, 0, true, VideoRect);\n vc.VideoProcessorSetStreamDestRect(vp, 0, true, rect);\n vc.VideoProcessorSetOutputTargetRect(vp, true, rect);\n\n if (frame.avFrame != null)\n {\n vpivd.Texture2D.ArraySlice = (uint) frame.avFrame->data[1];\n vd1.CreateVideoProcessorInputView(VideoDecoder.textureFFmpeg, vpe, vpivd, out vpiv);\n }\n else\n {\n vpivd.Texture2D.ArraySlice = 0;\n vd1.CreateVideoProcessorInputView(frame.textures[0], vpe, vpivd, out vpiv);\n }\n\n vpsa[0].InputSurface = vpiv;\n vc.VideoProcessorBlt(vp, vpov, 0, 1, vpsa);\n vpiv.Dispose();\n vpov.Dispose();\n tmpResource.Dispose();\n }\n else\n {\n context.OMSetRenderTargets(rtv);\n context.ClearRenderTargetView(rtv, Config.Video._BackgroundColor);\n context.RSSetViewport(viewport);\n context.PSSetShaderResources(0, frame.srvs);\n context.Draw(6, 0);\n }\n }\n\n /// \n /// Gets bitmap from a video frame\n /// \n /// Specify the width (-1: will keep the ratio based on height)\n /// Specify the height (-1: will keep the ratio based on width)\n /// Video frame to process (null: will use the current/last frame)\n /// \n unsafe public Bitmap GetBitmap(int width = -1, int height = -1, VideoFrame frame = null)\n {\n try\n {\n lock (lockDevice)\n {\n frame ??= LastFrame;\n\n if (Disposed || frame == null || (frame.textures == null && frame.avFrame == null))\n return null;\n\n if (width == -1 && height == -1)\n {\n width = VideoRect.Right;\n height = VideoRect.Bottom;\n }\n else if (width != -1 && height == -1)\n height = (int)(width / curRatio);\n else if (height != -1 && width == -1)\n width = (int)(height * curRatio);\n\n if (singleStageDesc.Width != width || singleStageDesc.Height != height)\n {\n singleGpu?.Dispose();\n singleStage?.Dispose();\n singleGpuRtv?.Dispose();\n\n singleStageDesc.Width = (uint)width;\n singleStageDesc.Height = (uint)height;\n singleGpuDesc.Width = (uint)width;\n singleGpuDesc.Height = (uint)height;\n\n singleStage = Device.CreateTexture2D(singleStageDesc);\n singleGpu = Device.CreateTexture2D(singleGpuDesc);\n singleGpuRtv= Device.CreateRenderTargetView(singleGpu);\n\n singleViewport = new Viewport(width, height);\n }\n\n PresentOffline(frame, singleGpuRtv, singleViewport);\n\n if (videoProcessor == VideoProcessors.D3D11)\n SetViewport();\n }\n\n context.CopyResource(singleStage, singleGpu);\n return GetBitmap(singleStage);\n\n } catch (Exception e)\n {\n Log.Warn($\"GetBitmap failed with: {e.Message}\");\n return null;\n }\n }\n public Bitmap GetBitmap(ID3D11Texture2D stageTexture)\n {\n Bitmap bitmap = new((int)stageTexture.Description.Width, (int)stageTexture.Description.Height);\n var db = context.Map(stageTexture, 0, MapMode.Read, Vortice.Direct3D11.MapFlags.None);\n var bitmapData = bitmap.LockBits(new Rectangle(0, 0, bitmap.Width, bitmap.Height), ImageLockMode.WriteOnly, PixelFormat.Format32bppArgb);\n\n if (db.RowPitch == bitmapData.Stride)\n MemoryHelpers.CopyMemory(bitmapData.Scan0, db.DataPointer, bitmap.Width * bitmap.Height * 4);\n else\n {\n var sourcePtr = db.DataPointer;\n var destPtr = bitmapData.Scan0;\n\n for (int y = 0; y < bitmap.Height; y++)\n {\n MemoryHelpers.CopyMemory(destPtr, sourcePtr, bitmap.Width * 4);\n\n sourcePtr = IntPtr.Add(sourcePtr, (int)db.RowPitch);\n destPtr = IntPtr.Add(destPtr, bitmapData.Stride);\n }\n }\n\n bitmap.UnlockBits(bitmapData);\n context.Unmap(stageTexture, 0);\n\n return bitmap;\n }\n /// \n /// Gets BitmapSource from a video frame\n /// \n /// Specify the width (-1: will keep the ratio based on height)\n /// Specify the height (-1: will keep the ratio based on width)\n /// Video frame to process (null: will use the current/last frame)\n /// \n unsafe public BitmapSource GetBitmapSource(int width = -1, int height = -1, VideoFrame frame = null)\n {\n try\n {\n lock (lockDevice)\n {\n frame ??= LastFrame;\n\n if (Disposed || frame == null || (frame.textures == null && frame.avFrame == null))\n return null;\n\n if (width == -1 && height == -1)\n {\n width = VideoRect.Right;\n height = VideoRect.Bottom;\n }\n else if (width != -1 && height == -1)\n height = (int)(width / curRatio);\n else if (height != -1 && width == -1)\n width = (int)(height * curRatio);\n\n if (singleStageDesc.Width != width || singleStageDesc.Height != height)\n {\n singleGpu?.Dispose();\n singleStage?.Dispose();\n singleGpuRtv?.Dispose();\n\n singleStageDesc.Width = (uint)width;\n singleStageDesc.Height = (uint)height;\n singleGpuDesc.Width = (uint)width;\n singleGpuDesc.Height = (uint)height;\n\n singleStage = Device.CreateTexture2D(singleStageDesc);\n singleGpu = Device.CreateTexture2D(singleGpuDesc);\n singleGpuRtv = Device.CreateRenderTargetView(singleGpu);\n\n singleViewport = new Viewport(width, height);\n }\n\n PresentOffline(frame, singleGpuRtv, singleViewport);\n\n if (videoProcessor == VideoProcessors.D3D11)\n SetViewport();\n }\n\n context.CopyResource(singleStage, singleGpu);\n return GetBitmapSource(singleStage);\n\n }\n catch (Exception e)\n {\n Log.Warn($\"GetBitmapSource failed with: {e.Message}\");\n return null;\n }\n }\n public BitmapSource GetBitmapSource(ID3D11Texture2D stageTexture)\n {\n WriteableBitmap bitmap = new((int)stageTexture.Description.Width, (int)stageTexture.Description.Height, 96, 96, System.Windows.Media.PixelFormats.Bgra32, null);\n var db = context.Map(stageTexture, 0, MapMode.Read, Vortice.Direct3D11.MapFlags.None);\n bitmap.Lock();\n\n if (db.RowPitch == bitmap.BackBufferStride)\n MemoryHelpers.CopyMemory(bitmap.BackBuffer, db.DataPointer, bitmap.PixelWidth * bitmap.PixelHeight * 4);\n else\n {\n var sourcePtr = db.DataPointer;\n var destPtr = bitmap.BackBuffer;\n\n for (int y = 0; y < bitmap.Height; y++)\n {\n MemoryHelpers.CopyMemory(destPtr, sourcePtr, bitmap.PixelWidth * 4);\n\n sourcePtr = IntPtr.Add(sourcePtr, (int)db.RowPitch);\n destPtr = IntPtr.Add(destPtr, bitmap.BackBufferStride);\n }\n }\n\n bitmap.Unlock();\n context.Unmap(stageTexture, 0);\n\n // Freezing animated wpf assets improves performance\n bitmap.Freeze();\n\n return bitmap;\n }\n\n /// \n /// Extracts a bitmap from a video frame\n /// (Currently cannot be used in parallel with the rendering)\n /// \n /// \n /// \n public Bitmap ExtractFrame(VideoFrame frame)\n {\n if (Device == null || frame == null) return null;\n\n int subresource = -1;\n\n Texture2DDescription stageDesc = new()\n {\n Usage = ResourceUsage.Staging,\n Width = VideoDecoder.VideoStream.Width,\n Height = VideoDecoder.VideoStream.Height,\n Format = Format.B8G8R8A8_UNorm,\n ArraySize = 1,\n MipLevels = 1,\n BindFlags = BindFlags.None,\n CPUAccessFlags = CpuAccessFlags.Read,\n SampleDescription = new SampleDescription(1, 0)\n };\n var stage = Device.CreateTexture2D(stageDesc);\n\n lock (lockDevice)\n {\n while (true)\n {\n for (int i=0; isample_rate};\n filtframe = av_frame_alloc();\n filterGraph = avfilter_graph_alloc();\n setFirstPts = true;\n abufferDrained = false;\n\n // IN (abuffersrc)\n linkCtx = abufferCtx = CreateFilter(\"abuffer\",\n $\"channel_layout={AudioStream.ChannelLayoutStr}:sample_fmt={AudioStream.SampleFormatStr}:sample_rate={codecCtx->sample_rate}:time_base={sinkTimebase.Num}/{sinkTimebase.Den}\");\n\n // USER DEFINED\n if (Config.Audio.Filters != null)\n foreach (var filter in Config.Audio.Filters)\n try\n {\n linkCtx = CreateFilter(filter.Name, filter.Args, linkCtx, filter.Id);\n }\n catch (Exception e) { Log.Error($\"{e.Message}\"); }\n\n // SPEED (atempo up to 3) | [0.125 - 0.25](3), [0.25 - 0.5](2), [0.5 - 2.0](1), [2.0 - 4.0](2), [4.0 - X](3)\n if (speed != 1)\n {\n if (speed >= 0.5 && speed <= 2)\n linkCtx = CreateFilter(\"atempo\", $\"tempo={speed.ToString(\"0.0000000000\", System.Globalization.CultureInfo.InvariantCulture)}\", linkCtx);\n else if ((speed > 2 & speed <= 4) || (speed >= 0.25 && speed < 0.5))\n {\n var singleAtempoSpeed = Math.Sqrt(speed);\n linkCtx = CreateFilter(\"atempo\", $\"tempo={singleAtempoSpeed.ToString(\"0.0000000000\", System.Globalization.CultureInfo.InvariantCulture)}\", linkCtx);\n linkCtx = CreateFilter(\"atempo\", $\"tempo={singleAtempoSpeed.ToString(\"0.0000000000\", System.Globalization.CultureInfo.InvariantCulture)}\", linkCtx);\n }\n else if (speed > 4 || speed >= 0.125 && speed < 0.25)\n {\n var singleAtempoSpeed = Math.Pow(speed, 1.0 / 3);\n linkCtx = CreateFilter(\"atempo\", $\"tempo={singleAtempoSpeed.ToString(\"0.0000000000\", System.Globalization.CultureInfo.InvariantCulture)}\", linkCtx);\n linkCtx = CreateFilter(\"atempo\", $\"tempo={singleAtempoSpeed.ToString(\"0.0000000000\", System.Globalization.CultureInfo.InvariantCulture)}\", linkCtx);\n linkCtx = CreateFilter(\"atempo\", $\"tempo={singleAtempoSpeed.ToString(\"0.0000000000\", System.Globalization.CultureInfo.InvariantCulture)}\", linkCtx);\n }\n }\n\n // OUT (abuffersink)\n abufferSinkCtx = CreateFilter(\"abuffersink\", null, null);\n\n int tmpSampleRate = AudioStream.SampleRate;\n fixed (AVSampleFormat* ptr = &AOutSampleFormat)\n ret = av_opt_set_bin(abufferSinkCtx , \"sample_fmts\" , (byte*)ptr, sizeof(AVSampleFormat) , OptSearchFlags.Children);\n ret = av_opt_set_bin(abufferSinkCtx , \"sample_rates\" , (byte*)&tmpSampleRate, sizeof(int) , OptSearchFlags.Children);\n ret = av_opt_set_int(abufferSinkCtx , \"all_channel_counts\" , 0 , OptSearchFlags.Children);\n ret = av_opt_set(abufferSinkCtx , \"ch_layouts\" , \"stereo\" , OptSearchFlags.Children);\n avfilter_link(linkCtx, 0, abufferSinkCtx, 0);\n\n // GRAPH CONFIG\n ret = avfilter_graph_config(filterGraph, null);\n\n // CRIT TBR:!!!\n var tb = 1000 * 10000.0 / sinkTimebase.Den; // Ensures we have at least 20-70ms samples to avoid audio crackling and av sync issues\n ((FilterLink*)abufferSinkCtx->inputs[0])->min_samples = (int) (20 * 10000 / tb);\n ((FilterLink*)abufferSinkCtx->inputs[0])->max_samples = (int) (70 * 10000 / tb);\n\n return ret < 0\n ? throw new Exception($\"[FilterGraph] {FFmpegEngine.ErrorCodeToMsg(ret)} ({ret})\")\n : 0;\n }\n catch (Exception e)\n {\n fixed(AVFilterGraph** filterGraphPtr = &filterGraph)\n avfilter_graph_free(filterGraphPtr);\n\n Log.Error($\"{e.Message}\");\n\n return ret;\n }\n }\n\n private void DisposeFilters()\n {\n if (filterGraph == null)\n return;\n\n fixed(AVFilterGraph** filterGraphPtr = &filterGraph)\n avfilter_graph_free(filterGraphPtr);\n\n if (filtframe != null)\n fixed (AVFrame** ptr = &filtframe)\n av_frame_free(ptr);\n\n abufferCtx = null;\n abufferSinkCtx = null;\n filterGraph = null;\n filtframe = null;\n }\n protected override void OnSpeedChanged(double value)\n {\n // Possible Task to avoid locking UI thread as lockAtempo can wait for the Frames queue to be freed (will cause other issues and couldnt reproduce the possible dead lock)\n cBufTimesCur = cBufTimesSize;\n lock (lockSpeed)\n {\n if (filterGraph != null)\n DrainFilters();\n\n cBufTimesCur= 1;\n oldSpeed = speed;\n speed = value;\n\n var frames = Frames.ToArray();\n for (int i = 0; i < frames.Length; i++)\n FixSample(frames[i], oldSpeed, speed);\n\n if (filterGraph != null)\n SetupFilters();\n }\n }\n internal void FixSample(AudioFrame frame, double oldSpeed, double speed)\n {\n var oldDataLen = frame.dataLen;\n frame.dataLen = Utils.Align((int) (oldDataLen * oldSpeed / speed), ASampleBytes);\n fixed (byte* cBufStartPosPtr = &cBuf[0])\n {\n var curOffset = (long)frame.dataPtr - (long)cBufStartPosPtr;\n\n if (speed < oldSpeed)\n {\n if (curOffset + frame.dataLen >= cBuf.Length)\n {\n frame.dataPtr = (IntPtr)cBufStartPosPtr;\n curOffset = 0;\n oldDataLen = 0;\n }\n\n // fill silence\n for (int p = oldDataLen; p < frame.dataLen; p++)\n cBuf[curOffset + p] = 0;\n }\n }\n }\n private int UpdateFilterInternal(string filterId, string key, string value)\n {\n int ret = avfilter_graph_send_command(filterGraph, filterId, key, value, null, 0, 0);\n Log.Info($\"[{filterId}] {key}={value} {(ret >=0 ? \"success\" : \"failed\")}\");\n\n return ret;\n }\n internal int SetupFiltersOrSwr()\n {\n lock (lockSpeed)\n {\n int ret = -1;\n\n if (Disposed)\n return ret;\n\n if (Config.Audio.FiltersEnabled)\n {\n ret = SetupFilters();\n\n if (ret != 0)\n {\n Log.Error($\"Setup filters failed. Fallback to Swr.\");\n ret = SetupSwr();\n }\n else\n DisposeSwr();\n }\n else\n {\n DisposeFilters();\n ret = SetupSwr();\n }\n\n return ret;\n }\n }\n\n public int UpdateFilter(string filterId, string key, string value)\n {\n lock (lockCodecCtx)\n return filterGraph != null ? UpdateFilterInternal(filterId, key, value) : -1;\n }\n public int ReloadFilters()\n {\n if (!Config.Audio.FiltersEnabled)\n return -1;\n\n lock (lockActions)\n lock (lockCodecCtx)\n return SetupFilters();\n }\n\n private void ProcessFilters()\n {\n if (setFirstPts)\n {\n setFirstPts = false;\n filterFirstPts = frame->pts;\n curSamples = 0;\n missedSamples = 0;\n }\n else if (Math.Abs(frame->pts - nextPts) > 10 * 10000) // 10ms distance should resync filters (TBR: it should be 0ms however we might get 0 pkt_duration for unknown?)\n {\n DrainFilters();\n Log.Warn($\"Resync filters! ({Utils.TicksToTime((long)((frame->pts - nextPts) * AudioStream.Timebase))} distance)\");\n //resyncWithVideoRequired = !VideoDecoder.Disposed;\n DisposeFrames();\n avcodec_flush_buffers(codecCtx);\n if (filterGraph != null)\n SetupFilters();\n return;\n }\n\n nextPts = frame->pts + frame->duration;\n\n int ret;\n\n if ((ret = av_buffersrc_add_frame_flags(abufferCtx, frame, AVBuffersrcFlag.KeepRef | AVBuffersrcFlag.NoCheckFormat)) < 0) // AV_BUFFERSRC_FLAG_KEEP_REF = 8, AV_BUFFERSRC_FLAG_NO_CHECK_FORMAT = 1 (we check format change manually before here)\n {\n Log.Warn($\"[buffersrc] {FFmpegEngine.ErrorCodeToMsg(ret)} ({ret})\");\n Status = Status.Stopping;\n return;\n }\n\n while (true)\n {\n if ((ret = av_buffersink_get_frame_flags(abufferSinkCtx, filtframe, 0)) < 0) // Sometimes we get AccessViolationException while we UpdateFilter (possible related with .NET7 debug only bug)\n return; // EAGAIN (Some filters will send EAGAIN even if EOF currently we handled cause our Status will be Draining)\n\n if (filtframe->pts == AV_NOPTS_VALUE) // we might desync here (we dont count frames->nb_samples) ?\n {\n av_frame_unref(filtframe);\n continue;\n }\n\n ProcessFilter();\n\n // Wait until Queue not Full or Stopped\n if (Frames.Count >= Config.Decoder.MaxAudioFrames * cBufTimesCur)\n {\n Monitor.Exit(lockCodecCtx);\n lock (lockStatus)\n if (Status == Status.Running)\n Status = Status.QueueFull;\n\n while (Frames.Count >= Config.Decoder.MaxAudioFrames * cBufTimesCur && (Status == Status.QueueFull || Status == Status.Draining))\n Thread.Sleep(20);\n\n Monitor.Enter(lockCodecCtx);\n\n lock (lockStatus)\n {\n if (Status == Status.QueueFull)\n Status = Status.Running;\n else if (Status != Status.Draining)\n return;\n }\n }\n }\n }\n private void DrainFilters()\n {\n if (abufferDrained)\n return;\n\n abufferDrained = true;\n\n int ret;\n\n if ((ret = av_buffersrc_add_frame(abufferCtx, null)) < 0)\n {\n Log.Warn($\"[buffersrc] {FFmpegEngine.ErrorCodeToMsg(ret)} ({ret})\");\n return;\n }\n\n while (true)\n {\n if ((ret = av_buffersink_get_frame_flags(abufferSinkCtx, filtframe, 0)) < 0)\n return;\n\n if (filtframe->pts == AV_NOPTS_VALUE)\n {\n av_frame_unref(filtframe);\n return;\n }\n\n ProcessFilter();\n }\n }\n private void ProcessFilter()\n {\n var curLen = filtframe->nb_samples * ASampleBytes;\n\n if (filtframe->nb_samples > cBufSamples) // (min 10000)\n AllocateCircularBuffer(filtframe->nb_samples);\n else if (cBufPos + curLen >= cBuf.Length)\n cBufPos = 0;\n\n long newPts = filterFirstPts + av_rescale_q((long)(curSamples + missedSamples), sinkTimebase, AudioStream.AVStream->time_base);\n var samplesSpeed1 = filtframe->nb_samples * speed;\n missedSamples += samplesSpeed1 - (int)samplesSpeed1;\n curSamples += (int)samplesSpeed1;\n\n AudioFrame mFrame = new()\n {\n dataLen = curLen,\n timestamp = (long)((newPts * AudioStream.Timebase) - demuxer.StartTime + Config.Audio.Delay)\n };\n\n if (CanTrace) Log.Trace($\"Processes {Utils.TicksToTime(mFrame.timestamp)}\");\n\n fixed (byte* circularBufferPosPtr = &cBuf[cBufPos])\n mFrame.dataPtr = (IntPtr)circularBufferPosPtr;\n\n Marshal.Copy((IntPtr) filtframe->data[0], cBuf, cBufPos, mFrame.dataLen);\n cBufPos += curLen;\n\n Frames.Enqueue(mFrame);\n av_frame_unref(filtframe);\n }\n}\n\n/// \n/// FFmpeg Filter\n/// \npublic class Filter\n{\n /// \n /// \n /// FFmpeg valid filter id\n /// (Required only to send commands)\n /// \n /// \n public string Id { get; set; }\n\n /// \n /// FFmpeg valid filter name\n /// \n public string Name { get; set; }\n\n /// \n /// FFmpeg valid filter args\n /// \n public string Args { get; set; }\n}\n"], ["/LLPlayer/FlyleafLib/MediaPlayer/Player.Keys.cs", "using System;\nusing System.Collections.Generic;\nusing System.ComponentModel;\nusing System.Runtime.InteropServices;\nusing System.Text.Json.Serialization;\nusing System.Windows.Input;\nusing static FlyleafLib.Logger;\n\nnamespace FlyleafLib.MediaPlayer;\n\npartial class Player\n{\n /* Player Key Bindings\n *\n * Config.Player.KeyBindings.Keys\n *\n * KeyDown / KeyUp Events (Control / WinFormsHost / WindowFront (FlyleafWindow))\n * Exposes KeyDown/KeyUp if required to listen on additional Controls/Windows\n * Allows KeyBindingAction.Custom to set an external Action for Key Binding\n */\n\n Tuple onKeyUpBinding;\n\n /// \n /// Can be used to route KeyDown events (WPF)\n /// \n /// \n /// \n public static bool KeyDown(Player player, KeyEventArgs e)\n {\n e.Handled = KeyDown(player, e.Key == Key.System ? e.SystemKey : e.Key);\n\n return e.Handled;\n }\n\n /// \n /// Can be used to route KeyDown events (WinForms)\n /// \n /// \n /// \n public static void KeyDown(Player player, System.Windows.Forms.KeyEventArgs e)\n => e.Handled = KeyDown(player, KeyInterop.KeyFromVirtualKey((int)e.KeyCode));\n\n /// \n /// Can be used to route KeyUp events (WPF)\n /// \n /// \n /// \n public static bool KeyUp(Player player, KeyEventArgs e)\n {\n e.Handled = KeyUp(player, e.Key == Key.System ? e.SystemKey : e.Key);\n\n return e.Handled;\n }\n\n /// \n /// Can be used to route KeyUp events (WinForms)\n /// \n /// \n /// \n public static void KeyUp(Player player, System.Windows.Forms.KeyEventArgs e)\n => e.Handled = KeyUp(player, KeyInterop.KeyFromVirtualKey((int)e.KeyCode));\n\n public static bool KeyDown(Player player, Key key)\n {\n if (player == null)\n return false;\n\n player.Activity.RefreshActive();\n\n if (player.onKeyUpBinding != null)\n {\n if (player.onKeyUpBinding.Item1.Key == key)\n return true;\n\n if (DateTime.UtcNow.Ticks - player.onKeyUpBinding.Item2 < TimeSpan.FromSeconds(2).Ticks)\n return false;\n\n player.onKeyUpBinding = null; // In case of keyboard lost capture (should be handled from hosts)\n }\n\n List keysList = new();\n var spanList = CollectionsMarshal.AsSpan(player.Config.Player.KeyBindings.Keys); // should create dictionary here with key+alt+ctrl+shift hash\n foreach(var binding in spanList)\n if (binding.Key == key && binding.IsEnabled)\n keysList.Add(binding);\n\n if (keysList.Count == 0)\n return false;\n\n bool alt, ctrl, shift;\n alt = Keyboard.IsKeyDown(Key.LeftAlt) || Keyboard.IsKeyDown(Key.RightAlt);\n ctrl = Keyboard.IsKeyDown(Key.LeftCtrl) || Keyboard.IsKeyDown(Key.RightCtrl);\n shift = Keyboard.IsKeyDown(Key.LeftShift) || Keyboard.IsKeyDown(Key.RightShift);\n\n var spanList2 = CollectionsMarshal.AsSpan(keysList);\n foreach(var binding in spanList2)\n {\n if (binding.Alt == alt && binding.Ctrl == ctrl && binding.Shift == shift && binding.IsEnabled)\n {\n if (binding.IsKeyUp)\n player.onKeyUpBinding = new(binding, DateTime.UtcNow.Ticks);\n else\n ExecuteBinding(player, binding, false);\n\n return true;\n }\n }\n\n return false;\n }\n public static bool KeyUp(Player player, Key key)\n {\n if (player == null || player.onKeyUpBinding == null || player.onKeyUpBinding.Item1.Key != key)\n return false;\n\n ExecuteBinding(player, player.onKeyUpBinding.Item1, true);\n player.onKeyUpBinding = null;\n return true;\n }\n\n static void ExecuteBinding(Player player, KeyBinding binding, bool isKeyUp)\n {\n if (CanDebug) player.Log.Debug($\"[Keys|{(isKeyUp ? \"Up\" : \"Down\")}] {(binding.Action == KeyBindingAction.Custom && binding.ActionName != null ? binding.ActionName : binding.Action)}\");\n binding.ActionInternal?.Invoke();\n }\n}\n\npublic class KeysConfig\n{\n /// \n /// Currently configured key bindings\n /// (Normally you should not access this directly)\n /// \n public List Keys { get ; set; }\n\n Player player;\n\n public KeysConfig() { }\n\n public KeysConfig Clone()\n {\n KeysConfig keys = (KeysConfig) MemberwiseClone();\n keys.player = null;\n keys.Keys = null;\n return keys;\n }\n\n internal void SetPlayer(Player player)\n {\n Keys ??= new List();\n\n if (!player.Config.Loaded && Keys.Count == 0)\n LoadDefault();\n\n this.player = player;\n\n foreach(var binding in Keys)\n {\n if (binding.Action != KeyBindingAction.Custom)\n binding.ActionInternal = GetKeyBindingAction(binding.Action);\n }\n }\n\n /// \n /// Adds a custom keybinding\n /// \n /// The key to bind\n /// If should fire on each keydown or just on keyup\n /// The action to execute\n /// A unique name to be able to identify it\n /// If Alt should be pressed\n /// If Ctrl should be pressed\n /// If Shift should be pressed\n /// Keybinding already exists\n public void AddCustom(Key key, bool isKeyUp, Action action, string actionName, bool alt = false, bool ctrl = false, bool shift = false)\n {\n for (int i=0; i\n /// Adds a new key binding\n /// \n /// The key to bind\n /// Which action from the available to assign\n /// If Alt should be pressed\n /// If Ctrl should be pressed\n /// If Shift should be pressed\n /// Keybinding already exists\n public void Add(Key key, KeyBindingAction action, bool alt = false, bool ctrl = false, bool shift = false)\n {\n for (int i=0; i\n /// Removes a binding based on Key/Ctrl combination\n /// \n /// The assigned key\n /// If Alt is assigned\n /// If Ctrl is assigned\n /// If Shift is assigned\n public void Remove(Key key, bool alt = false, bool ctrl = false, bool shift = false)\n {\n for (int i=Keys.Count-1; i >=0; i--)\n if (Keys[i].Key == key && Keys[i].Alt == alt && Keys[i].Ctrl == ctrl && Keys[i].Shift == shift)\n Keys.RemoveAt(i);\n }\n\n /// \n /// Removes a binding based on assigned action\n /// \n /// The assigned action\n public void Remove(KeyBindingAction action)\n {\n for (int i=Keys.Count-1; i >=0; i--)\n if (Keys[i].Action == action)\n Keys.RemoveAt(i);\n }\n\n /// \n /// Removes a binding based on assigned action's name\n /// \n /// The assigned action's name\n public void Remove(string actionName)\n {\n for (int i=Keys.Count-1; i >=0; i--)\n if (Keys[i].ActionName == actionName)\n Keys.RemoveAt(i);\n }\n\n /// \n /// Removes all the bindings\n /// \n public void RemoveAll() => Keys.Clear();\n\n /// \n /// Resets to default bindings\n /// \n public void LoadDefault()\n {\n if (Keys == null)\n Keys = new List();\n else\n Keys.Clear();\n\n Add(Key.OemSemicolon, KeyBindingAction.SubsDelayRemovePrimary);\n Add(Key.OemQuotes, KeyBindingAction.SubsDelayAddPrimary);\n Add(Key.OemSemicolon, KeyBindingAction.SubsDelayRemoveSecondary, shift: true);\n Add(Key.OemQuotes, KeyBindingAction.SubsDelayAddSecondary, shift: true);\n\n Add(Key.A, KeyBindingAction.SubsPrevSeek);\n Add(Key.S, KeyBindingAction.SubsCurSeek);\n Add(Key.D, KeyBindingAction.SubsNextSeek);\n\n Add(Key.J, KeyBindingAction.SubsPrevSeek);\n Add(Key.K, KeyBindingAction.SubsCurSeek);\n Add(Key.L, KeyBindingAction.SubsNextSeek);\n\n // Mouse backford/forward button\n Add(Key.Left, KeyBindingAction.SubsPrevSeekFallback, alt: true);\n Add(Key.Right, KeyBindingAction.SubsNextSeekFallback, alt: true);\n\n Add(Key.V, KeyBindingAction.OpenFromClipboardSafe, ctrl: true);\n Add(Key.O, KeyBindingAction.OpenFromFileDialog, ctrl: true);\n Add(Key.C, KeyBindingAction.CopyToClipboard, ctrl: true, shift: true);\n\n Add(Key.Left, KeyBindingAction.SeekBackward2);\n Add(Key.Left, KeyBindingAction.SeekBackward, ctrl: true);\n Add(Key.Right, KeyBindingAction.SeekForward2);\n Add(Key.Right, KeyBindingAction.SeekForward, ctrl: true);\n\n Add(Key.S, KeyBindingAction.ToggleSeekAccurate, ctrl: true);\n\n Add(Key.OemPlus, KeyBindingAction.SpeedAdd);\n Add(Key.OemPlus, KeyBindingAction.SpeedAdd2, shift: true);\n Add(Key.OemMinus, KeyBindingAction.SpeedRemove);\n Add(Key.OemMinus, KeyBindingAction.SpeedRemove2, shift: true);\n\n Add(Key.OemPlus, KeyBindingAction.ZoomIn, ctrl: true);\n Add(Key.OemMinus, KeyBindingAction.ZoomOut, ctrl: true);\n\n Add(Key.F, KeyBindingAction.ToggleFullScreen);\n\n Add(Key.Space, KeyBindingAction.TogglePlayPause);\n Add(Key.MediaPlayPause, KeyBindingAction.TogglePlayPause);\n Add(Key.Play, KeyBindingAction.TogglePlayPause);\n\n Add(Key.H, KeyBindingAction.ToggleSubtitlesVisibility);\n Add(Key.V, KeyBindingAction.ToggleSubtitlesVisibility);\n\n Add(Key.M, KeyBindingAction.ToggleMute);\n Add(Key.Up, KeyBindingAction.VolumeUp);\n Add(Key.Down, KeyBindingAction.VolumeDown);\n\n Add(Key.D0, KeyBindingAction.ResetAll);\n\n Add(Key.Escape, KeyBindingAction.NormalScreen);\n Add(Key.Q, KeyBindingAction.Stop, ctrl: true);\n }\n\n public Action GetKeyBindingAction(KeyBindingAction action)\n {\n switch (action)\n {\n case KeyBindingAction.ForceIdle:\n return player.Activity.ForceIdle;\n case KeyBindingAction.ForceActive:\n return player.Activity.ForceActive;\n case KeyBindingAction.ForceFullActive:\n return player.Activity.ForceFullActive;\n\n case KeyBindingAction.AudioDelayAdd:\n return player.Audio.DelayAdd;\n case KeyBindingAction.AudioDelayRemove:\n return player.Audio.DelayRemove;\n case KeyBindingAction.AudioDelayAdd2:\n return player.Audio.DelayAdd2;\n case KeyBindingAction.AudioDelayRemove2:\n return player.Audio.DelayRemove2;\n case KeyBindingAction.ToggleAudio:\n return player.Audio.Toggle;\n case KeyBindingAction.ToggleMute:\n return player.Audio.ToggleMute;\n case KeyBindingAction.VolumeUp:\n return player.Audio.VolumeUp;\n case KeyBindingAction.VolumeDown:\n return player.Audio.VolumeDown;\n\n case KeyBindingAction.ToggleVideo:\n return player.Video.Toggle;\n case KeyBindingAction.ToggleKeepRatio:\n return player.Video.ToggleKeepRatio;\n case KeyBindingAction.ToggleVideoAcceleration:\n return player.Video.ToggleVideoAcceleration;\n\n case KeyBindingAction.SubsDelayAddPrimary:\n return player.Subtitles.DelayAddPrimary;\n case KeyBindingAction.SubsDelayRemovePrimary:\n return player.Subtitles.DelayRemovePrimary;\n case KeyBindingAction.SubsDelayAdd2Primary:\n return player.Subtitles.DelayAdd2Primary;\n case KeyBindingAction.SubsDelayRemove2Primary:\n return player.Subtitles.DelayRemove2Primary;\n\n case KeyBindingAction.SubsDelayAddSecondary:\n return player.Subtitles.DelayAddSecondary;\n case KeyBindingAction.SubsDelayRemoveSecondary:\n return player.Subtitles.DelayRemoveSecondary;\n case KeyBindingAction.SubsDelayAdd2Secondary:\n return player.Subtitles.DelayAdd2Secondary;\n case KeyBindingAction.SubsDelayRemove2Secondary:\n return player.Subtitles.DelayRemove2Secondary;\n\n case KeyBindingAction.ToggleSubtitlesVisibility:\n return player.Subtitles.ToggleVisibility;\n case KeyBindingAction.ToggleSubtitlesVisibilityPrimary:\n return player.Subtitles.ToggleVisibilityPrimary;\n case KeyBindingAction.ToggleSubtitlesVisibilitySecondary:\n return player.Subtitles.ToggleVisibilitySecondary;\n\n case KeyBindingAction.OpenFromClipboard:\n return player.OpenFromClipboard;\n case KeyBindingAction.OpenFromClipboardSafe:\n return player.OpenFromClipboardSafe;\n\n case KeyBindingAction.OpenFromFileDialog:\n return player.OpenFromFileDialog;\n\n case KeyBindingAction.CopyToClipboard:\n return player.CopyToClipboard;\n\n case KeyBindingAction.CopyItemToClipboard:\n return player.CopyItemToClipboard;\n\n case KeyBindingAction.Flush:\n return player.Flush;\n\n case KeyBindingAction.Stop:\n return player.Stop;\n\n case KeyBindingAction.Pause:\n return player.Pause;\n\n case KeyBindingAction.Play:\n return player.Play;\n\n case KeyBindingAction.TogglePlayPause:\n return player.TogglePlayPause;\n\n case KeyBindingAction.TakeSnapshot:\n return player.Commands.TakeSnapshotAction;\n\n case KeyBindingAction.NormalScreen:\n return player.NormalScreen;\n\n case KeyBindingAction.FullScreen:\n return player.FullScreen;\n\n case KeyBindingAction.ToggleFullScreen:\n return player.ToggleFullScreen;\n\n case KeyBindingAction.ToggleRecording:\n return player.ToggleRecording;\n\n case KeyBindingAction.ToggleReversePlayback:\n return player.ToggleReversePlayback;\n\n case KeyBindingAction.ToggleLoopPlayback:\n return player.ToggleLoopPlayback;\n\n case KeyBindingAction.ToggleSeekAccurate:\n return player.ToggleSeekAccurate;\n\n case KeyBindingAction.SeekBackward:\n return player.SeekBackward;\n\n case KeyBindingAction.SeekForward:\n return player.SeekForward;\n\n case KeyBindingAction.SeekBackward2:\n return player.SeekBackward2;\n\n case KeyBindingAction.SeekForward2:\n return player.SeekForward2;\n\n case KeyBindingAction.SeekBackward3:\n return player.SeekBackward3;\n\n case KeyBindingAction.SeekForward3:\n return player.SeekForward3;\n\n case KeyBindingAction.SeekBackward4:\n return player.SeekBackward4;\n\n case KeyBindingAction.SeekForward4:\n return player.SeekForward4;\n\n case KeyBindingAction.SubsCurSeek:\n return player.Subtitles.CurSeek;\n case KeyBindingAction.SubsPrevSeek:\n return player.Subtitles.PrevSeek;\n case KeyBindingAction.SubsNextSeek:\n return player.Subtitles.NextSeek;\n case KeyBindingAction.SubsNextSeekFallback:\n return player.Subtitles.NextSeekFallback;\n case KeyBindingAction.SubsPrevSeekFallback:\n return player.Subtitles.PrevSeekFallback;\n\n case KeyBindingAction.SubsCurSeek2:\n return player.Subtitles.CurSeek2;\n case KeyBindingAction.SubsPrevSeek2:\n return player.Subtitles.PrevSeek2;\n case KeyBindingAction.SubsNextSeek2:\n return player.Subtitles.NextSeek2;\n case KeyBindingAction.SubsNextSeekFallback2:\n return player.Subtitles.NextSeekFallback2;\n case KeyBindingAction.SubsPrevSeekFallback2:\n return player.Subtitles.PrevSeekFallback2;\n\n case KeyBindingAction.SpeedAdd:\n return player.SpeedUp;\n\n case KeyBindingAction.SpeedAdd2:\n return player.SpeedUp2;\n\n case KeyBindingAction.SpeedRemove:\n return player.SpeedDown;\n\n case KeyBindingAction.SpeedRemove2:\n return player.SpeedDown2;\n\n case KeyBindingAction.ShowPrevFrame:\n return player.ShowFramePrev;\n\n case KeyBindingAction.ShowNextFrame:\n return player.ShowFrameNext;\n\n case KeyBindingAction.ZoomIn:\n return player.ZoomIn;\n\n case KeyBindingAction.ZoomOut:\n return player.ZoomOut;\n\n case KeyBindingAction.ResetAll:\n return player.ResetAll;\n\n case KeyBindingAction.ResetSpeed:\n return player.ResetSpeed;\n\n case KeyBindingAction.ResetRotation:\n return player.ResetRotation;\n\n case KeyBindingAction.ResetZoom:\n return player.ResetZoom;\n }\n\n return null;\n }\n private static HashSet isKeyUpBinding = new()\n {\n // TODO: Should Fire once one KeyDown and not again until KeyUp is fired (in case of Tasks keep track of already running actions?)\n\n // Having issues with alt/ctrl/shift (should save state of alt/ctrl/shift on keydown and not checked on keyup)\n\n { KeyBindingAction.OpenFromClipboard },\n { KeyBindingAction.OpenFromClipboardSafe },\n { KeyBindingAction.OpenFromFileDialog },\n { KeyBindingAction.CopyToClipboard },\n { KeyBindingAction.TakeSnapshot },\n { KeyBindingAction.NormalScreen },\n { KeyBindingAction.FullScreen },\n { KeyBindingAction.ToggleFullScreen },\n { KeyBindingAction.ToggleAudio },\n { KeyBindingAction.ToggleVideo },\n { KeyBindingAction.ToggleKeepRatio },\n { KeyBindingAction.ToggleVideoAcceleration },\n { KeyBindingAction.ToggleSubtitlesVisibility },\n { KeyBindingAction.ToggleSubtitlesVisibilityPrimary },\n { KeyBindingAction.ToggleSubtitlesVisibilitySecondary },\n { KeyBindingAction.ToggleMute },\n { KeyBindingAction.TogglePlayPause },\n { KeyBindingAction.ToggleRecording },\n { KeyBindingAction.ToggleReversePlayback },\n { KeyBindingAction.ToggleLoopPlayback },\n { KeyBindingAction.Play },\n { KeyBindingAction.Pause },\n { KeyBindingAction.Stop },\n { KeyBindingAction.Flush },\n { KeyBindingAction.ToggleSeekAccurate },\n { KeyBindingAction.SpeedAdd },\n { KeyBindingAction.SpeedAdd2 },\n { KeyBindingAction.SpeedRemove },\n { KeyBindingAction.SpeedRemove2 },\n { KeyBindingAction.ResetAll },\n { KeyBindingAction.ResetSpeed },\n { KeyBindingAction.ResetRotation },\n { KeyBindingAction.ResetZoom },\n { KeyBindingAction.ForceIdle },\n { KeyBindingAction.ForceActive },\n { KeyBindingAction.ForceFullActive }\n };\n}\npublic class KeyBinding\n{\n public bool IsEnabled { get; set; } = true;\n public bool Alt { get; set; }\n public bool Ctrl { get; set; }\n public bool Shift { get; set; }\n public Key Key { get; set; }\n public KeyBindingAction Action { get; set; }\n\n [JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)]\n public string ActionName\n {\n get => Action == KeyBindingAction.Custom ? field : null;\n set;\n }\n\n public bool IsKeyUp { get; set; }\n\n /// \n /// Sets action for custom key binding\n /// \n /// \n /// \n public void SetAction(Action action, bool isKeyUp)\n {\n ActionInternal = action;\n IsKeyUp = isKeyUp;\n }\n\n [JsonIgnore]\n public Action ActionInternal { get; internal set; }\n}\n\npublic enum KeyBindingAction\n{\n [Description(nameof(Custom))]\n Custom,\n [Description(\"Set Activity to Idle forcibly\")]\n ForceIdle,\n [Description(\"Set Activity to Active forcibly\")]\n ForceActive,\n [Description(\"Set Activity to FullActive forcibly\")]\n ForceFullActive,\n\n [Description(\"Increase Audio Delay (1)\")]\n AudioDelayAdd,\n [Description(\"Increase Audio Delay (2)\")]\n AudioDelayAdd2,\n [Description(\"Decrease Audio Delay (1)\")]\n AudioDelayRemove,\n [Description(\"Decrease Audio Delay (2)\")]\n AudioDelayRemove2,\n\n [Description(\"Toggle Audio Mute/Unmute\")]\n ToggleMute,\n [Description(\"Volume Up (1)\")]\n VolumeUp,\n [Description(\"Volume Down (1)\")]\n VolumeDown,\n\n [Description(\"Increase Primary Subtitles Delay (1)\")]\n SubsDelayAddPrimary,\n [Description(\"Increase Primary Subtitles Delay (2)\")]\n SubsDelayAdd2Primary,\n [Description(\"Decrease Primary Subtitles Delay (1)\")]\n SubsDelayRemovePrimary,\n [Description(\"Decrease Primary Subtitles Delay (2)\")]\n SubsDelayRemove2Primary,\n [Description(\"Increase Secondary Subtitles Delay (1)\")]\n SubsDelayAddSecondary,\n [Description(\"Increase Secondary Subtitles Delay (2)\")]\n SubsDelayAdd2Secondary,\n [Description(\"Decrease Secondary Subtitles Delay (1)\")]\n SubsDelayRemoveSecondary,\n [Description(\"Decrease Secondary Subtitles Delay (2)\")]\n SubsDelayRemove2Secondary,\n\n [Description(\"Copy Opened Item to Clipboard\")]\n CopyToClipboard,\n [Description(\"Copy Current Played Item to Clipboard\")]\n CopyItemToClipboard,\n [Description(\"Open a media from clipboard\")]\n OpenFromClipboard,\n [Description(\"Open a media from clipboard if not open\")]\n OpenFromClipboardSafe,\n [Description(\"Open a media from file dialog\")]\n OpenFromFileDialog,\n\n [Description(\"Stop playback\")]\n Stop,\n [Description(\"Pause playback\")]\n Pause,\n [Description(\"Play playback\")]\n Play,\n [Description(\"Toggle play playback\")]\n TogglePlayPause,\n\n [Description(\"Toggle reverse playback\")]\n ToggleReversePlayback,\n [Description(\"Toggle loop playback\")]\n ToggleLoopPlayback,\n [Description(\"Flushes the buffer of the player\")]\n Flush,\n [Description(\"Take snapshot\")]\n TakeSnapshot,\n [Description(\"Change to NormalScreen\")]\n NormalScreen,\n [Description(\"Change to FullScreen\")]\n FullScreen,\n [Description(\"Toggle NormalScreen / FullScreen\")]\n ToggleFullScreen,\n\n [Description(\"Toggle Audio Enabled\")]\n ToggleAudio,\n [Description(\"Toggle Video Enabled\")]\n ToggleVideo,\n\n [Description(\"Toggle All Subtitles Visibility\")]\n ToggleSubtitlesVisibility,\n [Description(\"Toggle Primary Subtitles Visibility\")]\n ToggleSubtitlesVisibilityPrimary,\n [Description(\"Toggle Secondary Subtitles Visibility\")]\n ToggleSubtitlesVisibilitySecondary,\n\n [Description(\"Toggle Keep Aspect Ratio\")]\n ToggleKeepRatio,\n [Description(\"Toggle Video Acceleration\")]\n ToggleVideoAcceleration,\n [Description(\"Toggle Recording\")]\n ToggleRecording,\n [Description(\"Toggle Always Seek Accurate Mode\")]\n ToggleSeekAccurate,\n\n [Description(\"Seek forwards (1)\")]\n SeekForward,\n [Description(\"Seek backwards (1)\")]\n SeekBackward,\n [Description(\"Seek forwards (2)\")]\n SeekForward2,\n [Description(\"Seek backwards (2)\")]\n SeekBackward2,\n [Description(\"Seek forwards (3)\")]\n SeekForward3,\n [Description(\"Seek backwards (3)\")]\n SeekBackward3,\n [Description(\"Seek forwards (4)\")]\n SeekForward4,\n [Description(\"Seek backwards (4)\")]\n SeekBackward4,\n\n [Description(\"Seek to the previous subtitle\")]\n SubsPrevSeek,\n [Description(\"Seek to the current subtitle\")]\n SubsCurSeek,\n [Description(\"Seek to the next subtitle\")]\n SubsNextSeek,\n [Description(\"Seek to the previous subtitle or seek backwards\")]\n SubsPrevSeekFallback,\n [Description(\"Seek to the next subtitle or seek forwards\")]\n SubsNextSeekFallback,\n\n [Description(\"Seek to the previous secondary subtitle\")]\n SubsPrevSeek2,\n [Description(\"Seek to the current secondary subtitle\")]\n SubsCurSeek2,\n [Description(\"Seek to the next secondary subtitle\")]\n SubsNextSeek2,\n [Description(\"Seek to the previous secondary subtitle or seek backwards\")]\n SubsPrevSeekFallback2,\n [Description(\"Seek to the next secondary subtitle or seek forwards\")]\n SubsNextSeekFallback2,\n\n [Description(\"Speed Up (1)\")]\n SpeedAdd,\n [Description(\"Speed Up (2)\")]\n SpeedAdd2,\n\n [Description(\"Speed Down (1)\")]\n SpeedRemove,\n [Description(\"Speed Down (2)\")]\n SpeedRemove2,\n\n [Description(\"Show Next Frame\")]\n ShowNextFrame,\n [Description(\"Show Previous Frame\")]\n ShowPrevFrame,\n\n [Description(\"Reset Zoom / Rotation / Speed\")]\n ResetAll,\n [Description(\"Reset Speed\")]\n ResetSpeed,\n [Description(\"Reset Rotation\")]\n ResetRotation,\n [Description(\"Reset Zoom\")]\n ResetZoom,\n\n [Description(\"Zoom In (1)\")]\n ZoomIn,\n [Description(\"Zoom Out (1)\")]\n ZoomOut,\n}\n"], ["/LLPlayer/FlyleafLib/MediaFramework/MediaDecoder/DataDecoder.cs", "using System.Threading;\nusing System.Collections.Concurrent;\nusing System.Runtime.InteropServices;\n\nusing FlyleafLib.MediaFramework.MediaFrame;\nusing FlyleafLib.MediaFramework.MediaStream;\n\nnamespace FlyleafLib.MediaFramework.MediaDecoder;\npublic unsafe class DataDecoder : DecoderBase\n{\n public DataStream DataStream => (DataStream)Stream;\n\n public ConcurrentQueue\n Frames { get; protected set; } = new ConcurrentQueue();\n\n public DataDecoder(Config config, int uniqueId = -1) : base(config, uniqueId) { }\n\n\n protected override unsafe int Setup(AVCodec* codec) => 0;\n protected override void DisposeInternal()\n => Frames = new ConcurrentQueue();\n\n public void Flush()\n {\n lock (lockActions)\n lock (lockCodecCtx)\n {\n if (Disposed)\n return;\n\n if (Status == Status.Ended)\n Status = Status.Stopped;\n else if (Status == Status.Draining)\n Status = Status.Stopping;\n\n DisposeFrames();\n }\n }\n\n protected override void RunInternal()\n {\n int allowedErrors = Config.Decoder.MaxErrors;\n AVPacket *packet;\n\n do\n {\n // Wait until Queue not Full or Stopped\n if (Frames.Count >= Config.Decoder.MaxDataFrames)\n {\n lock (lockStatus)\n if (Status == Status.Running)\n Status = Status.QueueFull;\n\n while (Frames.Count >= Config.Decoder.MaxDataFrames && Status == Status.QueueFull)\n Thread.Sleep(20);\n\n lock (lockStatus)\n {\n if (Status != Status.QueueFull)\n break;\n Status = Status.Running;\n }\n }\n\n // While Packets Queue Empty (Ended | Quit if Demuxer stopped | Wait until we get packets)\n if (demuxer.DataPackets.Count == 0)\n {\n CriticalArea = true;\n\n lock (lockStatus)\n if (Status == Status.Running)\n Status = Status.QueueEmpty;\n\n while (demuxer.DataPackets.Count == 0 && Status == Status.QueueEmpty)\n {\n if (demuxer.Status == Status.Ended)\n {\n Status = Status.Draining;\n break;\n }\n else if (!demuxer.IsRunning)\n {\n int retries = 5;\n\n while (retries > 0)\n {\n retries--;\n Thread.Sleep(10);\n if (demuxer.IsRunning)\n break;\n }\n\n lock (demuxer.lockStatus)\n lock (lockStatus)\n {\n if (demuxer.Status == Status.Pausing || demuxer.Status == Status.Paused)\n Status = Status.Pausing;\n else if (demuxer.Status == Status.QueueFull)\n Status = Status.Draining;\n else if (demuxer.Status == Status.Running)\n continue;\n else if (demuxer.Status != Status.Ended)\n Status = Status.Stopping;\n else\n continue;\n }\n\n break;\n }\n\n Thread.Sleep(20);\n }\n\n lock (lockStatus)\n {\n CriticalArea = false;\n if (Status != Status.QueueEmpty && Status != Status.Draining)\n break;\n if (Status != Status.Draining)\n Status = Status.Running;\n }\n }\n\n lock (lockCodecCtx)\n {\n if (Status == Status.Stopped || demuxer.DataPackets.Count == 0)\n continue;\n packet = demuxer.DataPackets.Dequeue();\n\n if (packet->size > 0 && packet->data != null)\n {\n var mFrame = ProcessDataFrame(packet);\n Frames.Enqueue(mFrame);\n }\n\n av_packet_free(&packet);\n }\n } while (Status == Status.Running);\n\n if (Status == Status.Draining) Status = Status.Ended;\n }\n\n private DataFrame ProcessDataFrame(AVPacket* packet)\n {\n IntPtr ptr = new IntPtr(packet->data);\n byte[] dataFrame = new byte[packet->size];\n Marshal.Copy(ptr, dataFrame, 0, packet->size); // for performance/in case of large data we could just keep the avpacket data directly (DataFrame instead of byte[] Data just use AVPacket* and move ref?)\n\n DataFrame mFrame = new()\n {\n timestamp = (long)(packet->pts * DataStream.Timebase) - demuxer.StartTime,\n DataCodecId = DataStream.CodecID,\n Data = dataFrame\n };\n\n return mFrame;\n }\n\n public void DisposeFrames()\n => Frames = new ConcurrentQueue();\n}\n"], ["/LLPlayer/FlyleafLib/MediaFramework/MediaRenderer/Renderer.SwapChain.cs", "using System.Windows;\n\nusing Vortice;\nusing Vortice.Direct3D;\nusing Vortice.Direct3D11;\nusing Vortice.DirectComposition;\nusing Vortice.DXGI;\n\nusing static FlyleafLib.Utils.NativeMethods;\nusing ID3D11Texture2D = Vortice.Direct3D11.ID3D11Texture2D;\n\nnamespace FlyleafLib.MediaFramework.MediaRenderer;\n\npublic partial class Renderer\n{\n ID3D11Texture2D backBuffer;\n ID3D11RenderTargetView backBufferRtv;\n IDXGISwapChain1 swapChain;\n IDCompositionDevice dCompDevice;\n IDCompositionVisual dCompVisual;\n IDCompositionTarget dCompTarget;\n\n const Int32 WM_NCDESTROY= 0x0082;\n const Int32 WM_SIZE = 0x0005;\n const Int32 WS_EX_NOREDIRECTIONBITMAP\n = 0x00200000;\n SubclassWndProc wndProcDelegate;\n IntPtr wndProcDelegatePtr;\n\n // Support Windows 8+\n private SwapChainDescription1 GetSwapChainDesc(int width, int height, bool isComp = false, bool alpha = false)\n {\n if (Device.FeatureLevel < FeatureLevel.Level_10_0 || (!string.IsNullOrWhiteSpace(Config.Video.GPUAdapter) && Config.Video.GPUAdapter.ToUpper() == \"WARP\"))\n {\n return new()\n {\n BufferUsage = Usage.RenderTargetOutput,\n Format = Config.Video.Swap10Bit ? Format.R10G10B10A2_UNorm : Format.B8G8R8A8_UNorm,\n Width = (uint)width,\n Height = (uint)height,\n AlphaMode = AlphaMode.Ignore,\n SwapEffect = isComp ? SwapEffect.FlipSequential : SwapEffect.Discard, // will this work for warp?\n Scaling = Scaling.Stretch,\n BufferCount = 1,\n SampleDescription = new SampleDescription(1, 0)\n };\n }\n else\n {\n SwapEffect swapEffect = isComp ? SwapEffect.FlipSequential : Environment.OSVersion.Version.Major >= 10 ? SwapEffect.FlipDiscard : SwapEffect.FlipSequential;\n\n return new()\n {\n BufferUsage = Usage.RenderTargetOutput,\n Format = Config.Video.Swap10Bit ? Format.R10G10B10A2_UNorm : (Config.Video.SwapForceR8G8B8A8 ? Format.R8G8B8A8_UNorm : Format.B8G8R8A8_UNorm),\n Width = (uint)width,\n Height = (uint)height,\n AlphaMode = alpha ? AlphaMode.Premultiplied : AlphaMode.Ignore,\n SwapEffect = swapEffect,\n Scaling = isComp ? Scaling.Stretch : Scaling.None,\n BufferCount = swapEffect == SwapEffect.FlipDiscard ? Math.Min(Config.Video.SwapBuffers, 2) : Config.Video.SwapBuffers,\n SampleDescription = new SampleDescription(1, 0),\n };\n }\n }\n\n internal void InitializeSwapChain(IntPtr handle)\n {\n lock (lockDevice)\n {\n if (!SCDisposed)\n DisposeSwapChain();\n\n if (Disposed && parent == null)\n Initialize(false);\n\n ControlHandle = handle;\n RECT rect = new();\n GetWindowRect(ControlHandle,ref rect);\n ControlWidth = rect.Right - rect.Left;\n ControlHeight = rect.Bottom - rect.Top;\n\n try\n {\n if (cornerRadius == zeroCornerRadius)\n {\n Log.Info($\"Initializing {(Config.Video.Swap10Bit ? \"10-bit\" : \"8-bit\")} swap chain with {Config.Video.SwapBuffers} buffers [Handle: {handle}]\");\n swapChain = Engine.Video.Factory.CreateSwapChainForHwnd(Device, handle, GetSwapChainDesc(ControlWidth, ControlHeight));\n }\n else\n {\n Log.Info($\"Initializing {(Config.Video.Swap10Bit ? \"10-bit\" : \"8-bit\")} composition swap chain with {Config.Video.SwapBuffers} buffers [Handle: {handle}]\");\n swapChain = Engine.Video.Factory.CreateSwapChainForComposition(Device, GetSwapChainDesc(ControlWidth, ControlHeight, true, true));\n using (var dxgiDevice = Device.QueryInterface())\n dCompDevice = DComp.DCompositionCreateDevice(dxgiDevice);\n dCompDevice.CreateTargetForHwnd(handle, false, out dCompTarget).CheckError();\n dCompDevice.CreateVisual(out dCompVisual).CheckError();\n dCompVisual.SetContent(swapChain).CheckError();\n dCompTarget.SetRoot(dCompVisual).CheckError();\n dCompDevice.Commit().CheckError();\n\n int styleEx = GetWindowLong(handle, (int)WindowLongFlags.GWL_EXSTYLE).ToInt32() | WS_EX_NOREDIRECTIONBITMAP;\n SetWindowLong(handle, (int)WindowLongFlags.GWL_EXSTYLE, new IntPtr(styleEx));\n }\n }\n catch (Exception e)\n {\n if (string.IsNullOrWhiteSpace(Config.Video.GPUAdapter) || Config.Video.GPUAdapter.ToUpper() != \"WARP\")\n {\n try { if (Device != null) Log.Warn($\"Device Remove Reason = {Device.DeviceRemovedReason.Description}\"); } catch { } // For troubleshooting\n\n Log.Warn($\"[SwapChain] Initialization failed ({e.Message}). Failling back to WARP device.\");\n Config.Video.GPUAdapter = \"WARP\";\n Flush();\n }\n else\n {\n ControlHandle = IntPtr.Zero;\n Log.Error($\"[SwapChain] Initialization failed ({e.Message})\");\n }\n\n return;\n }\n\n backBuffer = swapChain.GetBuffer(0);\n backBufferRtv = Device.CreateRenderTargetView(backBuffer);\n SCDisposed = false;\n\n if (!isFlushing) // avoid calling UI thread during Player.Stop\n {\n // SetWindowSubclass seems to require UI thread when RemoveWindowSubclass does not (docs are not mentioning this?)\n if (System.Threading.Thread.CurrentThread.ManagedThreadId == System.Windows.Application.Current.Dispatcher.Thread.ManagedThreadId)\n SetWindowSubclass(ControlHandle, wndProcDelegatePtr, UIntPtr.Zero, UIntPtr.Zero);\n else\n Utils.UI(() => SetWindowSubclass(ControlHandle, wndProcDelegatePtr, UIntPtr.Zero, UIntPtr.Zero));\n }\n\n Engine.Video.Factory.MakeWindowAssociation(ControlHandle, WindowAssociationFlags.IgnoreAll);\n\n ResizeBuffers(ControlWidth, ControlHeight); // maybe not required (only for vp)?\n }\n }\n internal void InitializeWinUISwapChain() // TODO: width/height directly here\n {\n lock (lockDevice)\n {\n if (!SCDisposed)\n DisposeSwapChain();\n\n if (Disposed)\n Initialize(false);\n\n Log.Info($\"Initializing {(Config.Video.Swap10Bit ? \"10-bit\" : \"8-bit\")} swap chain with {Config.Video.SwapBuffers} buffers\");\n\n try\n {\n swapChain = Engine.Video.Factory.CreateSwapChainForComposition(Device, GetSwapChainDesc(1, 1, true));\n }\n catch (Exception e)\n {\n Log.Error($\"Initialization failed [{e.Message}]\");\n\n // TODO fallback to WARP?\n\n SwapChainWinUIClbk?.Invoke(null);\n return;\n }\n\n backBuffer = swapChain.GetBuffer(0);\n backBufferRtv = Device.CreateRenderTargetView(backBuffer);\n SCDisposed = false;\n ResizeBuffers(1, 1);\n\n SwapChainWinUIClbk?.Invoke(swapChain.QueryInterface());\n }\n }\n\n public void DisposeSwapChain()\n {\n lock (lockDevice)\n {\n if (SCDisposed)\n return;\n\n SCDisposed = true;\n\n // Clear Screan\n if (!Disposed && swapChain != null)\n {\n try\n {\n context.ClearRenderTargetView(backBufferRtv, Config.Video._BackgroundColor);\n swapChain.Present(Config.Video.VSync, PresentFlags.None);\n }\n catch { }\n }\n\n Log.Info($\"Destroying swap chain [Handle: {ControlHandle}]\");\n\n // Unassign renderer's WndProc if still there and re-assign the old one\n if (ControlHandle != IntPtr.Zero)\n {\n if (!isFlushing) // SetWindowSubclass requires UI thread so avoid calling it on flush (Player.Stop)\n RemoveWindowSubclass(ControlHandle, wndProcDelegatePtr, UIntPtr.Zero);\n ControlHandle = IntPtr.Zero;\n }\n\n if (SwapChainWinUIClbk != null)\n {\n SwapChainWinUIClbk.Invoke(null);\n SwapChainWinUIClbk = null;\n swapChain?.Release(); // TBR: SwapChainPanel (SCP) should be disposed and create new instance instead (currently used from Template)\n }\n\n dCompVisual?.Dispose();\n dCompTarget?.Dispose();\n dCompDevice?.Dispose();\n dCompVisual = null;\n dCompTarget = null;\n dCompDevice = null;\n\n vpov?.Dispose();\n backBufferRtv?.Dispose();\n backBuffer?.Dispose();\n swapChain?.Dispose();\n\n if (Device != null)\n context?.Flush();\n }\n }\n\n public void RemoveViewportOffsets(ref Point p)\n {\n p.X -= (SideXPixels / 2 + PanXOffset);\n p.Y -= (SideYPixels / 2 + PanYOffset);\n }\n public bool IsPointWithInViewPort(Point p)\n => p.X >= GetViewport.X && p.X < GetViewport.X + GetViewport.Width && p.Y >= GetViewport.Y && p.Y < GetViewport.Y + GetViewport.Height;\n\n public static double GetCenterPoint(double zoom, double offset)\n => zoom == 1 ? offset : offset / (zoom - 1); // possible bug when zoom = 1 (noticed in out of bounds zoom out)\n\n /// \n /// Zooms in a way that the specified point before zoom will be at the same position after zoom\n /// \n /// \n /// \n public void ZoomWithCenterPoint(Point p, double zoom)\n {\n /* Notes\n *\n * Zoomed Point (ZP) // the current point in a -possible- zoomed viewport\n * Zoom (Z)\n * Unzoomed Point (UP) // the actual pixel of the current point\n * Viewport Point (VP)\n * Center Point (CP)\n *\n * UP = (VP + ZP) / Z =>\n * ZP = (UP * Z) - VP\n * CP = VP / (ZP - 1) (when UP = ZP)\n */\n\n if (!IsPointWithInViewPort(p))\n {\n SetZoom(zoom);\n return;\n }\n\n Point viewport = new(GetViewport.X, GetViewport.Y);\n RemoveViewportOffsets(ref viewport);\n RemoveViewportOffsets(ref p);\n\n // Finds the required center point so that p will have the same pixel after zoom\n Point zoomCenter = new(\n GetCenterPoint(zoom, ((p.X - viewport.X) / (this.zoom / zoom)) - p.X) / (GetViewport.Width / this.zoom),\n GetCenterPoint(zoom, ((p.Y - viewport.Y) / (this.zoom / zoom)) - p.Y) / (GetViewport.Height / this.zoom));\n\n SetZoomAndCenter(zoom, zoomCenter);\n }\n\n public void SetViewport(bool refresh = true)\n {\n float ratio;\n int x, y, newWidth, newHeight, xZoomPixels, yZoomPixels;\n\n if (Config.Video.AspectRatio == AspectRatio.Keep)\n ratio = curRatio;\n else ratio = Config.Video.AspectRatio == AspectRatio.Fill\n ? ControlWidth / (float)ControlHeight\n : Config.Video.AspectRatio == AspectRatio.Custom ? Config.Video.CustomAspectRatio.Value : Config.Video.AspectRatio.Value;\n\n if (ratio <= 0)\n ratio = 1;\n\n if (actualRotation == 90 || actualRotation == 270)\n ratio = 1 / ratio;\n\n if (ratio < ControlWidth / (float) ControlHeight)\n {\n newHeight = (int)(ControlHeight * zoom);\n newWidth = (int)(newHeight * ratio);\n\n SideXPixels = newWidth > ControlWidth && false ? 0 : (int) (ControlWidth - (ControlHeight * ratio)); // TBR\n SideYPixels = 0;\n\n y = PanYOffset;\n x = PanXOffset + SideXPixels / 2;\n\n yZoomPixels = newHeight - ControlHeight;\n xZoomPixels = newWidth - (ControlWidth - SideXPixels);\n }\n else\n {\n newWidth = (int)(ControlWidth * zoom);\n newHeight = (int)(newWidth / ratio);\n\n SideYPixels = newHeight > ControlHeight && false ? 0 : (int) (ControlHeight - (ControlWidth / ratio));\n SideXPixels = 0;\n\n x = PanXOffset;\n y = PanYOffset + SideYPixels / 2;\n\n xZoomPixels = newWidth - ControlWidth;\n yZoomPixels = newHeight - (ControlHeight - SideYPixels);\n }\n\n GetViewport = new(x - xZoomPixels * (float)zoomCenter.X, y - yZoomPixels * (float)zoomCenter.Y, newWidth, newHeight);\n ViewportChanged?.Invoke(this, new());\n\n if (videoProcessor == VideoProcessors.D3D11)\n {\n RawRect src, dst;\n\n if (GetViewport.Width < 1 || GetViewport.X + GetViewport.Width <= 0 || GetViewport.X >= ControlWidth || GetViewport.Y + GetViewport.Height <= 0 || GetViewport.Y >= ControlHeight)\n { // Out of screen\n src = new RawRect();\n dst = new RawRect();\n }\n else\n {\n int cropLeft = GetViewport.X < 0 ? (int) GetViewport.X * -1 : 0;\n int cropRight = GetViewport.X + GetViewport.Width > ControlWidth ? (int) (GetViewport.X + GetViewport.Width - ControlWidth) : 0;\n int cropTop = GetViewport.Y < 0 ? (int) GetViewport.Y * -1 : 0;\n int cropBottom = GetViewport.Y + GetViewport.Height > ControlHeight ? (int) (GetViewport.Y + GetViewport.Height - ControlHeight) : 0;\n\n dst = new RawRect(Math.Max((int)GetViewport.X, 0), Math.Max((int)GetViewport.Y, 0), Math.Min((int)GetViewport.Width + (int)GetViewport.X, ControlWidth), Math.Min((int)GetViewport.Height + (int)GetViewport.Y, ControlHeight));\n\n if (_RotationAngle == 90)\n {\n src = new RawRect(\n (int) (cropTop * (VideoRect.Right / GetViewport.Height)),\n (int) (cropRight * (VideoRect.Bottom / GetViewport.Width)),\n VideoRect.Right - (int) (cropBottom * VideoRect.Right / GetViewport.Height),\n VideoRect.Bottom - (int) (cropLeft * VideoRect.Bottom / GetViewport.Width));\n }\n else if (_RotationAngle == 270)\n {\n src = new RawRect(\n (int) (cropBottom * VideoRect.Right / GetViewport.Height),\n (int) (cropLeft * VideoRect.Bottom / GetViewport.Width),\n VideoRect.Right - (int) (cropTop * VideoRect.Right / GetViewport.Height),\n VideoRect.Bottom - (int) (cropRight * VideoRect.Bottom / GetViewport.Width));\n }\n else if (_RotationAngle == 180)\n {\n src = new RawRect(\n (int) (cropRight * VideoRect.Right / GetViewport.Width),\n (int) (cropBottom * VideoRect.Bottom /GetViewport.Height),\n VideoRect.Right - (int) (cropLeft * VideoRect.Right / GetViewport.Width),\n VideoRect.Bottom - (int) (cropTop * VideoRect.Bottom / GetViewport.Height));\n }\n else\n {\n src = new RawRect(\n (int) (cropLeft * VideoRect.Right / GetViewport.Width),\n (int) (cropTop * VideoRect.Bottom / GetViewport.Height),\n VideoRect.Right - (int) (cropRight * VideoRect.Right / GetViewport.Width),\n VideoRect.Bottom - (int) (cropBottom * VideoRect.Bottom / GetViewport.Height));\n }\n }\n\n vc.VideoProcessorSetStreamSourceRect(vp, 0, true, src);\n vc.VideoProcessorSetStreamDestRect (vp, 0, true, dst);\n vc.VideoProcessorSetOutputTargetRect(vp, true, new RawRect(0, 0, ControlWidth, ControlHeight));\n }\n\n if (refresh)\n Present();\n }\n public void ResizeBuffers(int width, int height)\n {\n lock (lockDevice)\n {\n if (SCDisposed)\n return;\n\n ControlWidth = width;\n ControlHeight = height;\n\n backBufferRtv.Dispose();\n vpov?.Dispose();\n backBuffer.Dispose();\n swapChain.ResizeBuffers(0, (uint)ControlWidth, (uint)ControlHeight, Format.Unknown, SwapChainFlags.None);\n UpdateCornerRadius();\n backBuffer = swapChain.GetBuffer(0);\n backBufferRtv = Device.CreateRenderTargetView(backBuffer);\n if (videoProcessor == VideoProcessors.D3D11)\n vd1.CreateVideoProcessorOutputView(backBuffer, vpe, vpovd, out vpov);\n\n SetViewport();\n }\n }\n\n internal void UpdateCornerRadius()\n {\n if (dCompDevice == null)\n return;\n\n dCompDevice.CreateRectangleClip(out var clip).CheckError();\n clip.SetLeft(0);\n clip.SetRight(ControlWidth);\n clip.SetTop(0);\n clip.SetBottom(ControlHeight);\n clip.SetTopLeftRadiusX((float)cornerRadius.TopLeft);\n clip.SetTopLeftRadiusY((float)cornerRadius.TopLeft);\n clip.SetTopRightRadiusX((float)cornerRadius.TopRight);\n clip.SetTopRightRadiusY((float)cornerRadius.TopRight);\n clip.SetBottomLeftRadiusX((float)cornerRadius.BottomLeft);\n clip.SetBottomLeftRadiusY((float)cornerRadius.BottomLeft);\n clip.SetBottomRightRadiusX((float)cornerRadius.BottomRight);\n clip.SetBottomRightRadiusY((float)cornerRadius.BottomRight);\n dCompVisual.SetClip(clip).CheckError();\n clip.Dispose();\n dCompDevice.Commit().CheckError();\n }\n\n private IntPtr WndProc(IntPtr hWnd, uint msg, IntPtr wParam, IntPtr lParam, IntPtr uIdSubclass, IntPtr dwRefData)\n {\n switch (msg)\n {\n case WM_NCDESTROY:\n if (SCDisposed)\n RemoveWindowSubclass(ControlHandle, wndProcDelegatePtr, UIntPtr.Zero);\n else\n DisposeSwapChain();\n break;\n\n case WM_SIZE:\n ResizeBuffers(SignedLOWORD(lParam), SignedHIWORD(lParam));\n break;\n }\n\n return DefSubclassProc(hWnd, msg, wParam, lParam);\n }\n}\n"], ["/LLPlayer/LLPlayer/Services/OpenSubtitlesProvider.cs", "using System.IO;\nusing System.IO.Compression;\nusing System.Net.Http;\nusing System.Text;\nusing System.Xml.Serialization;\nusing FlyleafLib;\nusing LLPlayer.Extensions;\n\nnamespace LLPlayer.Services;\n\npublic class OpenSubtitlesProvider\n{\n private readonly FlyleafManager FL;\n private readonly HttpClient _client;\n private string? _token;\n private bool _initialized = false;\n\n public OpenSubtitlesProvider(FlyleafManager fl)\n {\n FL = fl;\n HttpClient client = new();\n client.BaseAddress = new Uri(\"http://api.opensubtitles.org/xml-rpc\");\n client.Timeout = TimeSpan.FromSeconds(15);\n\n _client = client;\n }\n\n private readonly SemaphoreSlim _loginSemaphore = new(1);\n\n private async Task Initialize()\n {\n if (!_initialized)\n {\n try\n {\n await _loginSemaphore.WaitAsync();\n await Login();\n _initialized = true;\n }\n finally\n {\n _loginSemaphore.Release();\n }\n }\n }\n\n /// \n /// Login\n /// \n /// \n /// \n /// \n private async Task Login()\n {\n string loginReqXml =\n\"\"\"\n\n\n LogIn\n \n \n \n \n \n \n \n \n \n \n \n \n en\n \n \n VLsub 0.10.2\n \n \n\n\"\"\";\n\n var result = await _client.PostAsync(string.Empty, new StringContent(loginReqXml));\n var content = await result.Content.ReadAsStringAsync();\n\n var serializer = new XmlSerializer(typeof(MethodResponse));\n LoginResponse loginResponse = new();\n using (var reader = new StringReader(content))\n {\n MethodResponse? response = null;\n try\n {\n result.EnsureSuccessStatusCode();\n response = serializer.Deserialize(reader) as MethodResponse;\n if (response == null)\n {\n throw new InvalidOperationException(\"response is not MethodResponse\");\n }\n }\n catch (Exception ex)\n {\n throw new InvalidOperationException($\"Can't parse the login content: {ex.Message}\", ex)\n {\n Data =\n {\n [\"status_code\"] = ((int)result.StatusCode).ToString(),\n [\"login_content\"] = content\n }\n };\n }\n\n foreach (var member in response.Params.Param.Value.Struct.Member)\n {\n var propertyName = member.Name.ToUpperFirstChar();\n switch (propertyName)\n {\n case nameof(loginResponse.Token):\n loginResponse.Token = member.Value.String;\n break;\n case nameof(loginResponse.Status):\n loginResponse.Status = member.Value.String;\n break;\n }\n }\n }\n\n if (loginResponse.StatusCode != \"200\")\n throw new InvalidOperationException($\"Can't login because status is '{loginResponse.StatusCode}'\");\n\n if (string.IsNullOrWhiteSpace(loginResponse.Token))\n throw new InvalidOperationException(\"Can't login because token is empty\");\n\n _token = loginResponse.Token;\n }\n\n\n /// \n /// Search\n /// \n /// \n /// \n /// \n /// \n public async Task> Search(string query)\n {\n await Initialize();\n\n if (_token == null)\n throw new InvalidOperationException(\"token is not initialized\");\n\n var subLanguageId = \"all\";\n var limit = 500;\n\n string searchReqXml =\n$\"\"\"\n\n\n SearchSubtitles\n \n \n {_token}\n \n \n \n \n \n \n \n \n query\n {query}\n \n \n sublanguageid\n {subLanguageId}\n \n \n \n \n \n \n \n \n \n \n \n limit\n \n {limit}\n \n \n \n \n \n \n\n\"\"\";\n\n var result = await _client.PostAsync(string.Empty, new StringContent(searchReqXml));\n var content = await result.Content.ReadAsStringAsync();\n\n var serializer = new XmlSerializer(typeof(MethodResponse));\n\n List searchResponses = new();\n\n using (StringReader reader = new(content))\n {\n MethodResponse? response = null;\n try\n {\n result.EnsureSuccessStatusCode();\n response = serializer.Deserialize(reader) as MethodResponse;\n if (response == null)\n {\n throw new InvalidOperationException(\"response is not MethodResponse\");\n }\n }\n catch (Exception ex)\n {\n throw new InvalidOperationException($\"Can't parse the search content: {ex.Message}\", ex)\n {\n Data =\n {\n [\"status_code\"] = ((int)result.StatusCode).ToString(),\n [\"search_content\"] = content\n }\n };\n }\n\n if (!response.Params.Param.Value.Struct.Member.Any(m => m.Name == \"status\" && m.Value.String == \"200 OK\"))\n throw new InvalidOperationException(\"Can't get the search result, status is not 200.\");\n\n var resultMembers = response.Params.Param.Value.Struct.Member.FirstOrDefault(m => m.Name == \"data\");\n if (resultMembers == null)\n throw new InvalidOperationException(\"Can't get the search result, data is not found.\");\n\n foreach (var record in resultMembers.Value.Array.Data.Value)\n {\n SearchResponse searchResponse = new();\n foreach (var member in record.Struct.Member)\n {\n var propertyName = member.Name.ToUpperFirstChar();\n\n var property = typeof(SearchResponse).GetProperty(propertyName);\n if (property != null && property.CanWrite)\n {\n switch (Type.GetTypeCode(property.PropertyType))\n {\n case TypeCode.Int32:\n if (member.Value.String != null &&\n int.TryParse(member.Value.String, out var n))\n {\n property.SetValue(searchResponse, n);\n }\n else\n {\n property.SetValue(searchResponse, member.Value.Int);\n }\n break;\n\n case TypeCode.Double:\n if (member.Value.String != null &&\n double.TryParse(member.Value.String, out var d))\n {\n property.SetValue(searchResponse, d);\n }\n else\n {\n property.SetValue(searchResponse, member.Value.Double);\n }\n break;\n\n case TypeCode.String:\n property.SetValue(searchResponse, member.Value.String);\n break;\n }\n }\n }\n\n searchResponses.Add(searchResponse);\n }\n }\n\n return searchResponses;\n }\n\n /// \n /// Download\n /// \n /// \n /// \n /// \n /// \n public async Task<(byte[] data, bool isBitmap)> Download(SearchResponse sub)\n {\n await Initialize();\n\n if (_token == null)\n throw new InvalidOperationException(\"token is not initialized\");\n\n var idSubtitleFile = sub.IDSubtitleFile;\n var isBitmap = sub.SubFormat.ToLower() == \"sub\";\n\n string downloadReqXml =\n$\"\"\"\n \n \n DownloadSubtitles\n \n \n {_token}\n \n \n \n \n \n {idSubtitleFile}\n \n \n \n \n \n \n \"\"\";\n\n var result = await _client.PostAsync(string.Empty, new StringContent(downloadReqXml));\n var content = await result.Content.ReadAsStringAsync();\n\n XmlSerializer serializer = new(typeof(MethodResponse));\n\n DownloadResponse downloadResponse = new();\n\n using (StringReader reader = new(content))\n {\n MethodResponse? response = null;\n try\n {\n result.EnsureSuccessStatusCode();\n response = serializer.Deserialize(reader) as MethodResponse;\n if (response == null)\n {\n throw new InvalidOperationException(\"response is not MethodResponse\");\n }\n }\n catch (Exception ex)\n {\n throw new InvalidOperationException($\"Can't parse the download content: {ex.Message}\", ex)\n {\n Data =\n {\n [\"status_code\"] = ((int)result.StatusCode).ToString(),\n [\"download_content\"] = content\n }\n };\n }\n\n if (!response.Params.Param.Value.Struct.Member.Any(m => m.Name == \"status\" && m.Value.String == \"200 OK\"))\n throw new InvalidOperationException(\"Can't get the download result, status is not 200.\");\n\n var resultMembers = response.Params.Param.Value.Struct.Member.FirstOrDefault(m => m.Name == \"data\");\n if (resultMembers == null)\n throw new InvalidOperationException(\"Can't get the download result, data is not found.\");\n\n var data = resultMembers.Value.Array.Data.Value.First();\n\n foreach (var member in data.Struct.Member)\n {\n var propertyName = member.Name.ToUpperFirstChar();\n switch (propertyName)\n {\n case nameof(downloadResponse.Data):\n downloadResponse.Data = member.Value.String;\n break;\n case nameof(downloadResponse.Idsubtitlefile):\n downloadResponse.Idsubtitlefile = member.Value.String;\n break;\n }\n }\n }\n\n if (string.IsNullOrEmpty(downloadResponse.Data))\n throw new InvalidOperationException(\"Can't get the download result, base64 data is not found.\");\n\n var gzipSub = Convert.FromBase64String(downloadResponse.Data);\n byte[]? subData;\n\n using MemoryStream compressedStream = new(gzipSub);\n using (GZipStream gzipStream = new(compressedStream, CompressionMode.Decompress))\n using (MemoryStream resultStream = new())\n {\n gzipStream.CopyTo(resultStream);\n subData = resultStream.ToArray();\n }\n\n if (subData == null)\n throw new InvalidOperationException(\"Can't get the download result, decompressed data is not found.\");\n\n if (isBitmap)\n {\n return (subData, true);\n }\n\n Encoding? encoding = TextEncodings.DetectEncoding(subData);\n encoding ??= Encoding.UTF8;\n\n // If there is originally a BOM, it will remain even if it is converted to a string, so delete it.\n string subString = encoding.GetString(subData).TrimStart('\\uFEFF');\n\n // Convert to UTF-8 and return\n byte[] subText = Encoding.UTF8.GetBytes(subString);\n\n if (FL.Config.Subs.SubsExportUTF8WithBom)\n {\n // append BOM\n subText = Encoding.UTF8.GetPreamble().Concat(subText).ToArray();\n }\n\n return (subText, false);\n }\n}\n\n\npublic class LoginResponse\n{\n public string? Token { get; set; }\n public string? Status { get; set; }\n public string? StatusCode => Status?.Split(' ')[0];\n}\n\npublic class SearchResponse\n{\n public string IDSubtitleFile { get; set; } = \"\";\n public string SubFileName { get; set; } = \"\";\n public int SubSize { get; set; } // from string\n public string SubLastTS { get; set; } = \"\";\n public string IDSubtitle { get; set; } = \"\";\n public string SubLanguageID { get; set; } = \"\";\n public string SubFormat { get; set; } = \"\";\n public string SubAddDate { get; set; } = \"\";\n public double SubRating { get; set; } // from string\n public string SubSumVotes { get; set; } = \"\";\n public int SubDownloadsCnt { get; set; } // from string\n public string MovieName { get; set; } = \"\";\n public string MovieYear { get; set; } = \"\";\n public string MovieKind { get; set; } = \"\";\n public string ISO639 { get; set; } = \"\";\n public string LanguageName { get; set; } = \"\";\n public string SeriesSeason { get; set; } = \"\";\n public string SeriesEpisode { get; set; } = \"\";\n public string SubEncoding { get; set; } = \"\";\n public string SubDownloadLink { get; set; } = \"\";\n public string SubtitlesLink { get; set; } = \"\";\n public double Score { get; set; }\n}\n\npublic class DownloadResponse\n{\n public string? Data { get; set; }\n public string? Idsubtitlefile { get; set; }\n}\n\n[XmlRoot(\"value\")]\npublic class Value\n{\n [XmlElement(\"string\")]\n public string? String { get; set; }\n\n [XmlElement(\"struct\")]\n public Struct Struct { get; set; } = null!;\n\n [XmlElement(\"int\")]\n public int Int { get; set; }\n\n [XmlElement(\"double\")]\n public double Double { get; set; }\n\n [XmlElement(\"array\")]\n public Array Array { get; set; } = null!;\n}\n\n[XmlRoot(\"member\")]\npublic class Member\n{\n [XmlElement(\"name\")]\n public string Name { get; set; } = null!;\n\n [XmlElement(\"value\")]\n public Value Value { get; set; } = null!;\n}\n\n[XmlRoot(\"struct\")]\npublic class Struct\n{\n [XmlElement(\"member\")]\n public List Member { get; set; } = null!;\n}\n\n[XmlRoot(\"data\")]\npublic class Data\n{\n [XmlElement(\"value\")]\n public List Value { get; set; } = null!;\n}\n\n[XmlRoot(\"array\")]\npublic class Array\n{\n [XmlElement(\"data\")]\n public Data Data { get; set; } = null!;\n}\n\n[XmlRoot(\"param\")]\npublic class Param\n{\n [XmlElement(\"value\")]\n public Value Value { get; set; } = null!;\n}\n\n[XmlRoot(\"params\")]\npublic class Params\n{\n [XmlElement(\"param\")]\n public Param Param { get; set; } = null!;\n}\n\n[XmlRoot(\"methodResponse\")]\npublic class MethodResponse\n{\n [XmlElement(\"params\")]\n public Params Params { get; set; } = null!;\n}\n"], ["/LLPlayer/LLPlayer/ViewModels/FlyleafOverlayVM.cs", "using System.Diagnostics;\nusing System.Windows;\nusing System.Windows.Controls;\nusing System.Windows.Input;\nusing FlyleafLib;\nusing FlyleafLib.MediaPlayer;\nusing LLPlayer.Extensions;\nusing LLPlayer.Services;\nusing MaterialDesignThemes.Wpf;\nusing static FlyleafLib.Utils.NativeMethods;\n\nnamespace LLPlayer.ViewModels;\n\npublic class FlyleafOverlayVM : Bindable\n{\n public FlyleafManager FL { get; }\n\n public FlyleafOverlayVM(FlyleafManager fl)\n {\n FL = fl;\n }\n\n public DelegateCommand? CmdOnLoaded => field ??= new(() =>\n {\n SetupOSDStatus();\n SetupFlyleafContextMenu();\n SetupFlyleafKeybindings();\n\n FL.Config.FlyleafHostLoaded();\n });\n\n private void SetupFlyleafContextMenu()\n {\n // When a context menu is opened using the Overlay.MouseRightButtonUp event,\n // it is a bubble event and therefore has priority over the ContextMenu of the child controls.\n // so set ContextMenu directly to each of the controls in order to give priority to the child contextmenu.\n ContextMenu menu = (ContextMenu)Application.Current.FindResource(\"PopUpMenu\")!;\n menu.DataContext = this;\n menu.PlacementTarget = FL.FlyleafHost!.Overlay;\n\n FL.FlyleafHost!.Overlay.ContextMenu = menu;\n FL.FlyleafHost!.Surface.ContextMenu = menu;\n }\n\n #region Flyleaf Keybindings\n // TODO: L: Make it fully customizable like PotPlayer\n private void SetupFlyleafKeybindings()\n {\n // Subscribe to the same event to the following two\n // Surface: On Video Screen\n // Overlay: Content of FlyleafHost = FlyleafOverlay\n foreach (var window in (Window[])[FL.FlyleafHost!.Surface, FL.FlyleafHost!.Overlay])\n {\n window.MouseWheel += FlyleafOnMouseWheel;\n }\n FL.FlyleafHost.Surface.MouseUp += SurfaceOnMouseUp;\n FL.FlyleafHost.Surface.MouseDoubleClick += SurfaceOnMouseDoubleClick;\n FL.FlyleafHost.Surface.MouseLeftButtonDown += SurfaceOnMouseLeftButtonDown;\n FL.FlyleafHost.Surface.MouseLeftButtonUp += SurfaceOnMouseLeftButtonUp;\n FL.FlyleafHost.Surface.MouseMove += SurfaceOnMouseMove;\n FL.FlyleafHost.Surface.LostMouseCapture += SurfaceOnLostMouseCapture;\n }\n\n private void SurfaceOnMouseUp(object sender, MouseButtonEventArgs e)\n {\n switch (e.ChangedButton)\n {\n // Middle click: seek to current subtitle\n case MouseButton.Middle:\n bool ctrlDown = Keyboard.IsKeyDown(Key.LeftCtrl) || Keyboard.IsKeyDown(Key.RightCtrl);\n if (ctrlDown)\n {\n // CTRL + Middle click: Reset zoom\n FL.Player.ResetZoom();\n e.Handled = true;\n return;\n }\n\n if (FL.Player.Subtitles[0].Enabled)\n {\n FL.Player.Subtitles.CurSeek();\n }\n e.Handled = true;\n break;\n\n // X1 click: subtitles prev seek with fallback\n case MouseButton.XButton1:\n FL.Player.Subtitles.PrevSeekFallback();\n e.Handled = true;\n break;\n\n // X2 click: subtitles next seek with fallback\n case MouseButton.XButton2:\n FL.Player.Subtitles.NextSeekFallback();\n e.Handled = true;\n break;\n }\n }\n\n private void SurfaceOnMouseDoubleClick(object sender, MouseButtonEventArgs e)\n {\n if (FL.Config.MouseDoubleClickToFullScreen && e.ChangedButton == MouseButton.Left)\n {\n FL.Player.ToggleFullScreen();\n\n // Double and single clicks are not currently distinguished, so need to be re-fired\n // Timers need to be added to distinguish between the two,\n // but this is controversial because it delays a single click action\n SingleClickAction();\n\n e.Handled = true;\n }\n }\n\n private bool _isLeftDragging;\n private Point _downPoint;\n private Point _downCursorPoint;\n private long _downTick;\n\n private void SurfaceOnMouseLeftButtonDown(object sender, MouseButtonEventArgs e)\n {\n // Support window dragging & play / pause toggle\n if (Keyboard.Modifiers != ModifierKeys.None)\n return;\n\n if (FL.FlyleafHost is not { IsResizing: false, IsPanMoving: false, IsDragMoving: false })\n return;\n\n Point downPoint = FL.FlyleafHost!.Surface.PointToScreen(default);\n long downTick = Stopwatch.GetTimestamp();\n\n if (!FL.FlyleafHost.IsFullScreen && FL.FlyleafHost.Owner.WindowState == WindowState.Normal)\n {\n // normal window: window dragging\n DragMoveOwner();\n\n MouseLeftButtonUpAction(downPoint, downTick);\n }\n else\n {\n // fullscreen or maximized window: do action in KeyUp event\n _isLeftDragging = true;\n _downPoint = downPoint;\n _downTick = downTick;\n\n _downCursorPoint = e.GetPosition((IInputElement)sender);\n }\n }\n\n // When left dragging while maximized, move window back to normal and move window\n private void SurfaceOnMouseMove(object sender, MouseEventArgs e)\n {\n if (!_isLeftDragging || e.LeftButton != MouseButtonState.Pressed)\n return;\n\n if (FL.FlyleafHost!.IsFullScreen || FL.FlyleafHost.Owner.WindowState != WindowState.Maximized)\n return;\n\n Point curPoint = e.GetPosition((IInputElement)sender);\n\n // distinguish between mouse click and dragging (to prevent misfire)\n if (Math.Abs(curPoint.X - _downCursorPoint.X) >= 60 ||\n Math.Abs(curPoint.Y - _downCursorPoint.Y) >= 60)\n {\n _isLeftDragging = false;\n\n // change to normal window\n FL.FlyleafHost.Owner.WindowState = WindowState.Normal;\n\n // start dragging\n DragMoveOwner();\n }\n }\n\n private void DragMoveOwner()\n {\n // (!SeekBarShowOnlyMouseOver) always show cursor when moving\n // (SeekBarShowOnlyMouseOver) prevent to activate seek bar\n if (!FL.Config.SeekBarShowOnlyMouseOver)\n {\n FL.Player.Activity.IsEnabled = false;\n }\n\n FL.FlyleafHost!.Owner.DragMove();\n\n if (!FL.Config.SeekBarShowOnlyMouseOver)\n {\n FL.Player.Activity.IsEnabled = true;\n }\n }\n\n private void SurfaceOnMouseLeftButtonUp(object sender, MouseButtonEventArgs e)\n {\n if (!_isLeftDragging)\n return;\n\n _isLeftDragging = false;\n\n MouseLeftButtonUpAction(_downPoint, _downTick);\n }\n\n private void SurfaceOnLostMouseCapture(object sender, MouseEventArgs e)\n {\n _isLeftDragging = false;\n }\n\n private void MouseLeftButtonUpAction(Point downPoint, long downTick)\n {\n Point upPoint = FL.FlyleafHost!.Surface.PointToScreen(default);\n\n if (downPoint == upPoint // if not moved at all\n ||\n Stopwatch.GetElapsedTime(downTick) <= TimeSpan.FromMilliseconds(200)\n && // if click within 200ms and not so much moved\n Math.Abs(upPoint.X - downPoint.X) < 60 && Math.Abs(upPoint.Y - downPoint.Y) < 60)\n {\n SingleClickAction();\n }\n }\n\n private void SingleClickAction()\n {\n // Toggle play/pause on left click\n if (FL.Config.MouseSingleClickToPlay && FL.Player.CanPlay)\n FL.Player.TogglePlayPause();\n }\n\n private void FlyleafOnMouseWheel(object sender, MouseWheelEventArgs e)\n {\n // CTRL + Wheel : Zoom in / out\n // SHIFT + Wheel : Subtitles Up / Down\n // CTRL + SHIFT + Wheel : Subtitles Size Increase / Decrease\n if (e.Delta == 0)\n {\n return;\n }\n\n Window surface = FL.FlyleafHost!.Surface;\n\n bool ctrlDown = Keyboard.IsKeyDown(Key.LeftCtrl) || Keyboard.IsKeyDown(Key.RightCtrl);\n bool shiftDown = Keyboard.IsKeyDown(Key.LeftShift) || Keyboard.IsKeyDown(Key.RightShift);\n\n if (ctrlDown && shiftDown)\n {\n if (e.Delta > 0)\n {\n FL.Action.CmdSubsSizeIncrease.Execute();\n }\n else\n {\n FL.Action.CmdSubsSizeDecrease.Execute();\n }\n }\n else if (ctrlDown)\n {\n Point cur = e.GetPosition(surface);\n Point curDpi = new(cur.X * DpiX, cur.Y * DpiY);\n if (e.Delta > 0)\n {\n FL.Player.ZoomIn(curDpi);\n }\n else\n {\n FL.Player.ZoomOut(curDpi);\n }\n }\n else if (shiftDown)\n {\n if (e.Delta > 0)\n {\n FL.Action.CmdSubsPositionUp.Execute();\n }\n else\n {\n FL.Action.CmdSubsPositionDown.Execute();\n }\n }\n else\n {\n if (FL.Config.MouseWheelToVolumeUpDown)\n {\n if (e.Delta > 0)\n {\n FL.Player.Audio.VolumeUp();\n }\n else\n {\n FL.Player.Audio.VolumeDown();\n }\n }\n }\n\n e.Handled = true;\n }\n #endregion\n\n #region OSD\n private void SetupOSDStatus()\n {\n var player = FL.Player;\n\n player.PropertyChanged += (o, e) =>\n {\n switch (e.PropertyName)\n {\n case nameof(player.OSDMessage):\n OSDMessage = player.OSDMessage;\n break;\n case nameof(player.ReversePlayback):\n OSDMessage = $\"Reverse Playback {(player.ReversePlayback ? \"On\" : \"Off\")}\";\n break;\n case nameof(player.LoopPlayback):\n OSDMessage = $\"Loop Playback {(player.LoopPlayback ? \"On\" : \"Off\")}\";\n break;\n case nameof(player.Rotation):\n OSDMessage = $\"Rotation {player.Rotation}°\";\n break;\n case nameof(player.Speed):\n OSDMessage = $\"Speed x{player.Speed}\";\n break;\n case nameof(player.Zoom):\n OSDMessage = $\"Zoom {player.Zoom}%\";\n break;\n case nameof(player.Status):\n // Change only Play and Pause to icon\n switch (player.Status)\n {\n case Status.Paused:\n OSDIcon = PackIconKind.Pause;\n return;\n case Status.Playing:\n OSDIcon = PackIconKind.Play;\n return;\n }\n OSDMessage = $\"{player.Status.ToString()}\";\n break;\n }\n };\n\n player.Audio.PropertyChanged += (o, e) =>\n {\n switch (e.PropertyName)\n {\n case nameof(player.Audio.Volume):\n OSDMessage = $\"Volume {player.Audio.Volume}%\";\n break;\n case nameof(player.Audio.Mute):\n OSDIcon = player.Audio.Mute ? PackIconKind.VolumeOff : PackIconKind.VolumeHigh;\n break;\n }\n };\n\n player.Config.Player.PropertyChanged += (o, e) =>\n {\n switch (e.PropertyName)\n {\n case nameof(player.Config.Player.SeekAccurate):\n OSDMessage = $\"Always Seek Accurate {(player.Config.Player.SeekAccurate ? \"On\" : \"Off\")}\";\n break;\n }\n };\n\n player.Config.Audio.PropertyChanged += (o, e) =>\n {\n switch (e.PropertyName)\n {\n case nameof(player.Config.Audio.Enabled):\n OSDMessage = $\"Audio {(player.Config.Audio.Enabled ? \"Enabled\" : \"Disabled\")}\";\n break;\n case nameof(player.Config.Audio.Delay):\n OSDMessage = $\"Audio Delay {player.Config.Audio.Delay / 10000}ms\";\n break;\n }\n };\n\n player.Config.Video.PropertyChanged += (o, e) =>\n {\n switch (e.PropertyName)\n {\n case nameof(player.Config.Video.Enabled):\n OSDMessage = $\"Video {(player.Config.Video.Enabled ? \"Enabled\" : \"Disabled\")}\";\n break;\n case nameof(player.Config.Video.AspectRatio):\n OSDMessage = $\"Aspect Ratio {player.Config.Video.AspectRatio.ToString()}\";\n break;\n case nameof(player.Config.Video.VideoAcceleration):\n OSDMessage = $\"Video Acceleration {(player.Config.Video.VideoAcceleration ? \"On\" : \"Off\")}\";\n break;\n }\n };\n\n foreach (var (i, config) in player.Config.Subtitles.SubConfigs.Index())\n {\n config.PropertyChanged += (o, e) =>\n {\n switch (e.PropertyName)\n {\n case nameof(config.Delay):\n OSDMessage = $\"{(i == 0 ? \"Primary\" : \"Secondary\")} Subs Delay {config.Delay / 10000}ms\";\n break;\n case nameof(config.Visible):\n var primary = player.Config.Subtitles[0].Visible ? \"visible\" : \"hidden\";\n var secondary = player.Config.Subtitles[1].Visible ? \"visible\" : \"hidden\";\n\n if (player.Subtitles[1].Enabled)\n {\n OSDMessage = $\"Subs {primary} / {secondary}\";\n }\n else\n {\n OSDMessage = $\"Subs {primary}\";\n }\n break;\n }\n };\n }\n\n // app config\n FL.Config.PropertyChanged += (o, e) =>\n {\n switch (e.PropertyName)\n {\n case nameof(FL.Config.AlwaysOnTop):\n OSDMessage = $\"Always on Top {(FL.Config.AlwaysOnTop ? \"On\" : \"Off\")}\";\n break;\n }\n };\n\n FL.Config.Subs.PropertyChanged += (o, e) =>\n {\n switch (e.PropertyName)\n {\n case nameof(FL.Config.Subs.SubsAutoTextCopy):\n OSDMessage = $\"Subs Auto Text Copy {(FL.Config.Subs.SubsAutoTextCopy ? \"On\" : \"Off\")}\";\n break;\n }\n };\n }\n\n private CancellationTokenSource? _cancelMsgToken;\n\n public string OSDMessage\n {\n get => _osdMessage;\n set\n {\n if (Set(ref _osdMessage, value))\n {\n if (_cancelMsgToken != null)\n {\n _cancelMsgToken.Cancel();\n _cancelMsgToken.Dispose();\n _cancelMsgToken = null;\n }\n\n if (Set(ref _osdIcon, null, nameof(OSDIcon)))\n {\n OnPropertyChanged(nameof(IsOSDIcon));\n }\n\n _cancelMsgToken = new();\n\n var token = _cancelMsgToken.Token;\n _ = Task.Run(() => ClearOSD(3000, token));\n }\n }\n }\n private string _osdMessage = \"\";\n\n public PackIconKind? OSDIcon\n {\n get => _osdIcon;\n set\n {\n if (Set(ref _osdIcon, value))\n {\n OnPropertyChanged(nameof(IsOSDIcon));\n\n if (_cancelMsgToken != null)\n {\n _cancelMsgToken.Cancel();\n _cancelMsgToken.Dispose();\n _cancelMsgToken = null;\n }\n\n Set(ref _osdMessage, \"\", nameof(OSDMessage));\n\n _cancelMsgToken = new();\n\n var token = _cancelMsgToken.Token;\n _ = Task.Run(() => ClearOSD(500, token));\n }\n }\n }\n private PackIconKind? _osdIcon;\n\n public bool IsOSDIcon => OSDIcon != null;\n\n private async Task ClearOSD(int timeoutMs, CancellationToken token)\n {\n await Task.Delay(timeoutMs, token);\n\n if (token.IsCancellationRequested)\n return;\n\n Utils.UI(() =>\n {\n Set(ref _osdMessage, \"\", nameof(OSDMessage));\n if (Set(ref _osdIcon, null, nameof(OSDIcon)))\n {\n OnPropertyChanged(nameof(IsOSDIcon));\n }\n });\n }\n #endregion\n}\n"], ["/LLPlayer/FlyleafLib/Engine/Engine.Audio.cs", "using System;\nusing System.Collections.Generic;\nusing System.Collections.ObjectModel;\nusing System.ComponentModel;\nusing System.Threading.Tasks;\nusing System.Windows.Data;\n\nusing SharpGen.Runtime;\nusing SharpGen.Runtime.Win32;\n\nusing Vortice.MediaFoundation;\nusing static Vortice.XAudio2.XAudio2;\n\nusing FlyleafLib.MediaFramework.MediaDevice;\n\nnamespace FlyleafLib;\n\npublic class AudioEngine : CallbackBase, IMMNotificationClient, INotifyPropertyChanged\n{\n #region Properties (Public)\n\n public AudioEndpoint DefaultDevice { get; private set; } = new() { Id = \"0\", Name = \"Default\" };\n public AudioEndpoint CurrentDevice { get; private set; } = new();\n\n /// \n /// Whether no audio devices were found or audio failed to initialize\n /// \n public bool Failed { get; private set; }\n\n /// \n /// List of Audio Capture Devices\n /// \n public ObservableCollection\n CapDevices { get; set; } = new();\n\n public void RefreshCapDevices() => AudioDevice.RefreshDevices();\n\n /// \n /// List of Audio Devices\n /// \n public ObservableCollection\n Devices { get; private set; } = new();\n\n private readonly object lockDevices = new();\n #endregion\n\n IMMDeviceEnumerator deviceEnum;\n private object locker = new();\n\n public event PropertyChangedEventHandler PropertyChanged;\n\n public AudioEngine()\n {\n if (Engine.Config.DisableAudio)\n {\n Failed = true;\n return;\n }\n\n BindingOperations.EnableCollectionSynchronization(Devices, lockDevices);\n EnumerateDevices();\n }\n\n private void EnumerateDevices()\n {\n try\n {\n deviceEnum = new IMMDeviceEnumerator();\n\n var defaultDevice = deviceEnum.GetDefaultAudioEndpoint(DataFlow.Render, Role.Multimedia);\n if (defaultDevice == null)\n {\n Failed = true;\n return;\n }\n\n lock (lockDevices)\n {\n Devices.Clear();\n Devices.Add(DefaultDevice);\n foreach (var device in deviceEnum.EnumAudioEndpoints(DataFlow.Render, DeviceStates.Active))\n Devices.Add(new() { Id = device.Id, Name = device.FriendlyName });\n }\n\n CurrentDevice.Id = defaultDevice.Id;\n CurrentDevice.Name = defaultDevice.FriendlyName;\n\n if (Logger.CanInfo)\n {\n string dump = \"\";\n foreach (var device in deviceEnum.EnumAudioEndpoints(DataFlow.Render, DeviceStates.Active))\n dump += $\"{device.Id} | {device.FriendlyName} {(defaultDevice.Id == device.Id ? \"*\" : \"\")}\\r\\n\";\n Engine.Log.Info($\"Audio Devices\\r\\n{dump}\");\n }\n\n var xaudio2 = XAudio2Create();\n\n if (xaudio2 == null)\n Failed = true;\n else\n xaudio2.Dispose();\n\n deviceEnum.RegisterEndpointNotificationCallback(this);\n\n } catch { Failed = true; }\n }\n private void RefreshDevices()\n {\n lock (locker)\n {\n Utils.UIInvokeIfRequired(() => // UI Required?\n {\n List curs = new();\n List removed = new();\n\n lock (lockDevices)\n {\n foreach(var device in deviceEnum.EnumAudioEndpoints(DataFlow.Render, DeviceStates.Active))\n curs.Add(new () { Id = device.Id, Name = device.FriendlyName });\n\n foreach(var cur in curs)\n {\n bool exists = false;\n foreach (var device in Devices)\n if (cur.Id == device.Id)\n { exists = true; break; }\n\n if (!exists)\n {\n Engine.Log.Info($\"Audio device {cur} added\");\n Devices.Add(cur);\n }\n }\n\n foreach (var device in Devices)\n {\n if (device.Id == \"0\") // Default\n continue;\n\n bool exists = false;\n foreach(var cur in curs)\n if (cur.Id == device.Id)\n { exists = true; break; }\n\n if (!exists)\n {\n Engine.Log.Info($\"Audio device {device} removed\");\n removed.Add(device);\n }\n }\n\n foreach(var device in removed)\n Devices.Remove(device);\n }\n\n var defaultDevice = deviceEnum.GetDefaultAudioEndpoint(DataFlow.Render, Role.Multimedia);\n if (defaultDevice != null && CurrentDevice.Id != defaultDevice.Id)\n {\n CurrentDevice.Id = defaultDevice.Id;\n CurrentDevice.Name = defaultDevice.FriendlyName;\n PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(nameof(CurrentDevice)));\n }\n\n // Fall back to DefaultDevice *Non-UI thread otherwise will freeze (not sure where and why) during xaudio.Dispose()\n if (removed.Count > 0)\n Task.Run(() =>\n {\n foreach(var device in removed)\n {\n foreach(var player in Engine.Players)\n if (player.Audio.Device == device)\n player.Audio.Device = DefaultDevice;\n }\n });\n });\n }\n }\n\n public void OnDeviceStateChanged(string pwstrDeviceId, int newState) => RefreshDevices();\n public void OnDeviceAdded(string pwstrDeviceId) => RefreshDevices();\n public void OnDeviceRemoved(string pwstrDeviceId) => RefreshDevices();\n public void OnDefaultDeviceChanged(DataFlow flow, Role role, string pwstrDefaultDeviceId) => RefreshDevices();\n public void OnPropertyValueChanged(string pwstrDeviceId, PropertyKey key) { }\n\n public class AudioEndpoint\n {\n public string Id { get; set; }\n public string Name { get; set; }\n\n public override string ToString()\n => Name;\n }\n}\n"], ["/LLPlayer/LLPlayer/ViewModels/SubtitlesExportDialogVM.cs", "using System.Diagnostics;\nusing System.IO;\nusing System.Diagnostics.CodeAnalysis;\nusing System.Text;\nusing FlyleafLib.MediaPlayer;\nusing LLPlayer.Extensions;\nusing LLPlayer.Services;\nusing SaveFileDialog = Microsoft.Win32.SaveFileDialog;\n\nnamespace LLPlayer.ViewModels;\n\npublic class SubtitlesExportDialogVM : Bindable, IDialogAware\n{\n public FlyleafManager FL { get; }\n\n public SubtitlesExportDialogVM(FlyleafManager fl)\n {\n FL = fl;\n\n IsUtf8Bom = FL.Config.Subs.SubsExportUTF8WithBom;\n }\n\n public List SubIndexList { get; } = [0, 1];\n public int SelectedSubIndex\n {\n get;\n set\n {\n if (Set(ref field, value))\n {\n OnPropertyChanged(nameof(SubManager));\n }\n }\n }\n\n public SubManager SubManager => FL.Player.SubtitlesManager[SelectedSubIndex];\n\n public bool IsUtf8Bom { get; set => Set(ref field, value); }\n\n public TranslateExportOptions SelectedTranslateOpts { get; set => Set(ref field, value); }\n\n [field: AllowNull, MaybeNull]\n public DelegateCommand CmdExport => field ??= new(() =>\n {\n var playlist = FL.Player.Playlist.Selected;\n if (playlist == null)\n {\n return;\n }\n\n List lines = FL.Player.SubtitlesManager[SelectedSubIndex].Subs\n .Where(s =>\n {\n if (!s.IsText)\n {\n return false;\n }\n\n if (SelectedTranslateOpts == TranslateExportOptions.TranslatedOnly)\n {\n return s.IsTranslated;\n }\n\n return true;\n })\n .Select(s => new SubtitleLine()\n {\n Text = (SelectedTranslateOpts != TranslateExportOptions.Original\n ? s.DisplayText : s.Text)!,\n Start = s.StartTime,\n End = s.EndTime\n }).ToList();\n\n if (lines.Count == 0)\n {\n ErrorDialogHelper.ShowKnownErrorPopup(\"There were no subtitles to export.\", \"Export\");\n return;\n }\n\n string? initDir = null;\n string fileName;\n\n if (FL.Player.Playlist.Url != null && File.Exists(playlist.Url))\n {\n fileName = Path.GetFileNameWithoutExtension(playlist.Url);\n\n // If there is currently an open file, set that folder as the base folder\n initDir = Path.GetDirectoryName(playlist.Url);\n }\n else\n {\n // If live video, use title instead\n fileName = playlist.Title;\n }\n\n SaveFileDialog saveFileDialog = new()\n {\n Filter = \"SRT files (*.srt)|*.srt|All files (*.*)|*.*\",\n FileName = fileName + \".srt\",\n InitialDirectory = initDir\n };\n\n if (SelectedTranslateOpts != TranslateExportOptions.Original)\n {\n saveFileDialog.FileName = fileName + \".translated.srt\";\n }\n\n if (saveFileDialog.ShowDialog() == true)\n {\n SrtExporter.ExportSrt(lines, saveFileDialog.FileName, new UTF8Encoding(IsUtf8Bom));\n\n // open saved file in explorer\n Process.Start(\"explorer.exe\", $@\"/select,\"\"{saveFileDialog.FileName}\"\"\");\n }\n });\n\n #region IDialogAware\n public string Title { get; set => Set(ref field, value); }\n = $\"Subtitles Exporter - {App.Name}\";\n public double WindowWidth { get; set => Set(ref field, value); } = 350;\n public double WindowHeight { get; set => Set(ref field, value); } = 240;\n\n public DialogCloseListener RequestClose { get; }\n\n public bool CanCloseDialog()\n {\n return true;\n }\n public void OnDialogClosed() { }\n\n public void OnDialogOpened(IDialogParameters parameters) { }\n #endregion\n\n public enum TranslateExportOptions\n {\n Original,\n TranslatedOnly,\n TranslatedWithFallback\n }\n}\n"], ["/LLPlayer/LLPlayer/Services/AppActions.cs", "using System.ComponentModel;\nusing System.Diagnostics;\nusing System.IO;\nusing System.Reflection;\nusing System.Windows;\nusing System.Windows.Input;\nusing System.Windows.Media;\nusing FlyleafLib;\nusing FlyleafLib.Controls.WPF;\nusing FlyleafLib.MediaPlayer;\nusing LLPlayer.Extensions;\nusing LLPlayer.Views;\nusing WpfColorFontDialog;\nusing KeyBinding = FlyleafLib.MediaPlayer.KeyBinding;\n\nnamespace LLPlayer.Services;\n\npublic class AppActions\n{\n private readonly Player _player;\n private readonly AppConfig _config;\n private FlyleafHost? _flyleafHost => _player.Host as FlyleafHost;\n private readonly IDialogService _dialogService;\n\n#pragma warning disable CS9264\n public AppActions(Player player, AppConfig config, IDialogService dialogService)\n {\n _player = player;\n _config = config;\n _dialogService = dialogService;\n\n CustomActions = GetCustomActions();\n\n RegisterCustomKeyBindingsAction();\n }\n#pragma warning restore CS9264\n\n private void RegisterCustomKeyBindingsAction()\n {\n // Since the action name is defined in PlayerConfig, get the Action name from there and register delegate.\n foreach (var binding in _player.Config.Player.KeyBindings.Keys)\n {\n if (binding.Action == KeyBindingAction.Custom && !string.IsNullOrEmpty(binding.ActionName))\n {\n if (Enum.TryParse(binding.ActionName, out CustomKeyBindingAction key))\n {\n binding.SetAction(CustomActions[key], binding.IsKeyUp);\n }\n }\n }\n }\n\n public Dictionary CustomActions { get; }\n\n private Dictionary GetCustomActions()\n {\n return new Dictionary\n {\n [CustomKeyBindingAction.OpenNextFile] = CmdOpenNextFile.Execute,\n [CustomKeyBindingAction.OpenPrevFile] = CmdOpenPrevFile.Execute,\n [CustomKeyBindingAction.OpenCurrentPath] = CmdOpenCurrentPath.Execute,\n\n [CustomKeyBindingAction.SubsPositionUp] = CmdSubsPositionUp.Execute,\n [CustomKeyBindingAction.SubsPositionDown] = CmdSubsPositionDown.Execute,\n [CustomKeyBindingAction.SubsSizeIncrease] = CmdSubsSizeIncrease.Execute,\n [CustomKeyBindingAction.SubsSizeDecrease] = CmdSubsSizeDecrease.Execute,\n [CustomKeyBindingAction.SubsPrimarySizeIncrease] = CmdSubsPrimarySizeIncrease.Execute,\n [CustomKeyBindingAction.SubsPrimarySizeDecrease] = CmdSubsPrimarySizeDecrease.Execute,\n [CustomKeyBindingAction.SubsSecondarySizeIncrease] = CmdSubsSecondarySizeIncrease.Execute,\n [CustomKeyBindingAction.SubsSecondarySizeDecrease] = CmdSubsSecondarySizeDecrease.Execute,\n [CustomKeyBindingAction.SubsDistanceIncrease] = CmdSubsDistanceIncrease.Execute,\n [CustomKeyBindingAction.SubsDistanceDecrease] = CmdSubsDistanceDecrease.Execute,\n\n [CustomKeyBindingAction.SubsTextCopy] = () => CmdSubsTextCopy.Execute(false),\n [CustomKeyBindingAction.SubsPrimaryTextCopy] = () => CmdSubsPrimaryTextCopy.Execute(false),\n [CustomKeyBindingAction.SubsSecondaryTextCopy] = () => CmdSubsSecondaryTextCopy.Execute(false),\n [CustomKeyBindingAction.ToggleSubsAutoTextCopy] = CmdToggleSubsAutoTextCopy.Execute,\n [CustomKeyBindingAction.ToggleSidebarShowSecondary] = CmdToggleSidebarShowSecondary.Execute,\n [CustomKeyBindingAction.ToggleSidebarShowOriginalText] = CmdToggleSidebarShowOriginalText.Execute,\n [CustomKeyBindingAction.ActivateSubsSearch] = CmdActivateSubsSearch.Execute,\n\n [CustomKeyBindingAction.ToggleSidebar] = CmdToggleSidebar.Execute,\n [CustomKeyBindingAction.ToggleDebugOverlay] = CmdToggleDebugOverlay.Execute,\n [CustomKeyBindingAction.ToggleAlwaysOnTop] = CmdToggleAlwaysOnTop.Execute,\n\n [CustomKeyBindingAction.OpenWindowSettings] = CmdOpenWindowSettings.Execute,\n [CustomKeyBindingAction.OpenWindowSubsDownloader] = CmdOpenWindowSubsDownloader.Execute,\n [CustomKeyBindingAction.OpenWindowSubsExporter] = CmdOpenWindowSubsExporter.Execute,\n [CustomKeyBindingAction.OpenWindowCheatSheet] = CmdOpenWindowCheatSheet.Execute,\n\n [CustomKeyBindingAction.AppNew] = CmdAppNew.Execute,\n [CustomKeyBindingAction.AppClone] = CmdAppClone.Execute,\n [CustomKeyBindingAction.AppRestart] = CmdAppRestart.Execute,\n [CustomKeyBindingAction.AppExit] = CmdAppExit.Execute,\n };\n }\n\n public static List DefaultCustomActionsMap()\n {\n return\n [\n new() { ActionName = nameof(CustomKeyBindingAction.OpenNextFile), Key = Key.Right, Alt = true, Shift = true, IsKeyUp = true },\n new() { ActionName = nameof(CustomKeyBindingAction.OpenPrevFile), Key = Key.Left, Alt = true, Shift = true, IsKeyUp = true },\n new() { ActionName = nameof(CustomKeyBindingAction.SubsPositionUp), Key = Key.Up, Shift = true },\n new() { ActionName = nameof(CustomKeyBindingAction.SubsPositionDown), Key = Key.Down, Shift = true },\n new() { ActionName = nameof(CustomKeyBindingAction.SubsSizeIncrease), Key = Key.Right, Shift = true },\n new() { ActionName = nameof(CustomKeyBindingAction.SubsSizeDecrease), Key = Key.Left, Shift = true },\n new() { ActionName = nameof(CustomKeyBindingAction.SubsSecondarySizeIncrease), Key = Key.Right, Ctrl = true, Shift = true },\n new() { ActionName = nameof(CustomKeyBindingAction.SubsSecondarySizeDecrease), Key = Key.Left, Ctrl = true, Shift = true },\n new() { ActionName = nameof(CustomKeyBindingAction.SubsDistanceIncrease), Key = Key.Up, Ctrl = true, Shift = true },\n new() { ActionName = nameof(CustomKeyBindingAction.SubsDistanceDecrease), Key = Key.Down, Ctrl = true, Shift = true },\n new() { ActionName = nameof(CustomKeyBindingAction.SubsPrimaryTextCopy), Key = Key.C, Ctrl = true, IsKeyUp = true },\n new() { ActionName = nameof(CustomKeyBindingAction.ToggleSubsAutoTextCopy), Key = Key.A, Ctrl = true, IsKeyUp = true },\n new() { ActionName = nameof(CustomKeyBindingAction.ActivateSubsSearch), Key = Key.F, Ctrl = true, IsKeyUp = true },\n new() { ActionName = nameof(CustomKeyBindingAction.ToggleSidebar), Key = Key.B, Ctrl = true, IsKeyUp = true },\n new() { ActionName = nameof(CustomKeyBindingAction.ToggleDebugOverlay), Key = Key.D, Ctrl = true, Shift = true, IsKeyUp = true },\n new() { ActionName = nameof(CustomKeyBindingAction.ToggleAlwaysOnTop), Key = Key.T, Ctrl = true, IsKeyUp = true },\n new() { ActionName = nameof(CustomKeyBindingAction.OpenWindowSettings), Key = Key.OemComma, Ctrl = true, IsKeyUp = true },\n new() { ActionName = nameof(CustomKeyBindingAction.OpenWindowCheatSheet), Key = Key.F1, IsKeyUp = true },\n new() { ActionName = nameof(CustomKeyBindingAction.AppNew), Key = Key.N, Ctrl = true, IsKeyUp = true },\n ];\n }\n\n // ReSharper disable NullCoalescingConditionIsAlwaysNotNullAccordingToAPIContract\n\n #region Command used in key\n\n public DelegateCommand CmdOpenNextFile => field ??= new(() =>\n {\n OpenNextPrevInternal(isNext: true);\n });\n\n public DelegateCommand CmdOpenPrevFile => field ??= new(() =>\n {\n OpenNextPrevInternal(isNext: false);\n });\n\n private void OpenNextPrevInternal(bool isNext)\n {\n var playlist = _player.Playlist;\n if (playlist.Url == null)\n return;\n\n string url = playlist.Url;\n\n try\n {\n (string? prev, string? next) = FileHelper.GetNextAndPreviousFile(url);\n if (isNext && next != null)\n {\n _player.OpenAsync(next);\n }\n else if (!isNext && prev != null)\n {\n _player.OpenAsync(prev);\n }\n }\n catch (Exception ex)\n {\n MessageBox.Show($\"OpenNextPrevFile is failed: {ex.Message}\");\n }\n }\n\n public DelegateCommand CmdOpenCurrentPath => field ??= new(() =>\n {\n var playlist = _player.Playlist;\n if (playlist.Selected == null)\n return;\n\n string url = playlist.Url;\n\n bool isFile = File.Exists(url);\n bool isUrl = url.StartsWith(\"http:\", StringComparison.OrdinalIgnoreCase) ||\n url.StartsWith(\"https:\", StringComparison.OrdinalIgnoreCase);\n\n if (!isFile && !isUrl)\n {\n return;\n }\n\n if (isUrl)\n {\n // fix url\n url = playlist.Selected.DirectUrl;\n }\n\n // Open folder or URL\n string? fileName = isFile ? Path.GetDirectoryName(url) : url;\n\n Process.Start(new ProcessStartInfo\n {\n FileName = fileName,\n UseShellExecute = true,\n Verb = \"open\"\n });\n });\n\n public DelegateCommand CmdSubsPositionUp => field ??= new(() =>\n {\n SubsPositionUpActionInternal(true);\n });\n\n public DelegateCommand CmdSubsPositionDown => field ??= new(() =>\n {\n SubsPositionUpActionInternal(false);\n });\n\n public DelegateCommand CmdSubsSizeIncrease => field ??= new(() =>\n {\n SubsSizeActionInternal(SubsSizeActionType.All, increase: true);\n });\n\n public DelegateCommand CmdSubsSizeDecrease => field ??= new(() =>\n {\n SubsSizeActionInternal(SubsSizeActionType.All, increase: false);\n });\n\n public DelegateCommand CmdSubsPrimarySizeIncrease => field ??= new(() =>\n {\n SubsSizeActionInternal(SubsSizeActionType.Primary, increase: true);\n });\n\n public DelegateCommand CmdSubsPrimarySizeDecrease => field ??= new(() =>\n {\n SubsSizeActionInternal(SubsSizeActionType.Primary, increase: false);\n });\n\n public DelegateCommand CmdSubsSecondarySizeIncrease => field ??= new(() =>\n {\n SubsSizeActionInternal(SubsSizeActionType.Secondary, increase: true);\n });\n\n public DelegateCommand CmdSubsSecondarySizeDecrease => field ??= new(() =>\n {\n SubsSizeActionInternal(SubsSizeActionType.Secondary, increase: false);\n });\n\n private void SubsSizeActionInternal(SubsSizeActionType type, bool increase)\n {\n var primary = _player.Subtitles[0];\n var secondary = _player.Subtitles[1];\n\n if (type is SubsSizeActionType.All or SubsSizeActionType.Primary)\n {\n // TODO: L: Match scaling ratios in text and bitmap subtitles\n if (primary.Enabled && (!primary.IsBitmap || !string.IsNullOrEmpty(primary.Data.Text)))\n {\n _config.Subs.SubsFontSize += _config.Subs.SubsFontSizeOffset * (increase ? 1 : -1);\n }\n else if (primary.Enabled && primary.IsBitmap)\n {\n _player.Subtitles[0].Data.BitmapPosition.ConfScale += _config.Subs.SubsBitmapScaleOffset / 100.0 * (increase ? 1.0 : -1.0);\n }\n }\n\n if (type is SubsSizeActionType.All or SubsSizeActionType.Secondary)\n {\n if (secondary.Enabled && (!secondary.IsBitmap || !string.IsNullOrEmpty(secondary.Data.Text)))\n {\n _config.Subs.SubsFontSize2 += _config.Subs.SubsFontSizeOffset * (increase ? 1 : -1);\n }\n else if (secondary.Enabled && secondary.IsBitmap)\n {\n _player.Subtitles[1].Data.BitmapPosition.ConfScale += _config.Subs.SubsBitmapScaleOffset / 100.0 * (increase ? 1.0 : -1.0);\n }\n }\n }\n\n public DelegateCommand CmdSubsDistanceIncrease => field ??= new(() =>\n {\n SubsDistanceActionInternal(true);\n });\n\n public DelegateCommand CmdSubsDistanceDecrease => field ??= new(() =>\n {\n SubsDistanceActionInternal(false);\n });\n\n private void SubsDistanceActionInternal(bool increase)\n {\n _config.Subs.SubsDistance += _config.Subs.SubsDistanceOffset * (increase ? 1 : -1);\n }\n\n public DelegateCommand CmdSubsTextCopy => field ??= new((suppressOsd) =>\n {\n if (!_player.Subtitles[0].Enabled && !_player.Subtitles[1].Enabled)\n {\n return;\n }\n\n string text = _player.Subtitles[0].Data.Text;\n if (!string.IsNullOrEmpty(_player.Subtitles[1].Data.Text))\n {\n text += Environment.NewLine + \"( \" + _player.Subtitles[1].Data.Text + \" )\";\n }\n\n if (!string.IsNullOrEmpty(text))\n {\n try\n {\n WindowsClipboard.SetText(text);\n if (!suppressOsd.HasValue || !suppressOsd.Value)\n {\n _player.OSDMessage = \"Copy All Subtitle Text\";\n }\n }\n catch\n {\n // ignored\n }\n }\n });\n\n public DelegateCommand CmdSubsPrimaryTextCopy => field ??= new((suppressOsd) =>\n {\n SubsTextCopyInternal(0, suppressOsd);\n });\n\n public DelegateCommand CmdSubsSecondaryTextCopy => field ??= new((suppressOsd) =>\n {\n SubsTextCopyInternal(1, suppressOsd);\n });\n\n private void SubsTextCopyInternal(int subIndex, bool? suppressOsd)\n {\n if (!_player.Subtitles[subIndex].Enabled)\n {\n return;\n }\n\n string text = _player.Subtitles[subIndex].Data.Text;\n\n if (!string.IsNullOrEmpty(text))\n {\n try\n {\n WindowsClipboard.SetText(text);\n if (!suppressOsd.HasValue || !suppressOsd.Value)\n {\n _player.OSDMessage = $\"Copy {(subIndex == 0 ? \"Primary\" : \"Secondary\")} Subtitle Text\";\n }\n }\n catch\n {\n // ignored\n }\n }\n }\n\n public DelegateCommand CmdToggleSubsAutoTextCopy => field ??= new(() =>\n {\n _config.Subs.SubsAutoTextCopy = !_config.Subs.SubsAutoTextCopy;\n });\n\n public DelegateCommand CmdActivateSubsSearch => field ??= new(() =>\n {\n if (_flyleafHost is { IsFullScreen: true })\n {\n return;\n }\n\n _config.ShowSidebar = true;\n\n // for getting focus to TextBox\n _config.SidebarSearchActive = false;\n _config.SidebarSearchActive = true;\n });\n\n public DelegateCommand CmdToggleSidebarShowSecondary => field ??= new(() =>\n {\n _config.SidebarShowSecondary = !_config.SidebarShowSecondary;\n });\n\n public DelegateCommand CmdToggleSidebarShowOriginalText => field ??= new(() =>\n {\n _config.SidebarShowOriginalText = !_config.SidebarShowOriginalText;\n });\n\n public DelegateCommand CmdToggleSidebar => field ??= new(() =>\n {\n _config.ShowSidebar = !_config.ShowSidebar;\n });\n\n public DelegateCommand CmdToggleDebugOverlay => field ??= new(() =>\n {\n _config.ShowDebug = !_config.ShowDebug;\n });\n\n public DelegateCommand CmdToggleAlwaysOnTop => field ??= new(() =>\n {\n _config.AlwaysOnTop = !_config.AlwaysOnTop;\n });\n\n public DelegateCommand CmdOpenWindowSettings => field ??= new(() =>\n {\n if (_player.IsPlaying)\n {\n _player.Pause();\n }\n\n // Detects configuration changes necessary for restart\n // TODO: L: refactor\n bool requiredRestart = false;\n\n _config.PropertyChanged += ConfigOnPropertyChanged;\n _player.Config.Subtitles.WhisperCppConfig.PropertyChanged += ConfigOnPropertyChanged;\n\n void ConfigOnPropertyChanged(object? sender, PropertyChangedEventArgs e)\n {\n switch (e.PropertyName)\n {\n case nameof(_config.IsDarkTitlebar):\n case nameof(_player.Config.Subtitles.WhisperCppConfig.RuntimeLibraries):\n requiredRestart = true;\n break;\n }\n }\n\n _player.Activity.ForceFullActive();\n _dialogService.ShowSingleton(nameof(SettingsDialog), result =>\n {\n // Activate as it may be minimized for some reason\n if (!Application.Current.MainWindow!.IsActive)\n {\n Application.Current.MainWindow!.Activate();\n }\n\n _config.PropertyChanged -= ConfigOnPropertyChanged;\n _player.Config.Subtitles.WhisperCppConfig.PropertyChanged += ConfigOnPropertyChanged;\n\n if (result.Result == ButtonResult.OK)\n {\n SaveAllConfig();\n\n if (requiredRestart)\n {\n // Show confirmation dialog\n MessageBoxResult confirm = MessageBox.Show(\n \"A restart is required for the settings to take effect. Do you want to restart?\",\n \"Confirm to restart\",\n MessageBoxButton.YesNo,\n MessageBoxImage.Question\n );\n\n if (confirm == MessageBoxResult.Yes)\n {\n CmdAppRestart.Execute();\n }\n }\n }\n }, false);\n });\n\n public DelegateCommand CmdOpenWindowSubsDownloader => field ??= new(() =>\n {\n _player.Activity.ForceFullActive();\n _dialogService.ShowSingleton(nameof(SubtitlesDownloaderDialog), true);\n });\n\n public DelegateCommand CmdOpenWindowSubsExporter => field ??= new(() =>\n {\n _player.Activity.ForceFullActive();\n _dialogService.ShowSingleton(nameof(SubtitlesExportDialog), _ =>\n {\n // Activate as it may be minimized for some reason\n if (!Application.Current.MainWindow!.IsActive)\n {\n Application.Current.MainWindow!.Activate();\n }\n }, false);\n });\n\n public DelegateCommand CmdOpenWindowCheatSheet => field ??= new(() =>\n {\n _player.Activity.ForceFullActive();\n _dialogService.ShowSingleton(nameof(CheatSheetDialog), true);\n });\n\n public DelegateCommand CmdAppNew => field ??= new(() =>\n {\n string exePath = Process.GetCurrentProcess().MainModule!.FileName;\n Process.Start(exePath);\n });\n\n public DelegateCommand CmdAppClone => field ??= new(() =>\n {\n string exePath = Process.GetCurrentProcess().MainModule!.FileName;\n\n ProcessStartInfo startInfo = new()\n {\n FileName = exePath,\n UseShellExecute = false\n };\n\n // Launch New App with current url if opened\n var prevPlaylist = _player.Playlist.Selected;\n if (prevPlaylist != null)\n {\n startInfo.ArgumentList.Add(prevPlaylist.DirectUrl);\n }\n\n Process.Start(startInfo);\n });\n\n public DelegateCommand CmdAppRestart => field ??= new(() =>\n {\n // Clone\n CmdAppClone.Execute();\n\n // Exit\n CmdAppExit.Execute();\n });\n\n public DelegateCommand CmdAppExit => field ??= new(() =>\n {\n Application.Current.Shutdown();\n });\n #endregion\n\n #region Command not used in key\n private static FontWeightConverter _fontWeightConv = new();\n private static FontStyleConverter _fontStyleConv = new();\n private static FontStretchConverter _fontStretchConv = new();\n\n public DelegateCommand CmdSetSubtitlesFont => field ??= new(() =>\n {\n ColorFontDialog dialog = new();\n\n dialog.Topmost = _config.AlwaysOnTop;\n dialog.Font = new FontInfo(new FontFamily(_config.Subs.SubsFontFamily), _config.Subs.SubsFontSize, (FontStyle)_fontStyleConv.ConvertFromString(_config.Subs.SubsFontStyle)!, (FontStretch)_fontStretchConv.ConvertFromString(_config.Subs.SubsFontStretch)!, (FontWeight)_fontWeightConv.ConvertFromString(_config.Subs.SubsFontWeight)!, new SolidColorBrush(Colors.Black));\n\n _player.Activity.ForceFullActive();\n\n double prevFontSize = dialog.Font.Size;\n\n if (dialog.ShowDialog() == true && dialog.Font != null)\n {\n _config.Subs.SubsFontFamily = dialog.Font.Family.ToString();\n _config.Subs.SubsFontWeight = dialog.Font.Weight.ToString();\n _config.Subs.SubsFontStretch = dialog.Font.Stretch.ToString();\n _config.Subs.SubsFontStyle = dialog.Font.Style.ToString();\n\n if (prevFontSize != dialog.Font.Size)\n {\n _config.Subs.SubsFontSize = dialog.Font.Size;\n _config.Subs.SubsFontSize2 = dialog.Font.Size; // change secondary as well\n }\n\n // update display of secondary subtitles\n _config.Subs.UpdateSecondaryFonts();\n }\n });\n\n public DelegateCommand CmdSetSubtitlesFont2 => field ??= new(() =>\n {\n ColorFontDialog dialog = new();\n\n dialog.Topmost = _config.AlwaysOnTop;\n dialog.Font = new FontInfo(new FontFamily(_config.Subs.SubsFontFamily2), _config.Subs.SubsFontSize2, (FontStyle)_fontStyleConv.ConvertFromString(_config.Subs.SubsFontStyle2)!, (FontStretch)_fontStretchConv.ConvertFromString(_config.Subs.SubsFontStretch2)!, (FontWeight)_fontWeightConv.ConvertFromString(_config.Subs.SubsFontWeight2)!, new SolidColorBrush(Colors.Black));\n\n _player.Activity.ForceFullActive();\n\n if (dialog.ShowDialog() == true && dialog.Font != null)\n {\n _config.Subs.SubsFontFamily2 = dialog.Font.Family.ToString();\n _config.Subs.SubsFontWeight2 = dialog.Font.Weight.ToString();\n _config.Subs.SubsFontStretch2 = dialog.Font.Stretch.ToString();\n _config.Subs.SubsFontStyle2 = dialog.Font.Style.ToString();\n\n _config.Subs.SubsFontSize2 = dialog.Font.Size;\n\n // update display of secondary subtitles\n _config.Subs.UpdateSecondaryFonts();\n }\n });\n\n public DelegateCommand CmdSetSubtitlesFontSidebar => field ??= new(() =>\n {\n ColorFontDialog dialog = new();\n\n dialog.Topmost = _config.AlwaysOnTop;\n dialog.Font = new FontInfo(new FontFamily(_config.SidebarFontFamily), _config.SidebarFontSize, FontStyles.Normal, FontStretches.Normal, (FontWeight)_fontWeightConv.ConvertFromString(_config.SidebarFontWeight)!, new SolidColorBrush(Colors.Black));\n\n _player.Activity.ForceFullActive();\n\n if (dialog.ShowDialog() == true && dialog.Font != null)\n {\n _config.SidebarFontFamily = dialog.Font.Family.ToString();\n _config.SidebarFontSize = dialog.Font.Size;\n _config.SidebarFontWeight = dialog.Font.Weight.ToString();\n }\n });\n\n public DelegateCommand CmdResetSubsPosition => field ??= new(() =>\n {\n // TODO: L: Reset bitmap as well\n _config.Subs.ResetSubsPosition();\n });\n\n public DelegateCommand CmdChangeAspectRatio => field ??= new((ratio) =>\n {\n if (!ratio.HasValue)\n return;\n\n _player.Config.Video.AspectRatio = ratio.Value;\n });\n\n public DelegateCommand CmdSetSubPositionAlignment => field ??= new((alignment) =>\n {\n if (!alignment.HasValue)\n return;\n\n _config.Subs.SubsPositionAlignment = alignment.Value;\n });\n\n public DelegateCommand CmdSetSubPositionAlignmentWhenDual => field ??= new((alignment) =>\n {\n if (!alignment.HasValue)\n return;\n\n _config.Subs.SubsPositionAlignmentWhenDual = alignment.Value;\n });\n\n #endregion\n\n // ReSharper restore NullCoalescingConditionIsAlwaysNotNullAccordingToAPIContract\n\n // TODO: L: make it command?\n public void SaveAllConfig()\n {\n _config.Save(App.AppConfigPath);\n\n var opts = AppConfig.GetJsonSerializerOptions();\n _player.Config.Version = App.Version;\n _player.Config.Save(App.PlayerConfigPath, opts);\n\n Engine.Config.Version = App.Version;\n Engine.Config.Save(App.EngineConfigPath, opts);\n }\n\n private enum SubsSizeActionType\n {\n All,\n Primary,\n Secondary\n }\n\n private void SubsPositionUpActionInternal(bool up)\n {\n var primary = _player.Subtitles[0];\n var secondary = _player.Subtitles[1];\n\n bool bothEnabled = primary.Enabled && secondary.Enabled;\n\n if (bothEnabled || // both enabled\n primary.Enabled && !primary.IsBitmap || // When text subtitles are enabled\n secondary.Enabled && !secondary.IsBitmap || !string.IsNullOrEmpty(primary.Data.Text) || // If OCR subtitles are available\n !string.IsNullOrEmpty(secondary.Data.Text))\n {\n _config.Subs.SubsPosition += _config.Subs.SubsPositionOffset * (up ? -1 : 1);\n }\n else if (primary.IsBitmap || secondary.IsBitmap)\n {\n // For bitmap subtitles (absolute position)\n for (int i = 0; i < _player.Config.Subtitles.Max; i++)\n {\n _player.Subtitles[i].Data.BitmapPosition.ConfPos += _config.Subs.SubsPositionOffset * (up ? -1 : 1);\n }\n }\n }\n}\n\n// List of key actions to be added from the app side\npublic enum CustomKeyBindingAction\n{\n [Description(\"Open Next File\")]\n OpenNextFile,\n [Description(\"Open Previous File\")]\n OpenPrevFile,\n [Description(\"Open Folder or URL of the currently opened file\")]\n OpenCurrentPath,\n\n [Description(\"Subtitles Position Up\")]\n SubsPositionUp,\n [Description(\"Subtitles Position Down\")]\n SubsPositionDown,\n [Description(\"Subtitles Size Increase\")]\n SubsSizeIncrease,\n [Description(\"Subtitles Size Decrease\")]\n SubsSizeDecrease,\n [Description(\"Primary Subtitles Size Increase\")]\n SubsPrimarySizeIncrease,\n [Description(\"Primary Subtitles Size Decrease\")]\n SubsPrimarySizeDecrease,\n [Description(\"Secondary Subtitles Size Increase\")]\n SubsSecondarySizeIncrease,\n [Description(\"Secondary Subtitles Size Decrease\")]\n SubsSecondarySizeDecrease,\n [Description(\"Primary/Secondary Subtitles Distance Increase\")]\n SubsDistanceIncrease,\n [Description(\"Primary/Secondary Subtitles Distance Decrease\")]\n SubsDistanceDecrease,\n\n [Description(\"Copy All Subtiltes Text\")]\n SubsTextCopy,\n [Description(\"Copy Primary Subtiltes Text\")]\n SubsPrimaryTextCopy,\n [Description(\"Copy Secondary Subtiltes Text\")]\n SubsSecondaryTextCopy,\n [Description(\"Toggle Auto Subtitles Text Copy\")]\n ToggleSubsAutoTextCopy,\n\n [Description(\"Toggle Primary / Secondary in Subtitles Sidebar\")]\n ToggleSidebarShowSecondary,\n [Description(\"Toggle to show original text in Subtitles Sidebar\")]\n ToggleSidebarShowOriginalText,\n [Description(\"Activate Subtitles Search in Sidebar\")]\n ActivateSubsSearch,\n\n [Description(\"Toggle Subitltes Sidebar\")]\n ToggleSidebar,\n [Description(\"Toggle Debug Overlay\")]\n ToggleDebugOverlay,\n [Description(\"Toggle Always On Top\")]\n ToggleAlwaysOnTop,\n\n [Description(\"Open Settings Window\")]\n OpenWindowSettings,\n [Description(\"Open Subtitles Downloader Window\")]\n OpenWindowSubsDownloader,\n [Description(\"Open Subtitles Exporter Window\")]\n OpenWindowSubsExporter,\n [Description(\"Open Cheat Sheet Window\")]\n OpenWindowCheatSheet,\n\n [Description(\"Launch New Application\")]\n AppNew,\n [Description(\"Launch Clone Application\")]\n AppClone,\n [Description(\"Restart Application\")]\n AppRestart,\n [Description(\"Exit Application\")]\n AppExit,\n}\n\npublic enum KeyBindingActionGroup\n{\n Playback,\n Player,\n Audio,\n Video,\n Subtitles,\n SubtitlesPosition,\n Window,\n Other\n}\n\npublic static class KeyBindingActionExtensions\n{\n public static string ToString(this KeyBindingActionGroup group)\n {\n var str = group.ToString();\n if (group == KeyBindingActionGroup.SubtitlesPosition)\n {\n str = \"Subtitles Position\";\n }\n\n return str;\n }\n\n public static KeyBindingActionGroup ToGroup(this CustomKeyBindingAction action)\n {\n switch (action)\n {\n case CustomKeyBindingAction.OpenNextFile:\n case CustomKeyBindingAction.OpenPrevFile:\n case CustomKeyBindingAction.OpenCurrentPath:\n return KeyBindingActionGroup.Player; // TODO: L: ?\n\n case CustomKeyBindingAction.SubsPositionUp:\n case CustomKeyBindingAction.SubsPositionDown:\n case CustomKeyBindingAction.SubsSizeIncrease:\n case CustomKeyBindingAction.SubsSizeDecrease:\n case CustomKeyBindingAction.SubsPrimarySizeIncrease:\n case CustomKeyBindingAction.SubsPrimarySizeDecrease:\n case CustomKeyBindingAction.SubsSecondarySizeIncrease:\n case CustomKeyBindingAction.SubsSecondarySizeDecrease:\n case CustomKeyBindingAction.SubsDistanceIncrease:\n case CustomKeyBindingAction.SubsDistanceDecrease:\n return KeyBindingActionGroup.SubtitlesPosition;\n\n case CustomKeyBindingAction.SubsTextCopy:\n case CustomKeyBindingAction.SubsPrimaryTextCopy:\n case CustomKeyBindingAction.SubsSecondaryTextCopy:\n case CustomKeyBindingAction.ToggleSubsAutoTextCopy:\n case CustomKeyBindingAction.ToggleSidebarShowSecondary:\n case CustomKeyBindingAction.ToggleSidebarShowOriginalText:\n case CustomKeyBindingAction.ActivateSubsSearch:\n return KeyBindingActionGroup.Subtitles;\n\n case CustomKeyBindingAction.ToggleSidebar:\n case CustomKeyBindingAction.ToggleDebugOverlay:\n case CustomKeyBindingAction.ToggleAlwaysOnTop:\n case CustomKeyBindingAction.OpenWindowSettings:\n case CustomKeyBindingAction.OpenWindowSubsDownloader:\n case CustomKeyBindingAction.OpenWindowSubsExporter:\n case CustomKeyBindingAction.OpenWindowCheatSheet:\n return KeyBindingActionGroup.Window;\n\n // TODO: L: review group\n case CustomKeyBindingAction.AppNew:\n case CustomKeyBindingAction.AppClone:\n case CustomKeyBindingAction.AppRestart:\n case CustomKeyBindingAction.AppExit:\n return KeyBindingActionGroup.Other;\n\n default:\n return KeyBindingActionGroup.Other;\n }\n }\n\n public static KeyBindingActionGroup ToGroup(this KeyBindingAction action)\n {\n switch (action)\n {\n // TODO: L: review order and grouping\n case KeyBindingAction.ForceIdle:\n case KeyBindingAction.ForceActive:\n case KeyBindingAction.ForceFullActive:\n return KeyBindingActionGroup.Player;\n\n case KeyBindingAction.AudioDelayAdd:\n case KeyBindingAction.AudioDelayAdd2:\n case KeyBindingAction.AudioDelayRemove:\n case KeyBindingAction.AudioDelayRemove2:\n case KeyBindingAction.ToggleAudio:\n case KeyBindingAction.ToggleMute:\n case KeyBindingAction.VolumeUp:\n case KeyBindingAction.VolumeDown:\n return KeyBindingActionGroup.Audio;\n\n case KeyBindingAction.SubsDelayAddPrimary:\n case KeyBindingAction.SubsDelayAdd2Primary:\n case KeyBindingAction.SubsDelayRemovePrimary:\n case KeyBindingAction.SubsDelayRemove2Primary:\n case KeyBindingAction.SubsDelayAddSecondary:\n case KeyBindingAction.SubsDelayAdd2Secondary:\n case KeyBindingAction.SubsDelayRemoveSecondary:\n case KeyBindingAction.SubsDelayRemove2Secondary:\n return KeyBindingActionGroup.SubtitlesPosition;\n case KeyBindingAction.ToggleSubtitlesVisibility:\n case KeyBindingAction.ToggleSubtitlesVisibilityPrimary:\n case KeyBindingAction.ToggleSubtitlesVisibilitySecondary:\n return KeyBindingActionGroup.Subtitles;\n\n case KeyBindingAction.CopyToClipboard:\n case KeyBindingAction.CopyItemToClipboard:\n return KeyBindingActionGroup.Other; // TODO: L: ?\n\n case KeyBindingAction.OpenFromClipboard:\n case KeyBindingAction.OpenFromClipboardSafe:\n case KeyBindingAction.OpenFromFileDialog:\n return KeyBindingActionGroup.Player; // TODO: L: ?\n\n case KeyBindingAction.Stop:\n case KeyBindingAction.Pause:\n case KeyBindingAction.Play:\n case KeyBindingAction.TogglePlayPause:\n case KeyBindingAction.ToggleReversePlayback:\n case KeyBindingAction.ToggleLoopPlayback:\n case KeyBindingAction.SeekForward:\n case KeyBindingAction.SeekBackward:\n case KeyBindingAction.SeekForward2:\n case KeyBindingAction.SeekBackward2:\n case KeyBindingAction.SeekForward3:\n case KeyBindingAction.SeekBackward3:\n case KeyBindingAction.SeekForward4:\n case KeyBindingAction.SeekBackward4:\n return KeyBindingActionGroup.Playback;\n\n case KeyBindingAction.Flush:\n case KeyBindingAction.NormalScreen:\n case KeyBindingAction.FullScreen:\n case KeyBindingAction.ToggleFullScreen:\n return KeyBindingActionGroup.Player;\n\n case KeyBindingAction.ToggleVideo:\n case KeyBindingAction.ToggleKeepRatio:\n case KeyBindingAction.ToggleVideoAcceleration:\n case KeyBindingAction.TakeSnapshot:\n case KeyBindingAction.ToggleRecording:\n return KeyBindingActionGroup.Video;\n\n case KeyBindingAction.SubsPrevSeek:\n case KeyBindingAction.SubsCurSeek:\n case KeyBindingAction.SubsNextSeek:\n case KeyBindingAction.SubsPrevSeekFallback:\n case KeyBindingAction.SubsNextSeekFallback:\n case KeyBindingAction.SubsPrevSeek2:\n case KeyBindingAction.SubsCurSeek2:\n case KeyBindingAction.SubsNextSeek2:\n case KeyBindingAction.SubsPrevSeekFallback2:\n case KeyBindingAction.SubsNextSeekFallback2:\n return KeyBindingActionGroup.Subtitles;\n\n case KeyBindingAction.ShowNextFrame:\n case KeyBindingAction.ShowPrevFrame:\n case KeyBindingAction.SpeedAdd:\n case KeyBindingAction.SpeedAdd2:\n case KeyBindingAction.SpeedRemove:\n case KeyBindingAction.SpeedRemove2:\n case KeyBindingAction.ToggleSeekAccurate:\n return KeyBindingActionGroup.Playback;\n\n case KeyBindingAction.ResetAll:\n case KeyBindingAction.ResetSpeed:\n case KeyBindingAction.ResetRotation:\n case KeyBindingAction.ResetZoom:\n case KeyBindingAction.ZoomIn:\n case KeyBindingAction.ZoomOut:\n return KeyBindingActionGroup.Player;\n\n default:\n return KeyBindingActionGroup.Other;\n }\n }\n\n /// \n /// Gets the value of the Description attribute assigned to the Enum member.\n /// \n /// \n /// \n public static string GetDescription(this Enum value)\n {\n ArgumentNullException.ThrowIfNull(value);\n\n Type type = value.GetType();\n\n string name = value.ToString();\n\n MemberInfo[] member = type.GetMember(name);\n\n if (member.Length > 0)\n {\n if (Attribute.GetCustomAttribute(member[0], typeof(DescriptionAttribute)) is DescriptionAttribute attr)\n {\n return attr.Description;\n }\n }\n\n return name;\n }\n}\n"], ["/LLPlayer/FlyleafLib/MediaFramework/MediaDemuxer/CustomIOContext.cs", "using System.IO;\n\nnamespace FlyleafLib.MediaFramework.MediaDemuxer;\n\npublic unsafe class CustomIOContext\n{\n AVIOContext* avioCtx;\n public Stream stream;\n Demuxer demuxer;\n\n public CustomIOContext(Demuxer demuxer)\n {\n this.demuxer = demuxer;\n }\n\n public void Initialize(Stream stream)\n {\n this.stream = stream;\n //this.stream.Seek(0, SeekOrigin.Begin);\n\n ioread = IORead;\n ioseek = IOSeek;\n avioCtx = avio_alloc_context((byte*)av_malloc((nuint)demuxer.Config.IOStreamBufferSize), demuxer.Config.IOStreamBufferSize, 0, null, ioread, null, ioseek);\n demuxer.FormatContext->pb = avioCtx;\n demuxer.FormatContext->flags |= FmtFlags2.CustomIo;\n }\n\n public void Dispose()\n {\n if (avioCtx != null)\n {\n av_free(avioCtx->buffer);\n fixed (AVIOContext** ptr = &avioCtx) avio_context_free(ptr);\n }\n avioCtx = null;\n stream = null;\n ioread = null;\n ioseek = null;\n }\n\n avio_alloc_context_read_packet ioread;\n avio_alloc_context_seek ioseek;\n\n int IORead(void* opaque, byte* buffer, int bufferSize)\n {\n int ret;\n\n if (demuxer.Interrupter.ShouldInterrupt(null) != 0) return AVERROR_EXIT;\n\n ret = demuxer.CustomIOContext.stream.Read(new Span(buffer, bufferSize));\n\n if (ret > 0)\n return ret;\n\n if (ret == 0)\n return AVERROR_EOF;\n\n demuxer.Log.Warn(\"CustomIOContext Interrupted\");\n\n return AVERROR_EXIT;\n }\n\n long IOSeek(void* opaque, long offset, IOSeekFlags whence)\n {\n //System.Diagnostics.Debug.WriteLine($\"** S | {decCtx.demuxer.fmtCtx->pb->pos} - {decCtx.demuxer.ioStream.Position}\");\n\n return whence == IOSeekFlags.Size\n ? demuxer.CustomIOContext.stream.Length\n : demuxer.CustomIOContext.stream.Seek(offset, (SeekOrigin) whence);\n }\n}\n"], ["/LLPlayer/LLPlayer/Controls/Settings/SettingsSubtitlesASR.xaml.cs", "using System.Collections.ObjectModel;\nusing System.Collections.Specialized;\nusing System.Diagnostics;\nusing System.Globalization;\nusing System.IO;\nusing System.Windows;\nusing System.Windows.Controls;\nusing System.Windows.Data;\nusing CliWrap.Builders;\nusing FlyleafLib;\nusing FlyleafLib.MediaPlayer;\nusing LLPlayer.Extensions;\nusing LLPlayer.Services;\nusing LLPlayer.Views;\nusing Whisper.net.LibraryLoader;\n\nnamespace LLPlayer.Controls.Settings;\n\npublic partial class SettingsSubtitlesASR : UserControl\n{\n public SettingsSubtitlesASR()\n {\n InitializeComponent();\n\n DataContext = ((App)Application.Current).Container.Resolve();\n }\n}\n\npublic class SettingsSubtitlesASRVM : Bindable\n{\n public FlyleafManager FL { get; }\n private readonly IDialogService _dialogService;\n\n public SettingsSubtitlesASRVM(FlyleafManager fl, IDialogService dialogService)\n {\n FL = fl;\n _dialogService = dialogService;\n\n LoadDownloadedModels();\n\n foreach (RuntimeLibrary library in FL.PlayerConfig.Subtitles.WhisperCppConfig.RuntimeLibraries)\n {\n SelectedLibraries.Add(library);\n }\n\n foreach (RuntimeLibrary library in Enum.GetValues().Where(l => l != RuntimeLibrary.CoreML))\n {\n if (!SelectedLibraries.Contains(library))\n {\n AvailableLibraries.Add(library);\n }\n }\n SelectedLibraries.CollectionChanged += SelectedLibrariesOnCollectionChanged;\n\n foreach (WhisperLanguage lang in WhisperLanguage.GetWhisperLanguages())\n {\n WhisperLanguages.Add(lang);\n }\n\n ActiveEngineTabNo = (int)FL.PlayerConfig.Subtitles.ASREngine;\n }\n\n public int ActiveEngineTabNo { get; }\n\n public ObservableCollection WhisperLanguages { get; } = new();\n\n #region whisper.cpp\n public ObservableCollection AvailableLibraries { get; } = new();\n public ObservableCollection SelectedLibraries { get; } = new();\n\n public RuntimeLibrary? SelectedAvailable\n {\n get;\n set\n {\n if (Set(ref field, value))\n {\n OnPropertyChanged(nameof(CanMoveRight));\n }\n }\n }\n\n public RuntimeLibrary? SelectedSelected\n {\n get;\n set\n {\n if (Set(ref field, value))\n {\n OnPropertyChanged(nameof(CanMoveLeft));\n OnPropertyChanged(nameof(CanMoveUp));\n OnPropertyChanged(nameof(CanMoveDown));\n }\n }\n }\n\n public bool CanMoveRight => SelectedAvailable.HasValue;\n public bool CanMoveLeft => SelectedSelected.HasValue;\n public bool CanMoveUp => SelectedSelected.HasValue && SelectedLibraries.IndexOf(SelectedSelected.Value) > 0;\n public bool CanMoveDown => SelectedSelected.HasValue && SelectedLibraries.IndexOf(SelectedSelected.Value) < SelectedLibraries.Count - 1;\n\n private void SelectedLibrariesOnCollectionChanged(object? sender, NotifyCollectionChangedEventArgs e)\n {\n // Apply to config\n FL.PlayerConfig.Subtitles.WhisperCppConfig.RuntimeLibraries = [.. SelectedLibraries];\n }\n\n private void LoadDownloadedModels()\n {\n WhisperCppModel? prevSelected = FL.PlayerConfig.Subtitles.WhisperCppConfig.Model;\n FL.PlayerConfig.Subtitles.WhisperCppConfig.Model = null;\n DownloadModels.Clear();\n\n List models = WhisperCppModelLoader.LoadDownloadedModels();\n foreach (var model in models)\n {\n DownloadModels.Add(model);\n }\n\n FL.PlayerConfig.Subtitles.WhisperCppConfig.Model = DownloadModels.FirstOrDefault(m => m.Equals(prevSelected));\n\n if (FL.PlayerConfig.Subtitles.WhisperCppConfig.Model == null && DownloadModels.Count == 1)\n {\n // automatically set first downloaded model\n FL.PlayerConfig.Subtitles.WhisperCppConfig.Model = DownloadModels.First();\n }\n }\n\n public ObservableCollection DownloadModels { get; set => Set(ref field, value); } = new();\n\n public OrderedDictionary PromptPresets { get; } = new()\n {\n [\"Use Chinese (Simplified), with punctuation\"] = \"以下是普通话的句子。\",\n [\"Use Chinese (Traditional), with punctuation\"] = \"以下是普通話的句子。\"\n };\n\n public KeyValuePair? SelectedPromptPreset\n {\n get;\n set\n {\n if (Set(ref field, value))\n {\n if (value.HasValue)\n {\n FL.PlayerConfig.Subtitles.WhisperCppConfig.Prompt = value.Value.Value;\n }\n }\n }\n }\n\n public DelegateCommand? CmdDownloadModel => field ??= new(() =>\n {\n _dialogService.ShowDialog(nameof(WhisperModelDownloadDialog));\n\n LoadDownloadedModels();\n });\n\n public DelegateCommand? CmdMoveRight => field ??= new DelegateCommand(() =>\n {\n if (SelectedAvailable.HasValue && !SelectedLibraries.Contains(SelectedAvailable.Value))\n {\n SelectedLibraries.Add(SelectedAvailable.Value);\n AvailableLibraries.Remove(SelectedAvailable.Value);\n }\n }).ObservesCanExecute(() => CanMoveRight);\n\n public DelegateCommand? CmdMoveLeft => field ??= new DelegateCommand(() =>\n {\n if (SelectedSelected.HasValue)\n {\n AvailableLibraries.Add(SelectedSelected.Value);\n SelectedLibraries.Remove(SelectedSelected.Value);\n }\n }).ObservesCanExecute(() => CanMoveLeft);\n\n public DelegateCommand? CmdMoveUp => field ??= new DelegateCommand(() =>\n {\n int index = SelectedLibraries.IndexOf(SelectedSelected!.Value);\n if (index > 0)\n {\n SelectedLibraries.Move(index, index - 1);\n OnPropertyChanged(nameof(CanMoveUp));\n OnPropertyChanged(nameof(CanMoveDown));\n }\n }).ObservesCanExecute(() => CanMoveUp);\n\n public DelegateCommand? CmdMoveDown => field ??= new DelegateCommand(() =>\n {\n int index = SelectedLibraries.IndexOf(SelectedSelected!.Value);\n if (index < SelectedLibraries.Count - 1)\n {\n SelectedLibraries.Move(index, index + 1);\n OnPropertyChanged(nameof(CanMoveUp));\n OnPropertyChanged(nameof(CanMoveDown));\n }\n }).ObservesCanExecute(() => CanMoveDown);\n #endregion\n\n #region faster-whisper\n public OrderedDictionary ExtraArgumentsPresets { get; } = new()\n {\n [\"Use CUDA device\"] = \"--device cuda\",\n [\"Use CUDA second device\"] = \"--device cuda:1\",\n [\"Use CPU device\"] = \"--device cpu\",\n [\"Use Chinese (Simplified), with punctuation\"] = \"--initial_prompt \\\"以下是普通话的句子。\\\"\",\n [\"Use Chinese (Traditional), with punctuation\"] = \"--initial_prompt \\\"以下是普通話的句子。\\\"\"\n };\n\n public KeyValuePair? SelectedExtraArgumentsPreset\n {\n get;\n set\n {\n if (Set(ref field, value))\n {\n if (value.HasValue)\n {\n FL.PlayerConfig.Subtitles.FasterWhisperConfig.ExtraArguments = value.Value.Value;\n }\n }\n }\n }\n\n public DelegateCommand? CmdDownloadEngine => field ??= new(() =>\n {\n _dialogService.ShowDialog(nameof(WhisperEngineDownloadDialog));\n\n // update binding of downloaded state forcefully\n var prev = FL.PlayerConfig.Subtitles.ASREngine;\n FL.PlayerConfig.Subtitles.ASREngine = SubASREngineType.WhisperCpp;\n FL.PlayerConfig.Subtitles.ASREngine = prev;\n });\n\n public DelegateCommand? CmdOpenModelFolder => field ??= new(() =>\n {\n if (!Directory.Exists(WhisperConfig.ModelsDirectory))\n return;\n\n Process.Start(new ProcessStartInfo\n {\n FileName = WhisperConfig.ModelsDirectory,\n UseShellExecute = true,\n CreateNoWindow = true\n });\n });\n\n public DelegateCommand? CmdCopyDebugCommand => field ??= new(() =>\n {\n var cmdBase = FasterWhisperASRService.BuildCommand(FL.PlayerConfig.Subtitles.FasterWhisperConfig,\n FL.PlayerConfig.Subtitles.WhisperConfig);\n\n var sampleWavePath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, \"Assets\", \"kennedy.wav\");\n ArgumentsBuilder args = new();\n args.Add(sampleWavePath);\n\n string addedArgs = args.Build();\n\n var cmd = cmdBase.WithArguments($\"{cmdBase.Arguments} {addedArgs}\");\n Clipboard.SetText(cmd.CommandToText());\n });\n\n public DelegateCommand? CmdCopyHelpCommand => field ??= new(() =>\n {\n var cmdBase = FasterWhisperASRService.BuildCommand(FL.PlayerConfig.Subtitles.FasterWhisperConfig,\n FL.PlayerConfig.Subtitles.WhisperConfig);\n\n var cmd = cmdBase.WithArguments(\"--help\");\n Clipboard.SetText(cmd.CommandToText());\n });\n#endregion\n}\n\n[ValueConversion(typeof(Enum), typeof(bool))]\npublic class ASREngineDownloadedConverter : IValueConverter\n{\n public object Convert(object value, Type targetType, object parameter, CultureInfo culture)\n {\n if (value is SubASREngineType engine)\n {\n if (engine == SubASREngineType.FasterWhisper)\n {\n if (File.Exists(FasterWhisperConfig.DefaultEnginePath))\n {\n return true;\n }\n }\n }\n\n return false;\n }\n\n public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture) => throw new NotImplementedException();\n}\n"], ["/LLPlayer/FlyleafLib/MediaPlayer/Video.cs", "using System;\nusing System.Collections.ObjectModel;\n\nusing FlyleafLib.MediaFramework.MediaContext;\nusing FlyleafLib.MediaFramework.MediaStream;\n\nnamespace FlyleafLib.MediaPlayer;\n\npublic class Video : NotifyPropertyChanged\n{\n /// \n /// Embedded Streams\n /// \n public ObservableCollection\n Streams => decoder?.VideoDemuxer.VideoStreams;\n\n /// \n /// Whether the input has video and it is configured\n /// \n public bool IsOpened { get => isOpened; internal set => Set(ref _IsOpened, value); }\n internal bool _IsOpened, isOpened;\n\n public string Codec { get => codec; internal set => Set(ref _Codec, value); }\n internal string _Codec, codec;\n\n ///// \n ///// Video bitrate (Kbps)\n ///// \n public double BitRate { get => bitRate; internal set => Set(ref _BitRate, value); }\n internal double _BitRate, bitRate;\n\n public AspectRatio AspectRatio { get => aspectRatio; internal set => Set(ref _AspectRatio, value); }\n internal AspectRatio\n _AspectRatio, aspectRatio;\n\n ///// \n ///// Total Dropped Frames\n ///// \n public int FramesDropped { get => framesDropped; internal set => Set(ref _FramesDropped, value); }\n internal int _FramesDropped, framesDropped;\n\n /// \n /// Total Frames\n /// \n public int FramesTotal { get => framesTotal; internal set => Set(ref _FramesTotal, value); }\n internal int _FramesTotal, framesTotal;\n\n public int FramesDisplayed { get => framesDisplayed; internal set => Set(ref _FramesDisplayed, value); }\n internal int _FramesDisplayed, framesDisplayed;\n\n public double FPS { get => fps; internal set => Set(ref _FPS, value); }\n internal double _FPS, fps;\n\n /// \n /// Actual Frames rendered per second (FPS)\n /// \n public double FPSCurrent { get => fpsCurrent; internal set => Set(ref _FPSCurrent, value); }\n internal double _FPSCurrent, fpsCurrent;\n\n public string PixelFormat { get => pixelFormat; internal set => Set(ref _PixelFormat, value); }\n internal string _PixelFormat, pixelFormat;\n\n public int Width { get => width; internal set => Set(ref _Width, value); }\n internal int _Width, width;\n\n public int Height { get => height; internal set => Set(ref _Height, value); }\n internal int _Height, height;\n\n public bool VideoAcceleration\n { get => videoAcceleration; internal set => Set(ref _VideoAcceleration, value); }\n internal bool _VideoAcceleration, videoAcceleration;\n\n public bool ZeroCopy { get => zeroCopy; internal set => Set(ref _ZeroCopy, value); }\n internal bool _ZeroCopy, zeroCopy;\n\n public Player Player => player;\n\n Action uiAction;\n Player player;\n DecoderContext decoder => player.decoder;\n Config Config => player.Config;\n\n public Video(Player player)\n {\n this.player = player;\n\n uiAction = () =>\n {\n IsOpened = IsOpened;\n Codec = Codec;\n AspectRatio = AspectRatio;\n FramesTotal = FramesTotal;\n FPS = FPS;\n PixelFormat = PixelFormat;\n Width = Width;\n Height = Height;\n VideoAcceleration = VideoAcceleration;\n ZeroCopy = ZeroCopy;\n\n FramesDisplayed = FramesDisplayed;\n FramesDropped = FramesDropped;\n };\n }\n\n internal void Reset()\n {\n codec = null;\n aspectRatio = new AspectRatio(0, 0);\n bitRate = 0;\n fps = 0;\n pixelFormat = null;\n width = 0;\n height = 0;\n framesTotal = 0;\n videoAcceleration = false;\n zeroCopy = false;\n isOpened = false;\n\n player.UIAdd(uiAction);\n }\n internal void Refresh()\n {\n if (decoder.VideoStream == null) { Reset(); return; }\n\n codec = decoder.VideoStream.Codec;\n aspectRatio = decoder.VideoStream.AspectRatio;\n fps = decoder.VideoStream.FPS;\n pixelFormat = decoder.VideoStream.PixelFormatStr;\n width = (int)decoder.VideoStream.Width;\n height = (int)decoder.VideoStream.Height;\n framesTotal = decoder.VideoStream.TotalFrames;\n videoAcceleration\n = decoder.VideoDecoder.VideoAccelerated;\n zeroCopy = decoder.VideoDecoder.ZeroCopy;\n isOpened =!decoder.VideoDecoder.Disposed;\n\n framesDisplayed = 0;\n framesDropped = 0;\n\n player.UIAdd(uiAction);\n }\n\n internal void Enable()\n {\n if (player.VideoDemuxer.Disposed || Config.Player.Usage == Usage.Audio)\n return;\n\n bool wasPlaying = player.IsPlaying;\n\n player.Pause();\n decoder.OpenSuggestedVideo();\n player.ReSync(decoder.VideoStream, (int) (player.CurTime / 10000), true);\n\n if (wasPlaying || Config.Player.AutoPlay)\n player.Play();\n }\n internal void Disable()\n {\n if (!IsOpened)\n return;\n\n bool wasPlaying = player.IsPlaying;\n\n player.Pause();\n decoder.CloseVideo();\n player.SubtitleClear();\n\n if (!player.Audio.IsOpened)\n {\n player.canPlay = false;\n player.UIAdd(() => player.CanPlay = player.CanPlay);\n }\n\n Reset();\n player.UIAll();\n\n if (wasPlaying || Config.Player.AutoPlay)\n player.Play();\n }\n\n public void Toggle() => Config.Video.Enabled = !Config.Video.Enabled;\n public void ToggleKeepRatio()\n {\n if (Config.Video.AspectRatio == AspectRatio.Keep)\n Config.Video.AspectRatio = AspectRatio.Fill;\n else if (Config.Video.AspectRatio == AspectRatio.Fill)\n Config.Video.AspectRatio = AspectRatio.Keep;\n }\n public void ToggleVideoAcceleration() => Config.Video.VideoAcceleration = !Config.Video.VideoAcceleration;\n}\n"], ["/LLPlayer/FlyleafLib/Plugins/OpenDefault.cs", "using System;\nusing System.IO;\n\nusing FlyleafLib.MediaFramework.MediaPlaylist;\n\nnamespace FlyleafLib.Plugins;\n\npublic class OpenDefault : PluginBase, IOpen, IScrapeItem\n{\n /* TODO\n *\n * 1) Current Url Syntax issues\n * ..\\..\\..\\..\\folder\\file.mp3 | Cannot handle this\n * file:///C:/folder/fi%20le.mp3 | FFmpeg & File.Exists cannot handle this\n *\n */\n\n public new int Priority { get; set; } = 3000;\n\n public bool CanOpen() => true;\n\n public OpenResults Open()\n {\n try\n {\n if (Playlist.IOStream != null)\n {\n AddPlaylistItem(new()\n {\n IOStream= Playlist.IOStream,\n Title = \"Custom IO Stream\",\n FileSize= Playlist.IOStream.Length\n });\n\n Handler.OnPlaylistCompleted();\n\n return new();\n }\n\n // Proper Url Format\n string scheme;\n bool isWeb = false;\n string uriType = \"\";\n string ext = Utils.GetUrlExtention(Playlist.Url);\n string localPath= null;\n\n try\n {\n Uri uri = new(Playlist.Url);\n scheme = uri.Scheme.ToLower();\n isWeb = scheme.StartsWith(\"http\");\n uriType = uri.IsFile ? \"file\" : (uri.IsUnc ? \"unc\" : \"\");\n localPath = uri.LocalPath;\n } catch { }\n\n\n // Playlists (M3U, M3U8, PLS | TODO: WPL, XSPF)\n if (ext == \"m3u\")// || ext == \"m3u8\")\n {\n Playlist.InputType = InputType.Web; // TBR: Can be mixed\n Playlist.FolderBase = Path.GetTempPath();\n\n var items = isWeb ? M3UPlaylist.ParseFromHttp(Playlist.Url) : M3UPlaylist.Parse(Playlist.Url);\n\n foreach(var mitem in items)\n {\n AddPlaylistItem(new()\n {\n Title = mitem.Title,\n Url = mitem.Url,\n DirectUrl = mitem.Url,\n UserAgent = mitem.UserAgent,\n Referrer = mitem.Referrer\n });\n }\n\n Handler.OnPlaylistCompleted();\n\n return new();\n }\n else if (ext == \"pls\")\n {\n Playlist.InputType = InputType.Web; // TBR: Can be mixed\n Playlist.FolderBase = Path.GetTempPath();\n\n var items = PLSPlaylist.Parse(Playlist.Url);\n\n foreach(var mitem in items)\n {\n AddPlaylistItem(new PlaylistItem()\n {\n Title = mitem.Title,\n Url = mitem.Url,\n DirectUrl = mitem.Url,\n // Duration\n });\n }\n\n Handler.OnPlaylistCompleted();\n\n return new();\n }\n\n FileInfo fi = null;\n // Single Playlist Item\n if (uriType == \"file\")\n {\n Playlist.InputType = InputType.File;\n if (File.Exists(Playlist.Url))\n {\n fi = new(Playlist.Url);\n Playlist.FolderBase = fi.DirectoryName;\n }\n }\n else if (isWeb)\n {\n Playlist.InputType = InputType.Web;\n Playlist.FolderBase = Path.GetTempPath();\n }\n else if (uriType == \"unc\")\n {\n Playlist.InputType = InputType.UNC;\n Playlist.FolderBase = Path.GetTempPath();\n }\n else\n {\n //Playlist.InputType = InputType.Unknown;\n Playlist.FolderBase = Path.GetTempPath();\n }\n\n PlaylistItem item = new()\n {\n Url = Playlist.Url,\n DirectUrl = Playlist.Url\n };\n\n if (fi == null && File.Exists(Playlist.Url))\n {\n fi = new(Playlist.Url);\n item.Title = fi.Name;\n item.FileSize = fi.Length;\n }\n else\n {\n if (localPath != null)\n item.Title = Path.GetFileName(localPath);\n\n if (item.Title == null || item.Title.Trim().Length == 0)\n item.Title = Playlist.Url;\n }\n\n AddPlaylistItem(item);\n Handler.OnPlaylistCompleted();\n\n return new();\n } catch (Exception e)\n {\n return new(e.Message);\n }\n }\n\n public OpenResults OpenItem() => new();\n\n public void ScrapeItem(PlaylistItem item)\n {\n // Update Title (TBR: don't mess with other media types - only movies/tv shows)\n if (Playlist.InputType != InputType.File && Playlist.InputType != InputType.UNC && Playlist.InputType != InputType.Torrent)\n return;\n\n item.FillMediaParts();\n }\n}\n"], ["/LLPlayer/LLPlayer/ViewModels/SubtitlesSidebarVM.cs", "using System.ComponentModel;\nusing System.Windows.Data;\nusing FlyleafLib.MediaPlayer;\nusing LLPlayer.Extensions;\nusing LLPlayer.Services;\n\nnamespace LLPlayer.ViewModels;\n\npublic class SubtitlesSidebarVM : Bindable, IDisposable\n{\n public FlyleafManager FL { get; }\n\n public SubtitlesSidebarVM(FlyleafManager fl)\n {\n FL = fl;\n\n FL.Config.PropertyChanged += OnConfigOnPropertyChanged;\n\n // Initialize filtered view for the sidebar\n for (int i = 0; i < _filteredSubs.Length; i++)\n {\n _filteredSubs[i] = (ListCollectionView)CollectionViewSource.GetDefaultView(FL.Player.SubtitlesManager[i].Subs);\n }\n }\n\n public void Dispose()\n {\n FL.Config.PropertyChanged -= OnConfigOnPropertyChanged;\n }\n\n private void OnConfigOnPropertyChanged(object? sender, PropertyChangedEventArgs args)\n {\n switch (args.PropertyName)\n {\n case nameof(FL.Config.SidebarShowSecondary):\n OnPropertyChanged(nameof(SubIndex));\n OnPropertyChanged(nameof(SubManager));\n\n // prevent unnecessary filter update\n if (_lastSearchText[SubIndex] != _trimSearchText)\n {\n ApplyFilter(); // ensure filter applied\n }\n break;\n case nameof(FL.Config.SidebarShowOriginalText):\n // Update ListBox\n OnPropertyChanged(nameof(SubManager));\n\n if (_trimSearchText.Length != 0)\n {\n // because of switch between Text and DisplayText\n ApplyFilter();\n }\n break;\n }\n }\n\n public int SubIndex => !FL.Config.SidebarShowSecondary ? 0 : 1;\n\n public SubManager SubManager => FL.Player.SubtitlesManager[SubIndex];\n\n private readonly ListCollectionView[] _filteredSubs = new ListCollectionView[2];\n\n private string _searchText = string.Empty;\n public string SearchText\n {\n get => _searchText;\n set\n {\n if (Set(ref _searchText, value))\n {\n DebounceFilter();\n }\n }\n }\n\n private string _trimSearchText = string.Empty; // for performance\n\n public string HitCount { get; set => Set(ref field, value); } = string.Empty;\n\n public event EventHandler? RequestScrollToTop;\n\n // TODO: L: Fix implicit changes to reflect\n public DelegateCommand? CmdSubFontSizeChange => field ??= new(increase =>\n {\n if (int.TryParse(increase, out var value))\n {\n FL.Config.SidebarFontSize += value;\n }\n });\n\n public DelegateCommand? CmdSubTextMaskToggle => field ??= new(() =>\n {\n FL.Config.SidebarTextMask = !FL.Config.SidebarTextMask;\n\n // Update ListBox\n OnPropertyChanged(nameof(SubManager));\n });\n\n public DelegateCommand? CmdShowDownloadSubsDialog => field ??= new(() =>\n {\n FL.Action.CmdOpenWindowSubsDownloader.Execute();\n });\n\n public DelegateCommand? CmdShowExportSubsDialog => field ??= new(() =>\n {\n FL.Action.CmdOpenWindowSubsExporter.Execute();\n });\n\n public DelegateCommand? CmdSwapSidebarPosition => field ??= new(() =>\n {\n FL.Config.SidebarLeft = !FL.Config.SidebarLeft;\n });\n\n public DelegateCommand? CmdSubPlay => field ??= new((index) =>\n {\n if (!index.HasValue)\n {\n return;\n }\n\n var sub = SubManager.Subs[index.Value];\n FL.Player.SeekAccurate(sub.StartTime, SubIndex);\n });\n\n public DelegateCommand? CmdSubSync => field ??= new((index) =>\n {\n if (!index.HasValue)\n {\n return;\n }\n\n var sub = SubManager.Subs[index.Value];\n var newDelay = FL.Player.CurTime - sub.StartTime.Ticks;\n\n // Delay's OSD is not displayed, temporarily set to Active\n FL.Player.Activity.ForceActive();\n\n FL.PlayerConfig.Subtitles[SubIndex].Delay = newDelay;\n });\n\n public DelegateCommand? CmdClearSearch => field ??= new(() =>\n {\n if (!FL.Config.SidebarSearchActive)\n return;\n\n Set(ref _searchText, string.Empty, nameof(SearchText));\n _trimSearchText = string.Empty;\n HitCount = string.Empty;\n\n _debounceCts?.Cancel();\n _debounceCts?.Dispose();\n _debounceCts = null;\n\n for (int i = 0; i < _filteredSubs.Length; i++)\n {\n _lastSearchText[i] = string.Empty;\n _filteredSubs[i].Filter = null; // remove filter completely\n _filteredSubs[i].Refresh();\n }\n\n FL.Config.SidebarSearchActive = false;\n\n // move focus to video and enable keybindings\n FL.FlyleafHost!.Surface.Focus();\n\n // for scrolling to current sub\n var prev = SubManager.SelectedSub;\n SubManager.SelectedSub = null;\n SubManager.SelectedSub = prev;\n });\n\n public DelegateCommand? CmdNextMatch => field ??= new(() =>\n {\n if (_filteredSubs[SubIndex].IsEmpty)\n return;\n\n if (!_filteredSubs[SubIndex].MoveCurrentToNext())\n {\n // if last, move to first\n _filteredSubs[SubIndex].MoveCurrentToFirst();\n }\n\n var nextItem = (SubtitleData)_filteredSubs[SubIndex].CurrentItem;\n if (nextItem != null)\n {\n FL.Player.SeekAccurate(nextItem.StartTime, SubIndex);\n FL.Player.Activity.RefreshFullActive();\n }\n });\n\n public DelegateCommand? CmdPrevMatch => field ??= new(() =>\n {\n if (_filteredSubs[SubIndex].IsEmpty)\n return;\n\n if (!_filteredSubs[SubIndex].MoveCurrentToPrevious())\n {\n // if first, move to last\n _filteredSubs[SubIndex].MoveCurrentToLast();\n }\n\n var prevItem = (SubtitleData)_filteredSubs[SubIndex].CurrentItem;\n if (prevItem != null)\n {\n FL.Player.SeekAccurate(prevItem.StartTime, SubIndex);\n FL.Player.Activity.RefreshFullActive();\n }\n });\n\n // Debounce logic\n private CancellationTokenSource? _debounceCts;\n private async void DebounceFilter()\n {\n _debounceCts?.Cancel();\n _debounceCts?.Dispose();\n _debounceCts = new CancellationTokenSource();\n var token = _debounceCts.Token;\n\n try\n {\n await Task.Delay(300, token); // 300ms debounce\n\n if (!token.IsCancellationRequested)\n {\n ApplyFilter();\n }\n }\n catch (OperationCanceledException)\n {\n // ignore\n }\n }\n\n private readonly string[] _lastSearchText = [string.Empty, string.Empty];\n\n private void ApplyFilter()\n {\n _trimSearchText = SearchText.Trim();\n _lastSearchText[SubIndex] = _trimSearchText;\n\n // initialize filter lazily\n _filteredSubs[SubIndex].Filter ??= SubFilter;\n _filteredSubs[SubIndex].Refresh();\n\n int count = _filteredSubs[SubIndex].Count;\n HitCount = count > 0 ? $\"{count} hits\" : \"No hits\";\n\n if (SubManager.SelectedSub != null && _filteredSubs[SubIndex].MoveCurrentTo(SubManager.SelectedSub))\n {\n // scroll to current playing item\n var prev = SubManager.SelectedSub;\n SubManager.SelectedSub = null;\n SubManager.SelectedSub = prev;\n }\n else\n {\n // scroll to top\n if (!_filteredSubs[SubIndex].IsEmpty)\n {\n RequestScrollToTop?.Invoke(this, EventArgs.Empty);\n }\n }\n }\n\n private bool SubFilter(object obj)\n {\n if (_trimSearchText.Length == 0) return true;\n if (obj is not SubtitleData sub) return false;\n\n string? source = FL.Config.SidebarShowOriginalText ? sub.Text : sub.DisplayText;\n return source?.IndexOf(_trimSearchText, StringComparison.OrdinalIgnoreCase) >= 0;\n }\n}\n"], ["/LLPlayer/FlyleafLib/Engine/Engine.Video.cs", "using System;\nusing System.Collections.Generic;\nusing System.Collections.ObjectModel;\n\nusing Vortice.DXGI;\n\nusing FlyleafLib.MediaFramework.MediaDevice;\n\nnamespace FlyleafLib;\n\npublic class VideoEngine\n{\n /// \n /// List of Video Capture Devices\n /// \n public ObservableCollection\n CapDevices { get; set; } = new();\n public void RefreshCapDevices() => VideoDevice.RefreshDevices();\n\n /// \n /// List of GPU Adpaters \n /// \n public Dictionary\n GPUAdapters { get; private set; }\n\n /// \n /// List of GPU Outputs from default GPU Adapter (Note: will no be updated on screen connect/disconnect)\n /// \n public List Screens { get; private set; } = new List();\n\n internal IDXGIFactory2 Factory;\n\n internal VideoEngine()\n {\n if (DXGI.CreateDXGIFactory1(out Factory).Failure)\n throw new InvalidOperationException(\"Cannot create IDXGIFactory1\");\n\n GPUAdapters = GetAdapters();\n }\n\n private Dictionary GetAdapters()\n {\n Dictionary adapters = new();\n\n string dump = \"\";\n\n for (uint i=0; Factory.EnumAdapters1(i, out var adapter).Success; i++)\n {\n bool hasOutput = false;\n\n List outputs = new();\n\n int maxHeight = 0;\n for (uint o=0; adapter.EnumOutputs(o, out var output).Success; o++)\n {\n GPUOutput gpout = new()\n {\n Id = GPUOutput.GPUOutputIdGenerator++,\n DeviceName= output.Description.DeviceName,\n Left = output.Description.DesktopCoordinates.Left,\n Top = output.Description.DesktopCoordinates.Top,\n Right = output.Description.DesktopCoordinates.Right,\n Bottom = output.Description.DesktopCoordinates.Bottom,\n IsAttached= output.Description.AttachedToDesktop,\n Rotation = (int)output.Description.Rotation\n };\n\n if (maxHeight < gpout.Height)\n maxHeight = gpout.Height;\n\n outputs.Add(gpout);\n\n if (gpout.IsAttached)\n hasOutput = true;\n\n output.Dispose();\n }\n\n if (Screens.Count == 0 && outputs.Count > 0)\n Screens = outputs;\n\n adapters[adapter.Description1.Luid] = new GPUAdapter()\n {\n SystemMemory = adapter.Description1.DedicatedSystemMemory.Value,\n VideoMemory = adapter.Description1.DedicatedVideoMemory.Value,\n SharedMemory = adapter.Description1.SharedSystemMemory.Value,\n Vendor = VendorIdStr(adapter.Description1.VendorId),\n Description = adapter.Description1.Description,\n Id = adapter.Description1.DeviceId,\n Luid = adapter.Description1.Luid,\n MaxHeight = maxHeight,\n HasOutput = hasOutput,\n Outputs = outputs\n };\n\n dump += $\"[#{i+1}] {adapters[adapter.Description1.Luid]}\\r\\n\";\n\n adapter.Dispose();\n }\n\n Engine.Log.Info($\"GPU Adapters\\r\\n{dump}\");\n\n return adapters;\n }\n\n // Use instead System.Windows.Forms.Screen.FromPoint\n public GPUOutput GetScreenFromPosition(int top, int left)\n {\n foreach(var screen in Screens)\n {\n if (top >= screen.Top && top <= screen.Bottom && left >= screen.Left && left <= screen.Right)\n return screen;\n }\n\n return null;\n }\n\n private static string VendorIdStr(uint vendorId)\n {\n switch (vendorId)\n {\n case 0x1002:\n return \"ATI\";\n case 0x10DE:\n return \"NVIDIA\";\n case 0x1106:\n return \"VIA\";\n case 0x8086:\n return \"Intel\";\n case 0x5333:\n return \"S3 Graphics\";\n case 0x4D4F4351:\n return \"Qualcomm\";\n default:\n return \"Unknown\";\n }\n }\n}\n"], ["/LLPlayer/LLPlayer/Controls/WordPopup.xaml.cs", "using System.ComponentModel;\nusing System.Diagnostics;\nusing System.Runtime.CompilerServices;\nusing System.Windows;\nusing System.Windows.Controls;\nusing System.Windows.Controls.Primitives;\nusing System.Windows.Input;\nusing System.Windows.Threading;\nusing FlyleafLib;\nusing FlyleafLib.MediaPlayer;\nusing FlyleafLib.MediaPlayer.Translation;\nusing FlyleafLib.MediaPlayer.Translation.Services;\nusing LLPlayer.Extensions;\nusing LLPlayer.Services;\n\nnamespace LLPlayer.Controls;\n\npublic partial class WordPopup : UserControl, INotifyPropertyChanged\n{\n public FlyleafManager FL { get; }\n private ITranslateService? _translateService;\n private readonly TranslateServiceFactory _translateServiceFactory;\n private PDICSender? _pdicSender;\n private readonly Lock _locker = new();\n\n private string _clickedWords = string.Empty;\n private string _clickedText = string.Empty;\n\n private CancellationTokenSource? _cts;\n private readonly Dictionary _translateCache = new();\n private string? _lastSearchActionUrl;\n\n public WordPopup()\n {\n InitializeComponent();\n\n FL = ((App)Application.Current).Container.Resolve();\n\n FL.Player.PropertyChanged += Player_OnPropertyChanged;\n\n _translateServiceFactory = new TranslateServiceFactory(FL.PlayerConfig.Subtitles);\n\n FL.PlayerConfig.Subtitles.PropertyChanged += SubtitlesOnPropertyChanged;\n FL.PlayerConfig.Subtitles.TranslateChatConfig.PropertyChanged += ChatConfigOnPropertyChanged;\n FL.Player.SubtitlesManager[0].PropertyChanged += SubManagerOnPropertyChanged;\n FL.Player.SubtitlesManager[1].PropertyChanged += SubManagerOnPropertyChanged;\n FL.Config.Subs.PropertyChanged += SubsOnPropertyChanged;\n\n InitializeContextMenu();\n }\n\n public bool IsLoading { get; set => Set(ref field, value); }\n\n public bool IsOpen { get; set => Set(ref field, value); }\n\n public UIElement? PopupPlacementTarget { get; set => Set(ref field, value); }\n\n public double PopupHorizontalOffset { get; set => Set(ref field, value); }\n\n public double PopupVerticalOffset { get; set => Set(ref field, value); }\n\n public ContextMenu? PopupContextMenu { get; set => Set(ref field, value); }\n public ContextMenu? WordContextMenu { get; set => Set(ref field, value); }\n\n public bool IsSidebar { get; set; }\n\n private void SubtitlesOnPropertyChanged(object? sender, PropertyChangedEventArgs e)\n {\n switch (e.PropertyName)\n {\n case nameof(Config.SubtitlesConfig.TranslateWordServiceType):\n case nameof(Config.SubtitlesConfig.TranslateTargetLanguage):\n case nameof(Config.SubtitlesConfig.LanguageFallbackPrimary):\n // Apply translating settings changes\n Clear();\n break;\n }\n }\n\n private void ChatConfigOnPropertyChanged(object? sender, PropertyChangedEventArgs e)\n {\n // Apply translating settings changes\n Clear();\n }\n\n private void SubManagerOnPropertyChanged(object? sender, PropertyChangedEventArgs e)\n {\n if (e.PropertyName == nameof(SubManager.Language))\n {\n // Apply source language changes\n Clear();\n }\n }\n\n private void SubsOnPropertyChanged(object? sender, PropertyChangedEventArgs e)\n {\n if (e.PropertyName == nameof(AppConfigSubs.WordMenuActions))\n {\n // Apply word action settings changes\n InitializeContextMenu();\n }\n }\n\n private void Clear()\n {\n _translateService?.Dispose();\n _translateService = null;\n // clear cache\n _translateCache.Clear();\n }\n\n private void InitializeContextMenu()\n {\n var contextMenuStyle = (Style)FindResource(\"FlyleafContextMenu\");\n\n ContextMenu popupMenu = new()\n {\n Placement = PlacementMode.Mouse,\n Style = contextMenuStyle\n };\n\n SetupContextMenu(popupMenu);\n PopupContextMenu = popupMenu;\n\n ContextMenu wordMenu = new()\n {\n Placement = PlacementMode.Mouse,\n Style = contextMenuStyle\n };\n\n SetupContextMenu(wordMenu);\n WordContextMenu = wordMenu;\n }\n\n private void SetupContextMenu(ContextMenu contextMenu)\n {\n IEnumerable actions = FL.Config.Subs.WordMenuActions.Where(a => a.IsEnabled);\n foreach (IMenuAction action in actions)\n {\n MenuItem menuItem = new() { Header = action.Title };\n\n // Initialize default action at the top\n // TODO: L: want to make the default action bold.\n if (_lastSearchActionUrl == null && action is SearchMenuAction sa)\n {\n // Only word search available\n if (sa.Url.Contains(\"%w\") || sa.Url.Contains(\"%lw\"))\n {\n _lastSearchActionUrl = sa.Url;\n }\n }\n\n menuItem.Click += (o, args) =>\n {\n if (action is SearchMenuAction searchAction)\n {\n // Only word search available\n if (searchAction.Url.Contains(\"%w\") || searchAction.Url.Contains(\"%lw\"))\n {\n _lastSearchActionUrl = searchAction.Url;\n }\n\n OpenWeb(searchAction.Url, _clickedWords, _clickedText);\n }\n else if (action is ClipboardMenuAction clipboardAction)\n {\n CopyToClipboard(_clickedWords, clipboardAction.ToLower);\n }\n else if (action is ClipboardAllMenuAction clipboardAllAction)\n {\n CopyToClipboard(_clickedText, clipboardAllAction.ToLower);\n }\n };\n contextMenu.Items.Add(menuItem);\n }\n }\n\n // Click on video screen to close pop-up\n private void Player_OnPropertyChanged(object? sender, PropertyChangedEventArgs args)\n {\n if (args.PropertyName == nameof(FL.Player.Status) && FL.Player.Status == Status.Playing)\n {\n IsOpen = false;\n }\n }\n\n private async ValueTask TranslateWithCache(string text, WordClickedEventArgs e, CancellationToken token)\n {\n // already translated by translator\n if (e.IsTranslated)\n {\n return text;\n }\n\n var srcLang = FL.Player.SubtitlesManager[e.SubIndex].Language;\n var targetLang = FL.PlayerConfig.Subtitles.TranslateTargetLanguage;\n\n // Not set language or same language\n if (srcLang == null || srcLang.ISO6391 == targetLang.ToISO6391())\n {\n return text;\n }\n\n string lower = text.ToLower();\n if (_translateCache.TryGetValue(lower, out var cache))\n {\n return cache;\n }\n\n if (_translateService == null)\n {\n try\n {\n var service = _translateServiceFactory.GetService(FL.PlayerConfig.Subtitles.TranslateWordServiceType, true);\n service.Initialize(srcLang, targetLang);\n _translateService = service;\n }\n catch (TranslationConfigException ex)\n {\n Clear();\n ErrorDialogHelper.ShowKnownErrorPopup(ex.Message, KnownErrorType.Configuration);\n\n return text;\n }\n }\n\n try\n {\n string result = await _translateService.TranslateAsync(text, token);\n _translateCache.TryAdd(lower, result);\n\n return result;\n }\n catch (TranslationException ex)\n {\n ErrorDialogHelper.ShowUnknownErrorPopup(ex.Message, UnknownErrorType.Translation, ex);\n\n return text;\n }\n }\n\n public async Task OnWordClicked(WordClickedEventArgs e)\n {\n _clickedWords = e.Words;\n _clickedText = e.Text;\n\n if (FL.Player.Status == Status.Playing)\n {\n FL.Player.Pause();\n }\n\n if (e.Mouse is MouseClick.Left or MouseClick.Middle)\n {\n switch (FL.Config.Subs.WordClickActionMethod)\n {\n case WordClickAction.Clipboard:\n CopyToClipboard(e.Words);\n break;\n\n case WordClickAction.ClipboardAll:\n CopyToClipboard(e.Text);\n break;\n\n default:\n await Popup(e);\n break;\n }\n }\n else if (e.Mouse == MouseClick.Right)\n {\n WordContextMenu!.IsOpen = true;\n }\n }\n\n private async Task Popup(WordClickedEventArgs e)\n {\n if (FL.Config.Subs.WordCopyOnSelected)\n {\n CopyToClipboard(e.Words);\n }\n\n if (FL.Config.Subs.WordClickActionMethod == WordClickAction.PDIC && e.IsWord)\n {\n if (_pdicSender == null)\n {\n // Initialize PDIC lazily\n lock (_locker)\n {\n _pdicSender ??= ((App)Application.Current).Container.Resolve();\n }\n }\n\n _ = _pdicSender.SendWithPipe(e.Text, e.WordOffset + 1);\n return;\n }\n\n if (_cts != null)\n {\n // Canceled if running ahead\n _cts.Cancel();\n _cts.Dispose();\n }\n\n _cts = new CancellationTokenSource();\n\n string source = e.Words;\n\n IsLoading = true;\n\n SourceText.Text = source;\n TranslationText.Text = \"\";\n\n if (IsSidebar && e.Sender is SelectableTextBox)\n {\n var listBoxItem = UIHelper.FindParent(e.Sender);\n if (listBoxItem != null)\n {\n PopupPlacementTarget = listBoxItem;\n }\n }\n\n if (FL.Config.Subs.WordLastSearchOnSelected)\n {\n if (Keyboard.Modifiers == FL.Config.Subs.WordLastSearchOnSelectedModifier)\n {\n if (_lastSearchActionUrl != null)\n {\n OpenWeb(_lastSearchActionUrl, source);\n }\n }\n }\n\n IsOpen = true;\n\n await UpdatePosition();\n\n try\n {\n string result = await TranslateWithCache(source, e, _cts.Token);\n TranslationText.Text = result;\n IsLoading = false;\n }\n catch (OperationCanceledException)\n {\n return;\n }\n\n await UpdatePosition();\n\n return;\n\n async Task UpdatePosition()\n {\n // ActualWidth is updated asynchronously, so it needs to be offloaded in the Dispatcher.\n await Dispatcher.BeginInvoke(() =>\n {\n if (IsSidebar && PopupPlacementTarget != null)\n {\n // for sidebar\n PopupVerticalOffset = (((ListBoxItem)PopupPlacementTarget).ActualHeight - ActualHeight) / 2;\n PopupHorizontalOffset = -ActualWidth - 10;\n }\n else\n {\n // for subtitle\n PopupHorizontalOffset = e.WordsX + ((e.WordsWidth - ActualWidth) / 2);\n PopupVerticalOffset = -ActualHeight;\n }\n\n }, DispatcherPriority.Background);\n }\n }\n\n private void CloseButton_OnMouseLeftButtonUp(object sender, MouseButtonEventArgs e)\n {\n IsOpen = false;\n }\n\n private void SourceText_OnMouseLeftButtonUp(object sender, MouseButtonEventArgs e)\n {\n if (_lastSearchActionUrl != null)\n {\n OpenWeb(_lastSearchActionUrl, SourceText.Text);\n }\n }\n\n private static void CopyToClipboard(string text, bool toLower = false)\n {\n if (string.IsNullOrWhiteSpace(text))\n {\n return;\n }\n\n if (toLower)\n {\n text = text.ToLower();\n }\n\n // copy word\n try\n {\n // slow (10ms)\n //Clipboard.SetText(text);\n\n WindowsClipboard.SetText(text);\n }\n catch\n {\n // ignored\n }\n }\n\n private static void OpenWeb(string url, string words, string sentence = \"\")\n {\n if (url.Contains(\"%lw\"))\n {\n url = url.Replace(\"%lw\", Uri.EscapeDataString(words.ToLower()));\n }\n\n if (url.Contains(\"%w\"))\n {\n url = url.Replace(\"%w\", Uri.EscapeDataString(words));\n }\n\n if (url.Contains(\"%s\"))\n {\n url = url.Replace(\"%s\", Uri.EscapeDataString(sentence));\n }\n\n Process.Start(new ProcessStartInfo\n {\n FileName = url,\n UseShellExecute = true\n });\n }\n\n #region INotifyPropertyChanged\n public event PropertyChangedEventHandler? PropertyChanged;\n\n protected virtual void OnPropertyChanged([CallerMemberName] string? propertyName = null)\n {\n PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));\n }\n\n protected bool Set(ref T field, T value, [CallerMemberName] string? propertyName = null)\n {\n if (EqualityComparer.Default.Equals(field, value))\n return false;\n field = value;\n OnPropertyChanged(propertyName);\n return true;\n }\n #endregion\n}\n"], ["/LLPlayer/LLPlayer/Converters/FlyleafConverters.cs", "using System.Globalization;\nusing System.Windows;\nusing System.Windows.Controls.Primitives;\nusing System.Windows.Data;\nusing System.Windows.Media;\nusing FlyleafLib;\nusing static FlyleafLib.MediaFramework.MediaDemuxer.Demuxer;\n\nnamespace LLPlayer.Converters;\n\n[ValueConversion(typeof(int), typeof(Qualities))]\npublic class QualityToLevelsConverter : IValueConverter\n{\n public enum Qualities\n {\n None,\n Low,\n Med,\n High,\n _4k\n }\n\n public object Convert(object value, Type targetType, object parameter, CultureInfo culture)\n {\n int videoHeight = (int)value;\n\n if (videoHeight > 1080)\n return Qualities._4k;\n if (videoHeight > 720)\n return Qualities.High;\n if (videoHeight == 720)\n return Qualities.Med;\n\n return Qualities.Low;\n }\n public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture) { throw new NotImplementedException(); }\n}\n\n[ValueConversion(typeof(int), typeof(Volumes))]\npublic class VolumeToLevelsConverter : IValueConverter\n{\n public enum Volumes\n {\n Mute,\n Low,\n Med,\n High\n }\n\n public object Convert(object value, Type targetType, object parameter, CultureInfo culture)\n {\n int volume = (int)value;\n\n if (volume == 0)\n return Volumes.Mute;\n if (volume > 99)\n return Volumes.High;\n if (volume > 49)\n return Volumes.Med;\n return Volumes.Low;\n }\n public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture) { throw new NotImplementedException(); }\n}\n\npublic class SumConverter : IMultiValueConverter\n{\n public object Convert(object[] values, Type targetType, object parameter, CultureInfo culture)\n {\n double sum = 0;\n\n if (values == null)\n return sum;\n\n foreach (object value in values)\n {\n if (value == DependencyProperty.UnsetValue)\n continue;\n sum += (double)value;\n }\n\n return sum;\n }\n\n public object[] ConvertBack(object value, Type[] targetTypes, object parameter, CultureInfo culture)\n => throw new NotImplementedException();\n}\n\npublic class PlaylistItemsConverter : IMultiValueConverter\n{\n public object Convert(object[] values, Type targetType, object parameter, CultureInfo culture)\n {\n return $\"Playlist ({values[0]}/{values[1]})\";\n }\n\n public object[] ConvertBack(object value, Type[] targetTypes, object parameter, CultureInfo culture)\n => throw new NotImplementedException();\n}\n\n[ValueConversion(typeof(Color), typeof(string))]\npublic class ColorToHexConverter : IValueConverter\n{\n public object? Convert(object? value, Type targetType, object? parameter, CultureInfo culture)\n {\n if (value is null)\n return null;\n\n string UpperHexString(int i) => i.ToString(\"X2\").ToUpper();\n Color color = (Color)value;\n string hex = UpperHexString(color.R) +\n UpperHexString(color.G) +\n UpperHexString(color.B);\n return hex;\n }\n\n public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)\n {\n try\n {\n return ColorConverter.ConvertFromString(\"#\" + value.ToString());\n }\n catch (Exception)\n {\n // ignored\n }\n\n return Binding.DoNothing;\n }\n}\n\npublic class Tuple3Converter : IMultiValueConverter\n{\n public object Convert(object[] values, Type targetType, object parameter, CultureInfo culture)\n {\n return (values[0], values[1], values[2]);\n }\n\n public object[] ConvertBack(object value, Type[] targetTypes, object parameter, CultureInfo culture)\n {\n throw new NotImplementedException();\n }\n}\n\npublic class SubIndexToIsEnabledConverter : IMultiValueConverter\n{\n public object Convert(object[] values, Type targetType, object parameter, CultureInfo culture)\n {\n if (values.Any(x => x == DependencyProperty.UnsetValue))\n return DependencyProperty.UnsetValue;\n\n // values[0] = Tag (index)\n // values[1] = IsPrimaryEnabled\n // values[2] = IsSecondaryEnabled\n int index = int.Parse((string)values[0]);\n bool isPrimaryEnabled = (bool)values[1];\n bool isSecondaryEnabled = (bool)values[2];\n\n return index == 0 ? isPrimaryEnabled : isSecondaryEnabled;\n }\n\n public object[] ConvertBack(object value, Type[] targetTypes, object parameter, CultureInfo culture)\n {\n throw new NotImplementedException();\n }\n}\n\n[ValueConversion(typeof(IEnumerable), typeof(DoubleCollection))]\npublic class ChaptersToTicksConverter : IValueConverter\n{\n public object Convert(object value, Type targetType, object parameter, CultureInfo culture)\n {\n if (value is IEnumerable chapters)\n {\n // Convert tick count to seconds\n List secs = chapters.Select(c => c.StartTime / 10000000.0).ToList();\n if (secs.Count <= 1)\n {\n return Binding.DoNothing;\n }\n\n return new DoubleCollection(secs);\n }\n\n return Binding.DoNothing;\n }\n\n public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)\n {\n throw new NotImplementedException();\n }\n}\n\n[ValueConversion(typeof(IEnumerable), typeof(TickPlacement))]\npublic class ChaptersToTickPlacementConverter : IValueConverter\n{\n public TickPlacement TickPlacement { get; set; }\n\n public object Convert(object value, Type targetType, object parameter, CultureInfo culture)\n {\n if (value is IEnumerable chapters && chapters.Count() >= 2)\n {\n return TickPlacement;\n }\n\n return TickPlacement.None;\n }\n\n public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)\n {\n throw new NotImplementedException();\n }\n}\n\npublic class AspectRatioIsCheckedConverter : IMultiValueConverter\n{\n // values[0]: SelectedAspectRatio, values[1]: current AspectRatio\n public object Convert(object[] values, Type targetType, object parameter, CultureInfo culture)\n {\n if (values.Length < 2)\n {\n return false;\n }\n\n if (values[0] is AspectRatio selected && values[1] is AspectRatio current)\n {\n return selected.Equals(current);\n }\n return false;\n }\n\n public object[] ConvertBack(object value, Type[] targetTypes, object parameter, CultureInfo culture)\n {\n throw new NotImplementedException();\n }\n}\n"], ["/LLPlayer/FlyleafLib/MediaFramework/MediaFrame/SubtitlesFrame.cs", "using System.Collections.Generic;\nusing System.Drawing;\nusing System.Globalization;\n\nnamespace FlyleafLib.MediaFramework.MediaFrame;\n\npublic class SubtitlesFrame : FrameBase\n{\n public bool isBitmap;\n public uint duration;\n public string text;\n public List subStyles;\n public AVSubtitle sub;\n public SubtitlesFrameBitmap bitmap;\n\n // for translation switch\n public bool isTranslated;\n}\n\npublic class SubtitlesFrameBitmap\n{\n // Buffer to hold decoded pixels\n public byte[] data;\n public int width;\n public int height;\n public int x;\n public int y;\n}\n\npublic struct SubStyle\n{\n public SubStyles style;\n public Color value;\n\n public int from;\n public int len;\n\n public SubStyle(int from, int len, Color value) : this(SubStyles.COLOR, from, len, value) { }\n public SubStyle(SubStyles style, int from = -1, int len = -1, Color? value = null)\n {\n this.style = style;\n this.value = value == null ? Color.White : (Color)value;\n this.from = from;\n this.len = len;\n }\n}\n\npublic enum SubStyles\n{\n BOLD,\n ITALIC,\n UNDERLINE,\n STRIKEOUT,\n FONTSIZE,\n FONTNAME,\n COLOR\n}\n\n/// \n/// Default Subtitles Parser\n/// \npublic static class ParseSubtitles\n{\n public static void Parse(SubtitlesFrame sFrame)\n {\n sFrame.text = SSAtoSubStyles(sFrame.text, out var subStyles);\n sFrame.subStyles = subStyles;\n }\n public static string SSAtoSubStyles(string s, out List styles)\n {\n int pos = 0;\n string sout = \"\";\n styles = new List();\n\n SubStyle bold = new(SubStyles.BOLD);\n SubStyle italic = new(SubStyles.ITALIC);\n SubStyle underline = new(SubStyles.UNDERLINE);\n SubStyle strikeout = new(SubStyles.STRIKEOUT);\n SubStyle color = new(SubStyles.COLOR);\n\n //SubStyle fontname = new SubStyle(SubStyles.FONTNAME);\n //SubStyle fontsize = new SubStyle(SubStyles.FONTSIZE);\n\n if (string.IsNullOrEmpty(s))\n {\n return sout;\n }\n\n s = s.LastIndexOf(\",,\") == -1 ? s : s[(s.LastIndexOf(\",,\") + 2)..].Replace(\"\\\\N\", \"\\n\").Trim();\n\n for (int i = 0; i < s.Length; i++)\n {\n if (s[i] == '{') continue;\n\n if (s[i] == '\\\\' && s[i - 1] == '{')\n {\n int codeLen = s.IndexOf('}', i) - i;\n if (codeLen == -1) continue;\n\n string code = s.Substring(i, codeLen).Trim();\n\n switch (code[1])\n {\n case 'c':\n if (code.Length == 2)\n {\n if (color.from == -1) break;\n\n color.len = pos - color.from;\n if (color.value != Color.Transparent)\n styles.Add(color);\n\n color = new SubStyle(SubStyles.COLOR);\n }\n else\n {\n color.from = pos;\n color.value = Color.Transparent;\n if (code.Length < 7) break;\n\n int colorEnd = code.LastIndexOf('&');\n if (colorEnd < 6) break;\n\n string hexColor = code[4..colorEnd];\n\n int red = int.Parse(hexColor.Substring(hexColor.Length - 2, 2), NumberStyles.HexNumber);\n int green = 0;\n int blue = 0;\n\n if (hexColor.Length - 2 > 0)\n {\n hexColor = hexColor[..^2];\n if (hexColor.Length == 1)\n hexColor = \"0\" + hexColor;\n\n green = int.Parse(hexColor.Substring(hexColor.Length - 2, 2), NumberStyles.HexNumber);\n }\n\n if (hexColor.Length - 2 > 0)\n {\n hexColor = hexColor[..^2];\n if (hexColor.Length == 1)\n hexColor = \"0\" + hexColor;\n\n blue = int.Parse(hexColor.Substring(hexColor.Length - 2, 2), NumberStyles.HexNumber);\n }\n\n color.value = Color.FromArgb(255, red, green, blue);\n }\n break;\n\n case 'b':\n if (code[2] == '0')\n {\n if (bold.from == -1) break;\n\n bold.len = pos - bold.from;\n styles.Add(bold);\n bold = new SubStyle(SubStyles.BOLD);\n }\n else\n {\n bold.from = pos;\n //bold.value = code.Substring(2, code.Length-2);\n }\n\n break;\n\n case 'u':\n if (code[2] == '0')\n {\n if (underline.from == -1) break;\n\n underline.len = pos - underline.from;\n styles.Add(underline);\n underline = new SubStyle(SubStyles.UNDERLINE);\n }\n else\n {\n underline.from = pos;\n }\n\n break;\n\n case 's':\n if (code[2] == '0')\n {\n if (strikeout.from == -1) break;\n\n strikeout.len = pos - strikeout.from;\n styles.Add(strikeout);\n strikeout = new SubStyle(SubStyles.STRIKEOUT);\n }\n else\n {\n strikeout.from = pos;\n }\n\n break;\n\n case 'i':\n if (code.Length > 2 && code[2] == '0')\n {\n if (italic.from == -1) break;\n\n italic.len = pos - italic.from;\n styles.Add(italic);\n italic = new SubStyle(SubStyles.ITALIC);\n }\n else\n {\n italic.from = pos;\n }\n\n break;\n }\n\n i += codeLen;\n continue;\n }\n\n sout += s[i];\n pos++;\n }\n\n // Non-Closing Codes\n int soutPostLast = sout.Length;\n if (bold.from != -1) { bold.len = soutPostLast - bold.from; styles.Add(bold); }\n if (italic.from != -1) { italic.len = soutPostLast - italic.from; styles.Add(italic); }\n if (strikeout.from != -1) { strikeout.len = soutPostLast - strikeout.from; styles.Add(strikeout); }\n if (underline.from != -1) { underline.len = soutPostLast - underline.from; styles.Add(underline); }\n if (color.from != -1 && color.value != Color.Transparent) { color.len = soutPostLast - color.from; styles.Add(color); }\n\n // Greek issue?\n sout = sout.Replace(\"ʼ\", \"Ά\");\n\n return sout;\n }\n}\n"], ["/LLPlayer/FlyleafLib/MediaPlayer/Translation/Services/OpenAIBaseTranslateService.cs", "using System.Collections.Concurrent;\nusing System.Collections.Generic;\nusing System.Diagnostics;\nusing System.Linq;\nusing System.Net.Http;\nusing System.Text;\nusing System.Text.Encodings.Web;\nusing System.Text.Json;\nusing System.Text.Json.Nodes;\nusing System.Text.Json.Serialization;\nusing System.Threading;\nusing System.Threading.Tasks;\n\nnamespace FlyleafLib.MediaPlayer.Translation.Services;\n\n#nullable enable\n\n// All LLM translation use this class\n// Currently only supports OpenAI compatible API\npublic class OpenAIBaseTranslateService : ITranslateService\n{\n private readonly HttpClient _httpClient;\n private readonly OpenAIBaseTranslateSettings _settings;\n private readonly TranslateChatConfig _chatConfig;\n private readonly bool _wordMode;\n\n private ChatTranslateMethod TranslateMethod => _chatConfig.TranslateMethod;\n\n public OpenAIBaseTranslateService(OpenAIBaseTranslateSettings settings, TranslateChatConfig chatConfig, bool wordMode)\n {\n _httpClient = settings.GetHttpClient();\n _settings = settings;\n _chatConfig = chatConfig;\n _wordMode = wordMode;\n }\n\n private string? _basePrompt;\n private readonly ConcurrentQueue _messageQueue = new();\n\n private static readonly JsonSerializerOptions JsonOptions = new()\n {\n DefaultIgnoreCondition = JsonIgnoreCondition.WhenWritingNull,\n Encoder = JavaScriptEncoder.UnsafeRelaxedJsonEscaping\n };\n\n public TranslateServiceType ServiceType => _settings.ServiceType;\n\n public void Dispose()\n {\n _httpClient.Dispose();\n }\n\n public void Initialize(Language src, TargetLanguage target)\n {\n (TranslateLanguage srcLang, TranslateLanguage targetLang) = this.TryGetLanguage(src, target);\n\n // setup prompt\n string prompt = !_wordMode && TranslateMethod == ChatTranslateMethod.KeepContext\n ? _chatConfig.PromptKeepContext\n : _chatConfig.PromptOneByOne;\n\n string targetLangName = _chatConfig.IncludeTargetLangRegion\n ? target.DisplayName() : targetLang.Name;\n\n _basePrompt = prompt\n .Replace(\"{source_lang}\", srcLang.Name)\n .Replace(\"{target_lang}\", targetLangName);\n }\n\n public async Task TranslateAsync(string text, CancellationToken token)\n {\n if (!_wordMode && TranslateMethod == ChatTranslateMethod.KeepContext)\n {\n return await DoKeepContext(text, token);\n }\n\n return await DoOneByOne(text, token);\n }\n\n private async Task DoKeepContext(string text, CancellationToken token)\n {\n if (_basePrompt == null)\n throw new InvalidOperationException(\"must be initialized\");\n\n // Trim message history if required\n while (_messageQueue.Count / 2 > _chatConfig.SubtitleContextCount)\n {\n if (_chatConfig.ContextRetainPolicy == ChatContextRetainPolicy.KeepSize)\n {\n Debug.Assert(_messageQueue.Count >= 2);\n\n // user\n _messageQueue.TryDequeue(out _);\n // assistant\n _messageQueue.TryDequeue(out _);\n }\n else if (_chatConfig.ContextRetainPolicy == ChatContextRetainPolicy.Reset)\n {\n // clear\n _messageQueue.Clear();\n }\n }\n\n List messages = new(_messageQueue.Count + 2)\n {\n new OpenAIMessage { role = \"system\", content = _basePrompt },\n };\n\n // add history\n messages.AddRange(_messageQueue);\n\n // add new message\n OpenAIMessage newMessage = new() { role = \"user\", content = text };\n messages.Add(newMessage);\n\n string reply = await SendChatRequest(\n _httpClient, _settings, messages.ToArray(), token);\n\n // add to message history if success\n _messageQueue.Enqueue(newMessage);\n _messageQueue.Enqueue(new OpenAIMessage { role = \"assistant\", content = reply });\n\n return reply;\n }\n\n private async Task DoOneByOne(string text, CancellationToken token)\n {\n if (_basePrompt == null)\n throw new InvalidOperationException(\"must be initialized\");\n\n string prompt = _basePrompt.Replace(\"{source_text}\", text);\n\n OpenAIMessage[] messages =\n [\n new() { role = \"user\", content = prompt }\n ];\n\n return await SendChatRequest(_httpClient, _settings, messages, token);\n }\n\n public static async Task Hello(OpenAIBaseTranslateSettings settings)\n {\n using HttpClient client = settings.GetHttpClient();\n\n OpenAIMessage[] messages =\n [\n new() { role = \"user\", content = \"Hello\" }\n ];\n\n return await SendChatRequest(client, settings, messages, CancellationToken.None);\n }\n\n private static async Task SendChatRequest(\n HttpClient client,\n OpenAIBaseTranslateSettings settings,\n OpenAIMessage[] messages,\n CancellationToken token)\n {\n string jsonResultString = string.Empty;\n int statusCode = -1;\n\n // Create the request payload\n OpenAIRequest request = new()\n {\n model = settings.Model,\n stream = false,\n messages = messages,\n\n temperature = settings.TemperatureManual ? settings.Temperature : null,\n top_p = settings.TopPManual ? settings.TopP : null,\n max_completion_tokens = settings.MaxCompletionTokens,\n max_tokens = settings.MaxTokens,\n };\n\n if (!settings.ModelRequired && string.IsNullOrWhiteSpace(settings.Model))\n {\n request.model = null;\n }\n\n try\n {\n // Convert to JSON\n string jsonContent = JsonSerializer.Serialize(request, JsonOptions);\n using var content = new StringContent(jsonContent, Encoding.UTF8, \"application/json\");\n using var result = await client.PostAsync(settings.ChatPath, content, token);\n\n jsonResultString = await result.Content.ReadAsStringAsync(token);\n\n statusCode = (int)result.StatusCode;\n result.EnsureSuccessStatusCode();\n\n OpenAIResponse? chatResponse = JsonSerializer.Deserialize(jsonResultString);\n string reply = chatResponse!.choices[0].message.content;\n if (settings.ReasonStripRequired)\n {\n var stripped = ChatReplyParser.StripReasoning(reply);\n return stripped.Trim().ToString();\n }\n\n return reply.Trim();\n }\n // Distinguish between timeout and cancel errors\n catch (OperationCanceledException ex)\n when (!ex.Message.StartsWith(\"The request was canceled due to the configured HttpClient.Timeout\"))\n {\n // cancel\n throw;\n }\n catch (Exception ex)\n {\n // timeout and other error\n throw new TranslationException($\"Cannot request to {settings.ServiceType}: {ex.Message}\", ex)\n {\n Data =\n {\n [\"status_code\"] = statusCode.ToString(),\n [\"response\"] = jsonResultString\n }\n };\n }\n }\n\n public static async Task> GetLoadedModels(OpenAIBaseTranslateSettings settings)\n {\n using HttpClient client = settings.GetHttpClient(true);\n\n string jsonResultString = string.Empty;\n int statusCode = -1;\n\n // getting models\n try\n {\n using var result = await client.GetAsync(\"/v1/models\");\n\n jsonResultString = await result.Content.ReadAsStringAsync();\n\n statusCode = (int)result.StatusCode;\n result.EnsureSuccessStatusCode();\n\n JsonNode? node = JsonNode.Parse(jsonResultString);\n List models = node![\"data\"]!.AsArray()\n .Select(model => model![\"id\"]!.GetValue())\n .Order()\n .ToList();\n\n return models;\n }\n catch (Exception ex)\n {\n throw new InvalidOperationException($\"get models error: {ex.Message}\", ex)\n {\n Data =\n {\n [\"status_code\"] = statusCode.ToString(),\n [\"response\"] = jsonResultString\n }\n };\n }\n }\n}\n\npublic class OpenAIMessage\n{\n public required string role { get; init; }\n public required string content { get; init; }\n}\n\npublic class OpenAIRequest\n{\n public string? model { get; set; }\n public required OpenAIMessage[] messages { get; init; }\n public required bool stream { get; init; }\n public double? temperature { get; set; }\n public double? top_p { get; set; }\n public int? max_completion_tokens { get; set; }\n public int? max_tokens { get; set; }\n}\n\npublic class OpenAIResponse\n{\n public required OpenAIChoice[] choices { get; init; }\n}\n\npublic class OpenAIChoice\n{\n public required OpenAIMessage message { get; init; }\n}\n\npublic static class ChatReplyParser\n{\n // Target tag names to remove (lowercase)\n private static readonly string[] Tags = [\"think\", \"reason\", \"reasoning\", \"thought\"];\n\n // open/close tag strings from tag names\n private static readonly string[] OpenTags;\n private static readonly string[] CloseTags;\n\n static ChatReplyParser()\n {\n OpenTags = new string[Tags.Length];\n CloseTags = new string[Tags.Length];\n for (int i = 0; i < Tags.Length; i++)\n {\n OpenTags[i] = $\"<{Tags[i]}>\"; // e.g. \"\"\n CloseTags[i] = $\"\"; // e.g. \"\"\n }\n }\n\n /// \n /// Removes a leading reasoning tag if present and returns only the generated message portion.\n /// \n public static ReadOnlySpan StripReasoning(ReadOnlySpan input)\n {\n // Return immediately if it doesn't start with a tag\n if (input.Length == 0 || input[0] != '<')\n {\n return input;\n }\n\n for (int i = 0; i < OpenTags.Length; i++)\n {\n if (input.StartsWith(OpenTags[i], StringComparison.OrdinalIgnoreCase))\n {\n int endIdx = input.IndexOf(CloseTags[i], StringComparison.OrdinalIgnoreCase);\n if (endIdx >= 0)\n {\n int next = endIdx + CloseTags[i].Length;\n // Skip over any consecutive line breaks and whitespace\n while (next < input.Length && char.IsWhiteSpace(input[next]))\n {\n next++;\n }\n return input.Slice(next);\n }\n }\n }\n\n // Return original string if no tag matched\n return input;\n }\n}\n"], ["/LLPlayer/FlyleafLib/MediaFramework/MediaRenderer/Renderer.cs", "using System.Collections.Generic;\nusing System.Runtime.InteropServices;\nusing System.Windows;\n\nusing Vortice;\nusing Vortice.DXGI;\nusing Vortice.Direct3D11;\nusing Vortice.Mathematics;\n\nusing FlyleafLib.MediaFramework.MediaDecoder;\nusing FlyleafLib.MediaFramework.MediaFrame;\nusing FlyleafLib.MediaFramework.MediaStream;\n\nusing ID3D11Device = Vortice.Direct3D11.ID3D11Device;\n\nnamespace FlyleafLib.MediaFramework.MediaRenderer;\n\n/* TODO\n * 1) Attach on every frame video output configuration so we will not have to worry for video codec change etc.\n * this will fix also dynamic video stream change\n * we might have issue with bufRef / ffmpeg texture array on zero copy\n *\n * 2) Use different context/video processor for off rendering so we dont have to reset pixel shaders/viewports etc (review also rtvs for extractor)\n *\n * 3) Add Crop (Left/Right/Top/Bottom) -on Source- support per pixels (easy implemantation with D3D11VP, FlyleafVP requires more research)\n *\n * 4) Improve A/V Sync\n *\n * a. vsync / vblack\n * b. Present can cause a delay (based on device load), consider using more buffers for high frame rates that could minimize the delay\n * c. display refresh rate vs input rate, consider using max latency > 1 ?\n * d. frame drops\n *\n * swapChain.GetFrameStatistics(out var stats);\n * swapChain.LastPresentCount - stats.PresentCount;\n */\n\npublic partial class Renderer : NotifyPropertyChanged, IDisposable\n{\n public Config Config { get; private set;}\n public int ControlWidth { get; private set; }\n public int ControlHeight { get; private set; }\n internal IntPtr ControlHandle;\n\n internal Action\n SwapChainWinUIClbk;\n\n public ID3D11Device Device { get; private set; }\n public bool D3D11VPFailed => vc == null;\n public GPUAdapter GPUAdapter { get; private set; }\n public bool Disposed { get; private set; } = true;\n public bool SCDisposed { get; private set; } = true;\n public int MaxOffScreenTextures\n { get; set; } = 20;\n public VideoDecoder VideoDecoder { get; internal set; }\n public VideoStream VideoStream => VideoDecoder.VideoStream;\n\n public Viewport GetViewport { get; private set; }\n public event EventHandler ViewportChanged;\n\n public CornerRadius CornerRadius { get => cornerRadius; set { if (cornerRadius == value) return; cornerRadius = value; UpdateCornerRadius(); } }\n CornerRadius cornerRadius = new(0);\n CornerRadius zeroCornerRadius = new(0);\n\n public bool IsHDR { get => isHDR; private set { SetUI(ref _IsHDR, value); isHDR = value; } }\n bool _IsHDR, isHDR;\n\n public int SideXPixels { get; private set; }\n public int SideYPixels { get; private set; }\n\n public int PanXOffset { get => panXOffset; set => SetPanX(value); }\n int panXOffset;\n public void SetPanX(int panX, bool refresh = true)\n {\n lock(lockDevice)\n {\n panXOffset = panX;\n\n if (Disposed)\n return;\n\n SetViewport(refresh);\n }\n }\n\n public int PanYOffset { get => panYOffset; set => SetPanY(value); }\n int panYOffset;\n public void SetPanY(int panY, bool refresh = true)\n {\n lock(lockDevice)\n {\n panYOffset = panY;\n\n if (Disposed)\n return;\n\n SetViewport(refresh);\n }\n }\n\n public uint Rotation { get => _RotationAngle;set { lock (lockDevice) UpdateRotation(value); } }\n uint _RotationAngle;\n VideoProcessorRotation _d3d11vpRotation = VideoProcessorRotation.Identity;\n bool rotationLinesize; // if negative should be vertically flipped\n\n public bool HFlip { get => _HFlip;set { _HFlip = value; lock (lockDevice) UpdateRotation(_RotationAngle); } }\n bool _HFlip;\n\n public bool VFlip { get => _VFlip;set { _VFlip = value; lock (lockDevice) UpdateRotation(_RotationAngle); } }\n bool _VFlip;\n\n public VideoProcessors VideoProcessor { get => videoProcessor; private set => SetUI(ref videoProcessor, value); }\n VideoProcessors videoProcessor = VideoProcessors.Flyleaf;\n\n /// \n /// Zoom percentage (100% equals to 1.0)\n /// \n public double Zoom { get => zoom; set => SetZoom(value); }\n double zoom = 1;\n public void SetZoom(double zoom, bool refresh = true)\n {\n lock(lockDevice)\n {\n this.zoom = zoom;\n\n if (Disposed)\n return;\n\n SetViewport(refresh);\n }\n }\n\n public Point ZoomCenter { get => zoomCenter; set => SetZoomCenter(value); }\n Point zoomCenter = ZoomCenterPoint;\n public static Point ZoomCenterPoint = new(0.5, 0.5);\n public void SetZoomCenter(Point p, bool refresh = true)\n {\n lock(lockDevice)\n {\n zoomCenter = p;\n\n if (Disposed)\n return;\n\n if (refresh)\n SetViewport();\n }\n }\n public void SetZoomAndCenter(double zoom, Point p, bool refresh = true)\n {\n lock(lockDevice)\n {\n this.zoom = zoom;\n zoomCenter = p;\n\n if (Disposed)\n return;\n\n if (refresh)\n SetViewport();\n }\n }\n public void SetPanAll(int panX, int panY, uint rotation, double zoom, Point p, bool refresh = true)\n {\n lock(lockDevice)\n {\n panXOffset = panX;\n panYOffset = panY;\n this.zoom = zoom;\n zoomCenter = p;\n UpdateRotation(rotation, false);\n\n if (Disposed)\n return;\n\n if (refresh)\n SetViewport();\n }\n }\n\n public int UniqueId { get; private set; }\n\n public Dictionary\n Filters { get; set; }\n public VideoFrame LastFrame { get; set; }\n public RawRect VideoRect { get; set; }\n\n LogHandler Log;\n\n public Renderer(VideoDecoder videoDecoder, IntPtr handle = new IntPtr(), int uniqueId = -1)\n {\n UniqueId = uniqueId == -1 ? Utils.GetUniqueId() : uniqueId;\n VideoDecoder= videoDecoder;\n Config = videoDecoder.Config;\n Log = new LogHandler((\"[#\" + UniqueId + \"]\").PadRight(8, ' ') + \" [Renderer ] \");\n\n overlayTextureDesc = new()\n {\n Usage = ResourceUsage.Default,\n Width = 0,\n Height = 0,\n Format = Format.B8G8R8A8_UNorm,\n ArraySize = 1,\n MipLevels = 1,\n BindFlags = BindFlags.ShaderResource,\n SampleDescription = new SampleDescription(1, 0)\n };\n\n singleStageDesc = new Texture2DDescription()\n {\n Usage = ResourceUsage.Staging,\n Format = Format.B8G8R8A8_UNorm,\n ArraySize = 1,\n MipLevels = 1,\n BindFlags = BindFlags.None,\n CPUAccessFlags = CpuAccessFlags.Read,\n SampleDescription = new SampleDescription(1, 0),\n\n Width = 0,\n Height = 0\n };\n\n singleGpuDesc = new Texture2DDescription()\n {\n Usage = ResourceUsage.Default,\n Format = Format.B8G8R8A8_UNorm,\n ArraySize = 1,\n MipLevels = 1,\n BindFlags = BindFlags.RenderTarget | BindFlags.ShaderResource,\n SampleDescription = new SampleDescription(1, 0)\n };\n\n wndProcDelegate = new(WndProc);\n wndProcDelegatePtr = Marshal.GetFunctionPointerForDelegate(wndProcDelegate);\n ControlHandle = handle;\n Initialize();\n }\n\n #region Replica Renderer (Expiremental)\n public Renderer child; // allow access to child renderer (not safe)\n Renderer parent;\n public Renderer(Renderer renderer, IntPtr handle, int uniqueId = -1)\n {\n UniqueId = uniqueId == -1 ? Utils.GetUniqueId() : uniqueId;\n Log = new LogHandler((\"[#\" + UniqueId + \"]\").PadRight(8, ' ') + \" [Renderer Repl] \");\n\n renderer.child = this;\n parent = renderer;\n Config = renderer.Config;\n wndProcDelegate = new(WndProc);\n wndProcDelegatePtr = Marshal.GetFunctionPointerForDelegate(wndProcDelegate);\n ControlHandle = handle;\n }\n\n public void SetChildHandle(IntPtr handle)\n {\n lock (lockDevice)\n {\n if (child != null)\n DisposeChild();\n\n if (handle == IntPtr.Zero)\n return;\n\n child = new(this, handle, UniqueId);\n InitializeChildSwapChain();\n }\n }\n #endregion\n}\n"], ["/LLPlayer/LLPlayer/ViewModels/SelectLanguageDialogVM.cs", "using System.Collections.ObjectModel;\nusing System.ComponentModel;\nusing System.Windows.Data;\nusing FlyleafLib;\nusing LLPlayer.Extensions;\nusing LLPlayer.Services;\n\nnamespace LLPlayer.ViewModels;\n\npublic class SelectLanguageDialogVM : Bindable, IDialogAware\n{\n public FlyleafManager FL { get; }\n\n public SelectLanguageDialogVM(FlyleafManager fl)\n {\n FL = fl;\n\n _filteredAvailableLanguages = CollectionViewSource.GetDefaultView(AvailableLanguages);\n _filteredAvailableLanguages.Filter = obj =>\n {\n if (obj is not Language lang)\n return false;\n\n if (string.IsNullOrWhiteSpace(SearchText))\n return true;\n\n string query = SearchText.Trim();\n\n if (lang.TopEnglishName.Contains(query, StringComparison.OrdinalIgnoreCase))\n return true;\n\n return lang.TopNativeName.Contains(query, StringComparison.OrdinalIgnoreCase);\n };\n }\n\n public string SearchText\n {\n get;\n set\n {\n if (Set(ref field, value))\n {\n _filteredAvailableLanguages.Refresh();\n }\n }\n } = string.Empty;\n\n private readonly ICollectionView _filteredAvailableLanguages;\n public ObservableCollection AvailableLanguages { get; } = new();\n public ObservableCollection SelectedLanguages { get; } = new();\n\n public Language? SelectedAvailable\n {\n get;\n set\n {\n if (Set(ref field, value))\n {\n OnPropertyChanged(nameof(CanMoveRight));\n }\n }\n }\n\n // TODO: L: weird naming\n public Language? SelectedSelected\n {\n get;\n set\n {\n if (Set(ref field, value))\n {\n OnPropertyChanged(nameof(CanMoveLeft));\n OnPropertyChanged(nameof(CanMoveUp));\n OnPropertyChanged(nameof(CanMoveDown));\n }\n }\n }\n\n public bool CanMoveRight => SelectedAvailable != null;\n public bool CanMoveLeft => SelectedSelected != null;\n public bool CanMoveUp => SelectedSelected != null && SelectedLanguages.IndexOf(SelectedSelected) > 0;\n public bool CanMoveDown => SelectedSelected != null && SelectedLanguages.IndexOf(SelectedSelected) < SelectedLanguages.Count - 1;\n\n public DelegateCommand? CmdMoveRight => field ??= new DelegateCommand(() =>\n {\n if (SelectedAvailable != null && !SelectedLanguages.Contains(SelectedAvailable))\n {\n SelectedLanguages.Add(SelectedAvailable);\n AvailableLanguages.Remove(SelectedAvailable);\n }\n }).ObservesCanExecute(() => CanMoveRight);\n\n public DelegateCommand? CmdMoveLeft => field ??= new DelegateCommand(() =>\n {\n if (SelectedSelected != null)\n {\n // conform to order\n int insertIndex = 0;\n while (insertIndex < AvailableLanguages.Count &&\n string.Compare(AvailableLanguages[insertIndex].TopEnglishName, SelectedSelected.TopEnglishName, StringComparison.InvariantCulture) < 0)\n {\n insertIndex++;\n }\n\n AvailableLanguages.Insert(insertIndex, SelectedSelected);\n\n SelectedLanguages.Remove(SelectedSelected);\n }\n }).ObservesCanExecute(() => CanMoveLeft);\n\n public DelegateCommand? CmdMoveUp => field ??= new DelegateCommand(() =>\n {\n int index = SelectedLanguages.IndexOf(SelectedSelected!);\n if (index > 0)\n {\n SelectedLanguages.Move(index, index - 1);\n OnPropertyChanged(nameof(CanMoveUp));\n OnPropertyChanged(nameof(CanMoveDown));\n }\n }).ObservesCanExecute(() => CanMoveUp);\n\n public DelegateCommand? CmdMoveDown => field ??= new DelegateCommand(() =>\n {\n int index = SelectedLanguages.IndexOf(SelectedSelected!);\n if (index < SelectedLanguages.Count - 1)\n {\n SelectedLanguages.Move(index, index + 1);\n OnPropertyChanged(nameof(CanMoveUp));\n OnPropertyChanged(nameof(CanMoveDown));\n }\n }).ObservesCanExecute(() => CanMoveDown);\n\n #region IDialogAware\n public string Title { get; set => Set(ref field, value); }\n = $\"Select Language - {App.Name}\";\n public double WindowWidth { get; set => Set(ref field, value); } = 600;\n public double WindowHeight { get; set => Set(ref field, value); } = 360;\n\n public DialogCloseListener RequestClose { get; }\n\n public bool CanCloseDialog()\n {\n return true;\n }\n public void OnDialogClosed()\n {\n List langs = [.. SelectedLanguages];\n DialogParameters p = new()\n {\n { \"languages\", langs }\n };\n\n RequestClose.Invoke(p);\n }\n\n public void OnDialogOpened(IDialogParameters parameters)\n {\n List langs = parameters.GetValue>(\"languages\");\n\n foreach (var lang in langs)\n {\n SelectedLanguages.Add(lang);\n }\n\n foreach (Language lang in Language.AllLanguages)\n {\n if (!SelectedLanguages.Contains(lang))\n {\n AvailableLanguages.Add(lang);\n }\n }\n }\n #endregion\n}\n"], ["/LLPlayer/LLPlayer/ViewModels/CheatSheetDialogVM.cs", "using System.Diagnostics.CodeAnalysis;\nusing System.Globalization;\nusing System.Windows.Data;\nusing System.Windows.Input;\nusing System.Windows.Media;\nusing FlyleafLib.MediaPlayer;\nusing LLPlayer.Converters;\nusing LLPlayer.Extensions;\nusing LLPlayer.Services;\nusing MaterialDesignColors.Recommended;\nusing KeyBinding = FlyleafLib.MediaPlayer.KeyBinding;\n\nnamespace LLPlayer.ViewModels;\n\npublic class CheatSheetDialogVM : Bindable, IDialogAware\n{\n public FlyleafManager FL { get; }\n\n public CheatSheetDialogVM(FlyleafManager fl)\n {\n FL = fl;\n\n List keys = FL.PlayerConfig.Player.KeyBindings.Keys.Where(k => k.IsEnabled).ToList();\n\n HitCount = keys.Count;\n\n KeyToStringConverter keyConverter = new();\n\n List groups = keys.Select(k =>\n {\n KeyBindingCS key = new()\n {\n Action = k.Action,\n ActionName = k.Action.ToString(),\n Alt = k.Alt,\n Ctrl = k.Ctrl,\n Shift = k.Shift,\n Description = k.Action.GetDescription(),\n Group = k.Action.ToGroup(),\n Key = k.Key,\n KeyName = (string)keyConverter.Convert(k.Key, typeof(string), null, CultureInfo.CurrentCulture),\n ActionInternal = k.ActionInternal,\n };\n\n if (key.Action == KeyBindingAction.Custom)\n {\n if (!Enum.TryParse(k.ActionName, out CustomKeyBindingAction customAction))\n {\n HitCount -= 1;\n return null;\n }\n\n key.ActionName = customAction.ToString();\n key.CustomAction = customAction;\n key.Description = customAction.GetDescription();\n key.Group = customAction.ToGroup();\n }\n\n return key;\n })\n .Where(k => k != null)\n .OrderBy(k => k!.Action)\n .ThenBy(k => k!.CustomAction)\n .GroupBy(k => k!.Group)\n .OrderBy(g => g.Key)\n .Select(g => new KeyBindingCSGroup()\n {\n Group = g.Key,\n KeyBindings = g.ToList()!\n }).ToList();\n\n KeyBindingGroups = new List(groups);\n\n List collectionViews = KeyBindingGroups.Select(g => (ListCollectionView)CollectionViewSource.GetDefaultView(g.KeyBindings))\n .ToList();\n _collectionViews = collectionViews;\n\n foreach (ListCollectionView view in collectionViews)\n {\n view.Filter = (obj) =>\n {\n if (obj is not KeyBindingCS key)\n {\n return false;\n }\n\n if (string.IsNullOrWhiteSpace(SearchText))\n {\n return true;\n }\n\n string query = SearchText.Trim();\n\n bool match = key.Description.Contains(query, StringComparison.OrdinalIgnoreCase);\n if (match)\n {\n return true;\n }\n\n return key.Shortcut.Contains(query, StringComparison.OrdinalIgnoreCase);\n };\n }\n }\n\n public string SearchText\n {\n get;\n set\n {\n if (Set(ref field, value))\n {\n _collectionViews.ForEach(v => v.Refresh());\n\n HitCount = _collectionViews.Sum(v => v.Count);\n }\n }\n } = string.Empty;\n\n public int HitCount { get; set => Set(ref field, value); }\n\n private readonly List _collectionViews;\n public List KeyBindingGroups { get; set; }\n\n public DelegateCommand? CmdAction => field ??= new((key) =>\n {\n FL.Player.Activity.ForceFullActive();\n key.ActionInternal.Invoke();\n });\n\n #region IDialogAware\n public string Title { get; set => Set(ref field, value); } = $\"CheatSheet - {App.Name}\";\n public double WindowWidth { get; set => Set(ref field, value); } = 1000;\n public double WindowHeight { get; set => Set(ref field, value); } = 800;\n\n public bool CanCloseDialog() => true;\n public void OnDialogClosed() { }\n public void OnDialogOpened(IDialogParameters parameters) { }\n public DialogCloseListener RequestClose { get; }\n #endregion IDialogAware\n}\n\npublic class KeyBindingCS\n{\n public required bool Ctrl { get; init; }\n public required bool Shift { get; init; }\n public required bool Alt { get; init; }\n public required Key Key { get; init; }\n public required string KeyName { get; init; }\n\n [field: AllowNull, MaybeNull]\n public string Shortcut\n {\n get\n {\n if (field == null)\n {\n string modifiers = \"\";\n if (Ctrl)\n modifiers += \"Ctrl + \";\n if (Alt)\n modifiers += \"Alt + \";\n if (Shift)\n modifiers += \"Shift + \";\n field = $\"{modifiers}{KeyName}\";\n }\n\n return field;\n }\n }\n\n public required KeyBindingAction Action { get; init; }\n public CustomKeyBindingAction? CustomAction { get; set; }\n public required string ActionName { get; set; }\n public required string Description { get; set; }\n public required KeyBindingActionGroup Group { get; set; }\n\n public required Action ActionInternal { get; init; }\n}\n\npublic class KeyBindingCSGroup\n{\n public required KeyBindingActionGroup Group { get; init; }\n\n [field: AllowNull, MaybeNull]\n public string GroupName => field ??= Group.ToString();\n public required List KeyBindings { get; init; }\n\n public Color GroupColor =>\n Group switch\n {\n KeyBindingActionGroup.Playback => RedSwatch.Red500,\n KeyBindingActionGroup.Player => PinkSwatch.Pink500,\n KeyBindingActionGroup.Audio => PurpleSwatch.Purple500,\n KeyBindingActionGroup.Video => BlueSwatch.Blue500,\n KeyBindingActionGroup.Subtitles => TealSwatch.Teal500,\n KeyBindingActionGroup.SubtitlesPosition => GreenSwatch.Green500,\n KeyBindingActionGroup.Window => LightGreenSwatch.LightGreen500,\n KeyBindingActionGroup.Other => DeepOrangeSwatch.DeepOrange500,\n _ => BrownSwatch.Brown500\n };\n}\n"], ["/LLPlayer/FlyleafLib/MediaFramework/MediaStream/AudioStream.cs", "using FlyleafLib.MediaFramework.MediaDemuxer;\n\nnamespace FlyleafLib.MediaFramework.MediaStream;\n\npublic unsafe class AudioStream : StreamBase\n{\n public int Bits { get; set; }\n public int Channels { get; set; }\n public ulong ChannelLayout { get; set; }\n public string ChannelLayoutStr { get; set; }\n public AVSampleFormat SampleFormat { get; set; }\n public string SampleFormatStr { get; set; }\n public int SampleRate { get; set; }\n public AVCodecID CodecIDOrig { get; set; }\n\n public override string GetDump()\n => $\"[{Type} #{StreamIndex}-{Language.IdSubLanguage}{(Title != null ? \"(\" + Title + \")\" : \"\")}] {Codec} {SampleFormatStr}@{Bits} {SampleRate / 1000}KHz {ChannelLayoutStr} | [BR: {BitRate}] | {Utils.TicksToTime((long)(AVStream->start_time * Timebase))}/{Utils.TicksToTime((long)(AVStream->duration * Timebase))} | {Utils.TicksToTime(StartTime)}/{Utils.TicksToTime(Duration)}\";\n\n public AudioStream() { }\n public AudioStream(Demuxer demuxer, AVStream* st) : base(demuxer, st) => Refresh();\n\n public override void Refresh()\n {\n base.Refresh();\n\n SampleFormat = (AVSampleFormat) Enum.ToObject(typeof(AVSampleFormat), AVStream->codecpar->format);\n SampleFormatStr = av_get_sample_fmt_name(SampleFormat);\n SampleRate = AVStream->codecpar->sample_rate;\n\n if (AVStream->codecpar->ch_layout.order == AVChannelOrder.Unspec)\n av_channel_layout_default(&AVStream->codecpar->ch_layout, AVStream->codecpar->ch_layout.nb_channels);\n\n ChannelLayout = AVStream->codecpar->ch_layout.u.mask;\n Channels = AVStream->codecpar->ch_layout.nb_channels;\n Bits = AVStream->codecpar->bits_per_coded_sample;\n\n // https://trac.ffmpeg.org/ticket/7321\n CodecIDOrig = CodecID;\n if (CodecID == AVCodecID.Mp2 && (SampleFormat == AVSampleFormat.Fltp || SampleFormat == AVSampleFormat.Flt))\n CodecID = AVCodecID.Mp3; // OR? st->codecpar->format = (int) AVSampleFormat.AV_SAMPLE_FMT_S16P;\n\n byte[] buf = new byte[50];\n fixed (byte* bufPtr = buf)\n {\n av_channel_layout_describe(&AVStream->codecpar->ch_layout, bufPtr, (nuint)buf.Length);\n ChannelLayoutStr = Utils.BytePtrToStringUTF8(bufPtr);\n }\n }\n}\n"], ["/LLPlayer/LLPlayer/Controls/SelectableSubtitleText.xaml.cs", "using System.Diagnostics;\nusing System.Text.RegularExpressions;\nusing System.Windows;\nusing System.Windows.Controls;\nusing System.Windows.Data;\nusing System.Windows.Input;\nusing System.Windows.Media;\nusing FlyleafLib;\nusing LLPlayer.Extensions;\nusing NMeCab.Specialized;\n\nnamespace LLPlayer.Controls;\n\npublic partial class SelectableSubtitleText : UserControl\n{\n private readonly Binding _bindFontSize;\n private readonly Binding _bindFontWeight;\n private readonly Binding _bindFontFamily;\n private readonly Binding _bindFontStyle;\n private readonly Binding _bindFill;\n private readonly Binding _bindStroke;\n private readonly Binding _bindStrokeThicknessInitial;\n\n private OutlinedTextBlock? _wordStart;\n\n public SelectableSubtitleText()\n {\n InitializeComponent();\n\n // DataContext is set in WrapPanel, so there is no need to use ElementName.\n //_bindFontSize = new Binding(nameof(FontSize))\n //{\n // //ElementName = nameof(Root),\n // Mode = BindingMode.OneWay\n //};\n _bindFontSize = new Binding(nameof(FontSize));\n _bindFontWeight = new Binding(nameof(FontWeight));\n _bindFontFamily = new Binding(nameof(FontFamily));\n _bindFontStyle = new Binding(nameof(FontStyle));\n _bindFill = new Binding(nameof(Fill));\n _bindStroke = new Binding(nameof(Stroke));\n _bindStrokeThicknessInitial = new Binding(nameof(StrokeThicknessInitial));\n }\n\n public static readonly RoutedEvent WordClickedEvent =\n EventManager.RegisterRoutedEvent(nameof(WordClicked), RoutingStrategy.Bubble, typeof(WordClickedEventHandler), typeof(SelectableSubtitleText));\n\n public event WordClickedEventHandler WordClicked\n {\n add => AddHandler(WordClickedEvent, value);\n remove => RemoveHandler(WordClickedEvent, value);\n }\n\n public event EventHandler? WordClickedDown;\n\n public static readonly DependencyProperty TextProperty =\n DependencyProperty.Register(nameof(Text), typeof(string), typeof(SelectableSubtitleText), new FrameworkPropertyMetadata(string.Empty, OnTextChanged));\n\n public string Text\n {\n get => (string)GetValue(TextProperty);\n set => SetValue(TextProperty, value);\n }\n\n private string _textFix = string.Empty;\n\n public static readonly DependencyProperty IsTranslatedProperty =\n DependencyProperty.Register(nameof(IsTranslated), typeof(bool), typeof(SelectableSubtitleText), new FrameworkPropertyMetadata(false));\n\n public bool IsTranslated\n {\n get => (bool)GetValue(IsTranslatedProperty);\n set => SetValue(IsTranslatedProperty, value);\n }\n\n public static readonly DependencyProperty TextLanguageProperty =\n DependencyProperty.Register(nameof(TextLanguage), typeof(Language), typeof(SelectableSubtitleText), new FrameworkPropertyMetadata(null, OnTextLanguageChanged));\n\n public Language? TextLanguage\n {\n get => (Language)GetValue(TextLanguageProperty);\n set => SetValue(TextLanguageProperty, value);\n }\n\n public static readonly DependencyProperty SubIndexProperty =\n DependencyProperty.Register(nameof(SubIndex), typeof(int), typeof(SelectableSubtitleText), new FrameworkPropertyMetadata(0));\n\n public int SubIndex\n {\n get => (int)GetValue(SubIndexProperty);\n set => SetValue(SubIndexProperty, value);\n }\n\n public static readonly DependencyProperty FillProperty =\n OutlinedTextBlock.FillProperty.AddOwner(typeof(SelectableSubtitleText));\n\n public Brush Fill\n {\n get => (Brush)GetValue(FillProperty);\n set => SetValue(FillProperty, value);\n }\n\n public static readonly DependencyProperty StrokeProperty =\n OutlinedTextBlock.StrokeProperty.AddOwner(typeof(SelectableSubtitleText));\n\n public Brush Stroke\n {\n get => (Brush)GetValue(StrokeProperty);\n set => SetValue(StrokeProperty, value);\n }\n\n public static readonly DependencyProperty WidthPercentageProperty =\n DependencyProperty.Register(nameof(WidthPercentage), typeof(double), typeof(SelectableSubtitleText), new FrameworkPropertyMetadata(60.0, OnWidthPercentageChanged));\n\n public double WidthPercentage\n {\n get => (double)GetValue(WidthPercentageProperty);\n set => SetValue(WidthPercentageProperty, value);\n }\n\n public static readonly DependencyProperty WidthPercentageFixProperty =\n DependencyProperty.Register(nameof(WidthPercentageFix), typeof(double), typeof(SelectableSubtitleText), new FrameworkPropertyMetadata(60.0));\n\n public double WidthPercentageFix\n {\n get => (double)GetValue(WidthPercentageFixProperty);\n set => SetValue(WidthPercentageFixProperty, value);\n }\n\n public static readonly DependencyProperty IgnoreLineBreakProperty =\n DependencyProperty.Register(nameof(IgnoreLineBreak), typeof(bool), typeof(SelectableSubtitleText), new FrameworkPropertyMetadata(false));\n\n public double MaxFixedWidth\n {\n get => (double)GetValue(MaxFixedWidthProperty);\n set => SetValue(MaxFixedWidthProperty, value);\n }\n\n public static readonly DependencyProperty MaxFixedWidthProperty =\n DependencyProperty.Register(nameof(MaxFixedWidth), typeof(double), typeof(SelectableSubtitleText), new FrameworkPropertyMetadata(0.0));\n\n public bool IgnoreLineBreak\n {\n get => (bool)GetValue(IgnoreLineBreakProperty);\n set => SetValue(IgnoreLineBreakProperty, value);\n }\n\n public static readonly DependencyProperty StrokeThicknessInitialProperty =\n DependencyProperty.Register(nameof(StrokeThicknessInitial), typeof(double), typeof(SelectableSubtitleText), new FrameworkPropertyMetadata(3.0));\n\n public double StrokeThicknessInitial\n {\n get => (double)GetValue(StrokeThicknessInitialProperty);\n set => SetValue(StrokeThicknessInitialProperty, value);\n }\n\n public static readonly DependencyProperty WordHoverBorderBrushProperty =\n DependencyProperty.Register(nameof(WordHoverBorderBrush), typeof(Brush), typeof(SelectableSubtitleText), new FrameworkPropertyMetadata(Brushes.Cyan));\n\n public Brush WordHoverBorderBrush\n {\n get => (Brush)GetValue(WordHoverBorderBrushProperty);\n set => SetValue(WordHoverBorderBrushProperty, value);\n }\n\n private static void OnWidthPercentageChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)\n {\n var ctl = (SelectableSubtitleText)d;\n ctl.WidthPercentageFix = (double)e.NewValue;\n }\n\n private static void OnTextChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)\n {\n var ctl = (SelectableSubtitleText)d;\n ctl.SetText((string)e.NewValue);\n }\n\n private static void OnTextLanguageChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)\n {\n var ctl = (SelectableSubtitleText)d;\n if (ctl.TextLanguage != null && ctl.TextLanguage.IsRTL)\n {\n ctl.wrapPanel.FlowDirection = FlowDirection.RightToLeft;\n }\n else\n {\n ctl.wrapPanel.FlowDirection = FlowDirection.LeftToRight;\n }\n }\n\n // SelectableTextBox uses char.IsPunctuation(), so use a regular expression for it.\n // TODO: L: Sharing the code with TextBox\n [GeneratedRegex(@\"((?:[^\\P{P}'-]+|\\s))\")]\n private static partial Regex WordSplitReg { get; }\n\n [GeneratedRegex(@\"^(?:[^\\P{P}'-]+|\\s)$\")]\n private static partial Regex WordSplitFullReg { get; }\n\n [GeneratedRegex(@\"((?:[^\\P{P}'-]+|\\s|[\\p{IsCJKUnifiedIdeographs}\\p{IsCJKUnifiedIdeographsExtensionA}]))\")]\n private static partial Regex ChineseWordSplitReg { get; }\n\n\n private static readonly Lazy MeCabTagger = new(() => MeCabIpaDicTagger.Create(), true);\n\n private void SetText(string text)\n {\n if (text == null)\n {\n return;\n }\n\n if (IgnoreLineBreak)\n {\n text = SubtitleTextUtil.FlattenText(text);\n }\n\n _textFix = text;\n\n bool containLineBreak = text.AsSpan().ContainsAny('\\r', '\\n');\n\n // If it contains line feeds, expand them to the full screen width (respecting the formatting in the SRT subtitle)\n WidthPercentageFix = containLineBreak ? 100.0 : WidthPercentage;\n\n wrapPanel.Children.Clear();\n _wordStart = null;\n\n string[] lines = text.SplitToLines().ToArray();\n\n var wordOffset = 0;\n\n // Use an OutlinedTextBlock for each word to display the border Text and enclose it in a WrapPanel\n for (int i = 0; i < lines.Length; i++)\n {\n IEnumerable words;\n\n if (TextLanguage != null && TextLanguage.ISO6391 == \"ja\")\n {\n // word segmentation for Japanese\n // TODO: L: Also do word segmentation in sidebar\n var nodes = MeCabTagger.Value.Parse(lines[i]);\n List wordsList = new(nodes.Length);\n foreach (var node in nodes)\n {\n // If there are space-separated characters, such as English, add them manually since they are not on the Surface\n if (char.IsWhiteSpace(lines[i][node.BPos]))\n {\n wordsList.Add(\" \");\n }\n wordsList.Add(node.Surface);\n }\n\n words = wordsList;\n }\n else if (TextLanguage != null && TextLanguage.ISO6391 == \"zh\")\n {\n words = ChineseWordSplitReg.Split(lines[i]);\n }\n else\n {\n words = WordSplitReg.Split(lines[i]);\n }\n\n foreach (string word in words)\n {\n // skip empty string because Split includes\n if (word.Length == 0)\n {\n continue;\n }\n\n if (string.IsNullOrWhiteSpace(word))\n {\n // Blanks are inserted with TextBlock.\n TextBlock space = new()\n {\n Text = word,\n // Created a click judgment to prevent playback toggling when clicking between words.\n Background = new SolidColorBrush(Color.FromArgb(1, 0, 0, 0)),\n };\n space.SetBinding(TextBlock.FontSizeProperty, _bindFontSize);\n space.SetBinding(TextBlock.FontWeightProperty, _bindFontWeight);\n space.SetBinding(TextBlock.FontStyleProperty, _bindFontStyle);\n space.SetBinding(TextBlock.FontFamilyProperty, _bindFontFamily);\n wrapPanel.Children.Add(space);\n wordOffset += word.Length;\n continue;\n }\n\n bool isSplitChar = WordSplitFullReg.IsMatch(word);\n\n OutlinedTextBlock textBlock = new()\n {\n Text = word,\n ClipToBounds = false,\n TextWrapping = TextWrapping.Wrap,\n StrokePosition = StrokePosition.Outside,\n IsHitTestVisible = false,\n WordOffset = wordOffset,\n // Fixed because the word itself is inverted\n FlowDirection = FlowDirection.LeftToRight\n };\n\n wordOffset += word.Length;\n\n textBlock.SetBinding(OutlinedTextBlock.FontSizeProperty, _bindFontSize);\n textBlock.SetBinding(OutlinedTextBlock.FontWeightProperty, _bindFontWeight);\n textBlock.SetBinding(OutlinedTextBlock.FontStyleProperty, _bindFontStyle);\n textBlock.SetBinding(OutlinedTextBlock.FontFamilyProperty, _bindFontFamily);\n textBlock.SetBinding(OutlinedTextBlock.FillProperty, _bindFill);\n textBlock.SetBinding(OutlinedTextBlock.StrokeProperty, _bindStroke);\n textBlock.SetBinding(OutlinedTextBlock.StrokeThicknessInitialProperty, _bindStrokeThicknessInitial);\n\n if (isSplitChar)\n {\n wrapPanel.Children.Add(textBlock);\n }\n else\n {\n Border border = new()\n {\n // Set brush to Border because OutlinedTextBlock's character click judgment is only on the character.\n //ref: https://stackoverflow.com/questions/50653308/hit-testing-a-transparent-element-in-a-transparent-window\n Background = new SolidColorBrush(Color.FromArgb(1, 0, 0, 0)),\n BorderThickness = new Thickness(1),\n IsHitTestVisible = true,\n Child = textBlock,\n Cursor = Cursors.Hand,\n };\n\n border.MouseLeftButtonDown += WordMouseLeftButtonDown;\n border.MouseLeftButtonUp += WordMouseLeftButtonUp;\n border.MouseRightButtonUp += WordMouseRightButtonUp;\n border.MouseUp += WordMouseMiddleButtonUp;\n\n // Change background color on mouse over\n border.MouseEnter += (_, _) =>\n {\n border.BorderBrush = WordHoverBorderBrush;\n border.Background = new SolidColorBrush(Color.FromArgb(80, 127, 127, 127));\n };\n border.MouseLeave += (_, _) =>\n {\n border.BorderBrush = null;\n border.Background = new SolidColorBrush(Color.FromArgb(1, 0, 0, 0));\n };\n\n wrapPanel.Children.Add(border);\n }\n }\n\n if (containLineBreak && i != lines.Length - 1)\n {\n // Add line breaks except at the end when there are two or more lines\n wrapPanel.Children.Add(new NewLine());\n }\n }\n }\n\n private void WordMouseLeftButtonDown(object sender, MouseButtonEventArgs e)\n {\n if (sender is Border { Child: OutlinedTextBlock word })\n {\n _wordStart = word;\n WordClickedDown?.Invoke(this, EventArgs.Empty);\n\n e.Handled = true;\n }\n }\n\n private void WordMouseLeftButtonUp(object sender, MouseButtonEventArgs e)\n {\n if (sender is Border { Child: OutlinedTextBlock word })\n {\n if (_wordStart == word)\n {\n // word clicked\n Point wordPoint = word.TranslatePoint(default, Root);\n\n WordClickedEventArgs args = new(WordClickedEvent)\n {\n Mouse = MouseClick.Left,\n Words = word.Text,\n IsWord = true,\n Text = _textFix,\n IsTranslated = IsTranslated,\n SubIndex = SubIndex,\n WordOffset = word.WordOffset,\n WordsX = wordPoint.X,\n WordsWidth = word.ActualWidth\n };\n RaiseEvent(args);\n }\n else if (_wordStart != null)\n {\n // phrase selected\n var wordStart = _wordStart!;\n var wordEnd = word;\n\n // support right to left drag\n if (wordStart.WordOffset > wordEnd.WordOffset)\n {\n (wordStart, wordEnd) = (wordEnd, wordStart);\n }\n\n List elements = wrapPanel.Children.OfType().ToList();\n\n int startIndex = elements.IndexOf((FrameworkElement)wordStart.Parent);\n int endIndex = elements.IndexOf((FrameworkElement)wordEnd.Parent);\n\n if (startIndex == -1 || endIndex == -1)\n {\n Debug.Assert(startIndex >= 0);\n Debug.Assert(endIndex >= 0);\n return;\n }\n\n var selectedElements = elements[startIndex..(endIndex + 1)];\n var selectedWords = selectedElements.Select(fe =>\n {\n switch (fe)\n {\n case Border { Child: OutlinedTextBlock word }:\n return word.Text;\n case OutlinedTextBlock splitter:\n return splitter.Text;\n case TextBlock space:\n return space.Text;\n case NewLine:\n // convert to space\n return \" \";\n default:\n throw new InvalidOperationException();\n }\n }).ToList();\n string selectedText = string.Join(string.Empty, selectedWords);\n\n Point startPoint = wordStart.TranslatePoint(default, Root);\n Point endPoint = wordEnd.TranslatePoint(default, Root);\n\n // if different Y axis, then line break or text wrapping\n double wordsX = 0;\n double wordsWidth = wrapPanel.ActualWidth;\n\n if (startPoint.Y == endPoint.Y)\n {\n // selection in one line\n\n if (wrapPanel.FlowDirection == FlowDirection.LeftToRight)\n {\n wordsX = startPoint.X;\n wordsWidth = endPoint.X + wordEnd.ActualWidth - startPoint.X;\n }\n else\n {\n wordsX = endPoint.X;\n wordsWidth = startPoint.X + wordStart.ActualWidth - endPoint.X;\n }\n }\n\n WordClickedEventArgs args = new(WordClickedEvent)\n {\n Mouse = MouseClick.Left,\n Words = selectedText,\n IsWord = false,\n Text = _textFix,\n IsTranslated = IsTranslated,\n SubIndex = SubIndex,\n WordOffset = wordStart.WordOffset,\n WordsX = wordsX,\n WordsWidth = wordsWidth\n };\n RaiseEvent(args);\n }\n\n _wordStart = null;\n e.Handled = true;\n }\n }\n\n private void WordMouseRightButtonUp(object sender, MouseButtonEventArgs e)\n {\n if (sender is Border { Child: OutlinedTextBlock word })\n {\n Point wordPoint = word.TranslatePoint(default, Root);\n\n WordClickedEventArgs args = new(WordClickedEvent)\n {\n Mouse = MouseClick.Right,\n Words = word.Text,\n IsWord = true,\n Text = _textFix,\n IsTranslated = IsTranslated,\n SubIndex = SubIndex,\n WordOffset = word.WordOffset,\n WordsX = wordPoint.X,\n WordsWidth = word.ActualWidth\n };\n RaiseEvent(args);\n e.Handled = true;\n }\n }\n\n private void WordMouseMiddleButtonUp(object sender, MouseButtonEventArgs e)\n {\n if (e.ChangedButton == MouseButton.Middle)\n {\n WordClickedEventArgs args = new(WordClickedEvent)\n {\n Mouse = MouseClick.Middle,\n Words = _textFix,\n IsWord = false,\n Text = _textFix,\n IsTranslated = IsTranslated,\n SubIndex = SubIndex,\n WordOffset = 0,\n WordsX = 0,\n WordsWidth = wrapPanel.ActualWidth\n };\n RaiseEvent(args);\n e.Handled = true;\n }\n }\n}\n\npublic class NewLine : FrameworkElement\n{\n}\n"], ["/LLPlayer/FlyleafLib/Engine/Language.cs", "using System.Collections.Generic;\nusing System.Globalization;\nusing System.Linq;\nusing System.Text.Json.Serialization;\n\nnamespace FlyleafLib;\n\npublic class Language : IEquatable\n{\n public string CultureName { get => _CultureName; set\n { // Required for XML load\n Culture = CultureInfo.GetCultureInfo(value);\n Refresh(this);\n }\n }\n string _CultureName;\n\n [JsonIgnore]\n public string TopEnglishName { get; private set; }\n [JsonIgnore]\n public string TopNativeName { get; private set; }\n\n [JsonIgnore]\n public CultureInfo Culture { get; private set; }\n\n [JsonIgnore]\n public CultureInfo TopCulture { get; private set; }\n [JsonIgnore]\n public string DisplayName => $\"{TopEnglishName} ({TopNativeName})\";\n\n [JsonIgnore]\n public string ISO6391 { get; private set; }\n\n [JsonIgnore]\n public string IdSubLanguage { get; private set; } // Can search for online subtitles with this id\n\n [JsonIgnore]\n public string OriginalInput { get; private set; } // Only for Undetermined language (return clone)\n\n [JsonIgnore]\n public bool IsRTL { get; private set; }\n\n public override string ToString() => OriginalInput ?? TopEnglishName;\n\n public override int GetHashCode() => ToString().GetHashCode();\n\n public override bool Equals(object obj) => Equals(obj as Language);\n\n public bool Equals(Language lang)\n {\n if (lang is null)\n return false;\n\n if (ReferenceEquals(this, lang))\n return true;\n\n if (lang.Culture == null && Culture == null)\n {\n if (OriginalInput != null || lang.OriginalInput != null)\n return OriginalInput == lang.OriginalInput;\n\n return true; // und\n }\n\n return lang.IdSubLanguage == IdSubLanguage; // TBR: top level will be equal with lower\n }\n\n public static bool operator ==(Language lang1, Language lang2) => lang1 is null ? lang2 is null ? true : false : lang1.Equals(lang2);\n\n public static bool operator !=(Language lang1, Language lang2) => !(lang1 == lang2);\n\n private static readonly HashSet RTLCodes =\n [\n \"ae\",\n \"ar\",\n \"dv\",\n \"fa\",\n \"ha\",\n \"he\",\n \"ks\",\n \"ku\",\n \"ps\",\n \"sd\",\n \"ug\",\n \"ur\",\n \"yi\"\n ];\n\n public static void Refresh(Language lang)\n {\n lang._CultureName = lang.Culture.Name;\n\n lang.TopCulture = lang.Culture;\n while (lang.TopCulture.Parent.Name != \"\")\n lang.TopCulture = lang.TopCulture.Parent;\n\n lang.TopEnglishName = lang.TopCulture.EnglishName;\n lang.TopNativeName = lang.TopCulture.NativeName;\n lang.IdSubLanguage = lang.Culture.ThreeLetterISOLanguageName;\n lang.ISO6391 = lang.Culture.TwoLetterISOLanguageName;\n lang.IsRTL = RTLCodes.Contains(lang.ISO6391);\n }\n\n public static Language Get(CultureInfo cult)\n {\n Language lang = new() { Culture = cult };\n Refresh(lang);\n\n return lang;\n }\n public static Language Get(string name)\n {\n Language lang = new() { Culture = StringToCulture(name) };\n if (lang.Culture != null)\n Refresh(lang);\n else\n {\n lang.IdSubLanguage = \"und\";\n lang.TopEnglishName = \"Unknown\";\n if (name != \"und\")\n lang.OriginalInput = name;\n }\n\n return lang;\n }\n\n public static CultureInfo StringToCulture(string lang)\n {\n if (string.IsNullOrWhiteSpace(lang) || lang.Length < 2 || lang == \"und\")\n return null;\n\n string langLower = lang.ToLower();\n CultureInfo ret = null;\n\n try\n {\n ret = lang.Length == 3 ? ThreeLetterToCulture(langLower) : CultureInfo.GetCultureInfo(langLower);\n } catch { }\n\n StringComparer cmp = StringComparer.OrdinalIgnoreCase;\n\n // TBR: Check also -Country/region two letters?\n if (ret == null || ret.ThreeLetterISOLanguageName == \"\")\n foreach (var cult in CultureInfo.GetCultures(CultureTypes.AllCultures))\n if (cmp.Equals(cult.Name, langLower) || cmp.Equals(cult.NativeName, langLower) || cmp.Equals(cult.EnglishName, langLower))\n return cult;\n\n return ret;\n }\n\n public static CultureInfo ThreeLetterToCulture(string lang)\n {\n if (lang == \"zht\")\n return CultureInfo.GetCultureInfo(\"zh-Hant\");\n else if (lang == \"pob\")\n return CultureInfo.GetCultureInfo(\"pt-BR\");\n else if (lang == \"nor\")\n return CultureInfo.GetCultureInfo(\"nob\");\n else if (lang == \"scc\")\n return CultureInfo.GetCultureInfo(\"srp\");\n else if (lang == \"tgl\")\n return CultureInfo.GetCultureInfo(\"fil\");\n\n CultureInfo ret = CultureInfo.GetCultureInfo(lang);\n\n if (ret.ThreeLetterISOLanguageName == \"\")\n {\n ISO639_2B_TO_2T.TryGetValue(lang, out string iso639_2t);\n if (iso639_2t != null)\n ret = CultureInfo.GetCultureInfo(iso639_2t);\n }\n\n return ret.ThreeLetterISOLanguageName == \"\" ? null : ret;\n }\n\n public static readonly Dictionary ISO639_2T_TO_2B = new()\n {\n { \"bod\",\"tib\" },\n { \"ces\",\"cze\" },\n { \"cym\",\"wel\" },\n { \"deu\",\"ger\" },\n { \"ell\",\"gre\" },\n { \"eus\",\"baq\" },\n { \"fas\",\"per\" },\n { \"fra\",\"fre\" },\n { \"hye\",\"arm\" },\n { \"isl\",\"ice\" },\n { \"kat\",\"geo\" },\n { \"mkd\",\"mac\" },\n { \"mri\",\"mao\" },\n { \"msa\",\"may\" },\n { \"mya\",\"bur\" },\n { \"nld\",\"dut\" },\n { \"ron\",\"rum\" },\n { \"slk\",\"slo\" },\n { \"sqi\",\"alb\" },\n { \"zho\",\"chi\" },\n };\n public static readonly Dictionary ISO639_2B_TO_2T = new()\n {\n { \"alb\",\"sqi\" },\n { \"arm\",\"hye\" },\n { \"baq\",\"eus\" },\n { \"bur\",\"mya\" },\n { \"chi\",\"zho\" },\n { \"cze\",\"ces\" },\n { \"dut\",\"nld\" },\n { \"fre\",\"fra\" },\n { \"geo\",\"kat\" },\n { \"ger\",\"deu\" },\n { \"gre\",\"ell\" },\n { \"ice\",\"isl\" },\n { \"mac\",\"mkd\" },\n { \"mao\",\"mri\" },\n { \"may\",\"msa\" },\n { \"per\",\"fas\" },\n { \"rum\",\"ron\" },\n { \"slo\",\"slk\" },\n { \"tib\",\"bod\" },\n { \"wel\",\"cym\" },\n };\n\n public static Language English = Get(\"eng\");\n public static Language Unknown = Get(\"und\");\n\n public static List AllLanguages\n {\n get\n {\n if (field != null)\n {\n return field;\n }\n\n var neutralCultures = CultureInfo\n .GetCultures(CultureTypes.NeutralCultures)\n .Where(c => !string.IsNullOrEmpty(c.Name));\n\n var uniqueCultures = neutralCultures\n .GroupBy(c => c.ThreeLetterISOLanguageName)\n .Select(g => g.First());\n\n List languages = new();\n foreach (var culture in uniqueCultures)\n {\n languages.Add(Get(culture));\n }\n languages = languages.OrderBy(l => l.TopEnglishName, StringComparer.InvariantCulture).ToList();\n\n field = languages;\n\n return field;\n }\n }\n}\n"], ["/LLPlayer/LLPlayer/Controls/Settings/SettingsKeys.xaml.cs", "using System.Collections.ObjectModel;\nusing System.ComponentModel;\nusing System.Configuration;\nusing System.Diagnostics;\nusing System.Windows;\nusing System.Windows.Controls;\nusing System.Windows.Data;\nusing System.Windows.Input;\nusing FlyleafLib.MediaPlayer;\nusing LLPlayer.Converters;\nusing LLPlayer.Extensions;\nusing LLPlayer.Services;\nusing KeyBinding = FlyleafLib.MediaPlayer.KeyBinding;\n\nnamespace LLPlayer.Controls.Settings;\n\npublic partial class SettingsKeys : UserControl\n{\n private SettingsKeysVM VM => (SettingsKeysVM)DataContext;\n\n public SettingsKeys()\n {\n InitializeComponent();\n\n DataContext = ((App)Application.Current).Container.Resolve();\n }\n\n // Enable ComboBox to open when double-clicking a cell in Action\n private void ComboBox_Loaded(object sender, RoutedEventArgs e)\n {\n if (sender is ComboBox comboBox)\n {\n comboBox.IsDropDownOpen = true;\n }\n }\n\n // Scroll to the added record when a new record is added.\n private void KeyBindingsDataGrid_OnSelectionChanged(object sender, SelectionChangedEventArgs e)\n {\n if (VM.CmdLoad!.IsExecuting)\n {\n return;\n }\n\n if (KeyBindingsDataGrid.SelectedItem != null)\n {\n KeyBindingsDataGrid.UpdateLayout();\n KeyBindingsDataGrid.ScrollIntoView(KeyBindingsDataGrid.SelectedItem);\n }\n }\n}\n\npublic class SettingsKeysVM : Bindable\n{\n public FlyleafManager FL { get; }\n\n public SettingsKeysVM(FlyleafManager fl)\n {\n FL = fl;\n\n CmdLoad!.PropertyChanged += (sender, args) =>\n {\n if (args.PropertyName == nameof(CmdLoad.IsExecuting))\n {\n OnPropertyChanged(nameof(CanApply));\n }\n };\n\n List mergeActions = new();\n\n foreach (KeyBindingAction action in Enum.GetValues())\n {\n if (action != KeyBindingAction.Custom)\n {\n mergeActions.Add(new ActionData()\n {\n Action = action,\n Description = action.GetDescription(),\n DisplayName = action.ToString(),\n Group = action.ToGroup()\n });\n }\n }\n\n foreach (CustomKeyBindingAction action in Enum.GetValues())\n {\n mergeActions.Add(new ActionData()\n {\n Action = KeyBindingAction.Custom,\n CustomAction = action,\n Description = action.GetDescription(),\n DisplayName = action.ToString() + @\" ©︎\", // c=custom\n Group = action.ToGroup()\n });\n }\n\n mergeActions.Sort();\n\n Actions = mergeActions;\n\n // Grouping when displaying actions in ComboBox\n _actionsView = (ListCollectionView)CollectionViewSource.GetDefaultView(Actions);\n _actionsView.SortDescriptions.Add(new SortDescription(nameof(ActionData.Group), ListSortDirection.Ascending));\n _actionsView.SortDescriptions.Add(new SortDescription(nameof(ActionData.DisplayName), ListSortDirection.Ascending));\n\n _actionsView.GroupDescriptions!.Add(new PropertyGroupDescription(nameof(ActionData.Group)));\n }\n\n public List Actions { get; }\n private readonly ListCollectionView _actionsView;\n\n public ObservableCollection KeyBindings { get; } = new();\n\n public KeyBindingWrapper? SelectedKeyBinding { get; set => Set(ref field, value); }\n\n public int DuplicationCount\n {\n get;\n set\n {\n if (Set(ref field, value))\n {\n OnPropertyChanged(nameof(CanApply));\n }\n }\n }\n\n // Disable Apply button if there are duplicates or during loading\n public bool CanApply => DuplicationCount == 0 && !CmdLoad!.IsExecuting;\n\n public DelegateCommand? CmdAdd => field ??= new(() =>\n {\n KeyBindingWrapper added = new(new KeyBinding { Action = KeyBindingAction.AudioDelayAdd }, this);\n KeyBindings.Add(added);\n SelectedKeyBinding = added;\n\n added.ValidateShortcut();\n });\n\n public AsyncDelegateCommand? CmdLoad => field ??= new(async () =>\n {\n KeyBindings.Clear();\n DuplicationCount = 0;\n\n var keys = FL.PlayerConfig.Player.KeyBindings.Keys;\n\n var keyBindings = await Task.Run(() =>\n {\n List keyBindings = new(keys.Count);\n\n foreach (var k in keys)\n {\n try\n {\n keyBindings.Add(new KeyBindingWrapper(k, this));\n }\n catch (SettingsPropertyNotFoundException)\n {\n // ignored\n // TODO: L: error handling\n Debug.Fail(\"Weird custom key for settings?\");\n }\n }\n\n return Task.FromResult(keyBindings);\n });\n\n foreach (var b in keyBindings)\n {\n KeyBindings.Add(b);\n }\n });\n\n /// \n /// Reflect customized key settings to Config.\n /// \n public DelegateCommand? CmdApply => field ??= new DelegateCommand(() =>\n {\n foreach (var b in KeyBindings)\n {\n Debug.Assert(!b.Duplicated, \"Duplicate check not working\");\n }\n\n var newKeys = KeyBindings.Select(k => k.ToKeyBinding()).ToList();\n\n foreach (var k in newKeys)\n {\n if (k.Action == KeyBindingAction.Custom)\n {\n if (!Enum.TryParse(k.ActionName, out CustomKeyBindingAction customAction))\n {\n Guards.Fail();\n }\n k.SetAction(FL.Action.CustomActions[customAction], k.IsKeyUp);\n }\n else\n {\n k.SetAction(FL.PlayerConfig.Player.KeyBindings.GetKeyBindingAction(k.Action), k.IsKeyUp);\n }\n }\n\n FL.PlayerConfig.Player.KeyBindings.RemoveAll();\n FL.PlayerConfig.Player.KeyBindings.Keys = newKeys;\n\n }).ObservesCanExecute(() => CanApply);\n}\n\npublic class ActionData : IComparable, IEquatable\n{\n public string Description { get; set; } = null!;\n public string DisplayName { get; set; } = null!;\n public KeyBindingActionGroup Group { get; set; }\n public KeyBindingAction Action { get; set; }\n public CustomKeyBindingAction? CustomAction { get; set; }\n\n public int CompareTo(ActionData? other)\n {\n if (ReferenceEquals(this, other))\n return 0;\n if (other is null)\n return 1;\n return string.Compare(DisplayName, other.DisplayName, StringComparison.Ordinal);\n }\n\n public bool Equals(ActionData? other)\n {\n if (other is null) return false;\n if (ReferenceEquals(this, other)) return true;\n return Action == other.Action && CustomAction == other.CustomAction;\n }\n\n public override bool Equals(object? obj) => obj is ActionData o && Equals(o);\n\n public override int GetHashCode()\n {\n return HashCode.Combine((int)Action, CustomAction);\n }\n}\n\npublic class KeyBindingWrapper : Bindable\n{\n private readonly SettingsKeysVM _parent;\n\n /// \n /// constructor\n /// \n /// \n /// \n /// \n public KeyBindingWrapper(KeyBinding keyBinding, SettingsKeysVM parent)\n {\n ArgumentNullException.ThrowIfNull(parent);\n\n // TODO: L: performance issues when initializing?\n _parent = parent;\n\n Key = keyBinding.Key;\n\n ActionData action = new()\n {\n Action = keyBinding.Action,\n };\n\n if (keyBinding.Action != KeyBindingAction.Custom)\n {\n action.Description = keyBinding.Action.GetDescription();\n action.DisplayName = keyBinding.Action.ToString();\n }\n else if (Enum.TryParse(keyBinding.ActionName, out CustomKeyBindingAction customAction))\n {\n action.CustomAction = customAction;\n action.Description = customAction.GetDescription();\n action.DisplayName = keyBinding.ActionName + @\" ©︎\";\n }\n else\n {\n throw new SettingsPropertyNotFoundException($\"Custom Action '{keyBinding.ActionName}' does not exist.\");\n }\n\n Action = action;\n Alt = keyBinding.Alt;\n Ctrl = keyBinding.Ctrl;\n Shift = keyBinding.Shift;\n IsKeyUp = keyBinding.IsKeyUp;\n IsEnabled = keyBinding.IsEnabled;\n }\n\n public bool IsEnabled\n {\n get;\n set\n {\n if (Set(ref field, value))\n {\n if (!value)\n {\n Duplicated = false;\n DuplicatedInfo = null;\n }\n else\n {\n ValidateShortcut();\n }\n\n ValidateKey(Key);\n }\n }\n }\n\n public bool Alt\n {\n get;\n set\n {\n if (Set(ref field, value) && IsEnabled)\n {\n ValidateShortcut();\n ValidateKey(Key);\n }\n }\n }\n\n public bool Ctrl\n {\n get;\n set\n {\n if (Set(ref field, value) && IsEnabled)\n {\n ValidateShortcut();\n ValidateKey(Key);\n }\n }\n }\n\n public bool Shift\n {\n get;\n set\n {\n if (Set(ref field, value) && IsEnabled)\n {\n ValidateShortcut();\n ValidateKey(Key);\n }\n }\n }\n\n public Key Key\n {\n get;\n set\n {\n Key prevKey = field;\n if (Set(ref field, value) && IsEnabled)\n {\n ValidateShortcut();\n ValidateKey(Key); // maybe don't need?\n // When the key is changed from A -> B, the state of A also needs to be updated.\n ValidateKey(prevKey);\n }\n }\n }\n\n public ActionData Action { get; set => Set(ref field, value); }\n\n public bool IsKeyUp { get; set => Set(ref field, value); }\n\n public bool Duplicated\n {\n get;\n private set\n {\n if (Set(ref field, value))\n {\n // Update duplicate counters held by the parent.\n _parent.DuplicationCount += value ? 1 : -1;\n }\n }\n }\n\n public string? DuplicatedInfo { get; private set => Set(ref field, value); }\n\n private bool IsSameKey(KeyBindingWrapper key)\n {\n return key.Key == Key && key.Alt == Alt && key.Shift == Shift && key.Ctrl == Ctrl;\n }\n\n private void ValidateKey(Key key)\n {\n foreach (var b in _parent.KeyBindings.Where(k => k.IsEnabled && k != this && k.Key == key))\n {\n b.ValidateShortcut();\n }\n }\n\n public KeyBindingWrapper Clone()\n {\n KeyBindingWrapper clone = (KeyBindingWrapper)MemberwiseClone();\n\n return clone;\n }\n\n /// \n /// Convert Wrapper to KeyBinding\n /// \n /// \n public KeyBinding ToKeyBinding()\n {\n KeyBinding binding = new()\n {\n Key = Key,\n Action = Action.Action,\n Ctrl = Ctrl,\n Alt = Alt,\n Shift = Shift,\n IsKeyUp = IsKeyUp,\n IsEnabled = IsEnabled\n };\n\n if (Action.Action == KeyBindingAction.Custom)\n {\n binding.ActionName = Action.CustomAction.ToString();\n }\n\n return binding;\n }\n\n // TODO: L: This validation might be better done in the parent with event firing (I want to eliminate references to the parent).\n public void ValidateShortcut()\n {\n List sameKeys = _parent.KeyBindings\n .Where(k => k != this && k.IsEnabled && k.IsSameKey(this)).ToList();\n\n bool isDuplicate = sameKeys.Count > 0;\n\n UpdateDuplicated(isDuplicate);\n\n // Other records with the same key also update duplicate status\n foreach (KeyBindingWrapper b in sameKeys)\n {\n b.UpdateDuplicated(isDuplicate);\n }\n }\n\n private void UpdateDuplicated(bool duplicated)\n {\n Duplicated = duplicated;\n\n if (duplicated)\n {\n List duplicateActions = _parent.KeyBindings\n .Where(k => k != this && k.IsSameKey(this)).Select(k => k.Action.DisplayName)\n .ToList();\n\n DuplicatedInfo = $\"Key:{Key} is conflicted.\\r\\nAction:{string.Join(',', duplicateActions)} already uses.\";\n }\n else\n {\n DuplicatedInfo = null;\n }\n }\n\n // TODO: L: Enable firing for multiple selections\n public DelegateCommand CmdDeleteRow => new((binding) =>\n {\n if (binding.Duplicated)\n {\n // Reduce duplicate counters of parents\n binding.Duplicated = false;\n }\n _parent.KeyBindings.Remove(binding);\n\n // Update other keys\n if (binding.IsEnabled)\n {\n ValidateKey(binding.Key);\n }\n });\n\n public DelegateCommand CmdSetKey => new((key) =>\n {\n if (key.HasValue)\n {\n Key = key.Value;\n }\n });\n\n public DelegateCommand CmdCloneRow => new((keyBinding) =>\n {\n int index = _parent.KeyBindings.IndexOf(keyBinding);\n if (index != -1)\n {\n KeyBindingWrapper clone = Clone();\n\n _parent.KeyBindings.Insert(index + 1, clone);\n\n // Select added record\n _parent.SelectedKeyBinding = clone;\n\n // validate it\n clone.ValidateShortcut();\n }\n });\n}\n\npublic class KeyCaptureTextBox : TextBox\n{\n private static readonly HashSet IgnoreKeys =\n [\n Key.LeftShift,\n Key.RightShift,\n Key.LeftCtrl,\n Key.RightCtrl,\n Key.LeftAlt,\n Key.RightAlt,\n Key.LWin,\n Key.RWin,\n Key.CapsLock,\n Key.NumLock,\n Key.Scroll\n ];\n\n public static readonly DependencyProperty KeyProperty =\n DependencyProperty.Register(nameof(Key), typeof(Key), typeof(KeyCaptureTextBox),\n new FrameworkPropertyMetadata(Key.None, FrameworkPropertyMetadataOptions.BindsTwoWayByDefault));\n public Key Key\n {\n get => (Key)GetValue(KeyProperty);\n set => SetValue(KeyProperty, value);\n }\n\n public KeyCaptureTextBox()\n {\n Loaded += KeyCaptureTextBox_Loaded;\n }\n\n // Key input does not get focus when mouse clicked, so it gets it.\n private void KeyCaptureTextBox_Loaded(object sender, RoutedEventArgs e)\n {\n Focus();\n Keyboard.Focus(this);\n }\n\n protected override void OnPreviewKeyDown(KeyEventArgs e)\n {\n if (IgnoreKeys.Contains(e.Key))\n {\n return;\n }\n\n // Press Enter to confirm.\n if (e.Key == Key.Enter)\n {\n // This would go to the right cell.\n //MoveFocus(new TraversalRequest(FocusNavigationDirection.Down));\n\n // If the Enter key is pressed, it remains in place and the edit is confirmed\n var dataGrid = UIHelper.FindParent(this);\n if (dataGrid != null)\n {\n dataGrid.CommitEdit(DataGridEditingUnit.Cell, true);\n }\n\n e.Handled = true; // Suppress default behavior (focus movement)\n }\n else\n {\n // Capture other key\n Key = e.Key;\n\n // Converts input key into human understandable name.\n if (KeyToStringConverter.KeyMappings.TryGetValue(e.Key, out string? keyName))\n {\n Text = keyName;\n }\n else\n {\n Text = e.Key.ToString();\n }\n e.Handled = true;\n }\n\n base.OnPreviewKeyDown(e);\n }\n}\n"], ["/LLPlayer/LLPlayer/Controls/Settings/SettingsSubtitlesTrans.xaml.cs", "using System.Globalization;\nusing System.Windows;\nusing System.Windows.Controls;\nusing System.Windows.Data;\nusing FlyleafLib.MediaPlayer.Translation;\nusing FlyleafLib.MediaPlayer.Translation.Services;\nusing LLPlayer.Extensions;\nusing LLPlayer.Services;\n\nnamespace LLPlayer.Controls.Settings;\n\npublic partial class SettingsSubtitlesTrans : UserControl\n{\n public SettingsSubtitlesTrans()\n {\n InitializeComponent();\n\n DataContext = ((App)Application.Current).Container.Resolve();\n }\n}\n\npublic class SettingsSubtitlesTransVM : Bindable\n{\n public FlyleafManager FL { get; }\n\n public SettingsSubtitlesTransVM(FlyleafManager fl)\n {\n FL = fl;\n\n SelectedTranslateServiceType = FL.PlayerConfig.Subtitles.TranslateServiceType;\n }\n\n public TranslateServiceType SelectedTranslateServiceType\n {\n get;\n set\n {\n Set(ref field, value);\n\n FL.PlayerConfig.Subtitles.TranslateServiceType = value;\n\n if (FL.PlayerConfig.Subtitles.TranslateServiceSettings.TryGetValue(value, out var settings))\n {\n // It points to an instance of the same class, so change this will be reflected in the config.\n SelectedServiceSettings = settings;\n }\n else\n {\n ITranslateSettings? defaultSettings = value.DefaultSettings();\n FL.PlayerConfig.Subtitles.TranslateServiceSettings.Add(value, defaultSettings);\n\n SelectedServiceSettings = defaultSettings;\n }\n }\n }\n\n public ITranslateSettings? SelectedServiceSettings { get; set => Set(ref field, value); }\n\n public DelegateCommand? CmdSetDefaultPromptKeepContext => field ??= new(() =>\n {\n FL.PlayerConfig.Subtitles.TranslateChatConfig.PromptKeepContext = TranslateChatConfig.DefaultPromptKeepContext.ReplaceLineEndings(\"\\n\");\n });\n\n public DelegateCommand? CmdSetDefaultPromptOneByOne => field ??= new(() =>\n {\n FL.PlayerConfig.Subtitles.TranslateChatConfig.PromptOneByOne = TranslateChatConfig.DefaultPromptOneByOne.ReplaceLineEndings(\"\\n\");\n });\n}\n\n[ValueConversion(typeof(TargetLanguage), typeof(string))]\ninternal class TargetLanguageEnumToStringConverter : IValueConverter\n{\n public object Convert(object value, Type targetType, object parameter, CultureInfo culture)\n {\n if (value is TargetLanguage enumValue)\n {\n return enumValue.DisplayName();\n }\n return value?.ToString() ?? string.Empty;\n }\n\n public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)\n {\n throw new NotImplementedException();\n }\n}\n\n[ValueConversion(typeof(TranslateServiceType), typeof(string))]\ninternal class TranslateServiceTypeEnumToStringConverter : IValueConverter\n{\n public object Convert(object value, Type targetType, object parameter, CultureInfo culture)\n {\n if (value is TranslateServiceType enumValue)\n {\n string displayName = enumValue.GetDescription();\n\n if (enumValue.IsLLM())\n {\n return $\"{displayName} (LLM)\";\n }\n\n return $\"{displayName}\";\n }\n\n return value?.ToString() ?? string.Empty;\n }\n\n public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)\n {\n throw new NotImplementedException();\n }\n}\n\n[ValueConversion(typeof(TranslateServiceType), typeof(string))]\ninternal class TranslateServiceTypeEnumToUrlConverter : IValueConverter\n{\n private const string BaseUrl = \"https://github.com/umlx5h/LLPlayer/wiki/Translation-Engine\";\n public object Convert(object value, Type targetType, object parameter, CultureInfo culture)\n {\n if (value is TranslateServiceType enumValue)\n {\n string displayName = enumValue.GetDescription();\n\n return $\"{BaseUrl}#{displayName.ToLower().Replace(' ', '-')}\";\n }\n return BaseUrl;\n }\n\n public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)\n {\n throw new NotImplementedException();\n }\n}\n\n[ValueConversion(typeof(TargetLanguage), typeof(string))]\ninternal class TargetLanguageEnumToNoSupportedTranslateServiceConverter : IValueConverter\n{\n public object Convert(object value, Type targetType, object parameter, CultureInfo culture)\n {\n if (value is TargetLanguage enumValue)\n {\n TranslateServiceType supported = enumValue.SupportedServiceType();\n\n // DeepL = DeepLX\n List notSupported =\n Enum.GetValues()\n .Where(t => t != TranslateServiceType.DeepLX)\n .Where(t => !supported.HasFlag(t))\n .ToList();\n\n if (notSupported.Count == 0)\n {\n return \"[All supported]\";\n }\n\n return string.Join(',', notSupported.Select(t => t.ToString()));\n }\n return value?.ToString() ?? string.Empty;\n }\n\n public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)\n {\n throw new NotImplementedException();\n }\n}\n"], ["/LLPlayer/LLPlayer/Services/AppConfig.cs", "using System.Collections.ObjectModel;\nusing System.ComponentModel;\nusing System.IO;\nusing System.Text.Json;\nusing System.Text.Json.Serialization;\nusing System.Windows;\nusing System.Windows.Input;\nusing System.Windows.Media;\nusing FlyleafLib;\nusing FlyleafLib.MediaPlayer;\nusing FlyleafLib.MediaPlayer.Translation.Services;\nusing LLPlayer.Extensions;\nusing MaterialDesignThemes.Wpf;\nusing Vortice.Mathematics;\nusing Color = System.Windows.Media.Color;\nusing Colors = System.Windows.Media.Colors;\nusing Size = System.Windows.Size;\n\nnamespace LLPlayer.Services;\n\npublic class AppConfig : Bindable\n{\n private FlyleafManager FL = null!;\n\n public void Initialize(FlyleafManager fl)\n {\n FL = fl;\n Loaded = true;\n\n Subs.Initialize(this, fl);\n }\n\n public string Version { get; set; } = \"\";\n\n /// \n /// State to skip the setter run when reading JSON\n /// \n [JsonIgnore]\n public bool Loaded { get; private set; }\n\n public void FlyleafHostLoaded()\n {\n Subs.FlyleafHostLoaded();\n\n // Ensure that FlyeafHost reflects the configuration values when restoring the configuration.\n FL.FlyleafHost!.ActivityTimeout = FL.Config.ActivityTimeout;\n }\n\n public AppConfigSubs Subs { get; set => Set(ref field, value); } = new();\n\n public static AppConfig Load(string path)\n {\n AppConfig config = JsonSerializer.Deserialize(File.ReadAllText(path), GetJsonSerializerOptions())!;\n\n return config;\n }\n\n public void Save(string path)\n {\n Version = App.Version;\n File.WriteAllText(path, JsonSerializer.Serialize(this, GetJsonSerializerOptions()));\n\n Subs.SaveAfter();\n }\n\n public AppConfigTheme Theme { get; set => Set(ref field, value); } = new();\n\n public bool AlwaysOnTop { get; set => Set(ref field, value); }\n\n [JsonIgnore]\n public double ScreenWidth\n {\n private get;\n set => Set(ref field, value);\n }\n\n // Video Screen Height (including black background), without titlebar height\n [JsonIgnore]\n public double ScreenHeight\n {\n internal get;\n set\n {\n if (Set(ref field, value))\n {\n Subs.UpdateSubsConfig();\n }\n }\n }\n\n public bool IsDarkTitlebar { get; set => Set(ref field, value); } = true;\n\n public int ActivityTimeout\n {\n get;\n set\n {\n if (Set(ref field, value))\n {\n if (Loaded && FL.FlyleafHost != null)\n {\n FL.FlyleafHost.ActivityTimeout = value;\n }\n }\n }\n } = 1200;\n\n public bool ShowSidebar { get; set => Set(ref field, value); } = true;\n\n [JsonIgnore]\n public bool ShowDebug\n {\n get;\n set\n {\n if (Set(ref field, value))\n {\n FL.PlayerConfig.Player.Stats = value;\n }\n }\n }\n\n\n #region FlyleafBar\n public bool SeekBarShowOnlyMouseOver { get; set => Set(ref field, value); } = false;\n public int SeekBarFadeInTimeMs { get; set => Set(ref field, value); } = 80;\n public int SeekBarFadeOutTimeMs { get; set => Set(ref field, value); } = 150;\n #endregion\n\n #region Mouse\n public bool MouseSingleClickToPlay { get; set => Set(ref field, value); } = true;\n public bool MouseDoubleClickToFullScreen { get; set => Set(ref field, value); }\n public bool MouseWheelToVolumeUpDown { get; set => Set(ref field, value); } = true;\n #endregion\n\n // TODO: L: should be move to AppConfigSubs?\n public bool SidebarLeft\n {\n get;\n set\n {\n if (Set(ref field, value))\n {\n OnPropertyChanged(nameof(SidebarFlowDirection));\n }\n }\n }\n\n [JsonIgnore]\n public FlowDirection SidebarFlowDirection => !SidebarLeft ? FlowDirection.LeftToRight : FlowDirection.RightToLeft;\n\n public int SidebarWidth { get; set => Set(ref field, value); } = 300;\n\n public int SidebarSubPadding { get; set => Set(ref field, value); } = 5;\n\n [JsonIgnore]\n public bool SidebarShowSecondary { get; set => Set(ref field, value); }\n\n public bool SidebarShowOriginalText { get; set => Set(ref field, value); }\n\n public bool SidebarTextMask { get; set => Set(ref field, value); }\n\n [JsonIgnore]\n public bool SidebarSearchActive { get; set => Set(ref field, value); }\n\n public string SidebarFontFamily { get; set => Set(ref field, value); } = \"Segoe UI\";\n\n public double SidebarFontSize { get; set => Set(ref field, value); } = 16;\n\n public string SidebarFontWeight { get; set => Set(ref field, value); } = FontWeights.Normal.ToString();\n\n public static JsonSerializerOptions GetJsonSerializerOptions()\n {\n Dictionary typeMappingMenuAction = new()\n {\n { nameof(ClipboardMenuAction), typeof(ClipboardMenuAction) },\n { nameof(ClipboardAllMenuAction), typeof(ClipboardAllMenuAction) },\n { nameof(SearchMenuAction), typeof(SearchMenuAction) },\n };\n\n Dictionary typeMappingTranslateSettings = new()\n {\n { nameof(GoogleV1TranslateSettings), typeof(GoogleV1TranslateSettings) },\n { nameof(DeepLTranslateSettings), typeof(DeepLTranslateSettings) },\n { nameof(DeepLXTranslateSettings), typeof(DeepLXTranslateSettings) },\n { nameof(OllamaTranslateSettings), typeof(OllamaTranslateSettings) },\n { nameof(LMStudioTranslateSettings), typeof(LMStudioTranslateSettings) },\n { nameof(KoboldCppTranslateSettings), typeof(KoboldCppTranslateSettings) },\n { nameof(OpenAITranslateSettings), typeof(OpenAITranslateSettings) },\n { nameof(OpenAILikeTranslateSettings), typeof(OpenAILikeTranslateSettings) },\n { nameof(ClaudeTranslateSettings), typeof(ClaudeTranslateSettings) },\n { nameof(LiteLLMTranslateSettings), typeof(LiteLLMTranslateSettings) }\n };\n\n JsonSerializerOptions jsonOptions = new()\n {\n WriteIndented = true,\n DefaultIgnoreCondition = JsonIgnoreCondition.WhenWritingNull,\n Converters =\n {\n new JsonStringEnumConverter(),\n // TODO: L: should separate converters for different types of config?\n new JsonInterfaceConcreteConverter(typeMappingMenuAction),\n new JsonInterfaceConcreteConverter(typeMappingTranslateSettings),\n new ColorHexJsonConverter()\n }\n };\n\n return jsonOptions;\n }\n}\n\npublic class AppConfigSubs : Bindable\n{\n private AppConfig _rootConfig = null!;\n private FlyleafManager FL = null!;\n\n [JsonIgnore]\n public bool Loaded { get; private set; }\n\n public void Initialize(AppConfig rootConfig, FlyleafManager fl)\n {\n _rootConfig = rootConfig;\n FL = fl;\n Loaded = true;\n\n // Save the initial value of the position for reset.\n _subsPositionInitial = SubsPosition;\n\n // register event handler\n var pSubsAutoCopy = SubsAutoTextCopy;\n SubsAutoTextCopy = false;\n SubsAutoTextCopy = pSubsAutoCopy;\n }\n\n public void FlyleafHostLoaded()\n {\n Viewport = FL.Player.renderer.GetViewport;\n\n FL.Player.renderer.ViewportChanged += (sender, args) =>\n {\n Utils.UIIfRequired(() =>\n {\n Viewport = FL.Player.renderer.GetViewport;\n });\n };\n }\n\n public void SaveAfter()\n {\n // Update initial value\n _subsPositionInitial = SubsPosition;\n }\n\n [JsonIgnore]\n public Viewport Viewport\n {\n get;\n private set\n {\n var prev = Viewport;\n if (Set(ref field, value))\n {\n if ((int)prev.Width != (int)value.Width)\n {\n // update font size if width changed\n OnPropertyChanged(nameof(SubsFontSizeFix));\n OnPropertyChanged(nameof(SubsFontSize2Fix));\n }\n\n if ((int)prev.Height != (int)value.Height ||\n (int)prev.Y != (int)value.Y)\n {\n // update font margin/distance if height/Y changed\n UpdateSubsConfig();\n }\n }\n }\n }\n\n public bool SubsUseSeparateFonts\n {\n get;\n set\n {\n if (Set(ref field, value))\n {\n // update subtitles\n UpdateSecondaryFonts();\n\n OnPropertyChanged(nameof(SubsFontColor2Fix));\n OnPropertyChanged(nameof(SubsBackgroundBrush2));\n }\n }\n }\n\n internal void UpdateSecondaryFonts()\n {\n // update subtitles display\n OnPropertyChanged(nameof(SubsFontFamily2Fix));\n OnPropertyChanged(nameof(SubsFontStretch2Fix));\n OnPropertyChanged(nameof(SubsFontWeight2Fix));\n OnPropertyChanged(nameof(SubsFontStyle2Fix));\n\n CmdResetSubsFont2!.RaiseCanExecuteChanged();\n }\n\n // Primary Subtitle Size\n public double SubsFontSize\n {\n get;\n set\n {\n if (value <= 0)\n {\n return;\n }\n\n if (Set(ref field, Math.Round(value)))\n {\n OnPropertyChanged(nameof(SubsFontSizeFix));\n CmdResetSubsFontSize2!.RaiseCanExecuteChanged();\n }\n }\n } = 44;\n\n [JsonIgnore]\n public double SubsFontSizeFix => GetFixFontSize(SubsFontSize);\n\n // Secondary Subtitle Size\n public double SubsFontSize2\n {\n get;\n set\n {\n if (value <= 0)\n {\n return;\n }\n\n if (Set(ref field, Math.Round(value)))\n {\n OnPropertyChanged(nameof(SubsFontSize2Fix));\n CmdResetSubsFontSize2!.RaiseCanExecuteChanged();\n }\n }\n } = 44;\n\n [JsonIgnore]\n public double SubsFontSize2Fix => GetFixFontSize(SubsFontSize2);\n\n private double GetFixFontSize(double fontSize)\n {\n double scaleFactor = Viewport.Width / 1920;\n double size = fontSize * scaleFactor;\n if (size > 0)\n {\n return size;\n }\n\n return fontSize;\n }\n\n private const string DefaultFont = \"Segoe UI\";\n public string SubsFontFamily { get; set => Set(ref field, value); } = DefaultFont;\n public string SubsFontStretch { get; set => Set(ref field, value); } = FontStretches.Normal.ToString();\n public string SubsFontWeight { get; set => Set(ref field, value); } = FontWeights.Bold.ToString();\n public string SubsFontStyle { get; set => Set(ref field, value); } = FontStyles.Normal.ToString();\n public Color SubsFontColor\n {\n get;\n set\n {\n if (Set(ref field, value))\n {\n OnPropertyChanged(nameof(SubsFontColor2Fix));\n CmdResetSubsFontColor2!.RaiseCanExecuteChanged();\n }\n }\n } = Colors.White;\n\n [JsonIgnore]\n public string SubsFontFamily2Fix => SubsUseSeparateFonts ? SubsFontFamily2 : SubsFontFamily;\n public string SubsFontFamily2 { get; set => Set(ref field, value); } = DefaultFont;\n\n [JsonIgnore]\n public string SubsFontStretch2Fix => SubsUseSeparateFonts ? SubsFontStretch2 : SubsFontStretch;\n public string SubsFontStretch2 { get; set => Set(ref field, value); } = FontStretches.Normal.ToString();\n\n [JsonIgnore]\n public string SubsFontWeight2Fix => SubsUseSeparateFonts ? SubsFontWeight2 : SubsFontWeight;\n public string SubsFontWeight2 { get; set => Set(ref field, value); } = FontWeights.SemiBold.ToString(); // change from bold\n\n [JsonIgnore]\n public string SubsFontStyle2Fix => SubsUseSeparateFonts ? SubsFontStyle2 : SubsFontStyle;\n public string SubsFontStyle2 { get; set => Set(ref field, value); } = FontStyles.Normal.ToString();\n\n [JsonIgnore]\n public Color SubsFontColor2Fix => SubsUseSeparateFonts ? SubsFontColor2 : SubsFontColor;\n public Color SubsFontColor2\n {\n get;\n set\n {\n if (Set(ref field, value))\n {\n OnPropertyChanged(nameof(SubsFontColor2Fix));\n CmdResetSubsFontColor2!.RaiseCanExecuteChanged();\n }\n }\n } = Color.FromRgb(231, 231, 231); // #E7E7E7\n\n public Color SubsStrokeColor { get; set => Set(ref field, value); } = Colors.Black;\n public double SubsStrokeThickness { get; set => Set(ref field, value); } = 3.2;\n\n public Color SubsBackgroundColor\n {\n get;\n set\n {\n if (Set(ref field, value))\n {\n OnPropertyChanged(nameof(SubsBackgroundBrush));\n OnPropertyChanged(nameof(SubsBackgroundBrush2));\n }\n }\n } = Colors.Black;\n\n public double SubsBackgroundOpacity\n {\n get;\n set\n {\n if (value < 0.0 || value > 1.0)\n {\n return;\n }\n\n if (Set(ref field, Math.Round(value, 2)))\n {\n OnPropertyChanged(nameof(SubsBackgroundBrush));\n OnPropertyChanged(nameof(SubsBackgroundBrush2));\n CmdResetSubsBackgroundOpacity2!.RaiseCanExecuteChanged();\n }\n }\n } = 0; // default no background\n\n [JsonIgnore]\n public SolidColorBrush SubsBackgroundBrush\n {\n get\n {\n byte alpha = (byte)(SubsBackgroundOpacity * 255);\n return new SolidColorBrush(Color.FromArgb(alpha, SubsBackgroundColor.R, SubsBackgroundColor.G, SubsBackgroundColor.B));\n }\n }\n\n [JsonIgnore]\n private double SubsBackgroundOpacity2Fix => SubsUseSeparateFonts ? SubsBackgroundOpacity2 : SubsBackgroundOpacity;\n public double SubsBackgroundOpacity2\n {\n get;\n set\n {\n if (value < 0.0 || value > 1.0)\n {\n return;\n }\n\n if (Set(ref field, Math.Round(value, 2)))\n {\n OnPropertyChanged(nameof(SubsBackgroundBrush2));\n CmdResetSubsBackgroundOpacity2!.RaiseCanExecuteChanged();\n }\n }\n } = 0;\n\n [JsonIgnore]\n public SolidColorBrush SubsBackgroundBrush2\n {\n get\n {\n byte alpha = (byte)(SubsBackgroundOpacity2Fix * 255);\n return new SolidColorBrush(Color.FromArgb(alpha, SubsBackgroundColor.R, SubsBackgroundColor.G, SubsBackgroundColor.B));\n }\n }\n\n [JsonIgnore]\n public DelegateCommand? CmdResetSubsFontSize2 => field ??= new(() =>\n {\n SubsFontSize2 = SubsFontSize;\n }, () => SubsFontSize2 != SubsFontSize);\n\n [JsonIgnore]\n public DelegateCommand? CmdResetSubsFont2 => field ??= new(() =>\n {\n SubsFontFamily2 = SubsFontFamily;\n SubsFontStretch2 = SubsFontStretch;\n SubsFontWeight2 = SubsFontWeight;\n SubsFontStyle2 = SubsFontStyle;\n\n UpdateSecondaryFonts();\n }, () =>\n SubsFontFamily2 != SubsFontFamily ||\n SubsFontStretch2 != SubsFontStretch ||\n SubsFontWeight2 != SubsFontWeight ||\n SubsFontStyle2 != SubsFontStyle\n );\n\n [JsonIgnore]\n public DelegateCommand? CmdResetSubsFontColor2 => field ??= new(() =>\n {\n SubsFontColor2 = SubsFontColor;\n }, () => SubsFontColor2 != SubsFontColor);\n\n [JsonIgnore]\n public DelegateCommand? CmdResetSubsBackgroundOpacity2 => field ??= new(() =>\n {\n SubsBackgroundOpacity2 = SubsBackgroundOpacity;\n }, () => SubsBackgroundOpacity2 != SubsBackgroundOpacity);\n\n [JsonIgnore]\n public Size SubsPanelSize\n {\n private get;\n set\n {\n if (Set(ref field, value))\n {\n UpdateSubsMargin();\n }\n }\n }\n\n private bool _isSubsOverflowBottom;\n\n [JsonIgnore]\n public Thickness SubsMargin\n {\n get;\n set => Set(ref field, value);\n }\n\n private double _subsPositionInitial;\n public void ResetSubsPosition()\n {\n SubsPosition = _subsPositionInitial;\n }\n\n #region Offsets\n\n public double SubsPositionOffset { get; set => Set(ref field, value); } = 2;\n public int SubsFontSizeOffset { get; set => Set(ref field, value); } = 2;\n public double SubsBitmapScaleOffset { get; set => Set(ref field, value); } = 4;\n public double SubsDistanceOffset { get; set => Set(ref field, value); } = 5;\n\n #endregion\n\n // -25%-150%\n // Allow some going up and down from ViewPort\n public double SubsPosition\n {\n get;\n set\n {\n if (_isSubsOverflowBottom && SubsPanelSize.Height > 0 && field < value)\n {\n // Prohibit going further down when it overflows below.\n return;\n }\n\n if (value < -25 || value > 150)\n {\n return;\n }\n\n if (Set(ref field, Math.Round(value)))\n {\n UpdateSubsMargin();\n }\n }\n } = 85;\n\n public SubPositionAlignment SubsPositionAlignment\n {\n get;\n set\n {\n if (Set(ref field, value))\n {\n UpdateSubsConfig();\n }\n }\n } = SubPositionAlignment.Center;\n\n public SubPositionAlignment SubsPositionAlignmentWhenDual\n {\n get;\n set\n {\n if (Set(ref field, value))\n {\n UpdateSubsConfig();\n }\n }\n } = SubPositionAlignment.Top;\n\n // 0%-100%\n public double SubsFixOverflowMargin\n {\n get;\n set\n {\n if (value < 0.0 || value > 100.0)\n {\n return;\n }\n\n Set(ref field, value);\n }\n } = 3.0;\n\n [JsonIgnore]\n public double SubsDistanceFix { get; set => Set(ref field, value); }\n\n public double SubsDistance\n {\n get;\n set\n {\n if (value < 1)\n {\n return;\n }\n\n if (Set(ref field, Math.Round(value)))\n {\n UpdateSubsDistance();\n }\n }\n } = 16;\n\n public double SubsSeparatorMaxWidth { get; set => Set(ref field, value); } = 280;\n public double SubsSeparatorOpacity\n {\n get;\n set\n {\n if (value < 0.0 || value > 1.0)\n {\n return;\n }\n\n Set(ref field, value);\n }\n } = 0.3;\n\n public double SubsWidthPercentage\n {\n get;\n set\n {\n if (value < 1.0 || value > 100.0)\n {\n return;\n }\n\n Set(ref field, value);\n }\n } = 66.0;\n\n public double SubsMaxWidth\n {\n get;\n set\n {\n if (value < 0)\n {\n return;\n }\n\n Set(ref field, value);\n }\n } = 0;\n\n public bool SubsIgnoreLineBreak { get; set => Set(ref field, value); }\n\n internal void UpdateSubsConfig()\n {\n if (!Loaded)\n return;\n\n UpdateSubsDistance();\n UpdateSubsMargin();\n }\n\n private void UpdateSubsDistance()\n {\n if (!Loaded)\n return;\n\n float scaleFactor = Viewport.Height / 1080;\n double newDistance = SubsDistance * scaleFactor;\n\n SubsDistanceFix = newDistance;\n }\n\n private void UpdateSubsMargin()\n {\n if (!Loaded)\n return;\n\n // Set the margin from the top based on Viewport, not Window\n // Allow going above or below the Viewport\n float offset = Viewport.Y;\n float height = Viewport.Height;\n\n double marginTop = height * (SubsPosition / 100.0);\n double marginTopFix = marginTop + offset;\n\n // Adjustment for vertical alignment of subtitles\n SubPositionAlignment alignment = SubsPositionAlignment;\n if (FL.Player.Subtitles[0].Enabled && FL.Player.Subtitles[1].Enabled)\n {\n alignment = SubsPositionAlignmentWhenDual;\n }\n\n if (alignment == SubPositionAlignment.Center)\n {\n marginTopFix -= SubsPanelSize.Height / 2;\n }\n else if (alignment == SubPositionAlignment.Bottom)\n {\n marginTopFix -= SubsPanelSize.Height;\n }\n\n // Corrects for off-screen subtitles if they are detected.\n marginTopFix = FixOverflowSubsPosition(marginTopFix);\n\n SubsMargin = new Thickness(SubsMargin.Left, marginTopFix, SubsMargin.Right, SubsMargin.Bottom);\n }\n\n /// \n /// Detects whether subtitles are placed off-screen and corrects them if they appear\n /// \n /// \n /// \n private double FixOverflowSubsPosition(double marginTop)\n {\n double subHeight = SubsPanelSize.Height;\n\n double bottomMargin = Viewport.Height * (SubsFixOverflowMargin / 100.0);\n\n if (subHeight + marginTop + bottomMargin > _rootConfig.ScreenHeight)\n {\n // It overflowed, so fix it.\n _isSubsOverflowBottom = true;\n double fixedMargin = _rootConfig.ScreenHeight - subHeight - bottomMargin;\n return fixedMargin;\n }\n\n _isSubsOverflowBottom = false;\n return marginTop;\n }\n\n public bool SubsExportUTF8WithBom { get; set => Set(ref field, value); } = true;\n\n public bool SubsAutoTextCopy\n {\n get;\n set\n {\n if (Set(ref field, value) && Loaded)\n {\n if (value)\n {\n FL.Player.Subtitles[0].Data.PropertyChanged += SubtitleTextOnPropertyChanged;\n FL.Player.Subtitles[1].Data.PropertyChanged += SubtitleTextOnPropertyChanged;\n }\n else\n {\n FL.Player.Subtitles[0].Data.PropertyChanged -= SubtitleTextOnPropertyChanged;\n FL.Player.Subtitles[1].Data.PropertyChanged -= SubtitleTextOnPropertyChanged;\n }\n }\n }\n }\n\n public SubAutoTextCopyTarget SubsAutoTextCopyTarget { get; set => Set(ref field, value); } = SubAutoTextCopyTarget.Primary;\n\n private void SubtitleTextOnPropertyChanged(object? sender, PropertyChangedEventArgs e)\n {\n if (e.PropertyName != nameof(SubsData.Text))\n return;\n\n switch (SubsAutoTextCopyTarget)\n {\n case SubAutoTextCopyTarget.All:\n if (FL.Player.Subtitles[0].Data.Text != \"\" ||\n FL.Player.Subtitles[1].Data.Text != \"\")\n {\n FL.Action.CmdSubsTextCopy.Execute(true);\n }\n break;\n case SubAutoTextCopyTarget.Primary:\n if (FL.Player.Subtitles[0].Data == sender && FL.Player.Subtitles[0].Data.Text != \"\")\n {\n FL.Action.CmdSubsPrimaryTextCopy.Execute(true);\n }\n break;\n case SubAutoTextCopyTarget.Secondary:\n if (FL.Player.Subtitles[1].Data == sender && FL.Player.Subtitles[1].Data.Text != \"\")\n {\n FL.Action.CmdSubsSecondaryTextCopy.Execute(true);\n }\n break;\n }\n }\n\n public WordClickAction WordClickActionMethod { get; set => Set(ref field, value); }\n public bool WordCopyOnSelected { get; set => Set(ref field, value); } = true;\n public bool WordLastSearchOnSelected { get; set => Set(ref field, value); } = true;\n\n public ModifierKeys WordLastSearchOnSelectedModifier { get; set => Set(ref field, value); } = ModifierKeys.Control;\n public ObservableCollection WordMenuActions { get; set => Set(ref field, value); } = new(\n [\n new ClipboardMenuAction(),\n new ClipboardAllMenuAction(),\n new SearchMenuAction{ Title = \"Search Google\", Url = \"https://www.google.com/search?q=%w\" },\n new SearchMenuAction{ Title = \"Search Wiktionary\", Url = \"https://en.wiktionary.org/wiki/Special:Search?search=%w&go=Look+up\" },\n new SearchMenuAction{ Title = \"Search Longman\", Url = \"https://www.ldoceonline.com/search/english/direct/?q=%w\" },\n ]);\n public string? PDICPipeExecutablePath { get; set => Set(ref field, value); }\n}\n\npublic enum SubAutoTextCopyTarget\n{\n Primary,\n Secondary,\n All\n}\n\npublic enum SubPositionAlignment\n{\n Top, // This is useful for dual subs because primary sub position is stayed\n Center, // Same as bitmap subs\n Bottom // Normal video players use this\n}\n\npublic class AppConfigTheme : Bindable\n{\n private readonly PaletteHelper _paletteHelper = new();\n\n public Color PrimaryColor\n {\n get;\n set\n {\n if (Set(ref field, value))\n {\n Theme cur = _paletteHelper.GetTheme();\n cur.SetPrimaryColor(value);\n _paletteHelper.SetTheme(cur);\n }\n }\n } = (Color)ColorConverter.ConvertFromString(\"#D23D6F\"); // Pink\n // Desaturate and lighten from material pink 500\n // https://m2.material.io/design/color/the-color-system.html#tools-for-picking-colors\n // $ pastel color E91E63 | pastel desaturate 0.2 | pastel lighten 0.015\n\n public Color SecondaryColor\n {\n get;\n set\n {\n if (Set(ref field, value))\n {\n Theme cur = _paletteHelper.GetTheme();\n cur.SetSecondaryColor(value);\n _paletteHelper.SetTheme(cur);\n }\n }\n } = (Color)ColorConverter.ConvertFromString(\"#00B8D4\"); // Cyan\n}\n\npublic interface IMenuAction : INotifyPropertyChanged, ICloneable\n{\n [JsonIgnore]\n string Type { get; }\n string Title { get; set; }\n bool IsEnabled { get; set; }\n}\n\npublic class SearchMenuAction : Bindable, IMenuAction\n{\n [JsonIgnore]\n public string Type => \"Search\";\n public required string Title { get; set; }\n public required string Url { get; set => Set(ref field, value); }\n public bool IsEnabled { get; set => Set(ref field, value); } = true;\n\n public object Clone()\n {\n return new SearchMenuAction\n {\n Title = Title,\n Url = Url,\n IsEnabled = IsEnabled\n };\n }\n}\n\npublic class ClipboardMenuAction : Bindable, IMenuAction\n{\n [JsonIgnore]\n public string Type => \"Clipboard\";\n public string Title { get; set; } = \"Copy\";\n public bool ToLower { get; set => Set(ref field, value); }\n public bool IsEnabled { get; set => Set(ref field, value); } = true;\n\n public object Clone()\n {\n return new ClipboardMenuAction\n {\n Title = Title,\n ToLower = ToLower,\n IsEnabled = IsEnabled\n };\n }\n}\n\npublic class ClipboardAllMenuAction : Bindable, IMenuAction\n{\n [JsonIgnore]\n public string Type => \"ClipboardAll\";\n public string Title { get; set; } = \"Copy All\";\n public bool ToLower { get; set => Set(ref field, value); }\n public bool IsEnabled { get; set => Set(ref field, value); } = true;\n\n public object Clone()\n {\n return new ClipboardAllMenuAction\n {\n Title = Title,\n ToLower = ToLower,\n IsEnabled = IsEnabled\n };\n }\n}\n\npublic enum WordClickAction\n{\n Translation,\n Clipboard,\n ClipboardAll,\n PDIC\n}\n"], ["/LLPlayer/FlyleafLib/Controls/WPF/FlyleafHost.cs", "using System;\nusing System.ComponentModel;\nusing System.Windows.Controls;\nusing System.Windows;\nusing System.Windows.Media;\nusing System.Windows.Input;\nusing System.Windows.Interop;\n\nusing FlyleafLib.MediaPlayer;\n\nusing static FlyleafLib.Utils;\nusing static FlyleafLib.Utils.NativeMethods;\n\nusing Brushes = System.Windows.Media.Brushes;\n\nnamespace FlyleafLib.Controls.WPF;\n\npublic class FlyleafHost : ContentControl, IHostPlayer, IDisposable\n{\n /* -= FlyleafHost Properties Notes =-\n\n Player\t\t\t\t\t\t\t[Can be changed, can be null]\n ReplicaPlayer | Replicates frames of the assigned Player (useful for interactive zoom) without the pan/zoom config\n\n Surface\t\t\t\t\t\t\t[ReadOnly / Required]\n Overlay\t\t\t\t\t\t\t[AutoCreated OnContentChanged | Provided directly | Provided in Stand Alone Constructor]\n\n Content\t\t\t\t\t\t\t[Overlay's Content]\n DetachedContent\t\t\t\t\t[Host's actual content]\n\n DataContext\t\t\t\t\t\t[Set by the user or default inheritance]\n HostDataContext\t\t\t\t\t[Will be set Sync with DataContext as helper to Overlay when we pass this as Overlay's DataContext]\n\n OpenOnDrop\t\t\t\t\t\t[None, Surface, Overlay, Both]\t\t| Requires Player and AllowDrop\n SwapOnDrop\t\t\t\t\t\t[None, Surface, Overlay, Both]\t\t| Requires Player and AllowDrop\n\n SwapDragEnterOnShift\t\t\t[None, Surface, Overlay, Both]\t\t| Requires Player and SwapOnDrop\n ToggleFullScreenOnDoubleClick\t[None, Surface, Overlay, Both]\n\n PanMoveOnCtrl\t\t\t\t\t[None, Surface, Overlay, Both]\t\t| Requires Player and VideoStream Opened\n PanZoomOnCtrlWheel\t\t\t [None, Surface, Overlay, Both]\t\t| Requires Player and VideoStream Opened\n PanRotateOnShiftWheel [None, Surface, Overlay, Both] | Requires Player and VideoStream Opened\n\n AttachedDragMove\t\t\t\t[None, Surface, Overlay, Both, SurfaceOwner, OverlayOwner, BothOwner]\n DetachedDragMove\t\t\t\t[None, Surface, Overlay, Both]\n\n AttachedResize\t\t\t\t\t[None, Surface, Overlay, Both]\n DetachedResize\t\t\t\t\t[None, Surface, Overlay, Both]\n KeepRatioOnResize\t\t\t\t[False, True]\n PreferredLandscapeWidth [X] | When KeepRatioOnResize will use it as helper and try to stay close to this value (CurResizeRatio >= 1) - Will be updated when user resizes a landscape\n PreferredPortraitHeight [Y] | When KeepRatioOnResize will use it as helper and try to stay close to this value (CurResizeRatio < 1) - Will be updated when user resizes a portrait\n CurResizeRatio [0 if not Keep Ratio or Player's aspect ratio]\n ResizeSensitivity Pixels sensitivity from the window's edges\n\n BringToFrontOnClick [False, True]\n\n DetachedPosition\t\t\t\t[Custom, TopLeft, TopCenter, TopRight, CenterLeft, CenterCenter, CenterRight, BottomLeft, BottomCenter, BottomRight]\n DetachedPositionMargin\t\t\t[X, Y, CX, CY]\t\t\t\t\t\t| Does not affect the Size / Eg. No point to provide both X/CX\n DetachedFixedPosition\t\t\t[X, Y]\t\t\t\t\t\t\t\t| if remember only first time\n DetachedFixedSize\t\t\t\t[CX, CY]\t\t\t\t\t\t\t| if remember only first time\n DetachedRememberPosition\t\t[False, True]\n DetachedRememberSize\t\t\t[False, True]\n DetachedTopMost\t\t\t\t\t[False, True] (Surfaces Only Required?)\n DetachedShowInTaskbar [False, True] | When Detached or Fullscreen will be in Switch Apps\n DetachedNoOwner [False, True] | When Detached will not follow the owner's window state (Minimize/Maximize)\n\n KeyBindings\t\t\t\t\t\t[None, Surface, Overlay, Both]\n MouseBindings [None, Surface, Overlay, Both] | Required for all other mouse events\n\n ActivityTimeout\t\t\t\t\t[0: Disabled]\t\t\t\t\t\t| Requires Player?\n ActivityRefresh?\t\t\t\t[None, Surface, Overlay, Both]\t\t| MouseMove / MouseDown / KeyUp\n\n PassWheelToOwner?\t\t\t\t[None, Surface, Overlay, Both]\t\t| When host belongs to ScrollViewer\n\n IsAttached [False, True]\n IsFullScreen [False, True] | Should be used instead of WindowStates\n IsMinimized [False, True] | Should be used instead of WindowStates\n IsResizing\t\t\t\t\t\t[ReadOnly]\n IsSwapping\t\t\t\t\t\t[ReadOnly]\n IsStandAlone\t\t\t\t\t[ReadOnly]\n */\n\n /* TODO\n * 1) The surface / overlay events code is repeated\n * 2) PassWheelToOwner (Related with LayoutUpdate performance / ScrollViewer) / ActivityRefresh\n * 3) Attach to different Owner (Load/Unload) and change Overlay?\n * 4) WindowStates should not be used by user directly. Use IsMinimized and IsFullScreen instead.\n * 5) WS_EX_NOACTIVATE should be set but for some reason is not required (for none-styled windows)? Currently BringToFront does the job but (only for left clicks?)\n */\n\n #region Properties / Variables\n public Window Owner { get; private set; }\n public Window Surface { get; private set; }\n public IntPtr SurfaceHandle { get; private set; }\n public IntPtr OverlayHandle { get; private set; }\n public IntPtr OwnerHandle { get; private set; }\n public int ResizingSide { get; private set; }\n\n public int UniqueId { get; private set; }\n public bool Disposed { get; private set; }\n\n\n public event EventHandler SurfaceCreated;\n public event EventHandler OverlayCreated;\n public event DragEventHandler OnSurfaceDrop;\n public event DragEventHandler OnOverlayDrop;\n\n static bool isDesignMode;\n static int idGenerator = 1;\n static nint NONE_STYLE = (nint) (WindowStyles.WS_MINIMIZEBOX | WindowStyles.WS_CLIPSIBLINGS | WindowStyles.WS_CLIPCHILDREN | WindowStyles.WS_VISIBLE); // WS_MINIMIZEBOX required for swapchain\n static Rect rectRandom = new(1, 2, 3, 4);\n\n float curResizeRatio;\n float curResizeRatioIfEnabled;\n bool surfaceClosed, surfaceClosing, overlayClosed;\n int panPrevX, panPrevY;\n bool isMouseBindingsSubscribedSurface;\n bool isMouseBindingsSubscribedOverlay;\n Window standAloneOverlay;\n\n CornerRadius zeroCornerRadius = new(0);\n Point zeroPoint = new(0, 0);\n Point mouseLeftDownPoint = new(0, 0);\n Point mouseMoveLastPoint = new(0, 0);\n Point ownerZeroPointPos = new();\n\n Rect zeroRect = new(0, 0, 0, 0);\n Rect rectDetachedLast = Rect.Empty;\n Rect rectInit;\n Rect rectInitLast = rectRandom;\n Rect rectIntersect;\n Rect rectIntersectLast = rectRandom;\n RECT beforeResizeRect = new();\n RECT curRect = new();\n\n private class FlyleafHostDropWrap { public FlyleafHost FlyleafHost; } // To allow non FlyleafHosts to drag & drop\n protected readonly LogHandler Log;\n #endregion\n\n #region Dependency Properties\n public void BringToFront() => SetWindowPos(SurfaceHandle, IntPtr.Zero, 0, 0, 0, 0, (UInt32)(SetWindowPosFlags.SWP_SHOWWINDOW | SetWindowPosFlags.SWP_NOSIZE | SetWindowPosFlags.SWP_NOMOVE));\n public bool BringToFrontOnClick\n {\n get { return (bool)GetValue(BringToFrontOnClickProperty); }\n set { SetValue(BringToFrontOnClickProperty, value); }\n }\n public static readonly DependencyProperty BringToFrontOnClickProperty =\n DependencyProperty.Register(nameof(BringToFrontOnClick), typeof(bool), typeof(FlyleafHost), new PropertyMetadata(true));\n\n public AvailableWindows OpenOnDrop\n {\n get => (AvailableWindows)GetValue(OpenOnDropProperty);\n set => SetValue(OpenOnDropProperty, value);\n }\n public static readonly DependencyProperty OpenOnDropProperty =\n DependencyProperty.Register(nameof(OpenOnDrop), typeof(AvailableWindows), typeof(FlyleafHost), new PropertyMetadata(AvailableWindows.Surface, new PropertyChangedCallback(DropChanged)));\n\n public AvailableWindows SwapOnDrop\n {\n get => (AvailableWindows)GetValue(SwapOnDropProperty);\n set => SetValue(SwapOnDropProperty, value);\n }\n public static readonly DependencyProperty SwapOnDropProperty =\n DependencyProperty.Register(nameof(SwapOnDrop), typeof(AvailableWindows), typeof(FlyleafHost), new PropertyMetadata(AvailableWindows.Surface, new PropertyChangedCallback(DropChanged)));\n\n public AvailableWindows SwapDragEnterOnShift\n {\n get => (AvailableWindows)GetValue(SwapDragEnterOnShiftProperty);\n set => SetValue(SwapDragEnterOnShiftProperty, value);\n }\n public static readonly DependencyProperty SwapDragEnterOnShiftProperty =\n DependencyProperty.Register(nameof(SwapDragEnterOnShift), typeof(AvailableWindows), typeof(FlyleafHost), new PropertyMetadata(AvailableWindows.Surface));\n\n public AvailableWindows ToggleFullScreenOnDoubleClick\n {\n get => (AvailableWindows)GetValue(ToggleFullScreenOnDoubleClickProperty);\n set => SetValue(ToggleFullScreenOnDoubleClickProperty, value);\n }\n public static readonly DependencyProperty ToggleFullScreenOnDoubleClickProperty =\n DependencyProperty.Register(nameof(ToggleFullScreenOnDoubleClick), typeof(AvailableWindows), typeof(FlyleafHost), new PropertyMetadata(AvailableWindows.Surface));\n\n public AvailableWindows PanMoveOnCtrl\n {\n get => (AvailableWindows)GetValue(PanMoveOnCtrlProperty);\n set => SetValue(PanMoveOnCtrlProperty, value);\n }\n public static readonly DependencyProperty PanMoveOnCtrlProperty =\n DependencyProperty.Register(nameof(PanMoveOnCtrl), typeof(AvailableWindows), typeof(FlyleafHost), new PropertyMetadata(AvailableWindows.Surface));\n\n public AvailableWindows PanRotateOnShiftWheel\n {\n get => (AvailableWindows)GetValue(PanRotateOnShiftWheelProperty);\n set => SetValue(PanRotateOnShiftWheelProperty, value);\n }\n public static readonly DependencyProperty PanRotateOnShiftWheelProperty =\n DependencyProperty.Register(nameof(PanRotateOnShiftWheel), typeof(AvailableWindows), typeof(FlyleafHost), new PropertyMetadata(AvailableWindows.Surface));\n\n public AvailableWindows PanZoomOnCtrlWheel\n {\n get => (AvailableWindows)GetValue(PanZoomOnCtrlWheelProperty);\n set => SetValue(PanZoomOnCtrlWheelProperty, value);\n }\n public static readonly DependencyProperty PanZoomOnCtrlWheelProperty =\n DependencyProperty.Register(nameof(PanZoomOnCtrlWheel), typeof(AvailableWindows), typeof(FlyleafHost), new PropertyMetadata(AvailableWindows.Surface));\n\n public AttachedDragMoveOptions AttachedDragMove\n {\n get => (AttachedDragMoveOptions)GetValue(AttachedDragMoveProperty);\n set => SetValue(AttachedDragMoveProperty, value);\n }\n public static readonly DependencyProperty AttachedDragMoveProperty =\n DependencyProperty.Register(nameof(AttachedDragMove), typeof(AttachedDragMoveOptions), typeof(FlyleafHost), new PropertyMetadata(AttachedDragMoveOptions.Surface));\n\n public AvailableWindows DetachedDragMove\n {\n get => (AvailableWindows)GetValue(DetachedDragMoveProperty);\n set => SetValue(DetachedDragMoveProperty, value);\n }\n public static readonly DependencyProperty DetachedDragMoveProperty =\n DependencyProperty.Register(nameof(DetachedDragMove), typeof(AvailableWindows), typeof(FlyleafHost), new PropertyMetadata(AvailableWindows.Surface));\n\n public AvailableWindows AttachedResize\n {\n get => (AvailableWindows)GetValue(AttachedResizeProperty);\n set => SetValue(AttachedResizeProperty, value);\n }\n public static readonly DependencyProperty AttachedResizeProperty =\n DependencyProperty.Register(nameof(AttachedResize), typeof(AvailableWindows), typeof(FlyleafHost), new PropertyMetadata(AvailableWindows.Surface));\n\n public AvailableWindows DetachedResize\n {\n get => (AvailableWindows)GetValue(DetachedResizeProperty);\n set => SetValue(DetachedResizeProperty, value);\n }\n public static readonly DependencyProperty DetachedResizeProperty =\n DependencyProperty.Register(nameof(DetachedResize), typeof(AvailableWindows), typeof(FlyleafHost), new PropertyMetadata(AvailableWindows.Surface));\n\n public bool KeepRatioOnResize\n {\n get => (bool)GetValue(KeepRatioOnResizeProperty);\n set => SetValue(KeepRatioOnResizeProperty, value);\n }\n public static readonly DependencyProperty KeepRatioOnResizeProperty =\n DependencyProperty.Register(nameof(KeepRatioOnResize), typeof(bool), typeof(FlyleafHost), new PropertyMetadata(false, new PropertyChangedCallback(OnKeepRatioOnResizeChanged)));\n\n public int PreferredLandscapeWidth\n {\n get { return (int)GetValue(PreferredLandscapeWidthProperty); }\n set { SetValue(PreferredLandscapeWidthProperty, value); }\n }\n public static readonly DependencyProperty PreferredLandscapeWidthProperty =\n DependencyProperty.Register(nameof(PreferredLandscapeWidth), typeof(int), typeof(FlyleafHost), new PropertyMetadata(0));\n\n public int PreferredPortraitHeight\n {\n get { return (int)GetValue(PreferredPortraitHeightProperty); }\n set { SetValue(PreferredPortraitHeightProperty, value); }\n }\n public static readonly DependencyProperty PreferredPortraitHeightProperty =\n DependencyProperty.Register(nameof(PreferredPortraitHeight), typeof(int), typeof(FlyleafHost), new PropertyMetadata(0));\n\n public int ResizeSensitivity\n {\n get => (int)GetValue(ResizeSensitivityProperty);\n set => SetValue(ResizeSensitivityProperty, value);\n }\n public static readonly DependencyProperty ResizeSensitivityProperty =\n DependencyProperty.Register(nameof(ResizeSensitivity), typeof(int), typeof(FlyleafHost), new PropertyMetadata(6));\n\n public DetachedPositionOptions DetachedPosition\n {\n get => (DetachedPositionOptions)GetValue(DetachedPositionProperty);\n set => SetValue(DetachedPositionProperty, value);\n }\n public static readonly DependencyProperty DetachedPositionProperty =\n DependencyProperty.Register(nameof(DetachedPosition), typeof(DetachedPositionOptions), typeof(FlyleafHost), new PropertyMetadata(DetachedPositionOptions.CenterCenter));\n\n public Thickness DetachedPositionMargin\n {\n get => (Thickness)GetValue(DetachedPositionMarginProperty);\n set => SetValue(DetachedPositionMarginProperty, value);\n }\n public static readonly DependencyProperty DetachedPositionMarginProperty =\n DependencyProperty.Register(nameof(DetachedPositionMargin), typeof(Thickness), typeof(FlyleafHost), new PropertyMetadata(new Thickness(0, 0, 0, 0)));\n\n public Point DetachedFixedPosition\n {\n get => (Point)GetValue(DetachedFixedPositionProperty);\n set => SetValue(DetachedFixedPositionProperty, value);\n }\n public static readonly DependencyProperty DetachedFixedPositionProperty =\n DependencyProperty.Register(nameof(DetachedFixedPosition), typeof(Point), typeof(FlyleafHost), new PropertyMetadata(new Point()));\n\n public Size DetachedFixedSize\n {\n get => (Size)GetValue(DetachedFixedSizeProperty);\n set => SetValue(DetachedFixedSizeProperty, value);\n }\n public static readonly DependencyProperty DetachedFixedSizeProperty =\n DependencyProperty.Register(nameof(DetachedFixedSize), typeof(Size), typeof(FlyleafHost), new PropertyMetadata(new Size(300, 200)));\n\n public bool DetachedRememberPosition\n {\n get => (bool)GetValue(DetachedRememberPositionProperty);\n set => SetValue(DetachedRememberPositionProperty, value);\n }\n public static readonly DependencyProperty DetachedRememberPositionProperty =\n DependencyProperty.Register(nameof(DetachedRememberPosition), typeof(bool), typeof(FlyleafHost), new PropertyMetadata(true));\n\n public bool DetachedRememberSize\n {\n get => (bool)GetValue(DetachedRememberSizeProperty);\n set => SetValue(DetachedRememberSizeProperty, value);\n }\n public static readonly DependencyProperty DetachedRememberSizeProperty =\n DependencyProperty.Register(nameof(DetachedRememberSize), typeof(bool), typeof(FlyleafHost), new PropertyMetadata(true));\n\n public bool DetachedTopMost\n {\n get => (bool)GetValue(DetachedTopMostProperty);\n set => SetValue(DetachedTopMostProperty, value);\n }\n public static readonly DependencyProperty DetachedTopMostProperty =\n DependencyProperty.Register(nameof(DetachedTopMost), typeof(bool), typeof(FlyleafHost), new PropertyMetadata(false, new PropertyChangedCallback(OnDetachedTopMostChanged)));\n\n public bool DetachedShowInTaskbar\n {\n get { return (bool)GetValue(DetachedShowInTaskbarProperty); }\n set { SetValue(DetachedShowInTaskbarProperty, value); }\n }\n public static readonly DependencyProperty DetachedShowInTaskbarProperty =\n DependencyProperty.Register(nameof(DetachedShowInTaskbar), typeof(bool), typeof(FlyleafHost), new PropertyMetadata(false, new PropertyChangedCallback(OnShowInTaskBarChanged)));\n\n public bool DetachedNoOwner\n {\n get { return (bool)GetValue(DetachedNoOwnerProperty); }\n set { SetValue(DetachedNoOwnerProperty, value); }\n }\n public static readonly DependencyProperty DetachedNoOwnerProperty =\n DependencyProperty.Register(nameof(DetachedNoOwner), typeof(bool), typeof(FlyleafHost), new PropertyMetadata(false, new PropertyChangedCallback(OnNoOwnerChanged)));\n\n public int DetachedMinHeight\n {\n get { return (int)GetValue(DetachedMinHeightProperty); }\n set { SetValue(DetachedMinHeightProperty, value); }\n }\n public static readonly DependencyProperty DetachedMinHeightProperty =\n DependencyProperty.Register(nameof(DetachedMinHeight), typeof(int), typeof(FlyleafHost), new PropertyMetadata(0));\n\n public int DetachedMinWidth\n {\n get { return (int)GetValue(DetachedMinWidthProperty); }\n set { SetValue(DetachedMinWidthProperty, value); }\n }\n public static readonly DependencyProperty DetachedMinWidthProperty =\n DependencyProperty.Register(nameof(DetachedMinWidth), typeof(int), typeof(FlyleafHost), new PropertyMetadata(0));\n\n public double DetachedMaxHeight\n {\n get { return (double)GetValue(DetachedMaxHeightProperty); }\n set { SetValue(DetachedMaxHeightProperty, value); }\n }\n public static readonly DependencyProperty DetachedMaxHeightProperty =\n DependencyProperty.Register(nameof(DetachedMaxHeight), typeof(double), typeof(FlyleafHost), new PropertyMetadata(double.PositiveInfinity));\n\n public double DetachedMaxWidth\n {\n get { return (double)GetValue(DetachedMaxWidthProperty); }\n set { SetValue(DetachedMaxWidthProperty, value); }\n }\n public static readonly DependencyProperty DetachedMaxWidthProperty =\n DependencyProperty.Register(nameof(DetachedMaxWidth), typeof(double), typeof(FlyleafHost), new PropertyMetadata(double.PositiveInfinity));\n\n public AvailableWindows KeyBindings\n {\n get => (AvailableWindows)GetValue(KeyBindingsProperty);\n set => SetValue(KeyBindingsProperty, value);\n }\n public static readonly DependencyProperty KeyBindingsProperty =\n DependencyProperty.Register(nameof(KeyBindings), typeof(AvailableWindows), typeof(FlyleafHost), new PropertyMetadata(AvailableWindows.Surface));\n\n public AvailableWindows MouseBindings\n {\n get => (AvailableWindows)GetValue(MouseBindingsProperty);\n set => SetValue(MouseBindingsProperty, value);\n }\n public static readonly DependencyProperty MouseBindingsProperty =\n DependencyProperty.Register(nameof(MouseBindings), typeof(AvailableWindows), typeof(FlyleafHost), new PropertyMetadata(AvailableWindows.Both, new PropertyChangedCallback(OnMouseBindings)));\n\n public int ActivityTimeout\n {\n get => (int)GetValue(ActivityTimeoutProperty);\n set => SetValue(ActivityTimeoutProperty, value);\n }\n public static readonly DependencyProperty ActivityTimeoutProperty =\n DependencyProperty.Register(nameof(ActivityTimeout), typeof(int), typeof(FlyleafHost), new PropertyMetadata(0, new PropertyChangedCallback(OnActivityTimeoutChanged)));\n\n public bool IsAttached\n {\n get => (bool)GetValue(IsAttachedProperty);\n set => SetValue(IsAttachedProperty, value);\n }\n public static readonly DependencyProperty IsAttachedProperty =\n DependencyProperty.Register(nameof(IsAttached), typeof(bool), typeof(FlyleafHost), new PropertyMetadata(true, new PropertyChangedCallback(OnIsAttachedChanged)));\n\n public bool IsMinimized\n {\n get => (bool)GetValue(IsMinimizedProperty);\n set => SetValue(IsMinimizedProperty, value);\n }\n public static readonly DependencyProperty IsMinimizedProperty =\n DependencyProperty.Register(nameof(IsMinimized), typeof(bool), typeof(FlyleafHost), new PropertyMetadata(false, new PropertyChangedCallback(OnIsMinimizedChanged)));\n\n public bool IsFullScreen\n {\n get => (bool)GetValue(IsFullScreenProperty);\n set => SetValue(IsFullScreenProperty, value);\n }\n public static readonly DependencyProperty IsFullScreenProperty =\n DependencyProperty.Register(nameof(IsFullScreen), typeof(bool), typeof(FlyleafHost), new PropertyMetadata(false, new PropertyChangedCallback(OnIsFullScreenChanged)));\n\n public bool IsResizing\n {\n get => (bool)GetValue(IsResizingProperty);\n private set => SetValue(IsResizingProperty, value);\n }\n public static readonly DependencyProperty IsResizingProperty =\n DependencyProperty.Register(nameof(IsResizing), typeof(bool), typeof(FlyleafHost), new PropertyMetadata(false));\n\n public bool IsStandAlone\n {\n get => (bool)GetValue(IsStandAloneProperty);\n private set => SetValue(IsStandAloneProperty, value);\n }\n public static readonly DependencyProperty IsStandAloneProperty =\n DependencyProperty.Register(nameof(IsStandAlone), typeof(bool), typeof(FlyleafHost), new PropertyMetadata(false));\n\n public bool IsSwappingStarted\n {\n get => (bool)GetValue(IsSwappingStartedProperty);\n private set => SetValue(IsSwappingStartedProperty, value);\n }\n public static readonly DependencyProperty IsSwappingStartedProperty =\n DependencyProperty.Register(nameof(IsSwappingStarted), typeof(bool), typeof(FlyleafHost), new PropertyMetadata(false));\n\n public bool IsPanMoving\n {\n get { return (bool)GetValue(IsPanMovingProperty); }\n private set { SetValue(IsPanMovingProperty, value); }\n }\n public static readonly DependencyProperty IsPanMovingProperty =\n DependencyProperty.Register(nameof(IsPanMoving), typeof(bool), typeof(FlyleafHost), new PropertyMetadata(false));\n\n public bool IsDragMoving\n {\n get { return (bool)GetValue(IsDragMovingProperty); }\n set { SetValue(IsDragMovingProperty, value); }\n }\n public static readonly DependencyProperty IsDragMovingProperty =\n DependencyProperty.Register(nameof(IsDragMoving), typeof(bool), typeof(FlyleafHost), new PropertyMetadata(false));\n\n public bool IsDragMovingOwner\n {\n get { return (bool)GetValue(IsDragMovingOwnerProperty); }\n set { SetValue(IsDragMovingOwnerProperty, value); }\n }\n public static readonly DependencyProperty IsDragMovingOwnerProperty =\n DependencyProperty.Register(nameof(IsDragMovingOwner), typeof(bool), typeof(FlyleafHost), new PropertyMetadata(false));\n\n public FrameworkElement MarginTarget\n {\n get => (FrameworkElement)GetValue(MarginTargetProperty);\n set => SetValue(MarginTargetProperty, value);\n }\n public static readonly DependencyProperty MarginTargetProperty =\n DependencyProperty.Register(nameof(MarginTarget), typeof(FrameworkElement), typeof(FlyleafHost), new PropertyMetadata(null));\n\n public object HostDataContext\n {\n get => GetValue(HostDataContextProperty);\n set => SetValue(HostDataContextProperty, value);\n }\n public static readonly DependencyProperty HostDataContextProperty =\n DependencyProperty.Register(nameof(HostDataContext), typeof(object), typeof(FlyleafHost), new PropertyMetadata(null));\n\n public object DetachedContent\n {\n get => GetValue(DetachedContentProperty);\n set => SetValue(DetachedContentProperty, value);\n }\n public static readonly DependencyProperty DetachedContentProperty =\n DependencyProperty.Register(nameof(DetachedContent), typeof(object), typeof(FlyleafHost), new PropertyMetadata(null));\n\n public Player Player\n {\n get => (Player)GetValue(PlayerProperty);\n set => SetValue(PlayerProperty, value);\n }\n public static readonly DependencyProperty PlayerProperty =\n DependencyProperty.Register(nameof(Player), typeof(Player), typeof(FlyleafHost), new PropertyMetadata(null, OnPlayerChanged));\n\n public Player ReplicaPlayer\n {\n get => (Player)GetValue(ReplicaPlayerProperty);\n set => SetValue(ReplicaPlayerProperty, value);\n }\n public static readonly DependencyProperty ReplicaPlayerProperty =\n DependencyProperty.Register(nameof(ReplicaPlayer), typeof(Player), typeof(FlyleafHost), new PropertyMetadata(null, OnReplicaPlayerChanged));\n\n public ControlTemplate OverlayTemplate\n {\n get => (ControlTemplate)GetValue(OverlayTemplateProperty);\n set => SetValue(OverlayTemplateProperty, value);\n }\n public static readonly DependencyProperty OverlayTemplateProperty =\n DependencyProperty.Register(nameof(OverlayTemplate), typeof(ControlTemplate), typeof(FlyleafHost), new PropertyMetadata(null, new PropertyChangedCallback(OnOverlayTemplateChanged)));\n\n public Window Overlay\n {\n get => (Window)GetValue(OverlayProperty);\n set => SetValue(OverlayProperty, value);\n }\n public static readonly DependencyProperty OverlayProperty =\n DependencyProperty.Register(nameof(Overlay), typeof(Window), typeof(FlyleafHost), new PropertyMetadata(null, new PropertyChangedCallback(OnOverlayChanged)));\n\n public CornerRadius CornerRadius\n {\n get => (CornerRadius)GetValue(CornerRadiusProperty);\n set => SetValue(CornerRadiusProperty, value);\n }\n public static readonly DependencyProperty CornerRadiusProperty =\n DependencyProperty.Register(nameof(CornerRadius), typeof(CornerRadius), typeof(FlyleafHost), new PropertyMetadata(new CornerRadius(0), new PropertyChangedCallback(OnCornerRadiusChanged)));\n #endregion\n\n #region Events\n private static void OnMouseBindings(DependencyObject d, DependencyPropertyChangedEventArgs e)\n {\n if (isDesignMode)\n return;\n\n FlyleafHost host = d as FlyleafHost;\n if (host.Disposed)\n return;\n\n host.SetMouseSurface();\n host.SetMouseOverlay();\n }\n private static void OnDetachedTopMostChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)\n {\n if (isDesignMode)\n return;\n\n FlyleafHost host = d as FlyleafHost;\n if (host.Disposed)\n return;\n\n if (host.Surface != null)\n host.Surface.Topmost = !host.IsAttached && host.DetachedTopMost;\n }\n private static void DropChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)\n {\n FlyleafHost host = d as FlyleafHost;\n if (host.Disposed)\n return;\n\n if (host.Surface == null)\n return;\n\n host.Surface.AllowDrop =\n host.OpenOnDrop == AvailableWindows.Surface || host.OpenOnDrop == AvailableWindows.Both ||\n host.SwapOnDrop == AvailableWindows.Surface || host.SwapOnDrop == AvailableWindows.Both;\n\n if (host.Overlay == null)\n return;\n\n host.Overlay.AllowDrop =\n host.OpenOnDrop == AvailableWindows.Overlay || host.OpenOnDrop == AvailableWindows.Both ||\n host.SwapOnDrop == AvailableWindows.Overlay || host.SwapOnDrop == AvailableWindows.Both;\n }\n private void UpdateCurRatio()\n {\n if (!KeepRatioOnResize || IsFullScreen)\n return;\n\n if (Player != null && Player.Video.AspectRatio.Value > 0)\n curResizeRatio = Player.Video.AspectRatio.Value;\n else if (ReplicaPlayer != null && ReplicaPlayer.Video.AspectRatio.Value > 0)\n curResizeRatio = ReplicaPlayer.Video.AspectRatio.Value;\n else\n curResizeRatio = (float)(16.0/9.0);\n\n curResizeRatioIfEnabled = curResizeRatio;\n\n Rect screen;\n\n if (IsAttached)\n {\n if (Owner == null)\n {\n Height = ActualWidth / curResizeRatio;\n return;\n }\n\n screen = new(zeroPoint, Owner.RenderSize);\n }\n else\n {\n if (Surface == null)\n return;\n\n var bounds = System.Windows.Forms.Screen.FromPoint(new System.Drawing.Point((int)Surface.Top, (int)Surface.Left)).Bounds;\n screen = new(bounds.Left / DpiX, bounds.Top / DpiY, bounds.Width / DpiX, bounds.Height / DpiY);\n }\n\n double WindowWidth;\n double WindowHeight;\n\n if (curResizeRatio >= 1)\n {\n WindowHeight = PreferredLandscapeWidth / curResizeRatio;\n\n if (WindowHeight < Surface.MinHeight)\n {\n WindowHeight = Surface.MinHeight;\n WindowWidth = WindowHeight * curResizeRatio;\n }\n else if (WindowHeight > Surface.MaxHeight)\n {\n WindowHeight = Surface.MaxHeight;\n WindowWidth = Surface.Height * curResizeRatio;\n }\n else if (WindowHeight > screen.Height)\n {\n WindowHeight = screen.Height;\n WindowWidth = WindowHeight * curResizeRatio;\n }\n else\n WindowWidth = PreferredLandscapeWidth;\n }\n else\n {\n WindowWidth = PreferredPortraitHeight * curResizeRatio;\n\n if (WindowWidth < Surface.MinWidth)\n {\n WindowWidth = Surface.MinWidth;\n WindowHeight = WindowWidth / curResizeRatio;\n }\n else if (WindowWidth > Surface.MaxWidth)\n {\n WindowWidth = Surface.MaxWidth;\n WindowHeight = WindowWidth / curResizeRatio;\n }\n else if (WindowWidth > screen.Width)\n {\n WindowWidth = screen.Width;\n WindowHeight = WindowWidth / curResizeRatio;\n }\n else\n WindowHeight = PreferredPortraitHeight;\n }\n\n if (IsAttached)\n {\n\n Height = WindowHeight;\n Width = WindowWidth;\n }\n\n else if (Surface != null)\n {\n double WindowLeft;\n double WindowTop;\n\n if (Surface.Left + Surface.Width / 2 > screen.Width / 2)\n WindowLeft = Math.Min(Math.Max(Surface.Left + Surface.Width - WindowWidth, 0), screen.Width - WindowWidth);\n else\n WindowLeft = Surface.Left;\n\n if (Surface.Top + Surface.Height / 2 > screen.Height / 2)\n WindowTop = Math.Min(Math.Max(Surface.Top + Surface.Height - WindowHeight, 0), screen.Height - WindowHeight);\n else\n WindowTop = Surface.Top;\n\n WindowLeft *= DpiX;\n WindowTop *= DpiY;\n WindowWidth *= DpiX;\n WindowHeight*= DpiY;\n\n SetWindowPos(SurfaceHandle, IntPtr.Zero,\n (int)WindowLeft,\n (int)WindowTop,\n (int)Math.Ceiling(WindowWidth),\n (int)Math.Ceiling(WindowHeight),\n (uint)(SetWindowPosFlags.SWP_NOZORDER | SetWindowPosFlags.SWP_NOACTIVATE));\n }\n }\n private static void OnShowInTaskBarChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)\n {\n FlyleafHost host = d as FlyleafHost;\n if (host.Disposed)\n return;\n\n if (host.Surface == null)\n return;\n\n if (host.DetachedShowInTaskbar)\n SetWindowLong(host.SurfaceHandle, (int)WindowLongFlags.GWL_EXSTYLE, GetWindowLong(host.SurfaceHandle, (int)WindowLongFlags.GWL_EXSTYLE) | (nint)WindowStylesEx.WS_EX_APPWINDOW);\n else\n SetWindowLong(host.SurfaceHandle, (int)WindowLongFlags.GWL_EXSTYLE, GetWindowLong(host.SurfaceHandle, (int)WindowLongFlags.GWL_EXSTYLE) & ~(nint)WindowStylesEx.WS_EX_APPWINDOW);\n }\n private static void OnNoOwnerChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)\n {\n FlyleafHost host = d as FlyleafHost;\n if (host.Disposed)\n return;\n\n if (host.Surface == null)\n return;\n\n if (!host.IsAttached)\n host.Surface.Owner = host.DetachedNoOwner ? null : host.Owner;\n }\n private static void OnKeepRatioOnResizeChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)\n {\n if (isDesignMode)\n return;\n\n FlyleafHost host = d as FlyleafHost;\n if (host.Disposed)\n return;\n\n if (!host.KeepRatioOnResize)\n host.curResizeRatioIfEnabled = 0;\n else\n host.UpdateCurRatio();\n }\n private static void OnPlayerChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)\n {\n if (isDesignMode)\n return;\n\n FlyleafHost host = d as FlyleafHost;\n if (host.Disposed)\n return;\n\n host.SetPlayer((Player)e.OldValue);\n }\n private static void OnReplicaPlayerChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)\n {\n if (isDesignMode)\n return;\n\n FlyleafHost host = d as FlyleafHost;\n if (host.Disposed)\n return;\n\n host.SetReplicaPlayer((Player)e.OldValue);\n }\n private static void OnIsFullScreenChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)\n {\n if (isDesignMode)\n return;\n\n FlyleafHost host = d as FlyleafHost;\n if (host.Disposed)\n return;\n\n host.RefreshNormalFullScreen();\n }\n private static void OnIsMinimizedChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)\n {\n if (isDesignMode)\n return;\n\n FlyleafHost host = d as FlyleafHost;\n if (host.Disposed)\n return;\n\n host.Surface.WindowState = host.IsMinimized ? WindowState.Minimized : (host.IsFullScreen ? WindowState.Maximized : WindowState.Normal);\n }\n private static void OnIsAttachedChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)\n {\n if (isDesignMode)\n return;\n\n FlyleafHost host = d as FlyleafHost;\n if (host.Disposed)\n return;\n\n if (host.IsStandAlone)\n {\n host.IsAttached = false;\n return;\n }\n\n if (!host.IsLoaded)\n return;\n\n if (host.IsAttached)\n host.Attach();\n else\n host.Detach();\n }\n private static void OnActivityTimeoutChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)\n {\n FlyleafHost host = d as FlyleafHost;\n if (host.Disposed)\n return;\n\n if (host.Player == null)\n return;\n\n host.Player.Activity.Timeout = host.ActivityTimeout;\n }\n bool setTemplate; // Issue #481 - FlyleafME override SetOverlay will not have a template to initialize properly *bool required if SetOverlay can be called multiple times and with different configs\n private static void OnOverlayTemplateChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)\n {\n if (isDesignMode)\n return;\n\n FlyleafHost host = d as FlyleafHost;\n if (host.Disposed)\n return;\n\n if (host.Overlay == null)\n {\n host.setTemplate= true;\n host.Overlay = new Window() { WindowStyle = WindowStyle.None, ResizeMode = ResizeMode.NoResize, AllowsTransparency = true };\n host.setTemplate= false;\n }\n else\n host.Overlay.Template = host.OverlayTemplate;\n }\n private static void OnOverlayChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)\n {\n FlyleafHost host = d as FlyleafHost;\n if (host.Disposed)\n return;\n\n if (!isDesignMode)\n host.SetOverlay();\n else\n {\n // XSurface.Wpf.Window (can this work on designer?\n }\n }\n private static void OnCornerRadiusChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)\n {\n if (isDesignMode)\n return;\n\n FlyleafHost host = d as FlyleafHost;\n if (host.Disposed)\n return;\n\n if (host.Surface == null)\n return;\n\n if (host.CornerRadius == host.zeroCornerRadius)\n host.Surface.Background = Brushes.Black;\n else\n {\n host.Surface.Background = Brushes.Transparent;\n host.SetCornerRadiusBorder();\n }\n\n if (host?.Player == null)\n return;\n\n host.Player.renderer.CornerRadius = (CornerRadius)e.NewValue;\n\n }\n private void SetCornerRadiusBorder()\n {\n // Required to handle mouse events as the window's background will be transparent\n // This does not set the background color we do that with the renderer (which causes some issues eg. when returning from fullscreen to normalscreen)\n Surface.Content = new Border()\n {\n Background = Brushes.Black, // TBR: for alpha channel -> Background == Brushes.Transparent || Background ==null ? new SolidColorBrush(Color.FromArgb(1,0,0,0)) : Background\n HorizontalAlignment = HorizontalAlignment.Stretch,\n VerticalAlignment = VerticalAlignment.Stretch,\n CornerRadius = CornerRadius,\n };\n }\n private static object OnContentChanging(DependencyObject d, object baseValue)\n {\n if (isDesignMode)\n return baseValue;\n\n FlyleafHost host = d as FlyleafHost;\n if (host.Disposed)\n return host.DetachedContent;\n\n if (baseValue != null && host.Overlay == null)\n host.Overlay = new Window() { WindowStyle = WindowStyle.None, ResizeMode = ResizeMode.NoResize, AllowsTransparency = true };\n\n if (host.Overlay != null)\n host.Overlay.Content = baseValue;\n\n return host.DetachedContent;\n }\n\n private void Host_Loaded(object sender, RoutedEventArgs e)\n {\n Window owner = Window.GetWindow(this);\n if (owner == null)\n return;\n\n var ownerHandle = new WindowInteropHelper(owner).EnsureHandle();\n\n // Owner Changed\n if (Owner != null)\n {\n if (!IsAttached || OwnerHandle == ownerHandle)\n return; // Check OwnerHandle changed (NOTE: Owner can be the same class/window but the handle can be different)\n\n Owner.SizeChanged -= Owner_SizeChanged;\n\n Surface.Hide();\n Overlay?.Hide();\n Detach();\n\n Owner = owner;\n OwnerHandle = ownerHandle;\n Surface.Title = Owner.Title;\n Surface.Icon = Owner.Icon;\n\n Owner.SizeChanged += Owner_SizeChanged;\n Attach();\n rectDetachedLast = Rect.Empty; // Attach will set it wrong first time\n Host_IsVisibleChanged(null, new());\n\n return;\n }\n\n Owner = owner;\n OwnerHandle = ownerHandle;\n HostDataContext = DataContext;\n\n SetSurface();\n\n Surface.Title = Owner.Title;\n Surface.Icon = Owner.Icon;\n\n Owner.SizeChanged += Owner_SizeChanged;\n DataContextChanged += Host_DataContextChanged;\n LayoutUpdated += Host_LayoutUpdated;\n IsVisibleChanged += Host_IsVisibleChanged;\n\n // TBR: We need to ensure that Surface/Overlay will be initial Show once to work properly (issue #415)\n if (IsAttached)\n {\n Attach();\n rectDetachedLast = Rect.Empty; // Attach will set it wrong first time\n Surface.Show();\n Overlay?.Show();\n Host_IsVisibleChanged(null, new());\n }\n else\n {\n Detach();\n\n if (PreferredLandscapeWidth == 0)\n PreferredLandscapeWidth = (int)Surface.Width;\n\n if (PreferredPortraitHeight == 0)\n PreferredPortraitHeight = (int)Surface.Height;\n\n UpdateCurRatio();\n Surface.Show();\n Overlay?.Show();\n }\n }\n\n // WindowChrome Issue #410: It will not properly move child windows when resized from top or left\n private void Owner_SizeChanged(object sender, SizeChangedEventArgs e)\n => rectInitLast = Rect.Empty;\n\n private void Host_DataContextChanged(object sender, DependencyPropertyChangedEventArgs e) =>\n // TBR\n // 1. this.DataContext: FlyleafHost's DataContext will not be affected (Inheritance)\n // 2. Overlay.DataContext: Overlay's DataContext will be FlyleafHost itself\n // 3. Overlay.DataContext.HostDataContext: FlyleafHost's DataContext includes HostDataContext to access FlyleafHost's DataContext\n // 4. In case of Stand Alone will let the user to decide\n\n HostDataContext = DataContext;\n private void Host_IsVisibleChanged(object sender, DependencyPropertyChangedEventArgs e)\n {\n if (!IsAttached)\n return;\n\n if (IsVisible)\n {\n Host_Loaded(null, null);\n Surface.Show();\n\n if (Overlay != null)\n {\n Overlay.Show();\n\n // It happens (eg. with MetroWindow) that overlay left will not be equal to surface left so we reset it by detach/attach the overlay to surface (https://github.com/SuRGeoNix/Flyleaf/issues/370)\n RECT surfRect = new();\n RECT overRect = new();\n GetWindowRect(SurfaceHandle, ref surfRect);\n GetWindowRect(OverlayHandle, ref overRect);\n\n if (surfRect.Left != overRect.Left)\n {\n // Detach Overlay\n SetParent(OverlayHandle, IntPtr.Zero);\n SetWindowLong(OverlayHandle, (int)WindowLongFlags.GWL_STYLE, NONE_STYLE);\n Overlay.Owner = null;\n\n SetWindowPos(OverlayHandle, IntPtr.Zero, 0, 0, (int)Surface.ActualWidth, (int)Surface.ActualHeight,\n (uint)(SetWindowPosFlags.SWP_NOZORDER | SetWindowPosFlags.SWP_NOACTIVATE));\n\n // Attache Overlay\n SetWindowLong(OverlayHandle, (int)WindowLongFlags.GWL_STYLE, NONE_STYLE | (nint)(WindowStyles.WS_CHILD | WindowStyles.WS_MAXIMIZE));\n Overlay.Owner = Surface;\n SetParent(OverlayHandle, SurfaceHandle);\n\n // Required to restore overlay\n Rect tt1 = new(0, 0, 0, 0);\n SetRect(ref tt1);\n }\n }\n\n // TBR: First time loaded in a tab control could cause UCEERR_RENDERTHREADFAILURE (can be avoided by hide/show again here)\n }\n else\n {\n Surface.Hide();\n Overlay?.Hide();\n }\n }\n private void Host_LayoutUpdated(object sender, EventArgs e)\n {\n // Finds Rect Intersect with FlyleafHost's parents and Clips Surface/Overlay (eg. within ScrollViewer)\n // TBR: Option not to clip rect or stop at first/second parent?\n // For performance should focus only on ScrollViewer if any and Owner Window (other sources that clip our host?)\n\n if (!IsVisible || !IsAttached || IsFullScreen || IsResizing)\n return;\n\n try\n {\n rectInit = rectIntersect = new(TransformToAncestor(Owner).Transform(zeroPoint), RenderSize);\n\n FrameworkElement parent = this;\n while ((parent = VisualTreeHelper.GetParent(parent) as FrameworkElement) != null)\n {\n if (parent.FlowDirection == FlowDirection.RightToLeft)\n {\n var location = parent.TransformToAncestor(Owner).Transform(zeroPoint);\n location.X -= parent.RenderSize.Width;\n rectIntersect.Intersect(new Rect(location, parent.RenderSize));\n }\n else\n rectIntersect.Intersect(new Rect(parent.TransformToAncestor(Owner).Transform(zeroPoint), parent.RenderSize));\n }\n\n if (rectInit != rectInitLast)\n {\n SetRect(ref rectInit);\n rectInitLast = rectInit;\n }\n\n if (rectIntersect == Rect.Empty)\n {\n if (rectIntersect == rectIntersectLast)\n return;\n\n rectIntersectLast = rectIntersect;\n SetVisibleRect(ref zeroRect);\n }\n else\n {\n rectIntersect.X -= rectInit.X;\n rectIntersect.Y -= rectInit.Y;\n\n if (rectIntersect == rectIntersectLast)\n return;\n\n rectIntersectLast = rectIntersect;\n\n SetVisibleRect(ref rectIntersect);\n }\n }\n catch (Exception ex)\n {\n // It has been noticed with NavigationService (The visual tree changes, visual root IsVisible is false but FlyleafHost is still visible)\n if (Logger.CanDebug) Log.Debug($\"Host_LayoutUpdated: {ex.Message}\");\n\n // TBR: (Currently handle on each time Visible=true) It's possible that the owner/parent has been changed (for some reason Host_Loaded will not be called) *probably when the Owner stays the same but the actual Handle changes\n //if (ex.Message == \"The specified Visual is not an ancestor of this Visual.\")\n //Host_Loaded(null, null);\n }\n }\n private void Player_Video_PropertyChanged(object sender, PropertyChangedEventArgs e)\n {\n if (KeepRatioOnResize && e.PropertyName == nameof(Player.Video.AspectRatio) && Player.Video.AspectRatio.Value > 0)\n UpdateCurRatio();\n }\n private void ReplicaPlayer_Video_PropertyChanged(object sender, PropertyChangedEventArgs e)\n {\n if (KeepRatioOnResize && e.PropertyName == nameof(ReplicaPlayer.Video.AspectRatio) && ReplicaPlayer.Video.AspectRatio.Value > 0)\n UpdateCurRatio();\n }\n #endregion\n\n #region Events Surface / Overlay\n private void Surface_KeyDown(object sender, KeyEventArgs e) { if (KeyBindings == AvailableWindows.Surface || KeyBindings == AvailableWindows.Both) e.Handled = Player.KeyDown(Player, e); }\n private void Overlay_KeyDown(object sender, KeyEventArgs e) { if (KeyBindings == AvailableWindows.Overlay || KeyBindings == AvailableWindows.Both) e.Handled = Player.KeyDown(Player, e); }\n\n private void Surface_KeyUp(object sender, KeyEventArgs e) { if (KeyBindings == AvailableWindows.Surface || KeyBindings == AvailableWindows.Both) e.Handled = Player.KeyUp(Player, e); }\n private void Overlay_KeyUp(object sender, KeyEventArgs e) { if (KeyBindings == AvailableWindows.Overlay || KeyBindings == AvailableWindows.Both) e.Handled = Player.KeyUp(Player, e); }\n\n private void Surface_Drop(object sender, DragEventArgs e)\n {\n IsSwappingStarted = false;\n Surface.ReleaseMouseCapture();\n FlyleafHostDropWrap hostWrap = (FlyleafHostDropWrap) e.Data.GetData(typeof(FlyleafHostDropWrap));\n\n // Swap FlyleafHosts\n if (hostWrap != null)\n {\n (hostWrap.FlyleafHost.Player, Player) = (Player, hostWrap.FlyleafHost.Player);\n Surface.Activate();\n return;\n }\n\n if (Player == null)\n return;\n\n // Invoke event first and see if it gets handled\n OnSurfaceDrop?.Invoke(this, e);\n\n if (!e.Handled)\n {\n // Player Open Text (TBR: Priority matters, eg. firefox will set both - cached file thumbnail of a video & the link of the video)\n if (e.Data.GetDataPresent(DataFormats.Text))\n {\n string text = e.Data.GetData(DataFormats.Text, false).ToString();\n if (text.Length > 0)\n Player.OpenAsync(text);\n }\n\n // Player Open File\n else if (e.Data.GetDataPresent(DataFormats.FileDrop))\n {\n string filename = ((string[])e.Data.GetData(DataFormats.FileDrop, false))[0];\n Player.OpenAsync(filename);\n }\n }\n\n Surface.Activate();\n }\n private void Overlay_Drop(object sender, DragEventArgs e)\n {\n IsSwappingStarted = false;\n Overlay.ReleaseMouseCapture();\n FlyleafHostDropWrap hostWrap = (FlyleafHostDropWrap) e.Data.GetData(typeof(FlyleafHostDropWrap));\n\n // Swap FlyleafHosts\n if (hostWrap != null)\n {\n (hostWrap.FlyleafHost.Player, Player) = (Player, hostWrap.FlyleafHost.Player);\n Overlay.Activate();\n return;\n }\n\n if (Player == null)\n return;\n\n // Invoke event first and see if it gets handled\n OnOverlayDrop?.Invoke(this, e);\n\n if (!e.Handled)\n {\n // Player Open Text\n if (e.Data.GetDataPresent(DataFormats.Text))\n {\n string text = e.Data.GetData(DataFormats.Text, false).ToString();\n if (text.Length > 0)\n Player.OpenAsync(text);\n }\n\n // Player Open File\n else if (e.Data.GetDataPresent(DataFormats.FileDrop))\n {\n string filename = ((string[])e.Data.GetData(DataFormats.FileDrop, false))[0];\n Player.OpenAsync(filename);\n }\n }\n\n Overlay.Activate();\n }\n private void Surface_DragEnter(object sender, DragEventArgs e) { if (Player != null) e.Effects = DragDropEffects.All; }\n private void Overlay_DragEnter(object sender, DragEventArgs e) { if (Player != null) e.Effects = DragDropEffects.All; }\n private void Surface_StateChanged(object sender, EventArgs e)\n {\n switch (Surface.WindowState)\n {\n case WindowState.Maximized:\n IsFullScreen = true;\n IsMinimized = false;\n Player?.Activity.RefreshFullActive();\n\n break;\n\n case WindowState.Normal:\n\n IsFullScreen = false;\n IsMinimized = false;\n Player?.Activity.RefreshFullActive();\n\n break;\n\n case WindowState.Minimized:\n\n IsMinimized = true;\n break;\n }\n }\n\n private void Surface_MouseLeftButtonDown(object sender, MouseButtonEventArgs e) => SO_MouseLeftButtonDown(e, Surface);\n private void Overlay_MouseLeftButtonDown(object sender, MouseButtonEventArgs e) => SO_MouseLeftButtonDown(e, Overlay);\n private void SO_MouseLeftButtonDown(MouseButtonEventArgs e, Window window)\n {\n AvailableWindows availWindow;\n AttachedDragMoveOptions availDragMove;\n AttachedDragMoveOptions availDragMoveOwner;\n\n if (window == Surface)\n {\n availWindow = AvailableWindows.Surface;\n availDragMove = AttachedDragMoveOptions.Surface;\n availDragMoveOwner = AttachedDragMoveOptions.SurfaceOwner;\n }\n else\n {\n availWindow = AvailableWindows.Overlay;\n availDragMove = AttachedDragMoveOptions.Overlay;\n availDragMoveOwner = AttachedDragMoveOptions.OverlayOwner;\n }\n\n if (BringToFrontOnClick) // Activate and Z-order top\n BringToFront();\n\n window.Focus();\n Player?.Activity.RefreshFullActive();\n\n mouseLeftDownPoint = e.GetPosition(window);\n IsSwappingStarted = false; // currently we don't care if it was cancelled (it can be stay true if we miss the mouse up) - QueryContinueDrag\n\n // Resize\n if (ResizingSide != 0)\n {\n IsResizing = true;\n\n if (IsAttached)\n {\n ownerZeroPointPos = Owner.PointToScreen(zeroPoint);\n GetWindowRect(SurfaceHandle, ref beforeResizeRect);\n LayoutUpdated -= Host_LayoutUpdated;\n ResetVisibleRect();\n }\n }\n\n // Swap\n else if ((SwapOnDrop == availWindow || SwapOnDrop == AvailableWindows.Both) &&\n (Keyboard.IsKeyDown(Key.LeftShift) || Keyboard.IsKeyDown(Key.RightShift)))\n {\n IsSwappingStarted = true;\n DragDrop.DoDragDrop(this, new FlyleafHostDropWrap() { FlyleafHost = this }, DragDropEffects.Move);\n\n return; // No Capture\n }\n\n // PanMove\n else if (Player != null &&\n (PanMoveOnCtrl == availWindow || PanMoveOnCtrl == AvailableWindows.Both) &&\n (Keyboard.IsKeyDown(Key.LeftCtrl) || Keyboard.IsKeyDown(Key.RightCtrl)))\n {\n panPrevX = Player.PanXOffset;\n panPrevY = Player.PanYOffset;\n IsPanMoving = true;\n }\n\n // DragMoveOwner\n else if (IsAttached && Owner != null &&\n (AttachedDragMove == availDragMoveOwner || AttachedDragMove == AttachedDragMoveOptions.BothOwner))\n IsDragMovingOwner = true;\n\n\n // DragMove (Attach|Detach)\n else if ((IsAttached && (AttachedDragMove == availDragMove || AttachedDragMove == AttachedDragMoveOptions.Both))\n || (!IsAttached && (DetachedDragMove == availWindow || DetachedDragMove == AvailableWindows.Both)))\n IsDragMoving = true;\n\n else\n return; // No Capture\n\n window.CaptureMouse();\n }\n\n private void Surface_MouseLeftButtonUp(object sender, MouseButtonEventArgs e) => Surface_ReleaseCapture();\n private void Overlay_MouseLeftButtonUp(object sender, MouseButtonEventArgs e) => Overlay_ReleaseCapture();\n private void Surface_LostMouseCapture(object sender, MouseEventArgs e) => Surface_ReleaseCapture();\n private void Overlay_LostMouseCapture(object sender, MouseEventArgs e) => Overlay_ReleaseCapture();\n private void Surface_ReleaseCapture()\n {\n if (!IsResizing && !IsPanMoving && !IsDragMoving && !IsDragMovingOwner)\n return;\n\n Surface.ReleaseMouseCapture();\n\n if (IsResizing)\n {\n ResizingSide = 0;\n Surface.Cursor = Cursors.Arrow;\n IsResizing = false;\n\n if (IsAttached)\n {\n GetWindowRect(SurfaceHandle, ref curRect);\n MarginTarget.Margin = new(MarginTarget.Margin.Left + (curRect.Left - beforeResizeRect.Left) / DpiX, MarginTarget.Margin.Top + (curRect.Top - beforeResizeRect.Top) / DpiY, MarginTarget.Margin.Right, MarginTarget.Margin.Bottom);\n Width = Surface.Width;\n Height = Surface.Height;\n Host_LayoutUpdated(null, null); // When attached to restore the clipped rect\n LayoutUpdated += Host_LayoutUpdated;\n }\n }\n else if (IsPanMoving)\n IsPanMoving = false;\n else if (IsDragMoving)\n IsDragMoving = false;\n else if (IsDragMovingOwner)\n IsDragMovingOwner = false;\n else\n return;\n }\n private void Overlay_ReleaseCapture()\n {\n if (!IsResizing && !IsPanMoving && !IsDragMoving && !IsDragMovingOwner)\n return;\n\n Overlay.ReleaseMouseCapture();\n\n if (IsResizing)\n {\n ResizingSide = 0;\n Overlay.Cursor = Cursors.Arrow;\n IsResizing = false;\n\n if (IsAttached)\n {\n GetWindowRect(SurfaceHandle, ref curRect);\n MarginTarget.Margin = new(MarginTarget.Margin.Left + (curRect.Left - beforeResizeRect.Left) / DpiX, MarginTarget.Margin.Top + (curRect.Top - beforeResizeRect.Top) / DpiY, MarginTarget.Margin.Right, MarginTarget.Margin.Bottom);\n Width = Surface.Width;\n Height = Surface.Height;\n Host_LayoutUpdated(null, null); // When attached to restore the clipped rect\n LayoutUpdated += Host_LayoutUpdated;\n }\n }\n else if (IsPanMoving)\n IsPanMoving = false;\n else if (IsDragMoving)\n IsDragMoving = false;\n else if (IsDragMovingOwner)\n IsDragMovingOwner = false;\n }\n\n private void Surface_MouseMove(object sender, MouseEventArgs e)\n {\n var cur = e.GetPosition(Surface);\n\n if (Player != null && cur != mouseMoveLastPoint)\n {\n Player.Activity.RefreshFullActive();\n mouseMoveLastPoint = cur;\n }\n\n // Resize Sides (CanResize + !MouseDown + !FullScreen)\n if (e.MouseDevice.LeftButton != MouseButtonState.Pressed)\n {\n if ( !IsFullScreen &&\n ((IsAttached && (AttachedResize == AvailableWindows.Surface || AttachedResize == AvailableWindows.Both)) ||\n (!IsAttached && (DetachedResize == AvailableWindows.Surface || DetachedResize == AvailableWindows.Both))))\n {\n ResizingSide = ResizeSides(Surface, cur, ResizeSensitivity, CornerRadius);\n }\n\n return;\n }\n\n SO_MouseLeftDownAndMove(cur);\n }\n private void Overlay_MouseMove(object sender, MouseEventArgs e)\n {\n var cur = e.GetPosition(Overlay);\n\n if (Player != null && cur != mouseMoveLastPoint)\n {\n Player.Activity.RefreshFullActive();\n mouseMoveLastPoint = cur;\n }\n\n // Resize Sides (CanResize + !MouseDown + !FullScreen)\n if (e.MouseDevice.LeftButton != MouseButtonState.Pressed)\n {\n if (!IsFullScreen && cur != zeroPoint &&\n ((IsAttached && (AttachedResize == AvailableWindows.Overlay || AttachedResize == AvailableWindows.Both)) ||\n (!IsAttached && (DetachedResize == AvailableWindows.Overlay || DetachedResize == AvailableWindows.Both))))\n {\n ResizingSide = ResizeSides(Overlay, cur, ResizeSensitivity, CornerRadius);\n }\n\n return;\n }\n\n SO_MouseLeftDownAndMove(cur);\n }\n private void SO_MouseLeftDownAndMove(Point cur)\n {\n if (IsSwappingStarted)\n return;\n\n // Player's Pan Move (Ctrl + Drag Move)\n if (IsPanMoving)\n {\n Player.PanXOffset = panPrevX + (int) (cur.X - mouseLeftDownPoint.X);\n Player.PanYOffset = panPrevY + (int) (cur.Y - mouseLeftDownPoint.Y);\n\n return;\n }\n\n if (IsFullScreen)\n return;\n\n // Resize (MouseDown + ResizeSide != 0)\n if (IsResizing)\n Resize(cur, ResizingSide, curResizeRatioIfEnabled);\n\n // Drag Move Self (Attached|Detached)\n else if (IsDragMoving)\n {\n if (IsAttached)\n {\n MarginTarget.Margin = new(\n MarginTarget.Margin.Left + cur.X - mouseLeftDownPoint.X,\n MarginTarget.Margin.Top + cur.Y - mouseLeftDownPoint.Y,\n MarginTarget.Margin.Right,\n MarginTarget.Margin.Bottom);\n }\n else\n {\n Surface.Left += cur.X - mouseLeftDownPoint.X;\n Surface.Top += cur.Y - mouseLeftDownPoint.Y;\n }\n }\n\n // Drag Move Owner (Attached)\n else if (IsDragMovingOwner)\n {\n if (Owner.Owner != null)\n {\n Owner.Owner.Left += cur.X - mouseLeftDownPoint.X;\n Owner.Owner.Top += cur.Y - mouseLeftDownPoint.Y;\n }\n else\n {\n Owner.Left += cur.X - mouseLeftDownPoint.X;\n Owner.Top += cur.Y - mouseLeftDownPoint.Y;\n }\n }\n }\n\n private void Surface_MouseLeave(object sender, MouseEventArgs e) { ResizingSide = 0; Surface.Cursor = Cursors.Arrow; }\n private void Overlay_MouseLeave(object sender, MouseEventArgs e) { ResizingSide = 0; Overlay.Cursor = Cursors.Arrow; }\n\n private void Surface_MouseDoubleClick(object sender, MouseButtonEventArgs e) { if (ToggleFullScreenOnDoubleClick == AvailableWindows.Surface || ToggleFullScreenOnDoubleClick == AvailableWindows.Both) { IsFullScreen = !IsFullScreen; e.Handled = true; } }\n private void Overlay_MouseDoubleClick(object sender, MouseButtonEventArgs e) { if (ToggleFullScreenOnDoubleClick == AvailableWindows.Overlay || ToggleFullScreenOnDoubleClick == AvailableWindows.Both) { IsFullScreen = !IsFullScreen; e.Handled = true; } }\n\n private void Surface_MouseWheel(object sender, MouseWheelEventArgs e)\n {\n if (Player == null || e.Delta == 0)\n return;\n\n if ((Keyboard.IsKeyDown(Key.LeftCtrl) || Keyboard.IsKeyDown(Key.RightCtrl)) &&\n (PanZoomOnCtrlWheel == AvailableWindows.Surface || PanZoomOnCtrlWheel == AvailableWindows.Both))\n {\n var cur = e.GetPosition(Surface);\n Point curDpi = new(cur.X * DpiX, cur.Y * DpiY);\n if (e.Delta > 0)\n Player.ZoomIn(curDpi);\n else\n Player.ZoomOut(curDpi);\n }\n else if ((Keyboard.IsKeyDown(Key.LeftShift) || Keyboard.IsKeyDown(Key.RightShift)) &&\n (PanRotateOnShiftWheel == AvailableWindows.Surface || PanZoomOnCtrlWheel == AvailableWindows.Both))\n {\n if (e.Delta > 0)\n Player.RotateRight();\n else\n Player.RotateLeft();\n }\n\n //else if (IsAttached) // TBR ScrollViewer\n //{\n // RaiseEvent(e);\n //}\n }\n private void Overlay_MouseWheel(object sender, MouseWheelEventArgs e)\n {\n if (Player == null || e.Delta == 0)\n return;\n\n if ((Keyboard.IsKeyDown(Key.LeftCtrl) || Keyboard.IsKeyDown(Key.RightCtrl)) &&\n (PanZoomOnCtrlWheel == AvailableWindows.Overlay || PanZoomOnCtrlWheel == AvailableWindows.Both))\n {\n var cur = e.GetPosition(Overlay);\n Point curDpi = new(cur.X * DpiX, cur.Y * DpiY);\n if (e.Delta > 0)\n Player.ZoomIn(curDpi);\n else\n Player.ZoomOut(curDpi);\n }\n else if ((Keyboard.IsKeyDown(Key.LeftShift) || Keyboard.IsKeyDown(Key.RightShift)) &&\n (PanRotateOnShiftWheel == AvailableWindows.Overlay || PanZoomOnCtrlWheel == AvailableWindows.Both))\n {\n if (e.Delta > 0)\n Player.RotateRight();\n else\n Player.RotateLeft();\n }\n }\n\n private void Surface_Closed(object sender, EventArgs e)\n {\n surfaceClosed = true;\n Dispose();\n }\n private void Surface_Closing(object sender, CancelEventArgs e) => surfaceClosing = true;\n private void Overlay_Closed(object sender, EventArgs e)\n {\n overlayClosed = true;\n if (!surfaceClosing)\n Surface?.Close();\n }\n private void OverlayStandAlone_Loaded(object sender, RoutedEventArgs e)\n {\n if (Overlay != null)\n return;\n\n if (standAloneOverlay.WindowStyle != WindowStyle.None || standAloneOverlay.AllowsTransparency == false)\n throw new Exception(\"Stand-alone FlyleafHost requires WindowStyle = WindowStyle.None and AllowsTransparency = true\");\n\n SetSurface();\n Overlay = standAloneOverlay;\n Overlay.IsVisibleChanged += OverlayStandAlone_IsVisibleChanged;\n Surface.ShowInTaskbar = false; Surface.ShowInTaskbar = true; // It will not be visible in taskbar if user clicks in another window when loading\n OverlayStandAlone_IsVisibleChanged(null, new());\n }\n private void OverlayStandAlone_IsVisibleChanged(object sender, DependencyPropertyChangedEventArgs e)\n {\n // Surface should be visible first (this happens only on initialization of standalone)\n\n if (Surface.IsVisible)\n return;\n\n if (Overlay.IsVisible)\n {\n Surface.Show();\n ShowWindow(OverlayHandle, (int)ShowWindowCommands.SW_SHOWMINIMIZED);\n ShowWindow(OverlayHandle, (int)ShowWindowCommands.SW_SHOWMAXIMIZED);\n }\n }\n\n public void Resize(Point p, int resizingSide, double ratio = 0.0)\n {\n double WindowWidth = Surface.ActualWidth;\n double WindowHeight = Surface.ActualHeight;\n double WindowLeft;\n double WindowTop;\n\n if (IsAttached) // NOTE: Window.Left will not be updated when the Owner moves, don't use it when attached\n {\n GetWindowRect(SurfaceHandle, ref curRect);\n WindowLeft = (curRect.Left - ownerZeroPointPos.X) / DpiX;\n WindowTop = (curRect.Top - ownerZeroPointPos.Y) / DpiY;\n }\n else\n {\n WindowLeft = Surface.Left;\n WindowTop = Surface.Top;\n }\n\n if (resizingSide == 2 || resizingSide == 3 || resizingSide == 6)\n {\n p.X += 5;\n\n WindowWidth = p.X > Surface.MinWidth ?\n p.X < Surface.MaxWidth ? p.X : Surface.MaxWidth :\n Surface.MinWidth;\n }\n else if (resizingSide == 1 || resizingSide == 4 || resizingSide == 5)\n {\n p.X -= 5;\n double temp = Surface.ActualWidth - p.X;\n if (temp > Surface.MinWidth && temp < Surface.MaxWidth)\n {\n WindowWidth = temp;\n WindowLeft = WindowLeft + p.X;\n }\n }\n\n if (resizingSide == 2 || resizingSide == 4 || resizingSide == 8)\n {\n p.Y += 5;\n\n if (p.Y > Surface.MinHeight)\n {\n WindowHeight = p.Y < Surface.MaxHeight ? p.Y : Surface.MaxHeight;\n }\n else\n return;\n }\n else if (resizingSide == 1 || resizingSide == 3 || resizingSide == 7)\n {\n if (ratio != 0 && resizingSide != 7)\n {\n double temp = WindowWidth / ratio;\n if (temp > Surface.MinHeight && temp < Surface.MaxHeight)\n WindowTop += Surface.ActualHeight - temp;\n else\n return;\n }\n else\n {\n p.Y -= 5;\n double temp = Surface.ActualHeight - p.Y;\n if (temp > Surface.MinHeight && temp < Surface.MaxHeight)\n {\n WindowHeight= temp;\n WindowTop += p.Y;\n }\n else\n return;\n }\n }\n\n if (ratio != 0)\n {\n if (resizingSide == 7 || resizingSide == 8)\n WindowWidth = WindowHeight * ratio;\n else\n WindowHeight = WindowWidth / ratio;\n }\n\n if (WindowWidth >= WindowHeight)\n PreferredLandscapeWidth = (int)WindowWidth;\n else\n PreferredPortraitHeight = (int)WindowHeight;\n\n WindowLeft *= DpiX;\n WindowTop *= DpiY;\n WindowWidth *= DpiX;\n WindowHeight*= DpiY;\n\n SetWindowPos(SurfaceHandle, IntPtr.Zero,\n (int)WindowLeft,\n (int)WindowTop,\n (int)Math.Ceiling(WindowWidth),\n (int)Math.Ceiling(WindowHeight),\n (uint)(SetWindowPosFlags.SWP_NOZORDER | SetWindowPosFlags.SWP_NOACTIVATE));\n }\n public static int ResizeSides(Window Window, Point p, int ResizeSensitivity, CornerRadius cornerRadius)\n {\n if (p.X <= ResizeSensitivity + (cornerRadius.TopLeft / 2) && p.Y <= ResizeSensitivity + (cornerRadius.TopLeft / 2))\n {\n Window.Cursor = Cursors.SizeNWSE;\n return 1;\n }\n else if (p.X + ResizeSensitivity + (cornerRadius.BottomRight / 2) >= Window.ActualWidth && p.Y + ResizeSensitivity + (cornerRadius.BottomRight / 2) >= Window.ActualHeight)\n {\n Window.Cursor = Cursors.SizeNWSE;\n return 2;\n }\n else if (p.X + ResizeSensitivity + (cornerRadius.TopRight / 2) >= Window.ActualWidth && p.Y <= ResizeSensitivity + (cornerRadius.TopRight / 2))\n {\n Window.Cursor = Cursors.SizeNESW;\n return 3;\n }\n else if (p.X <= ResizeSensitivity + (cornerRadius.BottomLeft / 2) && p.Y + ResizeSensitivity + (cornerRadius.BottomLeft / 2) >= Window.ActualHeight)\n {\n Window.Cursor = Cursors.SizeNESW;\n return 4;\n }\n else if (p.X <= ResizeSensitivity)\n {\n Window.Cursor = Cursors.SizeWE;\n return 5;\n }\n else if (p.X + ResizeSensitivity >= Window.ActualWidth)\n {\n Window.Cursor = Cursors.SizeWE;\n return 6;\n }\n else if (p.Y <= ResizeSensitivity)\n {\n Window.Cursor = Cursors.SizeNS;\n return 7;\n }\n else if (p.Y + ResizeSensitivity >= Window.ActualHeight)\n {\n Window.Cursor = Cursors.SizeNS;\n return 8;\n }\n else\n {\n Window.Cursor = Cursors.Arrow;\n return 0;\n }\n }\n #endregion\n\n #region Constructors\n static FlyleafHost()\n {\n DefaultStyleKeyProperty.OverrideMetadata(typeof(FlyleafHost), new FrameworkPropertyMetadata(typeof(FlyleafHost)));\n ContentProperty.OverrideMetadata(typeof(FlyleafHost), new FrameworkPropertyMetadata(null, new CoerceValueCallback(OnContentChanging)));\n }\n public FlyleafHost()\n {\n UniqueId = idGenerator++;\n isDesignMode = DesignerProperties.GetIsInDesignMode(this);\n if (isDesignMode)\n return;\n\n MarginTarget= this;\n Log = new LogHandler((\"[#\" + UniqueId + \"]\").PadRight(8, ' ') + $\" [FlyleafHost NP] \");\n Loaded += Host_Loaded;\n }\n public FlyleafHost(Window standAloneOverlay)\n {\n UniqueId = idGenerator++;\n Log = new LogHandler((\"[#\" + UniqueId + \"]\").PadRight(8, ' ') + $\" [FlyleafHost NP] \");\n\n IsStandAlone = true;\n IsAttached = false;\n\n this.standAloneOverlay = standAloneOverlay;\n standAloneOverlay.Loaded += OverlayStandAlone_Loaded;\n if (standAloneOverlay.IsLoaded)\n OverlayStandAlone_Loaded(null, null);\n }\n #endregion\n\n #region Methods\n public virtual void SetReplicaPlayer(Player oldPlayer)\n {\n if (oldPlayer != null)\n {\n oldPlayer.renderer.SetChildHandle(IntPtr.Zero);\n oldPlayer.Video.PropertyChanged -= ReplicaPlayer_Video_PropertyChanged;\n }\n\n if (ReplicaPlayer == null)\n return;\n\n if (Surface != null)\n ReplicaPlayer.renderer.SetChildHandle(SurfaceHandle);\n\n ReplicaPlayer.Video.PropertyChanged += ReplicaPlayer_Video_PropertyChanged;\n }\n public virtual void SetPlayer(Player oldPlayer)\n {\n // De-assign old Player's Handle/FlyleafHost\n if (oldPlayer != null)\n {\n Log.Debug($\"De-assign Player #{oldPlayer.PlayerId}\");\n\n oldPlayer.Video.PropertyChanged -= Player_Video_PropertyChanged;\n oldPlayer.VideoDecoder.DestroySwapChain();\n oldPlayer.Host = null;\n }\n\n if (Player == null)\n return;\n\n Log.Prefix = (\"[#\" + UniqueId + \"]\").PadRight(8, ' ') + $\" [FlyleafHost #{Player.PlayerId}] \";\n\n // De-assign new Player's Handle/FlyleafHost\n Player.Host?.Player_Disposed();\n\n if (Player == null) // We might just de-assign our Player\n return;\n\n // Assign new Player's (Handle/FlyleafHost)\n Log.Debug($\"Assign Player #{Player.PlayerId}\");\n\n Player.Host = this;\n Player.Activity.Timeout = ActivityTimeout;\n if (Player.renderer != null) // TBR: using as AudioOnly with a Control*\n Player.renderer.CornerRadius = IsFullScreen ? zeroCornerRadius : CornerRadius;\n\n if (Surface != null)\n {\n if (CornerRadius == zeroCornerRadius)\n Surface.Background = new SolidColorBrush(Player.Config.Video.BackgroundColor);\n //else // TBR: this border probably not required? only when we don't have a renderer?\n //((Border)Surface.Content).Background = new SolidColorBrush(Player.Config.Video.BackgroundColor);\n\n Player.VideoDecoder.CreateSwapChain(SurfaceHandle);\n }\n\n Player.Video.PropertyChanged += Player_Video_PropertyChanged;\n UpdateCurRatio();\n }\n public virtual void SetSurface(bool fromSetOverlay = false)\n {\n if (Surface != null)\n return;\n\n // Required for some reason (WindowStyle.None will not be updated with our style)\n Surface = new();\n Surface.Name = $\"Surface_{UniqueId}\";\n Surface.Width = Surface.Height = 1; // Will be set on loaded\n Surface.WindowStyle = WindowStyle.None;\n Surface.ResizeMode = ResizeMode.NoResize;\n Surface.ShowInTaskbar = false;\n\n // CornerRadius must be set initially to AllowsTransparency!\n if (CornerRadius == zeroCornerRadius)\n Surface.Background = Player != null ? new SolidColorBrush(Player.Config.Video.BackgroundColor) : Brushes.Black;\n else\n {\n Surface.AllowsTransparency = true;\n Surface.Background = Brushes.Transparent;\n SetCornerRadiusBorder();\n }\n\n // When using ItemsControl with ObservableCollection to fill DataTemplates with FlyleafHost EnsureHandle will call Host_loaded\n if (IsAttached) Loaded -= Host_Loaded;\n SurfaceHandle = new WindowInteropHelper(Surface).EnsureHandle();\n if (IsAttached) Loaded += Host_Loaded;\n\n if (IsAttached)\n {\n SetWindowLong(SurfaceHandle, (int)WindowLongFlags.GWL_STYLE, NONE_STYLE | (nint)WindowStyles.WS_CHILD);\n SetWindowLong(SurfaceHandle, (int)WindowLongFlags.GWL_EXSTYLE, (nint)WindowStylesEx.WS_EX_LAYERED);\n }\n else // Detached || StandAlone\n {\n SetWindowLong(SurfaceHandle, (int)WindowLongFlags.GWL_STYLE, NONE_STYLE);\n if (DetachedShowInTaskbar || IsStandAlone)\n SetWindowLong(SurfaceHandle, (int)WindowLongFlags.GWL_EXSTYLE, (nint)(WindowStylesEx.WS_EX_APPWINDOW | WindowStylesEx.WS_EX_LAYERED));\n else\n SetWindowLong(SurfaceHandle, (int)WindowLongFlags.GWL_EXSTYLE, (nint)WindowStylesEx.WS_EX_LAYERED);\n }\n\n if (Player != null)\n Player.VideoDecoder.CreateSwapChain(SurfaceHandle);\n\n if (ReplicaPlayer != null)\n ReplicaPlayer.renderer.SetChildHandle(SurfaceHandle);\n\n Surface.Closed += Surface_Closed;\n Surface.Closing += Surface_Closing;\n Surface.KeyDown += Surface_KeyDown;\n Surface.KeyUp += Surface_KeyUp;\n Surface.Drop += Surface_Drop;\n Surface.DragEnter += Surface_DragEnter;\n Surface.StateChanged+= Surface_StateChanged;\n Surface.SizeChanged += SetRectOverlay;\n\n SetMouseSurface();\n\n Surface.AllowDrop =\n OpenOnDrop == AvailableWindows.Surface || OpenOnDrop == AvailableWindows.Both ||\n SwapOnDrop == AvailableWindows.Surface || SwapOnDrop == AvailableWindows.Both;\n\n if (IsAttached && IsLoaded && Owner == null && !fromSetOverlay)\n Host_Loaded(null, null);\n\n SurfaceCreated?.Invoke(this, new());\n }\n public virtual void SetOverlay()\n {\n if (Overlay == null)\n return;\n\n SetSurface(true);\n\n if (IsAttached) Loaded -= Host_Loaded;\n OverlayHandle = new WindowInteropHelper(Overlay).EnsureHandle();\n if (IsAttached) Loaded += Host_Loaded;\n\n if (IsStandAlone)\n {\n if (PreferredLandscapeWidth == 0)\n PreferredLandscapeWidth = (int)Overlay.Width;\n\n if (PreferredPortraitHeight == 0)\n PreferredPortraitHeight = (int)Overlay.Height;\n\n SetWindowPos(SurfaceHandle, IntPtr.Zero, (int)Math.Round(Overlay.Left * DpiX), (int)Math.Round(Overlay.Top * DpiY), (int)Math.Round(Overlay.ActualWidth * DpiX), (int)Math.Round(Overlay.ActualHeight * DpiY),\n (uint)(SetWindowPosFlags.SWP_NOZORDER | SetWindowPosFlags.SWP_NOACTIVATE));\n\n Surface.Title = Overlay.Title;\n Surface.Icon = Overlay.Icon;\n Surface.MinHeight = Overlay.MinHeight;\n Surface.MaxHeight = Overlay.MaxHeight;\n Surface.MinWidth = Overlay.MinWidth;\n Surface.MaxWidth = Overlay.MaxWidth;\n Surface.Topmost = DetachedTopMost;\n }\n else\n {\n Overlay.Resources = Resources;\n Overlay.DataContext = this; // TBR: or this.DataContext?\n }\n\n SetWindowPos(OverlayHandle, IntPtr.Zero, 0, 0, (int)Surface.ActualWidth, (int)Surface.ActualHeight,\n (uint)(SetWindowPosFlags.SWP_NOZORDER | SetWindowPosFlags.SWP_NOACTIVATE));\n\n Overlay.Name = $\"Overlay_{UniqueId}\";\n Overlay.Background = Brushes.Transparent;\n Overlay.ShowInTaskbar = false;\n Overlay.Owner = Surface;\n SetParent(OverlayHandle, SurfaceHandle);\n SetWindowLong(OverlayHandle, (int)WindowLongFlags.GWL_STYLE, NONE_STYLE | (nint)(WindowStyles.WS_CHILD | WindowStyles.WS_MAXIMIZE)); // TBR: WS_MAXIMIZE required? (possible better for DWM on fullscreen?)\n\n Overlay.KeyUp += Overlay_KeyUp;\n Overlay.KeyDown += Overlay_KeyDown;\n Overlay.Closed += Overlay_Closed;\n Overlay.Drop += Overlay_Drop;\n Overlay.DragEnter += Overlay_DragEnter;\n\n SetMouseOverlay();\n\n // Owner will close the overlay\n Overlay.KeyDown += (o, e) => { if (e.Key == Key.System && e.SystemKey == Key.F4) Surface?.Focus(); };\n\n Overlay.AllowDrop =\n OpenOnDrop == AvailableWindows.Overlay || OpenOnDrop == AvailableWindows.Both ||\n SwapOnDrop == AvailableWindows.Overlay || SwapOnDrop == AvailableWindows.Both;\n\n if (setTemplate)\n Overlay.Template = OverlayTemplate;\n\n if (Surface.IsVisible)\n Overlay.Show();\n else if (!IsStandAlone && !Overlay.IsVisible)\n {\n Overlay.Show();\n Overlay.Hide();\n }\n\n if (IsAttached && IsLoaded && Owner == null)\n Host_Loaded(null, null);\n\n OverlayCreated?.Invoke(this, new());\n }\n private void SetMouseSurface()\n {\n if (Surface == null)\n return;\n\n if ((MouseBindings == AvailableWindows.Surface || MouseBindings == AvailableWindows.Both) && !isMouseBindingsSubscribedSurface)\n {\n Surface.LostMouseCapture += Surface_LostMouseCapture;\n Surface.MouseLeftButtonDown += Surface_MouseLeftButtonDown;\n Surface.MouseLeftButtonUp += Surface_MouseLeftButtonUp;\n if (PanZoomOnCtrlWheel != AvailableWindows.None ||\n PanRotateOnShiftWheel != AvailableWindows.None)\n {\n Surface.MouseWheel += Surface_MouseWheel;\n }\n Surface.MouseMove += Surface_MouseMove;\n Surface.MouseLeave += Surface_MouseLeave;\n if (ToggleFullScreenOnDoubleClick != AvailableWindows.None)\n {\n Surface.MouseDoubleClick += Surface_MouseDoubleClick;\n }\n isMouseBindingsSubscribedSurface = true;\n }\n else if (isMouseBindingsSubscribedSurface)\n {\n Surface.LostMouseCapture -= Surface_LostMouseCapture;\n Surface.MouseLeftButtonDown -= Surface_MouseLeftButtonDown;\n Surface.MouseLeftButtonUp -= Surface_MouseLeftButtonUp;\n if (PanZoomOnCtrlWheel != AvailableWindows.None ||\n PanRotateOnShiftWheel != AvailableWindows.None)\n {\n Surface.MouseWheel -= Surface_MouseWheel;\n }\n Surface.MouseMove -= Surface_MouseMove;\n Surface.MouseLeave -= Surface_MouseLeave;\n if (ToggleFullScreenOnDoubleClick != AvailableWindows.None)\n {\n Surface.MouseDoubleClick -= Surface_MouseDoubleClick;\n }\n isMouseBindingsSubscribedSurface = false;\n }\n }\n private void SetMouseOverlay()\n {\n if (Overlay == null)\n return;\n\n if ((MouseBindings == AvailableWindows.Overlay || MouseBindings == AvailableWindows.Both) && !isMouseBindingsSubscribedOverlay)\n {\n Overlay.LostMouseCapture += Overlay_LostMouseCapture;\n Overlay.MouseLeftButtonDown += Overlay_MouseLeftButtonDown;\n Overlay.MouseLeftButtonUp += Overlay_MouseLeftButtonUp;\n if (PanZoomOnCtrlWheel != AvailableWindows.None ||\n PanRotateOnShiftWheel != AvailableWindows.None)\n {\n Overlay.MouseWheel += Overlay_MouseWheel;\n }\n Overlay.MouseMove += Overlay_MouseMove;\n Overlay.MouseLeave += Overlay_MouseLeave;\n if (ToggleFullScreenOnDoubleClick != AvailableWindows.None)\n {\n Overlay.MouseDoubleClick += Overlay_MouseDoubleClick;\n }\n isMouseBindingsSubscribedOverlay = true;\n }\n else if (isMouseBindingsSubscribedOverlay)\n {\n Overlay.LostMouseCapture -= Overlay_LostMouseCapture;\n Overlay.MouseLeftButtonDown -= Overlay_MouseLeftButtonDown;\n Overlay.MouseLeftButtonUp -= Overlay_MouseLeftButtonUp;\n if (PanZoomOnCtrlWheel != AvailableWindows.None ||\n PanRotateOnShiftWheel != AvailableWindows.None)\n {\n Overlay.MouseWheel -= Overlay_MouseWheel;\n }\n Overlay.MouseMove -= Overlay_MouseMove;\n Overlay.MouseLeave -= Overlay_MouseLeave;\n if (ToggleFullScreenOnDoubleClick != AvailableWindows.None)\n {\n Overlay.MouseDoubleClick -= Overlay_MouseDoubleClick;\n }\n\n isMouseBindingsSubscribedOverlay = false;\n }\n }\n\n public virtual void Attach(bool ignoreRestoreRect = false)\n {\n Window wasFocus = Overlay != null && Overlay.IsKeyboardFocusWithin ? Overlay : Surface;\n\n if (IsFullScreen)\n {\n IsFullScreen = false;\n return;\n }\n if (!ignoreRestoreRect)\n rectDetachedLast= new(Surface.Left, Surface.Top, Surface.Width, Surface.Height);\n\n Surface.Topmost = false;\n Surface.MinWidth = MinWidth;\n Surface.MinHeight = MinHeight;\n Surface.MaxWidth = MaxWidth;\n Surface.MaxHeight = MaxHeight;\n\n SetWindowLong(SurfaceHandle, (int)WindowLongFlags.GWL_STYLE, NONE_STYLE | (nint)WindowStyles.WS_CHILD);\n Surface.Owner = Owner;\n SetParent(SurfaceHandle, OwnerHandle);\n\n rectInitLast = rectIntersectLast = rectRandom;\n Host_LayoutUpdated(null, null);\n Owner.Activate();\n wasFocus.Focus();\n }\n public virtual void Detach()\n {\n if (IsFullScreen)\n IsFullScreen = false;\n\n Surface.MinWidth = DetachedMinWidth;\n Surface.MinHeight = DetachedMinHeight;\n Surface.MaxWidth = DetachedMaxWidth;\n Surface.MaxHeight = DetachedMaxHeight;\n\n // Calculate Size\n var newSize = DetachedRememberSize && rectDetachedLast != Rect.Empty\n ? new Size(rectDetachedLast.Width, rectDetachedLast.Height)\n : DetachedFixedSize;\n\n // Calculate Position\n Point newPos;\n if (DetachedRememberPosition && rectDetachedLast != Rect.Empty)\n newPos = new Point(rectDetachedLast.X, rectDetachedLast.Y);\n else\n {\n var screen = System.Windows.Forms.Screen.FromPoint(new System.Drawing.Point((int)Surface.Top, (int)Surface.Left)).Bounds;\n\n // Drop Dpi to work with screen (no Dpi)\n newSize.Width *= DpiX;\n newSize.Height *= DpiY;\n\n switch (DetachedPosition)\n {\n case DetachedPositionOptions.TopLeft:\n newPos = new Point(screen.Left, screen.Top);\n break;\n case DetachedPositionOptions.TopCenter:\n newPos = new Point(screen.Left + (screen.Width / 2) - (newSize.Width / 2), screen.Top);\n break;\n\n case DetachedPositionOptions.TopRight:\n newPos = new Point(screen.Left + screen.Width - newSize.Width, screen.Top);\n break;\n\n case DetachedPositionOptions.CenterLeft:\n newPos = new Point(screen.Left, screen.Top + (screen.Height / 2) - (newSize.Height / 2));\n break;\n\n case DetachedPositionOptions.CenterCenter:\n newPos = new Point(screen.Left + (screen.Width / 2) - (newSize.Width / 2), screen.Top + (screen.Height / 2) - (newSize.Height / 2));\n break;\n\n case DetachedPositionOptions.CenterRight:\n newPos = new Point(screen.Left + screen.Width - newSize.Width, screen.Top + (screen.Height / 2) - (newSize.Height / 2));\n break;\n\n case DetachedPositionOptions.BottomLeft:\n newPos = new Point(screen.Left, screen.Top + screen.Height - newSize.Height);\n break;\n\n case DetachedPositionOptions.BottomCenter:\n newPos = new Point(screen.Left + (screen.Width / 2) - (newSize.Width / 2), screen.Top + screen.Height - newSize.Height);\n break;\n\n case DetachedPositionOptions.BottomRight:\n newPos = new Point(screen.Left + screen.Width - newSize.Width, screen.Top + screen.Height - newSize.Height);\n break;\n\n case DetachedPositionOptions.Custom:\n newPos = DetachedFixedPosition;\n break;\n\n default:\n newPos = new(); //satisfy the compiler\n break;\n }\n\n // SetRect will drop DPI so we add it\n newPos.X /= DpiX;\n newPos.Y /= DpiY;\n\n newPos.X += DetachedPositionMargin.Left - DetachedPositionMargin.Right;\n newPos.Y += DetachedPositionMargin.Top - DetachedPositionMargin.Bottom;\n\n // Restore DPI\n newSize.Width /= DpiX;\n newSize.Height /= DpiY;\n }\n\n Rect final = new(newPos.X, newPos.Y, newSize.Width, newSize.Height);\n\n // Detach (Parent=Null, Owner=Null ?, ShowInTaskBar?, TopMost?)\n SetParent(SurfaceHandle, IntPtr.Zero);\n SetWindowLong(SurfaceHandle, (int)WindowLongFlags.GWL_STYLE, NONE_STYLE); // TBR (also in Attach/FullScren): Needs to be after SetParent. when detached and trying to close the owner will take two clicks (like mouse capture without release) //SetWindowLong(SurfaceHandle, (int)WindowLongFlags.GWL_STYLE, GetWindowLong(SurfaceHandle, (int)WindowLongFlags.GWL_STYLE) & ~(nint)WindowStyles.WS_CHILD);\n Surface.Owner = DetachedNoOwner ? null : Owner;\n Surface.Topmost = DetachedTopMost;\n\n SetRect(ref final);\n ResetVisibleRect();\n\n if (Surface.IsVisible) // Initially detached will not be visible yet and activate not required (in case of multiple)\n Surface.Activate();\n }\n\n public void RefreshNormalFullScreen()\n {\n if (IsFullScreen)\n {\n if (IsAttached)\n {\n // When we set the parent to null we don't really know in which left/top will be transfered and maximized into random screen\n GetWindowRect(SurfaceHandle, ref curRect);\n\n ResetVisibleRect();\n SetParent(SurfaceHandle, IntPtr.Zero);\n SetWindowLong(SurfaceHandle, (int)WindowLongFlags.GWL_STYLE, NONE_STYLE); // TBR (also in Attach/FullScren): Needs to be after SetParent. when detached and trying to close the owner will take two clicks (like mouse capture without release) //SetWindowLong(SurfaceHandle, (int)WindowLongFlags.GWL_STYLE, GetWindowLong(SurfaceHandle, (int)WindowLongFlags.GWL_STYLE) & ~(nint)WindowStyles.WS_CHILD);\n Surface.Owner = DetachedNoOwner ? null : Owner;\n Surface.Topmost = DetachedTopMost;\n\n SetWindowPos(SurfaceHandle, IntPtr.Zero, curRect.Left, curRect.Top, 0, 0, (uint)(SetWindowPosFlags.SWP_NOZORDER | SetWindowPosFlags.SWP_NOACTIVATE | SetWindowPosFlags.SWP_NOSIZE));\n }\n\n if (Player != null)\n Player.renderer.CornerRadius = zeroCornerRadius;\n\n if (CornerRadius != zeroCornerRadius)\n ((Border)Surface.Content).CornerRadius = zeroCornerRadius;\n\n Surface.WindowState = WindowState.Maximized;\n\n // If it was above the borders and double click (mouse didn't move to refresh)\n Surface.Cursor = Cursors.Arrow;\n if (Overlay != null)\n Overlay.Cursor = Cursors.Arrow;\n }\n else\n {\n if (IsStandAlone)\n Surface.WindowState = WindowState.Normal;\n\n if (IsAttached)\n {\n Attach(true);\n InvalidateVisual(); // To force the FlyleafSharedOverlay (if any) redraw on-top\n }\n else if (Surface.Topmost || DetachedTopMost) // Bring to front (in Desktop, above windows bar)\n {\n Surface.Topmost = false;\n Surface.Topmost = true;\n }\n\n UpdateCurRatio();\n\n // TBR: CornerRadius background has issue it's like a mask color?\n if (Player != null)\n Player.renderer.CornerRadius = CornerRadius;\n\n if (CornerRadius != zeroCornerRadius)\n ((Border)Surface.Content).CornerRadius = CornerRadius;\n\n if (!IsStandAlone) //when play with alpha video and not standalone, we need to set window state to normal last, otherwise it will be lost the background\n Surface.WindowState = WindowState.Normal;\n }\n }\n public void SetRect(ref Rect rect)\n => SetWindowPos(SurfaceHandle, IntPtr.Zero, (int)Math.Round(rect.X * DpiX), (int)Math.Round(rect.Y * DpiY), (int)Math.Round(rect.Width * DpiX), (int)Math.Round(rect.Height * DpiY),\n (uint)(SetWindowPosFlags.SWP_NOZORDER | SetWindowPosFlags.SWP_NOACTIVATE));\n\n private void SetRectOverlay(object sender, SizeChangedEventArgs e)\n {\n if (Overlay != null)\n SetWindowPos(OverlayHandle, IntPtr.Zero, 0, 0, (int)Math.Round(Surface.ActualWidth * DpiX), (int)Math.Round(Surface.ActualHeight * DpiY),\n (uint)(SetWindowPosFlags.SWP_NOZORDER | SetWindowPosFlags.SWP_NOMOVE | SetWindowPosFlags.SWP_NOACTIVATE));\n }\n\n public void ResetVisibleRect()\n {\n SetWindowRgn(SurfaceHandle, IntPtr.Zero, true);\n if (Overlay != null)\n SetWindowRgn(OverlayHandle, IntPtr.Zero, true);\n }\n public void SetVisibleRect(ref Rect rect)\n {\n SetWindowRgn(SurfaceHandle, CreateRectRgn((int)Math.Round(rect.X * DpiX), (int)Math.Round(rect.Y * DpiY), (int)Math.Round(rect.Right * DpiX), (int)Math.Round(rect.Bottom * DpiY)), true);\n if (Overlay != null)\n SetWindowRgn(OverlayHandle, CreateRectRgn((int)Math.Round(rect.X * DpiX), (int)Math.Round(rect.Y * DpiY), (int)Math.Round(rect.Right * DpiX), (int)Math.Round(rect.Bottom * DpiY)), true);\n }\n\n /// \n /// Disposes the Surface and Overlay Windows and de-assigns the Player\n /// \n public void Dispose()\n {\n lock (this)\n {\n if (Disposed)\n return;\n\n // Disposes SwapChain Only\n Player = null;\n ReplicaPlayer = null;\n Disposed = true;\n\n DataContextChanged -= Host_DataContextChanged;\n LayoutUpdated -= Host_LayoutUpdated;\n IsVisibleChanged -= Host_IsVisibleChanged;\n Loaded \t\t\t-= Host_Loaded;\n\n if (Overlay != null)\n {\n if (isMouseBindingsSubscribedOverlay)\n SetMouseOverlay();\n\n Overlay.IsVisibleChanged-= OverlayStandAlone_IsVisibleChanged;\n Overlay.KeyUp -= Overlay_KeyUp;\n Overlay.KeyDown -= Overlay_KeyDown;\n Overlay.Closed -= Overlay_Closed;\n Overlay.Drop -= Overlay_Drop;\n Overlay.DragEnter -= Overlay_DragEnter;\n }\n\n if (Surface != null)\n {\n if (isMouseBindingsSubscribedSurface)\n SetMouseSurface();\n\n Surface.Closed -= Surface_Closed;\n Surface.Closing -= Surface_Closing;\n Surface.KeyDown -= Surface_KeyDown;\n Surface.KeyUp -= Surface_KeyUp;\n Surface.Drop -= Surface_Drop;\n Surface.DragEnter -= Surface_DragEnter;\n Surface.StateChanged-= Surface_StateChanged;\n Surface.SizeChanged -= SetRectOverlay;\n\n // If not shown yet app will not close properly\n if (!surfaceClosed)\n {\n Surface.Owner = null;\n SetParent(SurfaceHandle, IntPtr.Zero);\n Surface.Width = Surface.Height = 1;\n Surface.Show();\n if (!overlayClosed)\n Overlay?.Show();\n Surface.Close();\n }\n }\n\n if (Owner != null)\n Owner.SizeChanged -= Owner_SizeChanged;\n\n Surface = null;\n Overlay = null;\n Owner = null;\n\n SurfaceHandle = IntPtr.Zero;\n OverlayHandle = IntPtr.Zero;\n OwnerHandle = IntPtr.Zero;\n\n Log.Debug(\"Disposed\");\n }\n }\n\n public bool Player_CanHideCursor() => (Surface != null && Surface.IsMouseOver) ||\n (Overlay != null && Overlay.IsActive);\n public bool Player_GetFullScreen() => IsFullScreen;\n public void Player_SetFullScreen(bool value) => IsFullScreen = value;\n public void Player_Disposed() => UIInvokeIfRequired(() => Player = null);\n #endregion\n}\n\npublic enum AvailableWindows\n{\n None, Surface, Overlay, Both\n}\n\npublic enum AttachedDragMoveOptions\n{\n None, Surface, Overlay, Both, SurfaceOwner, OverlayOwner, BothOwner\n}\n\npublic enum DetachedPositionOptions\n{\n Custom, TopLeft, TopCenter, TopRight, CenterLeft, CenterCenter, CenterRight, BottomLeft, BottomCenter, BottomRight\n}\n"], ["/LLPlayer/LLPlayer/Services/FlyleafLoader.cs", "using System.IO;\nusing System.Windows;\nusing FlyleafLib;\nusing FlyleafLib.MediaPlayer;\nusing FlyleafLib.MediaPlayer.Translation;\n\nnamespace LLPlayer.Services;\n\npublic static class FlyleafLoader\n{\n public static void StartEngine()\n {\n EngineConfig engineConfig = DefaultEngineConfig();\n\n // Load Player's Config\n if (File.Exists(App.EngineConfigPath))\n {\n try\n {\n var opts = AppConfig.GetJsonSerializerOptions();\n engineConfig = EngineConfig.Load(App.EngineConfigPath, opts);\n if (engineConfig.Version != App.Version)\n {\n engineConfig.Version = App.Version;\n engineConfig.Save(App.EngineConfigPath, opts);\n }\n }\n catch (Exception ex)\n {\n MessageBox.Show($\"Cannot load EngineConfig from {Path.GetFileName(App.EngineConfigPath)}, Please review the settings or delete the config file. Error details are recorded in {Path.GetFileName(App.CrashLogPath)}.\");\n try\n {\n File.WriteAllText(App.CrashLogPath, \"EngineConfig Loading Error: \" + ex);\n }\n catch\n {\n // ignored\n }\n\n Application.Current.Shutdown();\n }\n }\n\n Engine.Start(engineConfig);\n }\n\n public static Player CreateFlyleafPlayer()\n {\n Config? config = null;\n bool useConfig = false;\n\n // Load Player's Config\n if (File.Exists(App.PlayerConfigPath))\n {\n try\n {\n var opts = AppConfig.GetJsonSerializerOptions();\n config = Config.Load(App.PlayerConfigPath, opts);\n\n if (config.Version != App.Version)\n {\n config.Version = App.Version;\n config.Save(App.PlayerConfigPath, opts);\n }\n useConfig = true;\n }\n catch (Exception ex)\n {\n MessageBox.Show($\"Cannot load PlayerConfig from {Path.GetFileName(App.PlayerConfigPath)}, Please review the settings or delete the config file. Error details are recorded in {Path.GetFileName(App.CrashLogPath)}.\");\n try\n {\n File.WriteAllText(App.CrashLogPath, \"PlayerConfig Loading Error: \" + ex);\n }\n catch\n {\n // ignored\n }\n\n Application.Current.Shutdown();\n }\n }\n\n config ??= DefaultConfig();\n Player player = new(config);\n\n if (!useConfig)\n {\n // Initialize default key bindings for custom keys for new config.\n foreach (var binding in AppActions.DefaultCustomActionsMap())\n {\n config.Player.KeyBindings.Keys.Add(binding);\n }\n }\n\n return player;\n }\n\n public static EngineConfig DefaultEngineConfig()\n {\n EngineConfig engineConfig = new()\n {\n#if DEBUG\n PluginsPath = @\":Plugins\\bin\\Plugins.NET9\",\n#else\n PluginsPath = \":Plugins\",\n#endif\n FFmpegPath = \":FFmpeg\",\n FFmpegHLSLiveSeek = true,\n UIRefresh = true,\n FFmpegLoadProfile = Flyleaf.FFmpeg.LoadProfile.Filters,\n#if DEBUG\n LogOutput = \":debug\",\n LogLevel = LogLevel.Debug,\n FFmpegLogLevel = Flyleaf.FFmpeg.LogLevel.Warn,\n#endif\n };\n\n return engineConfig;\n }\n\n private static Config DefaultConfig()\n {\n Config config = new();\n config.Demuxer.FormatOptToUnderlying =\n true; // Mainly for HLS to pass the original query which might includes session keys\n config.Audio.FiltersEnabled = true; // To allow embedded atempo filter for speed\n config.Video.GPUAdapter = \"\"; // Set it empty so it will include it when we save it\n config.Subtitles.SearchLocal = true;\n config.Subtitles.TranslateTargetLanguage = Language.Get(Utils.OriginalCulture).ToTargetLanguage() ?? TargetLanguage.EnglishAmerican; // try to set native language\n\n return config;\n }\n}\n"], ["/LLPlayer/FlyleafLib/Engine/TesseractModel.cs", "using System.Collections.Generic;\nusing System.IO;\nusing System.Linq;\n\nnamespace FlyleafLib;\n\n#nullable enable\n\npublic class TesseractModel : NotifyPropertyChanged, IEquatable\n{\n public static Dictionary TesseractLangToISO6391 { get; } = new()\n {\n {TesseractOCR.Enums.Language.Afrikaans, \"af\"},\n {TesseractOCR.Enums.Language.Amharic, \"am\"},\n {TesseractOCR.Enums.Language.Arabic, \"ar\"},\n {TesseractOCR.Enums.Language.Assamese, \"as\"},\n {TesseractOCR.Enums.Language.Azerbaijani, \"az\"},\n //{TesseractOCR.Enums.Language.AzerbaijaniCyrilic, \"\"},\n {TesseractOCR.Enums.Language.Belarusian, \"be\"},\n {TesseractOCR.Enums.Language.Bengali, \"bn\"},\n {TesseractOCR.Enums.Language.Tibetan, \"bo\"},\n {TesseractOCR.Enums.Language.Bosnian, \"bs\"},\n {TesseractOCR.Enums.Language.Breton, \"br\"},\n {TesseractOCR.Enums.Language.Bulgarian, \"bg\"},\n {TesseractOCR.Enums.Language.CatalanValencian, \"ca\"},\n //{TesseractOCR.Enums.Language.Cebuano, \"\"},\n {TesseractOCR.Enums.Language.Czech, \"cs\"},\n {TesseractOCR.Enums.Language.ChineseSimplified, \"zh\"}, // do special handling\n {TesseractOCR.Enums.Language.ChineseTraditional, \"zh\"},\n //{TesseractOCR.Enums.Language.Cherokee, \"\"},\n {TesseractOCR.Enums.Language.Corsican, \"co\"},\n {TesseractOCR.Enums.Language.Welsh, \"cy\"},\n {TesseractOCR.Enums.Language.Danish, \"da\"},\n //{TesseractOCR.Enums.Language.DanishFraktur, \"\"},\n {TesseractOCR.Enums.Language.German, \"de\"},\n //{TesseractOCR.Enums.Language.GermanFrakturContrib, \"\"},\n {TesseractOCR.Enums.Language.Dzongkha, \"dz\"},\n {TesseractOCR.Enums.Language.GreekModern, \"el\"},\n {TesseractOCR.Enums.Language.English, \"en\"},\n //{TesseractOCR.Enums.Language.EnglishMiddle, \"\"},\n {TesseractOCR.Enums.Language.Esperanto, \"eo\"},\n //{TesseractOCR.Enums.Language.Math, \"zz\"},\n {TesseractOCR.Enums.Language.Estonian, \"et\"},\n {TesseractOCR.Enums.Language.Basque, \"eu\"},\n {TesseractOCR.Enums.Language.Faroese, \"fo\"},\n {TesseractOCR.Enums.Language.Persian, \"fa\"},\n //{TesseractOCR.Enums.Language.Filipino, \"\"},\n {TesseractOCR.Enums.Language.Finnish, \"fi\"},\n {TesseractOCR.Enums.Language.French, \"fr\"},\n //{TesseractOCR.Enums.Language.GermanFraktur, \"\"},\n {TesseractOCR.Enums.Language.FrenchMiddle, \"zz\"},\n //{TesseractOCR.Enums.Language.WesternFrisian, \"\"},\n {TesseractOCR.Enums.Language.ScottishGaelic, \"gd\"},\n {TesseractOCR.Enums.Language.Irish, \"ga\"},\n {TesseractOCR.Enums.Language.Galician, \"gl\"},\n //{TesseractOCR.Enums.Language.GreekAncientContrib, \"\"},\n {TesseractOCR.Enums.Language.Gujarati, \"gu\"},\n {TesseractOCR.Enums.Language.Haitian, \"ht\"},\n {TesseractOCR.Enums.Language.Hebrew, \"he\"},\n {TesseractOCR.Enums.Language.Hindi, \"hi\"},\n {TesseractOCR.Enums.Language.Croatian, \"hr\"},\n {TesseractOCR.Enums.Language.Hungarian, \"hu\"},\n {TesseractOCR.Enums.Language.Armenian, \"hy\"},\n {TesseractOCR.Enums.Language.Inuktitut, \"iu\"},\n {TesseractOCR.Enums.Language.Indonesian, \"id\"},\n {TesseractOCR.Enums.Language.Icelandic, \"is\"},\n {TesseractOCR.Enums.Language.Italian, \"it\"},\n //{TesseractOCR.Enums.Language.ItalianOld, \"\"},\n {TesseractOCR.Enums.Language.Javanese, \"jv\"},\n {TesseractOCR.Enums.Language.Japanese, \"ja\"},\n //{TesseractOCR.Enums.Language.JapaneseVertical, \"\"},\n {TesseractOCR.Enums.Language.Kannada, \"kn\"},\n {TesseractOCR.Enums.Language.Georgian, \"ka\"},\n //{TesseractOCR.Enums.Language.GeorgianOld, \"\"},\n {TesseractOCR.Enums.Language.Kazakh, \"kk\"},\n {TesseractOCR.Enums.Language.CentralKhmer, \"km\"},\n {TesseractOCR.Enums.Language.KirghizKyrgyz, \"ky\"},\n {TesseractOCR.Enums.Language.Kurmanji, \"ku\"},\n {TesseractOCR.Enums.Language.Korean, \"ko\"},\n //{TesseractOCR.Enums.Language.KoreanVertical, \"\"},\n //{TesseractOCR.Enums.Language.KurdishArabicScript, \"\"},\n {TesseractOCR.Enums.Language.Lao, \"lo\"},\n {TesseractOCR.Enums.Language.Latin, \"la\"},\n {TesseractOCR.Enums.Language.Latvian, \"lv\"},\n {TesseractOCR.Enums.Language.Lithuanian, \"lt\"},\n {TesseractOCR.Enums.Language.Luxembourgish, \"lb\"},\n {TesseractOCR.Enums.Language.Malayalam, \"ml\"},\n {TesseractOCR.Enums.Language.Marathi, \"mr\"},\n {TesseractOCR.Enums.Language.Macedonian, \"mk\"},\n {TesseractOCR.Enums.Language.Maltese, \"mt\"},\n {TesseractOCR.Enums.Language.Mongolian, \"mn\"},\n {TesseractOCR.Enums.Language.Maori, \"mi\"},\n {TesseractOCR.Enums.Language.Malay, \"ms\"},\n {TesseractOCR.Enums.Language.Burmese, \"my\"},\n {TesseractOCR.Enums.Language.Nepali, \"ne\"},\n {TesseractOCR.Enums.Language.Dutch, \"nl\"},\n {TesseractOCR.Enums.Language.Norwegian, \"no\"},\n {TesseractOCR.Enums.Language.Occitan, \"oc\"},\n {TesseractOCR.Enums.Language.Oriya, \"or\"},\n //{TesseractOCR.Enums.Language.Osd, \"\"},\n {TesseractOCR.Enums.Language.Panjabi, \"pa\"},\n {TesseractOCR.Enums.Language.Polish, \"pl\"},\n {TesseractOCR.Enums.Language.Portuguese, \"pt\"},\n {TesseractOCR.Enums.Language.Pushto, \"ps\"},\n {TesseractOCR.Enums.Language.Quechua, \"qu\"},\n {TesseractOCR.Enums.Language.Romanian, \"ro\"},\n {TesseractOCR.Enums.Language.Russian, \"ru\"},\n {TesseractOCR.Enums.Language.Sanskrit, \"sa\"},\n {TesseractOCR.Enums.Language.Sinhala, \"si\"},\n {TesseractOCR.Enums.Language.Slovak, \"sk\"},\n //{TesseractOCR.Enums.Language.SlovakFrakturContrib, \"\"},\n {TesseractOCR.Enums.Language.Slovenian, \"sl\"},\n {TesseractOCR.Enums.Language.Sindhi, \"sd\"},\n {TesseractOCR.Enums.Language.SpanishCastilian, \"es\"},\n //{TesseractOCR.Enums.Language.SpanishCastilianOld, \"\"},\n {TesseractOCR.Enums.Language.Albanian, \"sq\"},\n {TesseractOCR.Enums.Language.Serbian, \"sr\"},\n //{TesseractOCR.Enums.Language.SerbianLatin, \"\"},\n {TesseractOCR.Enums.Language.Sundanese, \"su\"},\n {TesseractOCR.Enums.Language.Swahili, \"sw\"},\n {TesseractOCR.Enums.Language.Swedish, \"sv\"},\n //{TesseractOCR.Enums.Language.Syriac, \"\"},\n {TesseractOCR.Enums.Language.Tamil, \"ta\"},\n {TesseractOCR.Enums.Language.Tatar, \"tt\"},\n {TesseractOCR.Enums.Language.Telugu, \"te\"},\n {TesseractOCR.Enums.Language.Tajik, \"tg\"},\n {TesseractOCR.Enums.Language.Tagalog, \"tl\"},\n {TesseractOCR.Enums.Language.Thai, \"th\"},\n {TesseractOCR.Enums.Language.Tigrinya, \"ti\"},\n {TesseractOCR.Enums.Language.Tonga, \"to\"},\n {TesseractOCR.Enums.Language.Turkish, \"tr\"},\n {TesseractOCR.Enums.Language.Uighur, \"ug\"},\n {TesseractOCR.Enums.Language.Ukrainian, \"uk\"},\n {TesseractOCR.Enums.Language.Urdu, \"ur\"},\n {TesseractOCR.Enums.Language.Uzbek, \"uz\"},\n //{TesseractOCR.Enums.Language.UzbekCyrilic, \"\"},\n {TesseractOCR.Enums.Language.Vietnamese, \"vi\"},\n {TesseractOCR.Enums.Language.Yiddish, \"yi\"},\n {TesseractOCR.Enums.Language.Yoruba, \"yo\"},\n };\n\n public static string ModelsDirectory { get; } = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, \"tesseractmodels\", \"tessdata\");\n\n public TesseractOCR.Enums.Language Lang { get; set; }\n\n public string ISO6391 => TesseractLangToISO6391[Lang];\n\n public string LangCode =>\n TesseractOCR.Enums.LanguageHelper.EnumToString(Lang);\n\n public long Size\n {\n get;\n set\n {\n if (Set(ref field, value))\n {\n Raise(nameof(Downloaded));\n }\n }\n }\n\n public string ModelFileName => $\"{LangCode}.traineddata\";\n\n public string ModelFilePath => Path.Combine(ModelsDirectory, ModelFileName);\n\n public bool Downloaded => Size > 0;\n\n public override string ToString() => LangCode;\n\n public bool Equals(TesseractModel? other)\n {\n if (other is null) return false;\n if (ReferenceEquals(this, other)) return true;\n return Lang == other.Lang;\n }\n\n public override bool Equals(object? obj) => obj is TesseractModel o && Equals(o);\n\n public override int GetHashCode()\n {\n return (int)Lang;\n }\n}\n\npublic class TesseractModelLoader\n{\n /// \n /// key: ISO6391, value: TesseractModel\n /// Chinese has multiple models for one ISO6391 key\n /// \n /// \n internal static Dictionary> GetAvailableModels()\n {\n List models = LoadDownloadedModels();\n\n Dictionary> dict = new();\n\n foreach (TesseractModel model in models)\n {\n if (TesseractModel.TesseractLangToISO6391.TryGetValue(model.Lang, out string? iso6391))\n {\n if (dict.ContainsKey(iso6391))\n {\n // for chinese (zh-CN, zh-TW)\n dict[iso6391].Add(model);\n }\n else\n {\n dict.Add(iso6391, [model]);\n }\n }\n }\n\n return dict;\n }\n\n public static List LoadAllModels()\n {\n EnsureModelsDirectory();\n\n List models = Enum.GetValues()\n .Where(l => TesseractModel.TesseractLangToISO6391.ContainsKey(l))\n .Select(l => new TesseractModel { Lang = l })\n .OrderBy(m => m.Lang.ToString())\n .ToList();\n\n foreach (TesseractModel model in models)\n {\n // Initialize download status of each model\n string path = model.ModelFilePath;\n if (File.Exists(path))\n {\n model.Size = new FileInfo(path).Length;\n }\n }\n\n return models;\n }\n\n public static List LoadDownloadedModels()\n {\n return LoadAllModels()\n .Where(m => m.Downloaded)\n .ToList();\n }\n\n private static void EnsureModelsDirectory()\n {\n if (!Directory.Exists(TesseractModel.ModelsDirectory))\n {\n Directory.CreateDirectory(TesseractModel.ModelsDirectory);\n }\n }\n}\n"], ["/LLPlayer/LLPlayer/Controls/FlyleafBar.xaml.cs", "using System.Windows;\nusing System.Windows.Controls;\nusing System.Windows.Controls.Primitives;\nusing System.Windows.Documents;\nusing System.Windows.Input;\nusing System.Windows.Media;\nusing System.Windows.Media.Animation;\nusing FlyleafLib;\nusing FlyleafLib.MediaFramework.MediaDemuxer;\nusing FlyleafLib.MediaPlayer;\nusing LLPlayer.Services;\nusing Microsoft.Xaml.Behaviors;\n\nnamespace LLPlayer.Controls;\n\npublic partial class FlyleafBar : UserControl\n{\n public FlyleafManager FL { get; }\n\n public FlyleafBar()\n {\n InitializeComponent();\n\n FL = ((App)Application.Current).Container.Resolve();\n\n DataContext = this;\n\n // Do not hide the cursor when it is on the seek bar\n MouseEnter += OnMouseEnter;\n LostFocus += OnMouseLeave;\n MouseLeave += OnMouseLeave;\n\n FL.Config.PropertyChanged += (sender, args) =>\n {\n if (args.PropertyName == nameof(FL.Config.SeekBarShowOnlyMouseOver))\n {\n // Avoided a problem in which Opacity was set to 0 when switching settings and was not displayed.\n FL.Player.Activity.ForceFullActive();\n IsShowing = true;\n\n if (FL.Config.SeekBarShowOnlyMouseOver && !MyCard.IsMouseOver)\n {\n IsShowing = false;\n }\n }\n };\n\n FL.Player.Activity.PropertyChanged += (sender, args) =>\n {\n switch (args.PropertyName)\n {\n case nameof(FL.Player.Activity.IsEnabled):\n if (FL.Config.SeekBarShowOnlyMouseOver)\n {\n IsShowing = !FL.Player.Activity.IsEnabled || MyCard.IsMouseOver;\n }\n break;\n\n case nameof(FL.Player.Activity.Mode):\n if (!FL.Config.SeekBarShowOnlyMouseOver)\n {\n IsShowing = FL.Player.Activity.Mode == ActivityMode.FullActive;\n }\n break;\n }\n };\n\n if (FL.Config.SeekBarShowOnlyMouseOver)\n {\n // start in hide\n MyCard.Opacity = 0.01;\n }\n else\n {\n // start in show\n IsShowing = true;\n }\n }\n\n public bool IsShowing\n {\n get;\n set\n {\n if (field == value)\n return;\n\n field = value;\n if (value)\n {\n // Fade In\n MyCard.BeginAnimation(OpacityProperty, new DoubleAnimation()\n {\n BeginTime = TimeSpan.Zero,\n To = 1,\n Duration = new Duration(TimeSpan.FromMilliseconds(FL.Config.SeekBarFadeInTimeMs))\n });\n }\n else\n {\n // Fade Out\n MyCard.BeginAnimation(OpacityProperty, new DoubleAnimation()\n {\n BeginTime = TimeSpan.Zero,\n // TODO: L: needs to be almost transparent to receive MouseEnter events\n To = FL.Config.SeekBarShowOnlyMouseOver ? 0.01 : 0,\n Duration = new Duration(TimeSpan.FromMilliseconds(FL.Config.SeekBarFadeOutTimeMs))\n });\n }\n }\n }\n\n private void OnMouseLeave(object sender, RoutedEventArgs e)\n {\n if (FL.Config.SeekBarShowOnlyMouseOver && FL.Player.Activity.IsEnabled)\n {\n IsShowing = false;\n }\n else\n {\n SetActivity(true);\n }\n }\n\n private void OnMouseEnter(object sender, MouseEventArgs e)\n {\n if (FL.Config.SeekBarShowOnlyMouseOver && FL.Player.Activity.IsEnabled)\n {\n IsShowing = true;\n }\n else\n {\n SetActivity(false);\n }\n }\n\n private void SetActivity(bool isActive)\n {\n FL.Player.Activity.IsEnabled = isActive;\n }\n\n // Left-click on button to open context menu\n private void ButtonBase_OnClick(object sender, RoutedEventArgs e)\n {\n if (sender is not Button btn)\n {\n return;\n }\n\n if (btn.ContextMenu == null)\n {\n return;\n }\n\n if (btn.ContextMenu.PlacementTarget == null)\n {\n // Do not hide seek bar when context menu is displayed (register once)\n btn.ContextMenu.Opened += OnContextMenuOnOpened;\n btn.ContextMenu.Closed += OnContextMenuOnClosed;\n btn.ContextMenu.MouseMove += OnContextMenuOnMouseMove;\n btn.ContextMenu.PlacementTarget = btn;\n }\n btn.ContextMenu.IsOpen = true;\n }\n\n private void OnContextMenuOnOpened(object o, RoutedEventArgs args)\n {\n SetActivity(false);\n }\n\n private void OnContextMenuOnClosed(object o, RoutedEventArgs args)\n {\n SetActivity(true);\n }\n\n private void OnContextMenuOnMouseMove(object o, MouseEventArgs args)\n {\n // this is necessary to keep PopupMenu visible when opened in succession when SeekBarShowOnlyMouseOver\n SetActivity(false);\n }\n}\n\npublic class SliderToolTipBehavior : Behavior\n{\n private const int PaddingSize = 5;\n private Popup? _valuePopup;\n private TextBlock? _tooltipText;\n private Border? _tooltipBorder;\n private Track? _track;\n\n public static readonly DependencyProperty ChaptersProperty =\n DependencyProperty.Register(nameof(Chapters), typeof(IList), typeof(SliderToolTipBehavior), new PropertyMetadata(null));\n\n public IList? Chapters\n {\n get => (IList)GetValue(ChaptersProperty);\n set => SetValue(ChaptersProperty, value);\n }\n\n protected override void OnAttached()\n {\n base.OnAttached();\n\n _tooltipText = new TextBlock\n {\n Foreground = Brushes.White,\n FontSize = 12,\n TextAlignment = TextAlignment.Center\n };\n\n _tooltipBorder = new Border\n {\n Background = new SolidColorBrush(Colors.Black) { Opacity = 0.7 },\n CornerRadius = new CornerRadius(4),\n Padding = new Thickness(PaddingSize),\n Child = _tooltipText\n };\n\n _valuePopup = new Popup\n {\n AllowsTransparency = true,\n Placement = PlacementMode.Absolute,\n PlacementTarget = AssociatedObject,\n Child = _tooltipBorder\n };\n\n AssociatedObject.MouseMove += Slider_MouseMove;\n AssociatedObject.MouseLeave += Slider_MouseLeave;\n }\n\n protected override void OnDetaching()\n {\n base.OnDetaching();\n\n AssociatedObject.MouseMove -= Slider_MouseMove;\n AssociatedObject.MouseLeave -= Slider_MouseLeave;\n }\n\n private void Slider_MouseMove(object sender, MouseEventArgs e)\n {\n _track ??= (Track)AssociatedObject.Template.FindName(\"PART_Track\", AssociatedObject);\n Point pos = e.GetPosition(_track);\n double value = _track.ValueFromPoint(pos);\n TimeSpan hoverTime = TimeSpan.FromSeconds(value);\n\n string dateFormat = hoverTime.Hours >= 1 ? @\"hh\\:mm\\:ss\" : @\"mm\\:ss\";\n string timestamp = hoverTime.ToString(dateFormat);\n\n // TODO: L: Allow customizable chapter display functionality\n string? chapterTitle = GetChapterTitleAtTime(hoverTime);\n\n _tooltipText!.Inlines.Clear();\n if (chapterTitle != null)\n {\n _tooltipText.Inlines.Add(chapterTitle);\n _tooltipText.Inlines.Add(new LineBreak());\n }\n\n _tooltipText.Inlines.Add(timestamp);\n\n Window window = Window.GetWindow(AssociatedObject)!;\n Point cursorPoint = window.PointToScreen(e.GetPosition(window));\n Point sliderPoint = AssociatedObject.PointToScreen(default);\n\n // Fix for high dpi because PointToScreen returns physical coords\n cursorPoint.X /= Utils.NativeMethods.DpiX;\n cursorPoint.Y /= Utils.NativeMethods.DpiY;\n\n sliderPoint.X /= Utils.NativeMethods.DpiX;\n sliderPoint.Y /= Utils.NativeMethods.DpiY;\n\n // Display on top of slider near mouse\n _valuePopup!.HorizontalOffset = cursorPoint.X - (_tooltipText.ActualWidth + PaddingSize * 2) / 2;\n _valuePopup!.VerticalOffset = sliderPoint.Y - _tooltipBorder!.ActualHeight - 5;\n\n // display popup\n _valuePopup.IsOpen = true;\n }\n\n private void Slider_MouseLeave(object sender, MouseEventArgs e)\n {\n _valuePopup!.IsOpen = false;\n }\n\n private string? GetChapterTitleAtTime(TimeSpan time)\n {\n if (Chapters == null || Chapters.Count <= 1)\n {\n return null;\n }\n\n var chapter = Chapters.FirstOrDefault(c => c.StartTime <= time.Ticks && time.Ticks <= c.EndTime);\n return chapter?.Title;\n }\n}\n"], ["/LLPlayer/LLPlayer/ViewModels/MainWindowVM.cs", "using System.IO;\nusing System.Windows;\nusing System.Windows.Media;\nusing System.Windows.Media.Imaging;\nusing System.Windows.Shell;\nusing FlyleafLib;\nusing FlyleafLib.MediaPlayer;\nusing LLPlayer.Extensions;\nusing LLPlayer.Services;\nusing InputType = FlyleafLib.InputType;\n\nnamespace LLPlayer.ViewModels;\n\npublic class MainWindowVM : Bindable\n{\n public FlyleafManager FL { get; }\n private readonly LogHandler Log;\n\n public MainWindowVM(FlyleafManager fl)\n {\n FL = fl;\n Log = new LogHandler(\"[App] [MainWindowVM ] \");\n }\n\n public string Title { get; set => Set(ref field, value); } = App.Name;\n\n #region Progress in TaskBar\n public double TaskBarProgressValue\n {\n get;\n set\n {\n double v = value;\n if (v < 0.01)\n {\n // Set to 1% because it is not displayed.\n v = 0.01;\n }\n Set(ref field, v);\n }\n }\n\n public TaskbarItemProgressState TaskBarProgressState { get; set => Set(ref field, value); }\n #endregion\n\n #region Action Button in TaskBar\n public Visibility PlayPauseVisibility { get; set => Set(ref field, value); } = Visibility.Collapsed;\n public ImageSource PlayPauseImageSource { get; set => Set(ref field, value); } = PlayIcon;\n\n private static readonly BitmapImage PlayIcon = new(\n new Uri(\"pack://application:,,,/Resources/Images/play.png\"));\n\n private static readonly BitmapImage PauseIcon = new(\n new Uri(\"pack://application:,,,/Resources/Images/pause.png\"));\n #endregion\n\n public DelegateCommand? CmdOnLoaded => field ??= new(() =>\n {\n // error handling\n FL.Player.KnownErrorOccurred += (sender, args) =>\n {\n Utils.UI(() =>\n {\n Log.Error($\"Known error occurred in Flyleaf: {args.Message} ({args.ErrorType.ToString()})\");\n ErrorDialogHelper.ShowKnownErrorPopup(args.Message, args.ErrorType);\n });\n };\n\n FL.Player.UnknownErrorOccurred += (sender, args) =>\n {\n Utils.UI(() =>\n {\n Log.Error($\"Unknown error occurred in Flyleaf: {args.Message}: {args.Exception}\");\n ErrorDialogHelper.ShowUnknownErrorPopup(args.Message, args.ErrorType, args.Exception);\n });\n };\n\n FL.Player.PropertyChanged += (sender, args) =>\n {\n switch (args.PropertyName)\n {\n case nameof(FL.Player.CurTime):\n {\n double prevValue = TaskBarProgressValue;\n double newValue = (double)FL.Player.CurTime / FL.Player.Duration;\n\n if (Math.Abs(newValue - prevValue) >= 0.01) // prevent frequent update\n {\n TaskBarProgressValue = newValue;\n }\n\n break;\n }\n case nameof(FL.Player.Status):\n // Progress in TaskBar (and title)\n switch (FL.Player.Status)\n {\n case Status.Stopped:\n // reset\n Title = App.Name;\n TaskBarProgressState = TaskbarItemProgressState.None;\n TaskBarProgressValue = 0;\n break;\n case Status.Playing:\n TaskBarProgressState = TaskbarItemProgressState.Normal;\n break;\n case Status.Opening:\n TaskBarProgressState = TaskbarItemProgressState.Indeterminate;\n TaskBarProgressValue = 0;\n break;\n case Status.Paused:\n TaskBarProgressState = TaskbarItemProgressState.Paused;\n break;\n case Status.Ended:\n TaskBarProgressState = TaskbarItemProgressState.Paused;\n TaskBarProgressValue = 1;\n break;\n case Status.Failed:\n TaskBarProgressState = TaskbarItemProgressState.Error;\n break;\n }\n\n // Action Button in TaskBar\n switch (FL.Player.Status)\n {\n case Status.Paused:\n case Status.Playing:\n PlayPauseVisibility = Visibility.Visible;\n PlayPauseImageSource = FL.Player.Status == Status.Playing ? PauseIcon : PlayIcon;\n break;\n default:\n PlayPauseVisibility = Visibility.Collapsed;\n break;\n }\n\n break;\n }\n };\n\n FL.Player.OpenCompleted += (sender, args) =>\n {\n if (!args.Success || args.IsSubtitles)\n {\n return;\n }\n\n string name = Path.GetFileName(args.Url);\n if (FL.Player.Playlist.InputType == InputType.Web)\n {\n name = FL.Player.Playlist.Selected.Title;\n }\n Title = $\"{name} - {App.Name}\";\n TaskBarProgressValue = 0;\n TaskBarProgressState = TaskbarItemProgressState.Normal;\n };\n\n if (App.CmdUrl != null)\n {\n FL.Player.OpenAsync(App.CmdUrl);\n }\n });\n\n public DelegateCommand? CmdOnClosing => field ??= new(() =>\n {\n FL.Player.Dispose();\n });\n}\n"], ["/LLPlayer/LLPlayer/ViewModels/TesseractDownloadDialogVM.cs", "using System.Collections.ObjectModel;\nusing System.Diagnostics;\nusing System.IO;\nusing System.Net.Http;\nusing FlyleafLib;\nusing LLPlayer.Extensions;\nusing LLPlayer.Services;\n\nnamespace LLPlayer.ViewModels;\n\n// TODO: L: consider commonization with WhisperModelDownloadDialogVM\npublic class TesseractDownloadDialogVM : Bindable, IDialogAware\n{\n public FlyleafManager FL { get; }\n\n public TesseractDownloadDialogVM(FlyleafManager fl)\n {\n FL = fl;\n\n List models = TesseractModelLoader.LoadAllModels();\n foreach (var model in models)\n {\n Models.Add(model);\n }\n\n SelectedModel = Models.First();\n\n CmdDownloadModel!.PropertyChanged += (sender, args) =>\n {\n if (args.PropertyName == nameof(CmdDownloadModel.IsExecuting))\n {\n OnPropertyChanged(nameof(CanDownload));\n OnPropertyChanged(nameof(CanDelete));\n }\n };\n }\n\n private const string TempExtension = \".tmp\";\n\n public ObservableCollection Models { get; set => Set(ref field, value); } = new();\n\n public TesseractModel SelectedModel\n {\n get;\n set\n {\n if (Set(ref field, value))\n {\n OnPropertyChanged(nameof(CanDownload));\n OnPropertyChanged(nameof(CanDelete));\n }\n }\n }\n\n public string StatusText { get; set => Set(ref field, value); } = \"Select a model to download.\";\n\n public long DownloadedSize { get; set => Set(ref field, value); }\n\n public bool CanDownload =>\n SelectedModel is { Downloaded: false } && !CmdDownloadModel!.IsExecuting;\n\n public bool CanDelete =>\n SelectedModel is { Downloaded: true } && !CmdDownloadModel!.IsExecuting;\n\n private CancellationTokenSource? _cts;\n\n public AsyncDelegateCommand? CmdDownloadModel => field ??= new AsyncDelegateCommand(async () =>\n {\n _cts = new CancellationTokenSource();\n CancellationToken token = _cts.Token;\n\n TesseractModel downloadModel = SelectedModel;\n string tempModelPath = downloadModel.ModelFilePath + TempExtension;\n\n try\n {\n if (downloadModel.Downloaded)\n {\n StatusText = $\"Model '{SelectedModel}' is already downloaded\";\n return;\n }\n\n // Delete temporary files if they exist (forces re-download)\n if (!DeleteTempModel())\n {\n StatusText = \"Failed to remove temp model\";\n return;\n }\n\n StatusText = $\"Model '{downloadModel}' downloading..\";\n\n long modelSize = await DownloadModelWithProgressAsync(downloadModel.LangCode, tempModelPath, token);\n\n // After successful download, rename temporary file to final file\n File.Move(tempModelPath, downloadModel.ModelFilePath);\n\n // Update downloaded status\n downloadModel.Size = modelSize;\n OnDownloadStatusChanged();\n\n StatusText = $\"Model '{SelectedModel}' is downloaded successfully\";\n }\n catch (OperationCanceledException ex)\n when (!ex.Message.StartsWith(\"The request was canceled due to the configured HttpClient.Timeout\"))\n {\n StatusText = \"Download canceled\";\n }\n catch (Exception ex)\n {\n StatusText = $\"Failed to download: {ex.Message}\";\n }\n finally\n {\n _cts = null;\n DeleteTempModel();\n }\n\n return;\n\n bool DeleteTempModel()\n {\n // Delete temporary files if they exist\n if (File.Exists(tempModelPath))\n {\n try\n {\n File.Delete(tempModelPath);\n }\n catch (Exception)\n {\n // ignore\n\n return false;\n }\n }\n\n return true;\n }\n }).ObservesCanExecute(() => CanDownload);\n\n public DelegateCommand? CmdCancelDownloadModel => field ??= new(() =>\n {\n _cts?.Cancel();\n });\n\n public DelegateCommand? CmdDeleteModel => field ??= new DelegateCommand(() =>\n {\n try\n {\n StatusText = $\"Model '{SelectedModel}' deleting...\";\n\n TesseractModel deleteModel = SelectedModel;\n\n // Delete model file if exists\n if (File.Exists(deleteModel.ModelFilePath))\n {\n File.Delete(deleteModel.ModelFilePath);\n }\n\n // Update downloaded status\n deleteModel.Size = 0;\n OnDownloadStatusChanged();\n\n StatusText = $\"Model '{deleteModel}' is deleted successfully\";\n }\n catch (Exception ex)\n {\n StatusText = $\"Failed to delete model: {ex.Message}\";\n }\n }).ObservesCanExecute(() => CanDelete);\n\n public DelegateCommand? CmdOpenFolder => field ??= new(() =>\n {\n if (!Directory.Exists(TesseractModel.ModelsDirectory))\n return;\n\n Process.Start(new ProcessStartInfo\n {\n FileName = TesseractModel.ModelsDirectory,\n UseShellExecute = true,\n CreateNoWindow = true\n });\n });\n\n private void OnDownloadStatusChanged()\n {\n OnPropertyChanged(nameof(CanDownload));\n OnPropertyChanged(nameof(CanDelete));\n }\n\n private async Task DownloadModelWithProgressAsync(string langCode, string destinationPath, CancellationToken token)\n {\n DownloadedSize = 0;\n\n using HttpClient httpClient = new();\n httpClient.Timeout = TimeSpan.FromSeconds(10);\n\n using var response = await httpClient.GetAsync($\"https://github.com/tesseract-ocr/tessdata/raw/refs/heads/main/{langCode}.traineddata\", HttpCompletionOption.ResponseHeadersRead, token);\n\n response.EnsureSuccessStatusCode();\n\n await using Stream modelStream = await response.Content.ReadAsStreamAsync(token);\n await using FileStream fileWriter = File.OpenWrite(destinationPath);\n\n byte[] buffer = new byte[1024 * 128];\n int bytesRead;\n long totalBytesRead = 0;\n\n Stopwatch sw = new();\n sw.Start();\n\n while ((bytesRead = await modelStream.ReadAsync(buffer, 0, buffer.Length, token)) > 0)\n {\n await fileWriter.WriteAsync(buffer, 0, bytesRead, token);\n totalBytesRead += bytesRead;\n\n if (sw.Elapsed > TimeSpan.FromMilliseconds(50))\n {\n DownloadedSize = totalBytesRead;\n sw.Restart();\n }\n\n token.ThrowIfCancellationRequested();\n }\n\n return totalBytesRead;\n }\n\n #region IDialogAware\n public string Title { get; set => Set(ref field, value); } = $\"Tesseract Downloader - {App.Name}\";\n public double WindowWidth { get; set => Set(ref field, value); } = 400;\n public double WindowHeight { get; set => Set(ref field, value); } = 200;\n\n public bool CanCloseDialog() => !CmdDownloadModel!.IsExecuting;\n public void OnDialogClosed() { }\n public void OnDialogOpened(IDialogParameters parameters) { }\n public DialogCloseListener RequestClose { get; }\n #endregion IDialogAware\n}\n"], ["/LLPlayer/FlyleafLib/MediaPlayer/Translation/Services/ITranslateSettings.cs", "using System.Collections.Generic;\nusing System.Collections.ObjectModel;\nusing System.ComponentModel;\nusing System.Diagnostics;\nusing System.Linq;\nusing System.Net.Http;\nusing System.Text;\nusing System.Text.Json.Serialization;\nusing System.Threading.Tasks;\nusing FlyleafLib.Controls.WPF;\n\nnamespace FlyleafLib.MediaPlayer.Translation.Services;\n\npublic interface ITranslateSettings : INotifyPropertyChanged;\n\npublic class GoogleV1TranslateSettings : NotifyPropertyChanged, ITranslateSettings\n{\n private const string DefaultEndpoint = \"https://translate.googleapis.com\";\n\n public string Endpoint\n {\n get;\n set\n {\n if (Set(ref field, value))\n {\n CmdSetDefaultEndpoint.OnCanExecuteChanged();\n }\n }\n } = DefaultEndpoint;\n\n [JsonIgnore]\n public RelayCommand CmdSetDefaultEndpoint => field ??= new(_ =>\n {\n Endpoint = DefaultEndpoint;\n }, _ => Endpoint != DefaultEndpoint);\n\n public int TimeoutMs { get; set => Set(ref field, value); } = 10000;\n\n public Dictionary Regions { get; set; } = new(GoogleV1TranslateService.DefaultRegions);\n\n /// \n /// for Settings\n /// \n [JsonIgnore]\n public ObservableCollection LanguageRegions\n {\n get\n {\n if (field == null)\n {\n field = LoadLanguageRegions();\n\n foreach (var pref in field)\n {\n pref.PropertyChanged += (sender, args) =>\n {\n if (args.PropertyName == nameof(Services.LanguageRegions.SelectedRegionMember))\n {\n // Apply changes in setting\n Regions[pref.ISO6391] = pref.SelectedRegionMember.Code;\n }\n };\n }\n }\n\n return field;\n }\n }\n\n private ObservableCollection LoadLanguageRegions()\n {\n List preferences = [\n new()\n {\n Name = \"Chinese\",\n ISO6391 = \"zh\",\n Regions =\n [\n // priority to the above\n new LanguageRegionMember { Name = \"Chinese (Simplified)\", Code = \"zh-CN\" },\n new LanguageRegionMember { Name = \"Chinese (Traditional)\", Code = \"zh-TW\" }\n ],\n },\n new()\n {\n Name = \"French\",\n ISO6391 = \"fr\",\n Regions =\n [\n new LanguageRegionMember { Name = \"French (French)\", Code = \"fr-FR\" },\n new LanguageRegionMember { Name = \"French (Canadian)\", Code = \"fr-CA\" }\n ],\n },\n new()\n {\n Name = \"Portuguese\",\n ISO6391 = \"pt\",\n Regions =\n [\n new LanguageRegionMember { Name = \"Portuguese (Portugal)\", Code = \"pt-PT\" },\n new LanguageRegionMember { Name = \"Portuguese (Brazil)\", Code = \"pt-BR\" }\n ],\n }\n ];\n\n foreach (LanguageRegions p in preferences)\n {\n if (Regions.TryGetValue(p.ISO6391, out string code))\n {\n // loaded from config\n p.SelectedRegionMember = p.Regions.FirstOrDefault(r => r.Code == code);\n }\n else\n {\n // select first\n p.SelectedRegionMember = p.Regions.First();\n }\n }\n\n return new ObservableCollection(preferences);\n }\n}\n\npublic class DeepLTranslateSettings : NotifyPropertyChanged, ITranslateSettings\n{\n public string ApiKey { get; set => Set(ref field, value); }\n\n public int TimeoutMs { get; set => Set(ref field, value); } = 10000;\n}\n\npublic class DeepLXTranslateSettings : NotifyPropertyChanged, ITranslateSettings\n{\n public string Endpoint { get; set => Set(ref field, value); } = \"http://127.0.0.1:1188\";\n\n public int TimeoutMs { get; set => Set(ref field, value); } = 10000;\n}\n\npublic abstract class OpenAIBaseTranslateSettings : NotifyPropertyChanged, ITranslateSettings\n{\n protected OpenAIBaseTranslateSettings()\n {\n // ReSharper disable once VirtualMemberCallInConstructor\n Endpoint = DefaultEndpoint;\n }\n\n public abstract TranslateServiceType ServiceType { get; }\n public string Endpoint\n {\n get;\n set\n {\n if (Set(ref field, value))\n {\n CmdSetDefaultEndpoint.OnCanExecuteChanged();\n }\n }\n }\n [JsonIgnore]\n protected virtual bool ReuseConnection => true;\n\n public abstract string DefaultEndpoint { get; }\n\n [JsonIgnore]\n public virtual string ChatPath\n {\n get => \"/v1/chat/completions\";\n set => throw new NotImplementedException();\n }\n\n public string Model { get; set => Set(ref field, value); }\n\n [JsonIgnore]\n public virtual bool ModelRequired => true;\n\n [JsonIgnore]\n public virtual bool ReasonStripRequired => true;\n\n public int TimeoutMs { get; set => Set(ref field, value); } = 15000;\n public int TimeoutHealthMs { get; set => Set(ref field, value); } = 2000;\n\n #region LLM Parameters\n public double Temperature\n {\n get;\n set\n {\n if (value is >= 0.0 and <= 2.0)\n {\n Set(ref field, Math.Round(value, 2));\n }\n }\n } = 0.0;\n\n public bool TemperatureManual { get; set => Set(ref field, value); } = true;\n\n public double TopP\n {\n get;\n set\n {\n if (value is >= 0.0 and <= 1.0)\n {\n Set(ref field, Math.Round(value, 2));\n }\n }\n } = 1;\n\n public bool TopPManual { get; set => Set(ref field, value); }\n\n public int? MaxTokens\n {\n get;\n set => Set(ref field, value is <= 0 ? null : value);\n }\n\n public int? MaxCompletionTokens\n {\n get;\n set => Set(ref field, value is <= 0 ? null : value);\n }\n #endregion\n\n /// \n /// GetHttpClient\n /// \n /// \n /// \n /// \n internal virtual HttpClient GetHttpClient(bool healthCheck = false)\n {\n if (string.IsNullOrWhiteSpace(Endpoint))\n {\n throw new TranslationConfigException(\n $\"Endpoint for {ServiceType} is not configured.\");\n }\n\n if (!healthCheck)\n {\n if (ModelRequired && string.IsNullOrWhiteSpace(Model))\n {\n throw new TranslationConfigException(\n $\"Model for {ServiceType} is not configured.\");\n }\n }\n\n // In KoboldCpp, if this is not set, even if it is sent with Connection: close,\n // the connection will be reused and an error will occur.\n HttpMessageHandler handler = ReuseConnection ?\n new HttpClientHandler() :\n new SocketsHttpHandler\n {\n PooledConnectionLifetime = TimeSpan.Zero,\n PooledConnectionIdleTimeout = TimeSpan.Zero,\n };\n\n HttpClient client = new(handler);\n client.BaseAddress = new Uri(Endpoint);\n client.Timeout = TimeSpan.FromMilliseconds(healthCheck ? TimeoutHealthMs : TimeoutMs);\n if (!ReuseConnection)\n {\n client.DefaultRequestHeaders.ConnectionClose = true;\n }\n\n return client;\n }\n\n #region For Settings\n [JsonIgnore]\n public ObservableCollection AvailableModels { get; } = new();\n\n [JsonIgnore]\n public string Status\n {\n get;\n set\n {\n if (Set(ref field, value))\n {\n Raise(nameof(StatusAvailable));\n }\n }\n }\n\n [JsonIgnore]\n public bool StatusAvailable => !string.IsNullOrEmpty(Status);\n\n [JsonIgnore]\n public RelayCommand CmdSetDefaultEndpoint => field ??= new(_ =>\n {\n Endpoint = DefaultEndpoint;\n }, _ => Endpoint != DefaultEndpoint);\n\n [JsonIgnore]\n public RelayCommand CmdCheckEndpoint => new(async void (_) =>\n {\n try\n {\n Status = \"Checking...\";\n await LoadModels();\n Status = \"OK\";\n }\n catch (Exception ex)\n {\n Status = GetErrorDetails($\"NG: {ex.Message}\", ex);\n }\n });\n\n [JsonIgnore]\n public RelayCommand CmdGetModels => new(async void (_) =>\n {\n try\n {\n Status = \"Checking...\";\n await LoadModels();\n Status = \"\"; // clear\n }\n catch (Exception ex)\n {\n Status = GetErrorDetails($\"NG: {ex.Message}\", ex);\n }\n });\n\n [JsonIgnore]\n public RelayCommand CmdHelloModel => new(async void (_) =>\n {\n Stopwatch sw = new();\n sw.Start();\n try\n {\n Status = \"Waiting...\";\n\n await OpenAIBaseTranslateService.Hello(this);\n\n Status = $\"OK in {sw.Elapsed.TotalSeconds} secs\";\n }\n catch (Exception ex)\n {\n Status = GetErrorDetails($\"NG in {sw.Elapsed.TotalSeconds} secs: {ex.Message}\", ex);\n }\n });\n\n private async Task LoadModels()\n {\n string prevModel = Model;\n AvailableModels.Clear();\n\n var models = await OpenAIBaseTranslateService.GetLoadedModels(this);\n foreach (var model in models)\n {\n AvailableModels.Add(model);\n }\n\n if (!string.IsNullOrEmpty(prevModel))\n {\n Model = AvailableModels.FirstOrDefault(m => m == prevModel);\n }\n }\n\n internal static string GetErrorDetails(string header, Exception ex)\n {\n StringBuilder sb = new();\n sb.Append(header);\n\n if (ex.Data.Contains(\"status_code\") && (string)ex.Data[\"status_code\"] != \"-1\")\n {\n sb.AppendLine();\n sb.AppendLine();\n sb.Append($\"status_code: {ex.Data[\"status_code\"]}\");\n }\n\n if (ex.Data.Contains(\"response\") && (string)ex.Data[\"response\"] != \"\")\n {\n sb.AppendLine();\n sb.Append($\"response: {ex.Data[\"response\"]}\");\n }\n\n return sb.ToString();\n }\n #endregion\n}\n\npublic class OllamaTranslateSettings : OpenAIBaseTranslateSettings\n{\n public OllamaTranslateSettings()\n {\n TimeoutMs = 20000;\n }\n\n [JsonIgnore]\n public override TranslateServiceType ServiceType => TranslateServiceType.Ollama;\n [JsonIgnore]\n public override string DefaultEndpoint => \"http://127.0.0.1:11434\";\n}\n\npublic class LMStudioTranslateSettings : OpenAIBaseTranslateSettings\n{\n public LMStudioTranslateSettings()\n {\n TimeoutMs = 20000;\n }\n\n [JsonIgnore]\n public override TranslateServiceType ServiceType => TranslateServiceType.LMStudio;\n [JsonIgnore]\n public override string DefaultEndpoint => \"http://127.0.0.1:1234\";\n [JsonIgnore]\n public override bool ModelRequired => false;\n}\n\npublic class KoboldCppTranslateSettings : OpenAIBaseTranslateSettings\n{\n public KoboldCppTranslateSettings()\n {\n TimeoutMs = 20000;\n }\n\n [JsonIgnore]\n public override TranslateServiceType ServiceType => TranslateServiceType.KoboldCpp;\n [JsonIgnore]\n public override string DefaultEndpoint => \"http://127.0.0.1:5001\";\n\n // Disabled due to error when reusing connections\n [JsonIgnore]\n protected override bool ReuseConnection => false;\n\n [JsonIgnore]\n public override bool ModelRequired => false;\n}\n\npublic class OpenAITranslateSettings : OpenAIBaseTranslateSettings\n{\n [JsonIgnore]\n public override TranslateServiceType ServiceType => TranslateServiceType.OpenAI;\n [JsonIgnore]\n public override string DefaultEndpoint => \"https://api.openai.com\";\n public string ApiKey { get; set => Set(ref field, value); }\n\n [JsonIgnore]\n public override bool ReasonStripRequired => false;\n\n /// \n /// GetHttpClient\n /// \n /// \n /// \n /// \n internal override HttpClient GetHttpClient(bool healthCheck = false)\n {\n if (string.IsNullOrWhiteSpace(ApiKey))\n {\n throw new TranslationConfigException(\n $\"API Key for {ServiceType} is not configured.\");\n }\n\n HttpClient client = base.GetHttpClient(healthCheck);\n client.DefaultRequestHeaders.Add(\"Authorization\", $\"Bearer {ApiKey}\");\n\n return client;\n }\n}\n\npublic class OpenAILikeTranslateSettings : OpenAIBaseTranslateSettings\n{\n [JsonIgnore]\n public override TranslateServiceType ServiceType => TranslateServiceType.OpenAILike;\n [JsonIgnore]\n public override string DefaultEndpoint => \"https://api.openai.com\";\n\n private const string DefaultChatPath = \"/v1/chat/completions\";\n public override string ChatPath\n {\n get;\n set\n {\n if (Set(ref field, value))\n {\n CmdSetDefaultChatPath.OnCanExecuteChanged();\n }\n }\n } = DefaultChatPath;\n\n [JsonIgnore]\n public RelayCommand CmdSetDefaultChatPath => field ??= new(_ =>\n {\n ChatPath = DefaultChatPath;\n }, _ => ChatPath != DefaultChatPath);\n\n [JsonIgnore]\n public override bool ModelRequired => false;\n public string ApiKey { get; set => Set(ref field, value); }\n\n /// \n /// GetHttpClient\n /// \n /// \n /// \n /// \n internal override HttpClient GetHttpClient(bool healthCheck = false)\n {\n HttpClient client = base.GetHttpClient(healthCheck);\n\n // optional ApiKey\n if (!string.IsNullOrWhiteSpace(ApiKey))\n {\n client.DefaultRequestHeaders.Add(\"Authorization\", $\"Bearer {ApiKey}\");\n }\n\n return client;\n }\n}\n\npublic class ClaudeTranslateSettings : OpenAIBaseTranslateSettings\n{\n [JsonIgnore]\n public override TranslateServiceType ServiceType => TranslateServiceType.Claude;\n [JsonIgnore]\n public override string DefaultEndpoint => \"https://api.anthropic.com\";\n public string ApiKey { get; set => Set(ref field, value); }\n\n [JsonIgnore]\n public override bool ReasonStripRequired => false;\n\n internal override HttpClient GetHttpClient(bool healthCheck = false)\n {\n if (string.IsNullOrWhiteSpace(ApiKey))\n {\n throw new TranslationConfigException(\n $\"API Key for {ServiceType} is not configured.\");\n }\n\n HttpClient client = base.GetHttpClient(healthCheck);\n client.DefaultRequestHeaders.Add(\"x-api-key\", ApiKey);\n client.DefaultRequestHeaders.Add(\"anthropic-version\", \"2023-06-01\");\n\n return client;\n }\n}\n\npublic class LiteLLMTranslateSettings : OpenAIBaseTranslateSettings\n{\n [JsonIgnore]\n public override TranslateServiceType ServiceType => TranslateServiceType.LiteLLM;\n [JsonIgnore]\n public override string DefaultEndpoint => \"http://127.0.0.1:4000\";\n}\n\npublic class LanguageRegionMember : NotifyPropertyChanged, IEquatable\n{\n public string Name { get; set; }\n public string Code { get; set; }\n\n public bool Equals(LanguageRegionMember other)\n {\n if (other is null) return false;\n if (ReferenceEquals(this, other)) return true;\n return Code == other.Code;\n }\n\n public override bool Equals(object obj) => obj is LanguageRegionMember o && Equals(o);\n\n public override int GetHashCode()\n {\n return (Code != null ? Code.GetHashCode() : 0);\n }\n}\n\npublic class LanguageRegions : NotifyPropertyChanged\n{\n public string ISO6391 { get; set; }\n public string Name { get; set; }\n public List Regions { get; set; }\n\n public LanguageRegionMember SelectedRegionMember { get; set => Set(ref field, value); }\n}\n"], ["/LLPlayer/FlyleafLib/Utils/Logger.cs", "using System.Collections.Generic;\nusing System.Collections.Concurrent;\nusing System.IO;\nusing System.Text;\nusing System.Threading.Tasks;\n\nnamespace FlyleafLib;\n\npublic static class Logger\n{\n public static bool CanError => Engine.Config.LogLevel >= LogLevel.Error;\n public static bool CanWarn => Engine.Config.LogLevel >= LogLevel.Warn;\n public static bool CanInfo => Engine.Config.LogLevel >= LogLevel.Info;\n public static bool CanDebug => Engine.Config.LogLevel >= LogLevel.Debug;\n public static bool CanTrace => Engine.Config.LogLevel >= LogLevel.Trace;\n\n\n public static Action\n CustomOutput = DevNullPtr;\n internal static Action\n Output = DevNullPtr;\n static string lastOutput = \"\";\n\n static ConcurrentQueue\n fileData = new();\n static bool fileTaskRunning;\n static FileStream fileStream;\n static object lockFileStream = new();\n static Dictionary\n logLevels = new();\n\n static Logger()\n {\n foreach (LogLevel loglevel in Enum.GetValues(typeof(LogLevel)))\n logLevels.Add(loglevel, loglevel.ToString().PadRight(5, ' '));\n\n // Flush File Data on Application Exit\n System.Windows.Application.Current.Exit += (o, e) =>\n {\n lock (lockFileStream)\n {\n if (fileStream != null)\n {\n while (fileData.TryDequeue(out byte[] data))\n fileStream.Write(data, 0, data.Length);\n fileStream.Dispose();\n }\n }\n };\n }\n\n internal static void SetOutput()\n {\n string output = Engine.Config.LogOutput;\n\n if (string.IsNullOrEmpty(output))\n {\n if (lastOutput != \"\")\n {\n Output = DevNullPtr;\n lastOutput = \"\";\n }\n }\n else if (output.StartsWith(\":\"))\n {\n if (output == \":console\")\n {\n if (lastOutput != \":console\")\n {\n Output = Console.WriteLine;\n lastOutput = \":console\";\n }\n }\n else if (output == \":debug\")\n {\n if (lastOutput != \":debug\")\n {\n Output = DebugPtr;\n lastOutput = \":debug\";\n }\n }\n else if (output == \":custom\")\n {\n if (lastOutput != \":custom\")\n {\n Output = CustomOutput;\n lastOutput = \":custom\";\n }\n }\n else\n throw new Exception(\"Invalid log output\");\n }\n else\n {\n lock (lockFileStream)\n {\n // Flush File Data on Previously Opened File Stream\n if (fileStream != null)\n {\n while (fileData.TryDequeue(out byte[] data))\n fileStream.Write(data, 0, data.Length);\n fileStream.Dispose();\n }\n\n string dir = Path.GetDirectoryName(output);\n if (!string.IsNullOrEmpty(dir))\n Directory.CreateDirectory(dir);\n\n fileStream = new FileStream(output, Engine.Config.LogAppend ? FileMode.Append : FileMode.Create, FileAccess.Write);\n if (lastOutput != \":file\")\n {\n Output = FilePtr;\n lastOutput = \":file\";\n }\n }\n }\n }\n static void DebugPtr(string msg) => System.Diagnostics.Debug.WriteLine(msg);\n static void DevNullPtr(string msg) { }\n static void FilePtr(string msg)\n {\n fileData.Enqueue(Encoding.UTF8.GetBytes($\"{msg}\\r\\n\"));\n\n if (!fileTaskRunning && fileData.Count > Engine.Config.LogCachedLines)\n FlushFileData();\n }\n\n static void FlushFileData()\n {\n fileTaskRunning = true;\n\n Task.Run(() =>\n {\n lock (lockFileStream)\n {\n while (fileData.TryDequeue(out byte[] data))\n fileStream.Write(data, 0, data.Length);\n\n fileStream.Flush();\n }\n\n fileTaskRunning = false;\n });\n }\n\n /// \n /// Forces cached file data to be written to the file\n /// \n public static void ForceFlush()\n {\n if (!fileTaskRunning && fileStream != null)\n FlushFileData();\n }\n\n internal static void Log(string msg, LogLevel logLevel)\n {\n if (logLevel <= Engine.Config.LogLevel)\n Output($\"{DateTime.Now.ToString(Engine.Config.LogDateTimeFormat)} | {logLevels[logLevel]} | {msg}\");\n }\n}\n\npublic class LogHandler\n{\n public string Prefix;\n\n public LogHandler(string prefix = \"\")\n => Prefix = prefix;\n\n public void Error(string msg) => Logger.Log($\"{Prefix}{msg}\", LogLevel.Error);\n public void Info(string msg) => Logger.Log($\"{Prefix}{msg}\", LogLevel.Info);\n public void Warn(string msg) => Logger.Log($\"{Prefix}{msg}\", LogLevel.Warn);\n public void Debug(string msg) => Logger.Log($\"{Prefix}{msg}\", LogLevel.Debug);\n public void Trace(string msg) => Logger.Log($\"{Prefix}{msg}\", LogLevel.Trace);\n}\n\npublic enum LogLevel\n{\n Quiet = 0x00,\n Error = 0x10,\n Warn = 0x20,\n Info = 0x30,\n Debug = 0x40,\n Trace = 0x50\n}\n"], ["/LLPlayer/FlyleafLib/MediaFramework/MediaPlaylist/M3UPlaylist.cs", "using System.Collections.Generic;\nusing System.IO;\nusing System.Text.RegularExpressions;\n\nnamespace FlyleafLib.MediaFramework.MediaPlaylist;\n\npublic class M3UPlaylistItem\n{\n public long Duration { get; set; }\n public string Title { get; set; }\n public string OriginalTitle\n { get; set; }\n public string Url { get; set; }\n public string UserAgent { get; set; }\n public string Referrer { get; set; }\n public bool GeoBlocked { get; set; }\n public bool Not_24_7 { get; set; }\n public int Height { get; set; }\n\n public Dictionary Tags { get; set; } = new Dictionary();\n}\n\npublic class M3UPlaylist\n{\n public static List ParseFromHttp(string url, int timeoutMs = 30000)\n {\n string downStr = Utils.DownloadToString(url, timeoutMs);\n if (downStr == null)\n return new();\n\n using StringReader reader = new(downStr);\n return Parse(reader);\n }\n\n public static List ParseFromString(string text)\n {\n using StringReader reader = new(text);\n return Parse(reader);\n }\n\n public static List Parse(string filename)\n {\n using StreamReader reader = new(filename);\n return Parse(reader);\n }\n private static List Parse(TextReader reader)\n {\n string line;\n List items = new();\n\n while ((line = reader.ReadLine()) != null)\n {\n if (line.StartsWith(\"#EXTINF\"))\n {\n M3UPlaylistItem item = new();\n var matches = Regex.Matches(line, \" ([^\\\\s=]+)=\\\"([^\\\\s\\\"]+)\\\"\");\n foreach (Match match in matches)\n {\n if (match.Groups.Count == 3 && !string.IsNullOrWhiteSpace(match.Groups[2].Value))\n item.Tags.Add(match.Groups[1].Value, match.Groups[2].Value);\n }\n\n item.Title = GetMatch(line, @\",\\s*(.*)$\");\n item.OriginalTitle = item.Title;\n\n if (item.Title.IndexOf(\" [Geo-blocked]\") >= 0)\n {\n item.GeoBlocked = true;\n item.Title = item.Title.Replace(\" [Geo-blocked]\", \"\");\n }\n\n if (item.Title.IndexOf(\" [Not 24/7]\") >= 0)\n {\n item.Not_24_7 = true;\n item.Title = item.Title.Replace(\" [Not 24/7]\", \"\");\n }\n\n var height = Regex.Match(item.Title, \" \\\\(([0-9]+)p\\\\)\");\n if (height.Groups.Count == 2)\n {\n item.Height = int.Parse(height.Groups[1].Value);\n item.Title = item.Title.Replace(height.Groups[0].Value, \"\");\n }\n\n while ((line = reader.ReadLine()) != null && line.StartsWith(\"#EXTVLCOPT\"))\n {\n if (item.UserAgent == null)\n {\n item.UserAgent = GetMatch(line, \"http-user-agent\\\\s*=\\\\s*\\\"*(.*)\\\"*\");\n if (item.UserAgent != null) continue;\n }\n\n if (item.Referrer == null)\n {\n item.Referrer = GetMatch(line, \"http-referrer\\\\s*=\\\\s*\\\"*(.*)\\\"*\");\n if (item.Referrer != null) continue;\n }\n }\n\n item.Url = line;\n items.Add(item);\n }\n\n // TODO: for m3u8 saved from windows media player\n //else if (!line.StartsWith(\"#\"))\n //{\n // M3UPlaylistItem item = new();\n // item.Url = line.Trim(); // this can be relative path (base path from the root m3u8) in case of http(s) this can be another m3u8*\n // if (item.Url.Length > 0)\n // {\n // item.Title = Path.GetFileName(item.Url);\n // items.Add(item);\n // }\n //}\n }\n\n return items;\n }\n\n private static string GetMatch(string text, string pattern)\n {\n var match = Regex.Match(text, pattern);\n return match.Success && match.Groups.Count > 1 ? match.Groups[1].Value : null;\n }\n}\n"], ["/LLPlayer/FlyleafLib/MediaPlayer/Data.cs", "using FlyleafLib.MediaFramework.MediaContext;\nusing FlyleafLib.MediaFramework.MediaStream;\nusing System;\nusing System.Collections.ObjectModel;\n\nnamespace FlyleafLib.MediaPlayer;\npublic class Data : NotifyPropertyChanged\n{\n /// \n /// Embedded Streams\n /// \n public ObservableCollection\n Streams => decoder?.DataDemuxer.DataStreams;\n\n /// \n /// Whether the input has data and it is configured\n /// \n public bool IsOpened { get => isOpened; internal set => Set(ref _IsOpened, value); }\n internal bool _IsOpened, isOpened;\n\n Action uiAction;\n Player player;\n DecoderContext decoder => player.decoder;\n Config Config => player.Config;\n\n public Data(Player player)\n {\n this.player = player;\n uiAction = () =>\n {\n IsOpened = IsOpened;\n };\n }\n internal void Reset()\n {\n isOpened = false;\n\n player.UIAdd(uiAction);\n }\n internal void Refresh()\n {\n if (decoder.DataStream == null)\n { Reset(); return; }\n\n isOpened = !decoder.DataDecoder.Disposed;\n\n player.UIAdd(uiAction);\n }\n internal void Enable()\n {\n if (!player.CanPlay)\n return;\n\n decoder.OpenSuggestedData();\n player.ReSync(decoder.DataStream, (int)(player.CurTime / 10000), true);\n\n Refresh();\n player.UIAll();\n }\n internal void Disable()\n {\n if (!IsOpened)\n return;\n\n decoder.CloseData();\n\n player.dFrame = null;\n Reset();\n player.UIAll();\n }\n}\n"], ["/LLPlayer/FlyleafLib/Utils/ZOrderHandler.cs", "using System;\nusing System.Collections.Generic;\nusing System.Diagnostics;\nusing System.Linq;\nusing System.Runtime.InteropServices;\nusing System.Threading.Tasks;\nusing System.Windows.Interop;\nusing System.Windows;\n\nnamespace FlyleafLib;\n\npublic static partial class Utils\n{\n public static class ZOrderHandler\n {\n [DllImport(\"user32.dll\", SetLastError = true)]\n public static extern IntPtr GetWindow(IntPtr hWnd, uint uCmd);\n\n enum GetWindow_Cmd : uint {\n GW_HWNDFIRST = 0,\n GW_HWNDLAST = 1,\n GW_HWNDNEXT = 2,\n GW_HWNDPREV = 3,\n GW_OWNER = 4,\n GW_CHILD = 5,\n GW_ENABLEDPOPUP = 6\n }\n\n public class ZOrder\n {\n public string window;\n public int order;\n }\n\n public class Owner\n {\n static int uniqueNameId = 0;\n\n public List CurZOrder = null;\n public List SavedZOrder = null;\n\n public Window Window;\n public IntPtr WindowHwnd;\n\n Dictionary WindowNamesHandles = new();\n Dictionary WindowNamesWindows = new();\n\n public Owner(Window window, IntPtr windowHwnd)\n {\n Window = window;\n WindowHwnd = windowHwnd;\n\n // TBR: Stand alone\n //if (Window.Owner != null)\n // Window.Owner.StateChanged += Window_StateChanged;\n //else\n\n Window.StateChanged += Window_StateChanged;\n lastState = Window.WindowState;\n\n // TBR: Minimize with WindowsKey + D for example will not fire (none of those)\n //HwndSource source = HwndSource.FromHwnd(WindowHwnd);\n //source.AddHook(new HwndSourceHook(WndProc));\n }\n\n public const Int32 WM_SYSCOMMAND = 0x112;\n public const Int32 SC_MAXIMIZE = 0xF030;\n private const int SC_MINIMIZE = 0xF020;\n private IntPtr WndProc(IntPtr hwnd, int msg, IntPtr wParam, IntPtr lParam, ref bool handled)\n {\n if (msg == WM_SYSCOMMAND)\n {\n if (wParam.ToInt32() == SC_MINIMIZE)\n {\n Save();\n //handled = true;\n }\n }\n return IntPtr.Zero;\n }\n\n private IntPtr GetHandle(Window window)\n {\n IntPtr hwnd = IntPtr.Zero;\n\n if (string.IsNullOrEmpty(window.Name))\n {\n hwnd = new WindowInteropHelper(window).Handle;\n window.Name = \"Zorder\" + uniqueNameId++.ToString();\n WindowNamesHandles.Add(window.Name, hwnd);\n WindowNamesWindows.Add(window.Name, window);\n }\n else if (!WindowNamesHandles.ContainsKey(window.Name))\n {\n hwnd = new WindowInteropHelper(window).Handle;\n WindowNamesHandles.Add(window.Name, hwnd);\n WindowNamesWindows.Add(window.Name, window);\n }\n else\n hwnd = WindowNamesHandles[window.Name];\n\n return hwnd;\n }\n\n WindowState lastState = WindowState.Normal;\n\n private void Window_StateChanged(object sender, EventArgs e)\n {\n if (Window.OwnedWindows.Count < 2)\n return;\n\n if (lastState == WindowState.Minimized)\n Restore();\n else if (Window.WindowState == WindowState.Minimized)\n Save();\n\n lastState = Window.WindowState;\n }\n\n public void Save()\n {\n SavedZOrder = GetZOrder();\n Debug.WriteLine(\"Saved\");\n DumpZOrder(SavedZOrder);\n }\n\n public void Restore()\n {\n if (SavedZOrder == null)\n return;\n\n Task.Run(() =>\n {\n System.Threading.Thread.Sleep(50);\n\n Application.Current.Dispatcher.Invoke(() =>\n {\n for (int i=0; i GetZOrder()\n {\n List zorders = new();\n\n foreach(Window window in Window.OwnedWindows)\n {\n ZOrder zorder = new();\n IntPtr curHwnd = GetHandle(window);\n if (curHwnd == IntPtr.Zero)\n continue;\n\n zorder.window = window.Name;\n\n while ((curHwnd = GetWindow(curHwnd, (uint)GetWindow_Cmd.GW_HWNDNEXT)) != WindowHwnd && curHwnd != IntPtr.Zero)\n zorder.order++;\n\n zorders.Add(zorder);\n }\n\n return zorders.OrderBy((o) => o.order).ToList();\n }\n\n public void DumpZOrder(List zorders)\n {\n for (int i=0; i Owners = new();\n\n public static void Register(Window window)\n {\n IntPtr hwnd = new WindowInteropHelper(window).Handle;\n if (Owners.ContainsKey(hwnd))\n return;\n\n Owners.Add(hwnd, new Owner(window, hwnd));\n }\n }\n}\n"], ["/LLPlayer/LLPlayer/ViewModels/WhisperModelDownloadDialogVM.cs", "using System.Collections.ObjectModel;\nusing System.Diagnostics;\nusing System.IO;\nusing System.Windows;\nusing FlyleafLib;\nusing LLPlayer.Extensions;\nusing LLPlayer.Services;\nusing Whisper.net.Ggml;\n\nnamespace LLPlayer.ViewModels;\n\npublic class WhisperModelDownloadDialogVM : Bindable, IDialogAware\n{\n public FlyleafManager FL { get; }\n\n public WhisperModelDownloadDialogVM(FlyleafManager fl)\n {\n FL = fl;\n\n List models = WhisperCppModelLoader.LoadAllModels();\n foreach (var model in models)\n {\n Models.Add(model);\n }\n\n SelectedModel = Models.First();\n\n CmdDownloadModel!.PropertyChanged += (sender, args) =>\n {\n if (args.PropertyName == nameof(CmdDownloadModel.IsExecuting))\n {\n OnPropertyChanged(nameof(CanDownload));\n OnPropertyChanged(nameof(CanDelete));\n }\n };\n }\n\n private const string TempExtension = \".tmp\";\n\n public ObservableCollection Models { get; set => Set(ref field, value); } = new();\n\n public WhisperCppModel SelectedModel\n {\n get;\n set\n {\n if (Set(ref field, value))\n {\n OnPropertyChanged(nameof(CanDownload));\n OnPropertyChanged(nameof(CanDelete));\n }\n }\n }\n\n public string StatusText { get; set => Set(ref field, value); } = \"Select a model to download.\";\n\n public long DownloadedSize { get; set => Set(ref field, value); }\n\n public bool CanDownload =>\n SelectedModel is { Downloaded: false } && !CmdDownloadModel!.IsExecuting;\n\n public bool CanDelete =>\n SelectedModel is { Downloaded: true } && !CmdDownloadModel!.IsExecuting;\n\n private CancellationTokenSource? _cts;\n\n public AsyncDelegateCommand? CmdDownloadModel => field ??= new AsyncDelegateCommand(async () =>\n {\n _cts = new CancellationTokenSource();\n CancellationToken token = _cts.Token;\n\n WhisperCppModel downloadModel = SelectedModel;\n string tempModelPath = downloadModel.ModelFilePath + TempExtension;\n\n try\n {\n if (downloadModel.Downloaded)\n {\n StatusText = $\"Model '{SelectedModel}' is already downloaded\";\n return;\n }\n\n // Delete temporary files if they exist (forces re-download)\n if (!DeleteTempModel())\n {\n StatusText = $\"Failed to remove temp model\";\n return;\n }\n\n StatusText = $\"Model '{downloadModel}' downloading..\";\n\n long modelSize = await DownloadModelWithProgressAsync(downloadModel.Model, tempModelPath, token);\n\n // After successful download, rename temporary file to final file\n File.Move(tempModelPath, downloadModel.ModelFilePath);\n\n // Update downloaded status\n downloadModel.Size = modelSize;\n OnDownloadStatusChanged();\n\n StatusText = $\"Model '{SelectedModel}' is downloaded successfully\";\n }\n catch (OperationCanceledException)\n {\n StatusText = \"Download canceled\";\n }\n catch (Exception ex)\n {\n StatusText = $\"Failed to download: {ex.Message}\";\n }\n finally\n {\n _cts = null;\n DeleteTempModel();\n }\n\n return;\n\n bool DeleteTempModel()\n {\n // Delete temporary files if they exist\n if (File.Exists(tempModelPath))\n {\n try\n {\n File.Delete(tempModelPath);\n }\n catch (Exception)\n {\n // ignore\n\n return false;\n }\n }\n\n return true;\n }\n }).ObservesCanExecute(() => CanDownload);\n\n public DelegateCommand? CmdCancelDownloadModel => field ??= new(() =>\n {\n _cts?.Cancel();\n });\n\n public DelegateCommand? CmdDeleteModel => field ??= new DelegateCommand(() =>\n {\n try\n {\n StatusText = $\"Model '{SelectedModel}' deleting...\";\n\n WhisperCppModel deleteModel = SelectedModel;\n\n // Delete model file if exists\n if (File.Exists(deleteModel.ModelFilePath))\n {\n File.Delete(deleteModel.ModelFilePath);\n }\n\n // Update downloaded status\n deleteModel.Size = 0;\n OnDownloadStatusChanged();\n\n StatusText = $\"Model '{deleteModel}' is deleted successfully\";\n }\n catch (Exception ex)\n {\n StatusText = $\"Failed to delete model: {ex.Message}\";\n }\n }).ObservesCanExecute(() => CanDelete);\n\n public DelegateCommand? CmdOpenFolder => field ??= new(() =>\n {\n if (!Directory.Exists(WhisperConfig.ModelsDirectory))\n return;\n\n try\n {\n Process.Start(new ProcessStartInfo\n {\n FileName = WhisperConfig.ModelsDirectory,\n UseShellExecute = true,\n CreateNoWindow = true\n });\n }\n catch (Exception ex)\n {\n MessageBox.Show($\"Failed to open folder: {ex.Message}\", \"Error\", MessageBoxButton.OK, MessageBoxImage.Error);\n }\n });\n\n private void OnDownloadStatusChanged()\n {\n OnPropertyChanged(nameof(CanDownload));\n OnPropertyChanged(nameof(CanDelete));\n }\n\n private async Task DownloadModelWithProgressAsync(GgmlType modelType, string destinationPath, CancellationToken token)\n {\n DownloadedSize = 0;\n\n await using Stream modelStream = await WhisperGgmlDownloader.Default.GetGgmlModelAsync(modelType, default, token);\n await using FileStream fileWriter = File.OpenWrite(destinationPath);\n\n byte[] buffer = new byte[1024 * 128];\n int bytesRead;\n long totalBytesRead = 0;\n\n Stopwatch sw = new();\n sw.Start();\n\n while ((bytesRead = await modelStream.ReadAsync(buffer, 0, buffer.Length, token)) > 0)\n {\n await fileWriter.WriteAsync(buffer, 0, bytesRead, token);\n totalBytesRead += bytesRead;\n\n if (sw.Elapsed > TimeSpan.FromMilliseconds(50))\n {\n DownloadedSize = totalBytesRead;\n sw.Restart();\n }\n\n token.ThrowIfCancellationRequested();\n }\n\n return totalBytesRead;\n }\n\n #region IDialogAware\n public string Title { get; set => Set(ref field, value); } = $\"Whisper Downloader - {App.Name}\";\n public double WindowWidth { get; set => Set(ref field, value); } = 400;\n public double WindowHeight { get; set => Set(ref field, value); } = 200;\n\n public bool CanCloseDialog() => !CmdDownloadModel!.IsExecuting;\n public void OnDialogClosed() { }\n public void OnDialogOpened(IDialogParameters parameters) { }\n public DialogCloseListener RequestClose { get; }\n #endregion IDialogAware\n}\n"], ["/LLPlayer/FlyleafLib/MediaFramework/MediaStream/ExternalSubtitlesStream.cs", "using System.Linq;\n\nnamespace FlyleafLib.MediaFramework.MediaStream;\n\npublic class ExternalSubtitlesStream : ExternalStream, ISubtitlesStream\n{\n public SelectedSubMethod[] SelectedSubMethods\n {\n get\n {\n var methods = (SelectSubMethod[])Enum.GetValues(typeof(SelectSubMethod));\n\n if (!IsBitmap)\n {\n // delete OCR if text sub\n methods = methods.Where(m => m != SelectSubMethod.OCR).ToArray();\n }\n\n return methods.\n Select(m => new SelectedSubMethod(this, m)).ToArray();\n }\n }\n\n public bool IsBitmap { get; set; }\n public bool ManualDownloaded{ get; set; }\n public bool Automatic { get; set; }\n public bool Downloaded { get; set; }\n public Language Language { get; set; } = Language.Unknown;\n public bool LanguageDetected{ get; set; }\n // TODO: Add confidence rating (maybe result is for other movie/episode) | Add Weight calculated based on rating/downloaded/confidence (and lang?) which can be used from suggesters\n public string Title { get; set; }\n\n public string DisplayMember =>\n $\"({Language}){(ManualDownloaded ? \" (DL)\" : \"\")}{(Automatic ? \" (Auto)\" : \"\")} {Utils.TruncateString(Title, 50)} ({(IsBitmap ? \"BMP\" : \"TXT\")})\";\n}\n"], ["/LLPlayer/FlyleafLib/MediaFramework/MediaPlaylist/Session.cs", "namespace FlyleafLib.MediaFramework.MediaPlaylist;\n\npublic class Session\n{\n public string Url { get; set; }\n public int PlaylistItem { get; set; } = -1;\n\n public int ExternalAudioStream { get; set; } = -1;\n public int ExternalVideoStream { get; set; } = -1;\n public string ExternalSubtitlesUrl { get; set; }\n\n public int AudioStream { get; set; } = -1;\n public int VideoStream { get; set; } = -1;\n public int SubtitlesStream { get; set; } = -1;\n\n public long CurTime { get; set; }\n\n public long AudioDelay { get; set; }\n public long SubtitlesDelay { get; set; }\n\n internal bool isReopen; // temp fix for opening existing playlist item as a new session (should not re-initialize - is like switch)\n\n //public SavedSession() { }\n //public SavedSession(int extVideoStream, int videoStream, int extAudioStream, int audioStream, int extSubtitlesStream, int subtitlesStream, long curTime, long audioDelay, long subtitlesDelay)\n //{\n // Update(extVideoStream, videoStream, extAudioStream, audioStream, extSubtitlesStream, subtitlesStream, curTime, audioDelay, subtitlesDelay);\n //}\n //public void Update(int extVideoStream, int videoStream, int extAudioStream, int audioStream, int extSubtitlesStream, int subtitlesStream, long curTime, long audioDelay, long subtitlesDelay)\n //{\n // ExternalVideoStream = extVideoStream; VideoStream = videoStream;\n // ExternalAudioStream = extAudioStream; AudioStream = audioStream;\n // ExternalSubtitlesStream = extSubtitlesStream; SubtitlesStream = subtitlesStream;\n // CurTime = curTime; AudioDelay = audioDelay; SubtitlesDelay = subtitlesDelay;\n //}\n}\n"], ["/LLPlayer/LLPlayer/Controls/Settings/SettingsSubtitles.xaml.cs", "using System.Windows;\nusing System.Windows.Controls;\nusing FlyleafLib;\nusing FlyleafLib.MediaPlayer.Translation;\nusing LLPlayer.Extensions;\nusing LLPlayer.Services;\nusing LLPlayer.Views;\n\nnamespace LLPlayer.Controls.Settings;\n\npublic partial class SettingsSubtitles : UserControl\n{\n public SettingsSubtitles()\n {\n InitializeComponent();\n\n DataContext = ((App)Application.Current).Container.Resolve();\n }\n}\n\npublic class SettingsSubtitlesVM : Bindable\n{\n public FlyleafManager FL { get; }\n private readonly IDialogService _dialogService;\n\n public SettingsSubtitlesVM(FlyleafManager fl, IDialogService dialogService)\n {\n _dialogService = dialogService;\n FL = fl;\n Languages = TranslateLanguage.Langs.Values.ToList();\n\n if (FL.PlayerConfig.Subtitles.LanguageFallbackPrimary != null)\n {\n SelectedPrimaryLanguage = Languages.FirstOrDefault(l => l.ISO6391 == FL.PlayerConfig.Subtitles.LanguageFallbackPrimary.ISO6391);\n }\n\n if (FL.PlayerConfig.Subtitles.LanguageFallbackSecondary != null)\n {\n SelectedSecondaryLanguage = Languages.FirstOrDefault(l => l.ISO6391 == FL.PlayerConfig.Subtitles.LanguageFallbackSecondary.ISO6391);\n }\n }\n\n public List Languages { get; set; }\n\n public TranslateLanguage? SelectedPrimaryLanguage\n {\n get;\n set\n {\n if (Set(ref field, value))\n {\n if (value == null)\n {\n FL.PlayerConfig.Subtitles.LanguageFallbackPrimary = null;\n }\n else\n {\n FL.PlayerConfig.Subtitles.LanguageFallbackPrimary = Language.Get(value.ISO6391);\n }\n\n if (FL.PlayerConfig.Subtitles.LanguageFallbackSecondarySame)\n {\n FL.PlayerConfig.Subtitles.LanguageFallbackSecondary = FL.PlayerConfig.Subtitles.LanguageFallbackPrimary;\n\n SelectedSecondaryLanguage = SelectedPrimaryLanguage;\n }\n }\n }\n }\n\n public TranslateLanguage? SelectedSecondaryLanguage\n {\n get;\n set\n {\n if (Set(ref field, value))\n {\n if (value == null)\n {\n FL.PlayerConfig.Subtitles.LanguageFallbackSecondary = null;\n }\n else\n {\n FL.PlayerConfig.Subtitles.LanguageFallbackSecondary = Language.Get(value.ISO6391);\n }\n }\n }\n }\n\n public DelegateCommand? CmdConfigureLanguage => field ??= new(() =>\n {\n DialogParameters p = new()\n {\n { \"languages\", FL.PlayerConfig.Subtitles.Languages }\n };\n\n _dialogService.ShowDialog(nameof(SelectLanguageDialog), p, result =>\n {\n List updated = result.Parameters.GetValue>(\"languages\");\n\n if (!FL.PlayerConfig.Subtitles.Languages.SequenceEqual(updated))\n {\n FL.PlayerConfig.Subtitles.Languages = updated;\n }\n });\n });\n}\n"], ["/LLPlayer/LLPlayer/App.xaml.cs", "using System.Diagnostics;\nusing System.Globalization;\nusing System.IO;\nusing System.Runtime.InteropServices;\nusing System.Windows;\nusing System.Windows.Threading;\nusing FlyleafLib;\nusing FlyleafLib.MediaPlayer;\nusing LLPlayer.Extensions;\nusing LLPlayer.Services;\nusing LLPlayer.Views;\n\nnamespace LLPlayer;\n\npublic partial class App : PrismApplication\n{\n public static string Name => \"LLPlayer\";\n public static string? CmdUrl { get; private set; } = null;\n public static string PlayerConfigPath { get; } = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, \"LLPlayer.PlayerConfig.json\");\n public static string EngineConfigPath { get; } = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, \"LLPlayer.Engine.json\");\n public static string AppConfigPath { get; } = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, \"LLPlayer.Config.json\");\n public static string CrashLogPath { get; } = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, \"crash.log\");\n\n private readonly LogHandler Log;\n\n public App()\n {\n Log = new LogHandler(\"[App] [MainApp ] \");\n }\n\n static App()\n {\n // Set thread culture to English and error messages to English\n Utils.SaveOriginalCulture();\n\n CultureInfo.DefaultThreadCurrentCulture = new CultureInfo(\"en-US\");\n CultureInfo.DefaultThreadCurrentUICulture = new CultureInfo(\"en-US\");\n }\n\n protected override void RegisterTypes(IContainerRegistry containerRegistry)\n {\n containerRegistry\n .Register(FlyleafLoader.CreateFlyleafPlayer)\n .RegisterSingleton()\n .RegisterSingleton();\n\n containerRegistry.RegisterDialogWindow();\n\n containerRegistry.RegisterDialog();\n containerRegistry.RegisterDialog();\n containerRegistry.RegisterDialog();\n containerRegistry.RegisterDialog();\n containerRegistry.RegisterDialog();\n containerRegistry.RegisterDialog();\n containerRegistry.RegisterDialog();\n containerRegistry.RegisterDialog();\n containerRegistry.RegisterDialog();\n }\n\n protected override Window CreateShell()\n {\n return Container.Resolve();\n }\n\n protected override void OnStartup(StartupEventArgs e)\n {\n if (e.Args.Length == 1)\n {\n CmdUrl = e.Args[0];\n }\n\n // TODO: L: customizable?\n // Ensures that we have enough worker threads to avoid the UI from freezing or not updating on time\n ThreadPool.GetMinThreads(out int workers, out int ports);\n ThreadPool.SetMinThreads(workers + 6, ports + 6);\n\n // Start flyleaf engine\n FlyleafLoader.StartEngine();\n\n base.OnStartup(e);\n }\n\n private void App_OnDispatcherUnhandledException(object sender, DispatcherUnhandledExceptionEventArgs e)\n {\n // Ignore WPF Clipboard exception\n if (e.Exception is COMException { ErrorCode: -2147221040 })\n {\n e.Handled = true;\n }\n\n if (!e.Handled)\n {\n Log.Error($\"Unknown error occurred in App: {e.Exception}\");\n Logger.ForceFlush();\n\n ErrorDialogHelper.ShowUnknownErrorPopup($\"Unhandled Exception: {e.Exception.Message}\", \"Global\", e.Exception);\n e.Handled = true;\n }\n }\n\n #region App Version\n public static string OSArchitecture => RuntimeInformation.OSArchitecture.ToString().ToLowerFirstChar();\n public static string ProcessArchitecture => RuntimeInformation.ProcessArchitecture.ToString().ToLowerFirstChar();\n\n private static string? _version;\n public static string Version\n {\n get\n {\n if (_version == null)\n {\n (_version, _commitHash) = GetVersion();\n }\n\n return _version;\n }\n }\n\n private static string? _commitHash;\n public static string CommitHash\n {\n get\n {\n if (_commitHash == null)\n {\n (_version, _commitHash) = GetVersion();\n }\n\n return _commitHash;\n }\n }\n\n private static (string version, string commitHash) GetVersion()\n {\n string exeLocation = Process.GetCurrentProcess().MainModule!.FileName;\n FileVersionInfo fvi = FileVersionInfo.GetVersionInfo(exeLocation);\n\n Guards.ThrowIfNull(fvi.ProductVersion);\n\n var version = fvi.ProductVersion.Split(\"+\");\n if (version.Length != 2)\n {\n throw new InvalidOperationException($\"ProductVersion is invalid: {fvi.ProductVersion}\");\n }\n\n return (version[0], version[1]);\n }\n #endregion\n}\n"], ["/LLPlayer/LLPlayer/Controls/AlignableWrapPanel.cs", "using System.Windows;\nusing System.Windows.Controls;\n\nnamespace LLPlayer.Controls;\n\n// The standard WrapPanel does not have a centering function, so add it.\n// ref: https://stackoverflow.com/a/7747002\npublic class AlignableWrapPanel : Panel\n{\n public static readonly DependencyProperty HorizontalContentAlignmentProperty =\n DependencyProperty.Register(nameof(HorizontalContentAlignment), typeof(HorizontalAlignment), typeof(AlignableWrapPanel), new FrameworkPropertyMetadata(HorizontalAlignment.Left, FrameworkPropertyMetadataOptions.AffectsArrange));\n public HorizontalAlignment HorizontalContentAlignment\n {\n get => (HorizontalAlignment)GetValue(HorizontalContentAlignmentProperty);\n set => SetValue(HorizontalContentAlignmentProperty, value);\n }\n\n protected override Size MeasureOverride(Size constraint)\n {\n Size curLineSize = new();\n Size panelSize = new();\n\n UIElementCollection children = InternalChildren;\n\n for (int i = 0; i < children.Count; i++)\n {\n UIElement child = children[i];\n\n // Flow passes its own constraint to children\n child.Measure(constraint);\n Size sz = child.DesiredSize;\n\n if (child is NewLine ||\n curLineSize.Width + sz.Width > constraint.Width) //need to switch to another line\n {\n panelSize.Width = Math.Max(curLineSize.Width, panelSize.Width);\n panelSize.Height += curLineSize.Height;\n curLineSize = sz;\n\n if (sz.Width > constraint.Width) // if the element is wider then the constraint - give it a separate line\n {\n panelSize.Width = Math.Max(sz.Width, panelSize.Width);\n panelSize.Height += sz.Height;\n curLineSize = new Size();\n }\n }\n else //continue to accumulate a line\n {\n curLineSize.Width += sz.Width;\n curLineSize.Height = Math.Max(sz.Height, curLineSize.Height);\n }\n }\n\n // the last line size, if any need to be added\n panelSize.Width = Math.Max(curLineSize.Width, panelSize.Width);\n panelSize.Height += curLineSize.Height;\n\n return panelSize;\n }\n\n protected override Size ArrangeOverride(Size arrangeBounds)\n {\n int firstInLine = 0;\n Size curLineSize = new();\n double accumulatedHeight = 0;\n UIElementCollection children = InternalChildren;\n\n for (int i = 0; i < children.Count; i++)\n {\n UIElement child = children[i];\n\n Size sz = child.DesiredSize;\n\n if (child is NewLine ||\n curLineSize.Width + sz.Width > arrangeBounds.Width) //need to switch to another line\n {\n ArrangeLine(accumulatedHeight, curLineSize, arrangeBounds.Width, firstInLine, i);\n\n accumulatedHeight += curLineSize.Height;\n curLineSize = sz;\n\n if (sz.Width > arrangeBounds.Width) //the element is wider then the constraint - give it a separate line\n {\n ArrangeLine(accumulatedHeight, sz, arrangeBounds.Width, i, ++i);\n accumulatedHeight += sz.Height;\n curLineSize = new Size();\n }\n firstInLine = i;\n }\n else //continue to accumulate a line\n {\n curLineSize.Width += sz.Width;\n curLineSize.Height = Math.Max(sz.Height, curLineSize.Height);\n }\n }\n\n if (firstInLine < children.Count)\n ArrangeLine(accumulatedHeight, curLineSize, arrangeBounds.Width, firstInLine, children.Count);\n\n return arrangeBounds;\n }\n\n private void ArrangeLine(double y, Size lineSize, double boundsWidth, int start, int end)\n {\n double x = 0;\n if (this.HorizontalContentAlignment == HorizontalAlignment.Center)\n {\n x = (boundsWidth - lineSize.Width) / 2;\n }\n else if (this.HorizontalContentAlignment == HorizontalAlignment.Right)\n {\n x = (boundsWidth - lineSize.Width);\n }\n\n UIElementCollection children = InternalChildren;\n for (int i = start; i < end; i++)\n {\n UIElement child = children[i];\n child.Arrange(new Rect(x, y, child.DesiredSize.Width, lineSize.Height));\n x += child.DesiredSize.Width;\n }\n }\n}\n"], ["/LLPlayer/LLPlayer/Converters/SubtitleConverters.cs", "using System.Globalization;\nusing System.Windows;\nusing System.Windows.Data;\nusing System.Windows.Media.Imaging;\nusing FlyleafLib.MediaPlayer;\nusing LLPlayer.Services;\n\nnamespace LLPlayer.Converters;\n\npublic class WidthPercentageMultiConverter : IMultiValueConverter\n{\n public object Convert(object[] values, Type targetType, object parameter, CultureInfo culture)\n {\n if (values[0] is double actualWidth &&\n values[1] is double maxWidth &&\n values[2] is double percentage)\n {\n if (percentage >= 100.0)\n {\n // respect line break\n return actualWidth;\n }\n\n var calcWidth = actualWidth * (percentage / 100.0);\n\n if (maxWidth > 0)\n {\n return Math.Min(maxWidth, calcWidth);\n }\n\n return calcWidth;\n }\n return 0;\n }\n\n public object[] ConvertBack(object value, Type[] targetTypes, object parameter, CultureInfo culture)\n {\n throw new NotImplementedException();\n }\n}\n\npublic class SubTextMaskConverter : IMultiValueConverter\n{\n public object Convert(object[] values, Type targetType, object parameter, CultureInfo culture)\n {\n if (values.Length != 6)\n return DependencyProperty.UnsetValue;\n\n if (values[0] is int index && // Index of sub to be processed\n values[1] is string displayText && // Sub text to be processed (may be translated)\n values[2] is string text && // Sub text to be processed\n values[3] is int selectedIndex && // Index of the selected ListItem\n values[4] is bool isEnabled && // whether to enable this feature\n values[5] is bool showOriginal) // whether to show original text\n {\n string show = showOriginal ? text : displayText;\n\n if (isEnabled && index > selectedIndex && !string.IsNullOrEmpty(show))\n {\n return new string('_', show.Length);\n }\n\n return show;\n }\n return DependencyProperty.UnsetValue;\n }\n\n public object[] ConvertBack(object value, Type[] targetTypes, object parameter, CultureInfo culture)\n {\n throw new NotSupportedException();\n }\n}\n\npublic class SubTextFlowDirectionConverter : IMultiValueConverter\n{\n public object Convert(object[] values, Type targetType, object parameter, CultureInfo culture)\n {\n if (values.Length != 3)\n {\n return DependencyProperty.UnsetValue;\n }\n\n if (values[0] is bool isTranslated &&\n values[1] is int subIndex &&\n values[2] is FlyleafManager fl)\n {\n var language = isTranslated ? fl.PlayerConfig.Subtitles.TranslateLanguage : fl.Player.SubtitlesManager[subIndex].Language;\n if (language != null && language.IsRTL)\n {\n return FlowDirection.RightToLeft;\n }\n\n return FlowDirection.LeftToRight;\n }\n\n return DependencyProperty.UnsetValue;\n }\n\n public object[] ConvertBack(object value, Type[] targetTypes, object parameter, CultureInfo culture)\n {\n throw new NotSupportedException();\n }\n}\n\npublic class SubIsPlayingConverter : IMultiValueConverter\n{\n public object Convert(object[] values, Type targetType, object parameter, CultureInfo culture)\n {\n if (values.Length != 3)\n {\n return DependencyProperty.UnsetValue;\n }\n\n if (values[0] is int index &&\n values[1] is int currentIndex &&\n values[2] is bool isDisplaying)\n {\n return isDisplaying && index == currentIndex;\n }\n\n return DependencyProperty.UnsetValue;\n }\n\n public object[] ConvertBack(object value, Type[] targetTypes, object parameter, CultureInfo culture)\n {\n throw new NotSupportedException();\n }\n}\n\npublic class ListItemIndexVisibilityConverter : IMultiValueConverter\n{\n public object Convert(object[] values, Type targetType, object parameter, CultureInfo culture)\n {\n if (values.Length != 3)\n {\n return DependencyProperty.UnsetValue;\n }\n\n if (values[0] is int itemIndex && // Index of sub to be processed\n values[1] is int selectedIndex && // Index of the selected ListItem\n values[2] is bool isEnabled) // whether to enable this feature\n {\n if (isEnabled && itemIndex > selectedIndex)\n {\n return Visibility.Collapsed;\n }\n\n return Visibility.Visible;\n }\n return DependencyProperty.UnsetValue;\n }\n\n public object[] ConvertBack(object value, Type[] targetTypes, object parameter, CultureInfo culture)\n {\n throw new NotSupportedException();\n }\n}\n\n[ValueConversion(typeof(TimeSpan), typeof(string))]\npublic class TimeSpanToStringConverter : IValueConverter\n{\n public object Convert(object value, Type targetType, object parameter, CultureInfo culture)\n {\n if (value is TimeSpan ts)\n {\n if (ts.TotalHours >= 1)\n {\n return ts.ToString(@\"hh\\:mm\\:ss\");\n }\n else\n {\n return ts.ToString(@\"mm\\:ss\");\n }\n }\n\n return DependencyProperty.UnsetValue;\n }\n\n public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)\n {\n throw new NotImplementedException();\n }\n}\n\n[ValueConversion(typeof(SubtitleData), typeof(WriteableBitmap))]\npublic class SubBitmapImageSourceConverter : IValueConverter\n{\n public object? Convert(object? value, Type targetType, object? parameter, CultureInfo culture)\n {\n if (value is not SubtitleData item)\n {\n return null;\n }\n\n if (!item.IsBitmap || item.Bitmap == null || !string.IsNullOrEmpty(item.Text))\n {\n return null;\n }\n\n WriteableBitmap wb = item.Bitmap.SubToWritableBitmap(false);\n\n return wb;\n }\n\n public object ConvertBack(object? value, Type targetType, object? parameter, CultureInfo culture)\n => throw new NotImplementedException();\n}\n\n[ValueConversion(typeof(int), typeof(string))]\npublic class SubIndexToDisplayStringConverter : IValueConverter\n{\n public object Convert(object value, Type targetType, object parameter, CultureInfo culture)\n {\n if (value is int subIndex)\n {\n return subIndex == 0 ? \"Primary\" : \"Secondary\";\n }\n return DependencyProperty.UnsetValue;\n }\n\n public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)\n {\n if (value is string str)\n {\n return str == \"Primary\" ? 0 : 1;\n }\n return DependencyProperty.UnsetValue;\n }\n}\n"], ["/LLPlayer/FlyleafLib/Engine/Globals.cs", "global using System;\nglobal using Flyleaf.FFmpeg;\nglobal using static Flyleaf.FFmpeg.Raw;\n\nusing System.Collections.Generic;\nusing System.ComponentModel;\nusing System.Globalization;\nusing System.Runtime.CompilerServices;\nusing System.Text.RegularExpressions;\n\nnamespace FlyleafLib;\n\npublic enum PixelFormatType\n{\n Hardware,\n Software_Handled,\n Software_Sws\n}\npublic enum MediaType\n{\n Audio,\n Video,\n Subs,\n Data\n}\npublic enum InputType\n{\n File = 0,\n UNC = 1,\n Torrent = 2,\n Web = 3,\n Unknown = 4\n}\npublic enum HDRtoSDRMethod : int\n{\n None = 0,\n Aces = 1,\n Hable = 2,\n Reinhard = 3\n}\npublic enum VideoProcessors\n{\n Auto,\n D3D11,\n Flyleaf,\n}\npublic enum ZeroCopy : int\n{\n Auto = 0,\n Enabled = 1,\n Disabled = 2\n}\npublic enum ColorSpace : int\n{\n None = 0,\n BT601 = 1,\n BT709 = 2,\n BT2020 = 3\n}\npublic enum ColorRange : int\n{\n None = 0,\n Full = 1,\n Limited = 2\n}\n\npublic enum SubOCREngineType\n{\n Tesseract,\n MicrosoftOCR\n}\n\npublic enum SubASREngineType\n{\n [Description(\"whisper.cpp\")]\n WhisperCpp,\n [Description(\"faster-whisper (Recommended)\")]\n FasterWhisper\n}\n\npublic class GPUOutput\n{\n public static int GPUOutputIdGenerator;\n\n public int Id { get; set; }\n public string DeviceName { get; internal set; }\n public int Left { get; internal set; }\n public int Top { get; internal set; }\n public int Right { get; internal set; }\n public int Bottom { get; internal set; }\n public int Width => Right- Left;\n public int Height => Bottom- Top;\n public bool IsAttached { get; internal set; }\n public int Rotation { get; internal set; }\n\n public override string ToString()\n {\n int gcd = Utils.GCD(Width, Height);\n return $\"{DeviceName,-20} [Id: {Id,-4}\\t, Top: {Top,-4}, Left: {Left,-4}, Width: {Width,-4}, Height: {Height,-4}, Ratio: [\" + (gcd > 0 ? $\"{Width/gcd}:{Height/gcd}]\" : \"]\");\n }\n}\n\npublic class GPUAdapter\n{\n public int MaxHeight { get; internal set; }\n public nuint SystemMemory { get; internal set; }\n public nuint VideoMemory { get; internal set; }\n public nuint SharedMemory { get; internal set; }\n\n\n public uint Id { get; internal set; }\n public string Vendor { get; internal set; }\n public string Description { get; internal set; }\n public long Luid { get; internal set; }\n public bool HasOutput { get; internal set; }\n public List\n Outputs { get; internal set; }\n\n public override string ToString()\n => (Vendor + \" \" + Description).PadRight(40) + $\"[ID: {Id,-6}, LUID: {Luid,-6}, DVM: {Utils.GetBytesReadable(VideoMemory),-8}, DSM: {Utils.GetBytesReadable(SystemMemory),-8}, SSM: {Utils.GetBytesReadable(SharedMemory)}]\";\n}\npublic enum VideoFilters\n{\n // Ensure we have the same values with Vortice.Direct3D11.VideoProcessorFilterCaps (d3d11.h) | we can extended if needed with other values\n\n Brightness = 0x01,\n Contrast = 0x02,\n Hue = 0x04,\n Saturation = 0x08,\n NoiseReduction = 0x10,\n EdgeEnhancement = 0x20,\n AnamorphicScaling = 0x40,\n StereoAdjustment = 0x80\n}\n\npublic struct AspectRatio : IEquatable\n{\n public static readonly AspectRatio Keep = new(-1, 1);\n public static readonly AspectRatio Fill = new(-2, 1);\n public static readonly AspectRatio Custom = new(-3, 1);\n public static readonly AspectRatio Invalid = new(-999, 1);\n\n public static readonly List AspectRatios = new()\n {\n Keep,\n Fill,\n Custom,\n new AspectRatio(1, 1),\n new AspectRatio(4, 3),\n new AspectRatio(16, 9),\n new AspectRatio(16, 10),\n new AspectRatio(2.35f, 1),\n };\n\n public static implicit operator AspectRatio(string value) => new AspectRatio(value);\n\n public float Num { get; set; }\n public float Den { get; set; }\n\n public float Value\n {\n get => Num / Den;\n set { Num = value; Den = 1; }\n }\n\n public string ValueStr\n {\n get => ToString();\n set => FromString(value);\n }\n\n public AspectRatio(float value) : this(value, 1) { }\n public AspectRatio(float num, float den) { Num = num; Den = den; }\n public AspectRatio(string value) { Num = Invalid.Num; Den = Invalid.Den; FromString(value); }\n\n public bool Equals(AspectRatio other) => Num == other.Num && Den == other.Den;\n public override bool Equals(object obj) => obj is AspectRatio o && Equals(o);\n public override int GetHashCode() => HashCode.Combine(Num, Den);\n public static bool operator ==(AspectRatio a, AspectRatio b) => a.Equals(b);\n public static bool operator !=(AspectRatio a, AspectRatio b) => !(a == b);\n\n public void FromString(string value)\n {\n if (value == \"Keep\")\n { Num = Keep.Num; Den = Keep.Den; return; }\n else if (value == \"Fill\")\n { Num = Fill.Num; Den = Fill.Den; return; }\n else if (value == \"Custom\")\n { Num = Custom.Num; Den = Custom.Den; return; }\n else if (value == \"Invalid\")\n { Num = Invalid.Num; Den = Invalid.Den; return; }\n\n string newvalue = value.ToString().Replace(',', '.');\n\n if (Regex.IsMatch(newvalue.ToString(), @\"^\\s*[0-9\\.]+\\s*[:/]\\s*[0-9\\.]+\\s*$\"))\n {\n string[] values = newvalue.ToString().Split(':');\n if (values.Length < 2)\n values = newvalue.ToString().Split('/');\n\n Num = float.Parse(values[0], NumberStyles.Any, CultureInfo.InvariantCulture);\n Den = float.Parse(values[1], NumberStyles.Any, CultureInfo.InvariantCulture);\n }\n\n else if (float.TryParse(newvalue.ToString(), NumberStyles.Any, CultureInfo.InvariantCulture, out float result))\n { Num = result; Den = 1; }\n\n else\n { Num = Invalid.Num; Den = Invalid.Den; }\n }\n public override string ToString() => this == Keep ? \"Keep\" : (this == Fill ? \"Fill\" : (this == Custom ? \"Custom\" : (this == Invalid ? \"Invalid\" : $\"{Num}:{Den}\")));\n}\n\nclass PlayerStats\n{\n public long TotalBytes { get; set; }\n public long VideoBytes { get; set; }\n public long AudioBytes { get; set; }\n public long FramesDisplayed { get; set; }\n}\npublic class NotifyPropertyChanged : INotifyPropertyChanged\n{\n public event PropertyChangedEventHandler PropertyChanged;\n\n //public bool DisableNotifications { get; set; }\n\n //private static bool IsUI() => System.Threading.Thread.CurrentThread.ManagedThreadId == System.Windows.Application.Current.Dispatcher.Thread.ManagedThreadId;\n\n protected bool Set(ref T field, T value, bool check = true, [CallerMemberName] string propertyName = \"\")\n {\n //Utils.Log($\"[===| {propertyName} |===] | Set | {IsUI()}\");\n\n if (!check || !EqualityComparer.Default.Equals(field, value))\n {\n field = value;\n\n //if (!DisableNotifications)\n PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));\n\n return true;\n }\n\n return false;\n }\n\n protected bool SetUI(ref T field, T value, bool check = true, [CallerMemberName] string propertyName = \"\")\n {\n //Utils.Log($\"[===| {propertyName} |===] | SetUI | {IsUI()}\");\n\n if (!check || !EqualityComparer.Default.Equals(field, value))\n {\n field = value;\n\n //if (!DisableNotifications)\n Utils.UI(() => PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName)));\n\n return true;\n }\n\n return false;\n }\n protected void Raise([CallerMemberName] string propertyName = \"\")\n {\n //Utils.Log($\"[===| {propertyName} |===] | Raise | {IsUI()}\");\n\n //if (!DisableNotifications)\n PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));\n }\n\n\n protected void RaiseUI([CallerMemberName] string propertyName = \"\")\n {\n //Utils.Log($\"[===| {propertyName} |===] | RaiseUI | {IsUI()}\");\n\n //if (!DisableNotifications)\n Utils.UI(() => PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName)));\n }\n}\n"], ["/LLPlayer/FlyleafLibTests/MediaPlayer/SubtitlesManagerTest.cs", "using FluentAssertions;\nusing FluentAssertions.Execution;\n\nnamespace FlyleafLib.MediaPlayer;\n\npublic class SubManagerTests\n{\n private readonly SubManager _subManager;\n\n public SubManagerTests()\n {\n SubManager subManager = new(new Config(true), 0, false);\n List subsData =\n [\n new() { StartTime = TimeSpan.FromSeconds(1), EndTime = TimeSpan.FromSeconds(5), Text = \"1. Hello World!\" },\n new() { StartTime = TimeSpan.FromSeconds(10), EndTime = TimeSpan.FromSeconds(15), Text = \"2. How are you\" },\n new() { StartTime = TimeSpan.FromSeconds(20), EndTime = TimeSpan.FromSeconds(25), Text = \"3. I'm fine\" },\n new() { StartTime = TimeSpan.FromSeconds(28), EndTime = TimeSpan.FromSeconds(29), Text = \"4. Thank you\" },\n new() { StartTime = TimeSpan.FromSeconds(30), EndTime = TimeSpan.FromSeconds(35), Text = \"5. Good bye\" }\n ];\n\n subManager.Load(subsData);\n\n _subManager = subManager;\n }\n\n #region Seek\n [Fact]\n public void SubManagerTest_First_Yet()\n {\n // before the first subtitle\n TimeSpan currentTime = TimeSpan.FromSeconds(0.5);\n _subManager.SetCurrentTime(currentTime);\n\n // 1. Hello World!\n var nextIndex = 0;\n\n var subsData = _subManager.Subs;\n\n using (new AssertionScope())\n {\n _subManager.State.Should().Be(SubManager.PositionState.First);\n _subManager.CurrentIndex.Should().Be(-1);\n\n _subManager.GetCurrent().Should().BeNull();\n _subManager.GetPrev().Should().BeNull();\n _subManager.GetNext().Should()\n .NotBeNull().And\n .Match(s => s.Text == subsData[nextIndex].Text);\n }\n }\n\n [Fact]\n public void SubManagerTest_First_Showing()\n {\n // During playback of the first subtitle\n TimeSpan currentTime = TimeSpan.FromSeconds(1);\n _subManager.SetCurrentTime(currentTime);\n\n // 1. Hello World!\n var curIndex = 0;\n\n var subsData = _subManager.Subs;\n\n using (new AssertionScope())\n {\n _subManager.State.Should().Be(SubManager.PositionState.Showing);\n _subManager.CurrentIndex.Should().Be(curIndex);\n\n _subManager.GetCurrent().Should()\n .NotBeNull().And\n .Match(s => s.Text == subsData[curIndex].Text);\n _subManager.GetPrev().Should().BeNull();\n _subManager.GetNext().Should()\n .NotBeNull().And\n .Match(s => s.Text == subsData[curIndex + 1].Text);\n }\n }\n\n [Fact]\n public void SubManagerTest_Middle_Showing()\n {\n // During playback of the middle subtitle\n TimeSpan currentTime = TimeSpan.FromSeconds(22);\n _subManager.SetCurrentTime(currentTime);\n\n // 3. I'm fine\n var curIndex = 2;\n\n var subsData = _subManager.Subs;\n\n using (new AssertionScope())\n {\n _subManager.State.Should().Be(SubManager.PositionState.Showing);\n _subManager.CurrentIndex.Should().Be(curIndex);\n\n _subManager.GetCurrent().Should()\n .NotBeNull().And\n .Match(s => s.Text == subsData[curIndex].Text);\n _subManager.GetPrev().Should()\n .NotBeNull().And\n .Match(s => s.Text == subsData[curIndex - 1].Text);\n _subManager.GetNext().Should()\n .NotBeNull().And\n .Match(s => s.Text == subsData[curIndex + 1].Text);\n }\n }\n\n [Fact]\n public void SubManagerTest_Middle_Yet()\n {\n // just before the middle subtitle\n TimeSpan currentTime = TimeSpan.FromSeconds(18);\n _subManager.SetCurrentTime(currentTime);\n\n // 3. I'm fine\n var nextIndex = 2;\n\n var subsData = _subManager.Subs;\n\n using (new AssertionScope())\n {\n _subManager.State.Should().Be(SubManager.PositionState.Around);\n _subManager.CurrentIndex.Should().Be(nextIndex - 1);\n\n // Seek falls back to PrevSeek so we can seek, this class returns null\n _subManager.GetCurrent().Should().BeNull();\n _subManager.GetPrev().Should()\n .NotBeNull().And\n .Match(s => s.Text == subsData[nextIndex - 1].Text);\n _subManager.GetNext().Should()\n .NotBeNull().And\n .Match(s => s.Text == subsData[nextIndex].Text);\n }\n }\n\n [Fact]\n public void SubManagerTest_Last_Showing()\n {\n // During playback of the last subtitle\n TimeSpan currentTime = TimeSpan.FromSeconds(35);\n _subManager.SetCurrentTime(currentTime);\n\n // 5. Good bye\n var curIndex = 4;\n\n var subsData = _subManager.Subs;\n\n using (new AssertionScope())\n {\n _subManager.State.Should().Be(SubManager.PositionState.Showing);\n _subManager.CurrentIndex.Should().Be(curIndex);\n\n _subManager.GetCurrent().Should()\n .NotBeNull().And\n .Match(s => s.Text == subsData[curIndex].Text);\n _subManager.GetPrev().Should()\n .NotBeNull().And\n .Match(s => s.Text == subsData[curIndex - 1].Text);\n _subManager.GetNext().Should().BeNull();\n }\n }\n\n [Fact]\n public void SubManagerTest_Last_Past()\n {\n // after the last subtitle\n TimeSpan currentTime = TimeSpan.FromSeconds(99);\n _subManager.SetCurrentTime(currentTime);\n\n // 5. Good bye\n var prevIndex = 4;\n\n var subsData = _subManager.Subs;\n\n using (new AssertionScope())\n {\n _subManager.State.Should().Be(SubManager.PositionState.Last);\n // OK?\n _subManager.CurrentIndex.Should().Be(prevIndex);\n\n // Seek falls back to PrevSeek so we can seek, this returns null\n _subManager.GetCurrent().Should().BeNull();\n _subManager.GetPrev().Should()\n .NotBeNull().And\n .Match(s => s.Text == subsData[prevIndex].Text);\n _subManager.GetNext().Should().BeNull();\n }\n }\n #endregion\n\n #region DeleteAfter\n [Fact]\n public void SubManagerTest_DeleteAfter_DeleteFromMiddle()\n {\n _subManager.DeleteAfter(TimeSpan.FromSeconds(20));\n\n using (new AssertionScope())\n {\n _subManager.Subs.Count.Should().Be(2);\n _subManager.Subs.Select(s => s.Text!.Substring(0, 1))\n .Should().BeEquivalentTo([\"1\", \"2\"]);\n }\n }\n\n [Fact]\n public void SubManagerTest_DeleteAfter_DeleteAll()\n {\n _subManager.DeleteAfter(TimeSpan.FromSeconds(3));\n\n _subManager.Subs.Count.Should().Be(0);\n }\n\n [Fact]\n public void SubManagerTest_DeleteAfter_DeleteLast()\n {\n _subManager.DeleteAfter(TimeSpan.FromSeconds(32));\n\n using (new AssertionScope())\n {\n _subManager.Subs.Count.Should().Be(4);\n _subManager.Subs.Select(s => s.Text!.Substring(0, 1))\n .Should().BeEquivalentTo([\"1\", \"2\", \"3\", \"4\"]);\n }\n }\n\n [Fact]\n public void SubManagerTest_DeleteAfter_NoDelete()\n {\n _subManager.DeleteAfter(TimeSpan.FromSeconds(36));\n\n _subManager.Subs.Count.Should().Be(5);\n }\n #endregion\n}\n"], ["/LLPlayer/FlyleafLib/MediaPlayer/Activity.cs", "using System.Diagnostics;\nusing System.Windows.Forms;\n\nnamespace FlyleafLib.MediaPlayer;\n\npublic class Activity : NotifyPropertyChanged\n{\n /* Player Activity Mode ( Idle / Active / FullActive )\n *\n * Required Engine's Thread (UIRefresh)\n *\n * TODO: Static?\n */\n\n public ActivityMode Mode\n {\n get => mode;\n set {\n\n if (value == mode)\n return;\n\n mode = value;\n\n if (value == ActivityMode.Idle)\n {\n swKeyboard.Reset();\n swMouse.Reset();\n }\n else if (value == ActivityMode.Active)\n swKeyboard.Restart();\n else\n swMouse.Restart();\n\n Utils.UI(() => SetMode());\n }\n }\n internal ActivityMode _Mode = ActivityMode.FullActive, mode = ActivityMode.FullActive;\n\n /// \n /// Should use Timeout to Enable/Disable it. Use this only for temporary disable.\n /// \n public bool IsEnabled { get => _IsEnabled;\n set {\n\n if (value && _Timeout <= 0)\n {\n if (_IsEnabled)\n {\n _IsEnabled = false;\n RaiseUI(nameof(IsEnabled));\n }\n else\n _IsEnabled = false;\n\n }\n else\n {\n if (_IsEnabled == value)\n return;\n\n if (value)\n {\n swKeyboard.Restart();\n swMouse.Restart();\n }\n\n _IsEnabled = value;\n RaiseUI(nameof(IsEnabled));\n }\n }\n }\n bool _IsEnabled;\n\n public int Timeout { get => _Timeout; set { _Timeout = value; IsEnabled = value > 0; } }\n int _Timeout;\n\n Player player;\n Stopwatch swKeyboard = new();\n Stopwatch swMouse = new();\n\n public Activity(Player player) => this.player = player;\n\n /// \n /// Updates Mode UI value and shows/hides mouse cursor if required\n /// Must be called from a UI Thread\n /// \n internal void SetMode()\n {\n _Mode = mode;\n Raise(nameof(Mode));\n player.Log.Trace(mode.ToString());\n\n if (player.Activity.Mode == ActivityMode.Idle && player.Host != null /*&& player.Host.Player_GetFullScreen() */&& player.Host.Player_CanHideCursor())\n {\n lock (cursorLocker)\n {\n while (Utils.NativeMethods.ShowCursor(false) >= 0) { }\n isCursorHidden = true;\n }\n\n }\n else if (isCursorHidden && player.Activity.Mode == ActivityMode.FullActive)\n {\n lock (cursorLocker)\n {\n while (Utils.NativeMethods.ShowCursor(true) < 0) { }\n isCursorHidden = false;\n }\n }\n }\n\n /// \n /// Refreshes mode value based on current timestamps\n /// \n internal void RefreshMode()\n {\n if (!IsEnabled)\n mode = ActivityMode.FullActive;\n else mode = swMouse.IsRunning && swMouse.ElapsedMilliseconds < Timeout\n ? ActivityMode.FullActive\n : swKeyboard.IsRunning && swKeyboard.ElapsedMilliseconds < Timeout ? ActivityMode.Active : ActivityMode.Idle;\n }\n\n /// \n /// Sets Mode to Idle\n /// \n public void ForceIdle()\n {\n if (Timeout > 0)\n Mode = ActivityMode.Idle;\n }\n /// \n /// Sets Mode to Active\n /// \n public void ForceActive() => Mode = ActivityMode.Active;\n /// \n /// Sets Mode to Full Active\n /// \n public void ForceFullActive() => Mode = ActivityMode.FullActive;\n\n /// \n /// Updates Active Timestamp\n /// \n public void RefreshActive() => swKeyboard.Restart();\n\n /// \n /// Updates Full Active Timestamp\n /// \n public void RefreshFullActive() => swMouse.Restart();\n\n #region Ensures we catch the mouse move even when the Cursor is hidden\n static bool isCursorHidden;\n static object cursorLocker = new();\n public class GlobalMouseHandler : IMessageFilter\n {\n public bool PreFilterMessage(ref Message m)\n {\n if (isCursorHidden && m.Msg == 0x0200)\n {\n try\n {\n lock (cursorLocker)\n {\n while (Utils.NativeMethods.ShowCursor(true) < 0) { }\n isCursorHidden = false;\n foreach(var player in Engine.Players)\n player.Activity.RefreshFullActive();\n }\n\n } catch { }\n }\n\n return false;\n }\n }\n static Activity()\n {\n GlobalMouseHandler gmh = new();\n Application.AddMessageFilter(gmh);\n }\n #endregion\n}\n\npublic enum ActivityMode\n{\n Idle,\n Active, // Keyboard only\n FullActive // Mouse\n}\n"], ["/LLPlayer/FlyleafLib/Engine/Engine.Plugins.cs", "using System;\nusing System.Collections.Generic;\nusing System.IO;\nusing System.Reflection;\n\nusing FlyleafLib.Plugins;\n\nnamespace FlyleafLib;\n\npublic class PluginsEngine\n{\n public Dictionary\n Types { get; private set; } = new Dictionary();\n\n public string Folder { get; private set; }\n\n private Type pluginBaseType = typeof(PluginBase);\n\n internal PluginsEngine()\n {\n Folder = string.IsNullOrEmpty(Engine.Config.PluginsPath) ? null : Utils.GetFolderPath(Engine.Config.PluginsPath);\n\n LoadAssemblies();\n }\n\n internal void LoadAssemblies()\n {\n // Load FlyleafLib's Embedded Plugins\n LoadPlugin(Assembly.GetExecutingAssembly());\n\n // Load External Plugins Folder\n if (Folder != null && Directory.Exists(Folder))\n {\n string[] dirs = Directory.GetDirectories(Folder);\n\n foreach(string dir in dirs)\n foreach(string file in Directory.GetFiles(dir, \"*.dll\"))\n LoadPlugin(Assembly.LoadFrom(Path.GetFullPath(file)));\n }\n else\n {\n Engine.Log.Info($\"[PluginHandler] No external plugins found\");\n }\n }\n\n /// \n /// Manually load plugins\n /// \n /// The assembly to search for plugins\n public void LoadPlugin(Assembly assembly)\n {\n try\n {\n var types = assembly.GetTypes();\n\n foreach (var type in types)\n {\n if (pluginBaseType.IsAssignableFrom(type) && type.IsClass && !type.IsAbstract)\n {\n // Force static constructors to execute (For early load, will be useful with c# 8.0 and static properties for interfaces eg. DefaultOptions)\n // System.Runtime.CompilerServices.RuntimeHelpers.RunClassConstructor(type.TypeHandle);\n\n if (!Types.ContainsKey(type.Name))\n {\n Types.Add(type.Name, new PluginType() { Name = type.Name, Type = type, Version = assembly.GetName().Version});\n Engine.Log.Info($\"Plugin loaded ({type.Name} - {assembly.GetName().Version})\");\n }\n else\n Engine.Log.Info($\"Plugin already exists ({type.Name} - {assembly.GetName().Version})\");\n }\n }\n }\n catch (Exception e) { Engine.Log.Error($\"[PluginHandler] [Error] Failed to load assembly ({e.Message} {Utils.GetRecInnerException(e)})\"); }\n }\n}\n"], ["/LLPlayer/LLPlayer/Controls/Settings/SettingsSubtitlesAction.xaml.cs", "using System.Collections.ObjectModel;\nusing System.Windows;\nusing System.Windows.Controls;\nusing System.Windows.Input;\nusing FlyleafLib.MediaPlayer.Translation.Services;\nusing LLPlayer.Extensions;\nusing LLPlayer.Services;\n\nnamespace LLPlayer.Controls.Settings;\n\npublic partial class SettingsSubtitlesAction : UserControl\n{\n public SettingsSubtitlesAction()\n {\n InitializeComponent();\n\n DataContext = ((App)Application.Current).Container.Resolve();\n }\n}\n\npublic class SettingsSubtitlesActionVM : Bindable\n{\n public FlyleafManager FL { get; }\n\n public SettingsSubtitlesActionVM(FlyleafManager fl)\n {\n FL = fl;\n\n SelectedTranslateWordServiceType = FL.PlayerConfig.Subtitles.TranslateWordServiceType;\n\n List wordClickActions = Enum.GetValues().ToList();\n if (string.IsNullOrEmpty(FL.Config.Subs.PDICPipeExecutablePath))\n {\n // PDIC is enabled only when exe is configured\n wordClickActions.Remove(WordClickAction.PDIC);\n }\n WordClickActions = wordClickActions;\n\n foreach (IMenuAction menuAction in FL.Config.Subs.WordMenuActions)\n {\n MenuActions.Add((IMenuAction)menuAction.Clone());\n }\n }\n\n public TranslateServiceType SelectedTranslateWordServiceType\n {\n get;\n set\n {\n if (Set(ref field, value))\n {\n FL.PlayerConfig.Subtitles.TranslateWordServiceType = value;\n }\n }\n }\n\n public List WordClickActions { get; }\n\n public List ModifierKeys { get; } =\n [\n System.Windows.Input.ModifierKeys.Control,\n System.Windows.Input.ModifierKeys.Shift,\n System.Windows.Input.ModifierKeys.Alt,\n System.Windows.Input.ModifierKeys.None\n ];\n\n public ObservableCollection MenuActions { get; } = new();\n\n public DelegateCommand? CmdApplyContextMenu => field ??= new(() =>\n {\n ObservableCollection newActions = new(MenuActions.Select(a => (IMenuAction)a.Clone()));\n\n // Apply to config\n FL.Config.Subs.WordMenuActions = newActions;\n });\n\n public DelegateCommand? CmdAddSearchAction => field ??= new(() =>\n {\n MenuActions.Add(new SearchMenuAction\n {\n Title = \"New Search\",\n Url = \"https://example.com/?q=%w\"\n });\n });\n\n public DelegateCommand? CmdAddClipboardAction => field ??= new(() =>\n {\n MenuActions.Add(new ClipboardMenuAction());\n });\n\n public DelegateCommand? CmdAddClipboardAllAction => field ??= new(() =>\n {\n MenuActions.Add(new ClipboardAllMenuAction());\n });\n\n public DelegateCommand? CmdRemoveAction => field ??= new((action) =>\n {\n if (action != null)\n {\n MenuActions.Remove(action);\n }\n });\n\n // TODO: L: SaveCommand?\n}\n\nclass DataGridRowOrderBehaviorMenuAction : DataGridRowOrderBehavior;\n\nclass MenuActionTemplateSelector : DataTemplateSelector\n{\n public required DataTemplate SearchTemplate { get; set; }\n public required DataTemplate ClipboardTemplate { get; set; }\n public required DataTemplate ClipboardAllTemplate { get; set; }\n\n public override DataTemplate? SelectTemplate(object? item, DependencyObject container)\n {\n return item switch\n {\n SearchMenuAction => SearchTemplate,\n ClipboardMenuAction => ClipboardTemplate,\n ClipboardAllMenuAction => ClipboardAllTemplate,\n _ => null\n };\n }\n}\n"], ["/LLPlayer/LLPlayer/ViewModels/ErrorDialogVM.cs", "using System.Collections;\nusing System.Diagnostics.CodeAnalysis;\nusing System.Media;\nusing System.Text;\nusing System.Windows;\nusing LLPlayer.Extensions;\nusing LLPlayer.Services;\n\nnamespace LLPlayer.ViewModels;\n\npublic class ErrorDialogVM : Bindable, IDialogAware\n{\n public FlyleafManager FL { get; }\n\n public ErrorDialogVM(FlyleafManager fl)\n {\n FL = fl;\n }\n\n public string Message { get; set => Set(ref field, value); } = \"\";\n\n public Exception? Exception\n {\n get;\n set\n {\n if (Set(ref field, value))\n {\n OnPropertyChanged(nameof(HasException));\n ExceptionDetail = value == null ? \"\" : GetExceptionWithAllData(value);\n }\n }\n }\n public bool HasException => Exception != null;\n\n public string ExceptionDetail { get; set => Set(ref field, value); } = \"\";\n\n public bool IsUnknown\n {\n get;\n set\n {\n if (Set(ref field, value))\n {\n OnPropertyChanged(nameof(ErrorTitle));\n }\n }\n }\n\n public string ErrorType\n {\n get;\n set\n {\n if (Set(ref field, value))\n {\n OnPropertyChanged(nameof(ErrorTitle));\n }\n }\n } = \"\";\n\n public string ErrorTitle => IsUnknown ? $\"{ErrorType} Unknown Error\" : $\"{ErrorType} Error\";\n\n [field: AllowNull, MaybeNull]\n public DelegateCommand CmdCopyMessage => field ??= new(() =>\n {\n string text = $\"\"\"\n [{ErrorTitle}]\n {Message}\n \"\"\";\n\n if (Exception != null)\n {\n text += $\"\"\"\n\n\n ```\n {ExceptionDetail}\n ```\n \"\"\";\n }\n\n text += $\"\"\"\n\n\n Version: {App.Version}, CommitHash: {App.CommitHash}\n OS Architecture: {App.OSArchitecture}, Process Architecture: {App.ProcessArchitecture}\n \"\"\";\n Clipboard.SetText(text);\n });\n\n [field: AllowNull, MaybeNull]\n public DelegateCommand CmdCloseDialog => field ??= new(() =>\n {\n RequestClose.Invoke(ButtonResult.OK);\n });\n\n private static string GetExceptionWithAllData(Exception ex)\n {\n string exceptionInfo = ex.ToString();\n\n // Collect all Exception.Data to dictionary\n Dictionary allData = new();\n CollectExceptionData(ex, allData);\n\n if (allData.Count == 0)\n {\n // not found Exception.Data\n return exceptionInfo;\n }\n\n // found Exception.Data\n StringBuilder sb = new();\n sb.Append(exceptionInfo);\n\n sb.AppendLine();\n sb.AppendLine();\n sb.AppendLine(\"---------------------- All Exception Data ----------------------\");\n foreach (var (i, entry) in allData.Index())\n {\n sb.AppendLine($\" [{entry.Key}]: {entry.Value}\");\n if (i != allData.Count - 1)\n {\n sb.AppendLine();\n }\n }\n\n return sb.ToString();\n }\n\n private static void CollectExceptionData(Exception? ex, Dictionary allData)\n {\n if (ex == null) return;\n\n foreach (DictionaryEntry entry in ex.Data)\n {\n if (entry.Value != null)\n {\n allData.TryAdd(entry.Key, entry.Value);\n }\n }\n\n if (ex.InnerException != null)\n {\n CollectExceptionData(ex.InnerException, allData);\n }\n\n if (ex is AggregateException aggregateEx)\n {\n foreach (var innerEx in aggregateEx.InnerExceptions)\n {\n CollectExceptionData(innerEx, allData);\n }\n }\n }\n\n #region IDialogAware\n public string Title => \"Error Occured\";\n public double WindowWidth { get; set => Set(ref field, value); } = 450;\n public double WindowHeight { get; set => Set(ref field, value); } = 250;\n\n public bool CanCloseDialog() => true;\n\n public void OnDialogClosed()\n {\n FL.Player.Activity.Timeout = _prevTimeout;\n FL.Player.Activity.IsEnabled = true;\n }\n\n private int _prevTimeout;\n\n public void OnDialogOpened(IDialogParameters parameters)\n {\n _prevTimeout = FL.Player.Activity.Timeout;\n FL.Player.Activity.Timeout = 0;\n FL.Player.Activity.IsEnabled = false;\n\n switch (parameters.GetValue(\"type\"))\n {\n case \"known\":\n Message = parameters.GetValue(\"message\");\n ErrorType = parameters.GetValue(\"errorType\");\n IsUnknown = false;\n\n break;\n case \"unknown\":\n Message = parameters.GetValue(\"message\");\n ErrorType = parameters.GetValue(\"errorType\");\n IsUnknown = true;\n\n if (parameters.ContainsKey(\"exception\"))\n {\n Exception = parameters.GetValue(\"exception\");\n }\n\n WindowHeight += 100;\n WindowWidth += 20;\n\n // Play alert sound\n SystemSounds.Hand.Play();\n\n break;\n }\n }\n\n public DialogCloseListener RequestClose { get; }\n #endregion IDialogAware\n}\n"], ["/LLPlayer/FlyleafLib/MediaFramework/RunThreadBase.cs", "using System.Threading;\n\nusing static FlyleafLib.Logger;\n\nnamespace FlyleafLib.MediaFramework;\n\npublic abstract class RunThreadBase : NotifyPropertyChanged\n{\n Status _Status = Status.Stopped;\n public Status Status {\n get => _Status;\n set\n {\n lock (lockStatus)\n {\n if (CanDebug && _Status != Status.QueueFull && value != Status.QueueFull && _Status != Status.QueueEmpty && value != Status.QueueEmpty)\n Log.Debug($\"{_Status} -> {value}\");\n\n _Status = value;\n }\n }\n }\n public bool IsRunning {\n get\n {\n bool ret = false;\n lock (lockStatus) ret = thread != null && thread.IsAlive && Status != Status.Paused;\n return ret;\n }\n }\n\n public bool CriticalArea { get; protected set; }\n public bool Disposed { get; protected set; } = true;\n public int UniqueId { get; protected set; } = -1;\n public bool PauseOnQueueFull{ get; set; }\n\n protected Thread thread;\n protected AutoResetEvent threadARE = new(false);\n protected string threadName {\n get => _threadName;\n set\n {\n _threadName = value;\n Log = new LogHandler((\"[#\" + UniqueId + \"]\").PadRight(8, ' ') + $\" [{threadName}] \");\n }\n }\n string _threadName;\n\n internal LogHandler Log;\n internal object lockActions = new();\n internal object lockStatus = new();\n\n public RunThreadBase(int uniqueId = -1)\n => UniqueId = uniqueId == -1 ? Utils.GetUniqueId() : uniqueId;\n\n public void Pause()\n {\n lock (lockActions)\n {\n lock (lockStatus)\n {\n PauseOnQueueFull = false;\n\n if (Disposed || thread == null || !thread.IsAlive || Status == Status.Stopping || Status == Status.Stopped || Status == Status.Ended || Status == Status.Pausing || Status == Status.Paused) return;\n Status = Status.Pausing;\n }\n while (Status == Status.Pausing) Thread.Sleep(5);\n }\n }\n public void Start()\n {\n lock (lockActions)\n {\n int retries = 1;\n while (thread != null && thread.IsAlive && CriticalArea)\n {\n Thread.Sleep(5); // use small steps to re-check CriticalArea (demuxer can have 0 packets again after processing the received ones)\n retries++;\n if (retries > 16)\n {\n if (CanTrace) Log.Trace($\"Start() exhausted\");\n return;\n }\n }\n\n lock (lockStatus)\n {\n if (Disposed) return;\n\n PauseOnQueueFull = false;\n\n if (Status == Status.Draining) while (Status != Status.Draining) Thread.Sleep(3);\n if (Status == Status.Stopping) while (Status != Status.Stopping) Thread.Sleep(3);\n if (Status == Status.Pausing) while (Status != Status.Pausing) Thread.Sleep(3);\n\n if (Status == Status.Ended) return;\n\n if (Status == Status.Paused)\n {\n threadARE.Set();\n while (Status == Status.Paused) Thread.Sleep(3);\n return;\n }\n\n if (thread != null && thread.IsAlive) return; // might re-check CriticalArea\n\n thread = new Thread(() => Run());\n Status = Status.Running;\n\n thread.Name = $\"[#{UniqueId}] [{threadName}]\"; thread.IsBackground= true; thread.Start();\n while (!thread.IsAlive) { if (CanTrace) Log.Trace(\"Waiting thread to come up\"); Thread.Sleep(3); }\n }\n }\n }\n public void Stop()\n {\n lock (lockActions)\n {\n lock (lockStatus)\n {\n PauseOnQueueFull = false;\n\n if (Disposed || thread == null || !thread.IsAlive || Status == Status.Stopping || Status == Status.Stopped || Status == Status.Ended) return;\n if (Status == Status.Pausing) while (Status != Status.Pausing) Thread.Sleep(3);\n Status = Status.Stopping;\n threadARE.Set();\n }\n\n while (Status == Status.Stopping && thread != null && thread.IsAlive) Thread.Sleep(5);\n }\n }\n\n protected void Run()\n {\n if (CanDebug) Log.Debug($\"Thread started ({Status})\");\n\n do\n {\n RunInternal();\n\n if (Status == Status.Pausing)\n {\n threadARE.Reset();\n Status = Status.Paused;\n threadARE.WaitOne();\n if (Status == Status.Paused)\n {\n if (CanDebug) Log.Debug($\"{_Status} -> {Status.Running}\");\n _Status = Status.Running;\n }\n }\n\n } while (Status == Status.Running);\n\n if (Status != Status.Ended) Status = Status.Stopped;\n\n if (CanDebug) Log.Debug($\"Thread stopped ({Status})\");\n }\n protected abstract void RunInternal();\n}\n\npublic enum Status\n{\n Opening,\n\n Stopping,\n Stopped,\n\n Pausing,\n Paused,\n\n Running,\n QueueFull,\n QueueEmpty,\n Draining,\n\n Ended\n}\n"], ["/LLPlayer/FlyleafLib/Engine/WhisperConfig.cs", "using System.Collections.Generic;\nusing System.Diagnostics;\nusing System.IO;\nusing System.Text.Json.Serialization;\nusing Whisper.net;\nusing Whisper.net.LibraryLoader;\n\nnamespace FlyleafLib;\n\n#nullable enable\n\n// Whisper Common Config (whisper.cpp, faster-whisper)\npublic class WhisperConfig : NotifyPropertyChanged\n{\n public static string ModelsDirectory { get; } = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, \"whispermodels\");\n public static string EnginesDirectory { get; } = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, \"Whisper\");\n\n // For UI\n public string LanguageName\n {\n get\n {\n string translate = Translate ? \", Trans\" : \"\";\n\n if (LanguageDetection)\n {\n return \"Auto\" + translate;\n }\n\n var lang = FlyleafLib.Language.Get(Language);\n\n if (lang != null)\n {\n return lang.TopEnglishName + translate;\n }\n\n return Language + translate;\n }\n }\n\n public string Language\n {\n get;\n set\n {\n if (Set(ref field, value))\n {\n Raise(LanguageName);\n }\n }\n } = \"en\";\n\n public bool LanguageDetection\n {\n get;\n set\n {\n if (Set(ref field, value))\n {\n Raise(LanguageName);\n }\n }\n } = true;\n\n public bool Translate\n {\n get;\n set\n {\n if (Set(ref field, value))\n {\n Raise(LanguageName);\n }\n }\n }\n\n public static void EnsureModelsDirectory()\n {\n if (!Directory.Exists(ModelsDirectory))\n {\n Directory.CreateDirectory(ModelsDirectory);\n }\n }\n\n public static void EnsureEnginesDirectory()\n {\n if (!Directory.Exists(EnginesDirectory))\n {\n Directory.CreateDirectory(EnginesDirectory);\n }\n }\n}\n\n// TODO: L: Add other options\npublic class WhisperCppConfig : NotifyPropertyChanged\n{\n public WhisperCppModel? Model\n {\n get;\n set\n {\n if (Set(ref field, value))\n {\n Raise(nameof(IsEnglishModel));\n }\n }\n }\n\n [JsonIgnore]\n public bool IsEnglishModel => Model != null && Model.Model.ToString().EndsWith(\"En\");\n\n public List RuntimeLibraries { get; set => Set(ref field, value); } = [RuntimeLibrary.Cpu, RuntimeLibrary.CpuNoAvx];\n public RuntimeLibrary? LoadedLibrary => RuntimeOptions.LoadedLibrary;\n\n public int? GpuDevice { get; set => Set(ref field, value); }\n\n public int? Threads { get; set => Set(ref field, value); }\n public int? MaxSegmentLength { get; set => Set(ref field, value); }\n public int? MaxTokensPerSegment { get; set => Set(ref field, value); }\n public bool SplitOnWord { get; set => Set(ref field, value); }\n public float? NoSpeechThreshold { get; set => Set(ref field, value); }\n public bool NoContext { get; set => Set(ref field, value); }\n public int? AudioContextSize { get; set => Set(ref field, value); }\n public string Prompt { get; set => Set(ref field, value); } = string.Empty;\n\n public WhisperFactoryOptions GetFactoryOptions()\n {\n WhisperFactoryOptions opts = WhisperFactoryOptions.Default;\n\n if (GpuDevice.HasValue)\n opts.GpuDevice = GpuDevice.Value;\n\n return opts;\n }\n\n public WhisperProcessorBuilder ConfigureBuilder(WhisperConfig whisperConfig, WhisperProcessorBuilder builder)\n {\n if (IsEnglishModel)\n {\n // set English forcefully if English-only models\n builder.WithLanguage(\"en\");\n }\n else\n {\n if (!string.IsNullOrEmpty(whisperConfig.Language))\n builder.WithLanguage(whisperConfig.Language);\n\n // prefer auto\n if (whisperConfig.LanguageDetection)\n builder.WithLanguageDetection();\n\n if (whisperConfig.Translate)\n builder.WithTranslate();\n }\n\n if (Threads is > 0)\n builder.WithThreads(Threads.Value);\n\n if (MaxSegmentLength is > 0)\n builder.WithMaxSegmentLength(MaxSegmentLength.Value);\n\n if (MaxTokensPerSegment is > 0)\n builder.WithMaxTokensPerSegment(MaxTokensPerSegment.Value);\n\n if (SplitOnWord)\n builder.SplitOnWord();\n\n if (NoSpeechThreshold is > 0)\n builder.WithNoSpeechThreshold(NoSpeechThreshold.Value);\n\n if (NoContext)\n builder.WithNoContext();\n\n if (AudioContextSize is > 0)\n builder.WithAudioContextSize(AudioContextSize.Value);\n\n if (!string.IsNullOrWhiteSpace(Prompt))\n builder.WithPrompt(Prompt);\n\n // auto set\n if (MaxSegmentLength is > 0 || MaxSegmentLength is > 0)\n builder.WithTokenTimestamps();\n\n return builder;\n }\n}\n\npublic class FasterWhisperConfig : NotifyPropertyChanged\n{\n public static string DefaultEnginePath { get; } = Path.Combine(WhisperConfig.EnginesDirectory, \"Faster-Whisper-XXL\", \"faster-whisper-xxl.exe\");\n\n // can get by faster-whisper-xxl.exe --model foo bar.wav\n public static List ModelOptions { get; } = [\n \"tiny\",\n \"tiny.en\",\n \"base\",\n \"base.en\",\n \"small\",\n \"small.en\",\n \"medium\",\n \"medium.en\",\n \"large-v1\",\n \"large-v2\",\n \"large-v3\",\n //\"large\", // = large-v3\n \"large-v3-turbo\",\n //\"turbo\", // = large-v3-turbo\n \"distil-large-v2\",\n \"distil-medium.en\",\n \"distil-small.en\",\n \"distil-large-v3\",\n \"distil-large-v3.5\"\n ];\n\n public bool UseManualEngine { get; set => Set(ref field, value); }\n public string? ManualEnginePath { get; set => Set(ref field, value); }\n public bool UseManualModel { get; set => Set(ref field, value); }\n public string? ManualModelDir { get; set => Set(ref field, value); }\n public string Model\n {\n get;\n set\n {\n if (Set(ref field, value))\n {\n Raise(nameof(IsEnglishModel));\n }\n }\n } = \"tiny\";\n [JsonIgnore]\n public bool IsEnglishModel => Model.EndsWith(\".en\") ||\n Model is \"distil-large-v2\"\n or \"distil-large-v3\"\n or \"distil-large-v3.5\";\n public string ExtraArguments { get; set => Set(ref field, value); } = string.Empty;\n\n public ProcessPriorityClass ProcessPriority { get; set => Set(ref field, value); } = ProcessPriorityClass.Normal;\n}\n"], ["/LLPlayer/FlyleafLib/Utils/SubtitleTextUtil.cs", "using System.Text;\n\nnamespace FlyleafLib;\n\npublic static class SubtitleTextUtil\n{\n /// \n /// Flattens the text into a single line.\n /// - If every line (excluding empty lines) starts with dash, returns the original string.\n /// - For all other text, replaces newlines with spaces and flattens into a single line.\n /// \n public static string FlattenText(string text)\n {\n ArgumentNullException.ThrowIfNull(text);\n\n ReadOnlySpan span = text.AsSpan();\n\n // If there are no newlines, return the text as-is\n if (!span.ContainsAny('\\r', '\\n'))\n {\n return text;\n }\n\n int length = span.Length;\n\n // Determine if the first character is dash to enter list mode\n bool startDash = span.Length > 0 && IsDash(span[0]);\n\n if (startDash)\n {\n char dashChar = span[0];\n\n // Check if all lines start with dash (ignore empty lines)\n bool allDash = true;\n bool atLineStart = true;\n int i;\n for (i = 0; i < length; i++)\n {\n if (atLineStart)\n {\n // Skip empty lines\n if (span[i] == '\\r' || span[i] == '\\n')\n {\n continue;\n }\n if (span[i] != dashChar)\n {\n allDash = false;\n // Done checking\n break;\n }\n atLineStart = false;\n }\n else\n {\n if (span[i] == '\\r')\n {\n if (i + 1 < length && span[i + 1] == '\\n') i++;\n atLineStart = true;\n }\n else if (span[i] == '\\n')\n {\n atLineStart = true;\n }\n }\n }\n\n // If every line starts with dash, return original text\n if (allDash)\n {\n return text;\n }\n\n // list mode\n StringBuilder sb = new(length);\n bool firstItem = true;\n i = 0;\n\n while (i < length)\n {\n int start;\n\n // Start of a dash line\n if (span[i] == dashChar)\n {\n if (!firstItem)\n {\n sb.Append('\\n');\n }\n // Append until end of line\n start = i;\n while (i < length && span[i] != '\\r' && span[i] != '\\n') i++;\n sb.Append(span.Slice(start, i - start));\n firstItem = false;\n continue;\n }\n\n // Skip empty lines\n if (span[i] == '\\r' || span[i] == '\\n')\n {\n i++;\n continue;\n }\n\n // Continuation line\n start = i;\n while (i < length && span[i] != '\\r' && span[i] != '\\n') i++;\n sb.Append(' ');\n sb.Append(span.Slice(start, i - start));\n }\n return sb.ToString();\n }\n\n // Default mode: replace all newlines with spaces in one pass\n char[] buffer = new char[length];\n int pos = 0;\n bool lastWasNewline = false;\n for (int i = 0; i < length; i++)\n {\n char c = span[i];\n if (c == '\\r' || c == '\\n')\n {\n if (!lastWasNewline)\n {\n buffer[pos++] = ' ';\n lastWasNewline = true;\n }\n }\n else\n {\n buffer[pos++] = c;\n lastWasNewline = false;\n }\n }\n return new string(buffer, 0, pos);\n }\n\n private static bool IsDash(char c)\n {\n switch (c)\n {\n case '-':\n case '\\u2043': // ⁃ Hyphen bullet\n case '\\u2010': // ‐ Hyphen\n case '\\u2012': // ‒ Figure dash\n case '\\u2013': // – En dash\n case '\\u2014': // — Em dash\n case '\\u2015': // ― Horizontal bar\n case '\\u2212': // − Minus Sign\n return true;\n }\n\n return false;\n }\n}\n"], ["/LLPlayer/LLPlayer/Extensions/FileHelper.cs", "using System.IO;\nusing static FlyleafLib.Utils;\n\nnamespace LLPlayer.Extensions;\n\npublic static class FileHelper\n{\n /// \n /// Retrieves the next and previous file from the specified file path.\n /// Select files with the same extension in the same folder, sorted in natural alphabetical order.\n /// Returns null if the next or previous file does not exist.\n /// \n /// \n /// \n /// \n /// \n /// \n public static (string? prev, string? next) GetNextAndPreviousFile(string filePath)\n {\n if (!File.Exists(filePath))\n {\n throw new FileNotFoundException(\"file does not exist\", filePath);\n }\n\n string? directory = Path.GetDirectoryName(filePath);\n string? extension = Path.GetExtension(filePath);\n\n if (string.IsNullOrEmpty(directory) || string.IsNullOrEmpty(extension))\n {\n throw new InvalidOperationException($\"filePath is invalid: {filePath}\");\n }\n\n // Get files with the same extension, ignoring case\n List foundFiles = Directory.GetFiles(directory, $\"*{extension}\")\n .Where(f => string.Equals(Path.GetExtension(f), extension, StringComparison.OrdinalIgnoreCase))\n .OrderBy(f => Path.GetFileName(f), new NaturalStringComparer())\n .ToList();\n\n if (foundFiles.Count == 0)\n {\n throw new InvalidOperationException($\"same extension file does not exist: {filePath}\");\n }\n\n int currentIndex = foundFiles.FindIndex(f => string.Equals(f, filePath, StringComparison.OrdinalIgnoreCase));\n if (currentIndex == -1)\n {\n throw new InvalidOperationException($\"current file does not exist: {filePath}\");\n }\n\n string? next = (currentIndex < foundFiles.Count - 1) ? foundFiles[currentIndex + 1] : null;\n string? prev = (currentIndex > 0) ? foundFiles[currentIndex - 1] : null;\n\n return (prev, next);\n }\n}\n"], ["/LLPlayer/LLPlayer/ViewModels/WhisperEngineDownloadDialogVM.cs", "using System.Diagnostics;\nusing System.IO;\nusing System.Net.Http;\nusing FlyleafLib;\nusing LLPlayer.Extensions;\nusing LLPlayer.Services;\nusing SevenZip;\nusing File = System.IO.File;\n\nnamespace LLPlayer.ViewModels;\n\npublic class WhisperEngineDownloadDialogVM : Bindable, IDialogAware\n{\n // currently not reusable at all\n public static string EngineURL => \"https://github.com/Purfview/whisper-standalone-win/releases/tag/Faster-Whisper-XXL\";\n public static string EngineFile => \"Faster-Whisper-XXL_r245.4_windows.7z\";\n private static string EngineDownloadURL =\n \"https://github.com/umlx5h/LLPlayer/releases/download/v0.0.1/Faster-Whisper-XXL_r245.4_windows.7z\";\n private static string EngineName = \"Faster-Whisper-XXL\";\n private static string EnginePath = Path.Combine(WhisperConfig.EnginesDirectory, EngineName);\n\n public FlyleafManager FL { get; }\n\n public WhisperEngineDownloadDialogVM(FlyleafManager fl)\n {\n FL = fl;\n\n CmdDownloadEngine!.PropertyChanged += (sender, args) =>\n {\n if (args.PropertyName == nameof(CmdDownloadEngine.IsExecuting))\n {\n OnPropertyChanged(nameof(CanDownload));\n OnPropertyChanged(nameof(CanDelete));\n }\n };\n }\n\n public string StatusText { get; set => Set(ref field, value); } = \"\";\n\n public long DownloadedSize { get; set => Set(ref field, value); }\n\n public bool Downloaded => Directory.Exists(EnginePath);\n\n public bool CanDownload => !Downloaded && !CmdDownloadEngine!.IsExecuting;\n\n public bool CanDelete => Downloaded && !CmdDownloadEngine!.IsExecuting;\n\n private CancellationTokenSource? _cts;\n\n public AsyncDelegateCommand? CmdDownloadEngine => field ??= new AsyncDelegateCommand(async () =>\n {\n _cts = new CancellationTokenSource();\n CancellationToken token = _cts.Token;\n\n string tempPath = Path.GetTempPath();\n string tempDownloadFile = Path.Combine(tempPath, EngineFile);\n\n try\n {\n StatusText = $\"Engine '{EngineName}' downloading..\";\n\n await DownloadEngineWithProgressAsync(EngineDownloadURL, tempDownloadFile, token);\n\n StatusText = $\"Engine '{EngineName}' unzipping..\";\n await UnzipEngine(tempDownloadFile);\n\n StatusText = $\"Engine '{EngineName}' is downloaded successfully\";\n OnDownloadStatusChanged();\n }\n catch (OperationCanceledException)\n {\n StatusText = \"Download canceled\";\n }\n catch (Exception ex)\n {\n StatusText = $\"Failed to download: {ex.Message}\";\n }\n finally\n {\n _cts = null;\n DeleteTempEngine();\n }\n\n return;\n\n bool DeleteTempEngine()\n {\n // Delete temporary files if they exist\n if (File.Exists(tempDownloadFile))\n {\n try\n {\n File.Delete(tempDownloadFile);\n }\n catch (Exception)\n {\n // ignore\n\n return false;\n }\n }\n\n return true;\n }\n }).ObservesCanExecute(() => CanDownload);\n\n public DelegateCommand? CmdCancelDownloadEngine => field ??= new(() =>\n {\n _cts?.Cancel();\n });\n\n public AsyncDelegateCommand? CmdDeleteEngine => field ??= new AsyncDelegateCommand(async () =>\n {\n try\n {\n StatusText = $\"Engine '{EngineName}' deleting...\";\n\n // Delete engine if exists\n if (Directory.Exists(EnginePath))\n {\n await Task.Run(() =>\n {\n Directory.Delete(EnginePath, true);\n });\n }\n\n OnDownloadStatusChanged();\n\n StatusText = $\"Engine '{EngineName}' is deleted successfully\";\n }\n catch (Exception ex)\n {\n StatusText = $\"Failed to delete engine: {ex.Message}\";\n }\n }).ObservesCanExecute(() => CanDelete);\n\n public DelegateCommand? CmdOpenFolder => field ??= new(() =>\n {\n if (!Directory.Exists(WhisperConfig.EnginesDirectory))\n return;\n\n Process.Start(new ProcessStartInfo\n {\n FileName = WhisperConfig.EnginesDirectory,\n UseShellExecute = true,\n CreateNoWindow = true\n });\n });\n\n private void OnDownloadStatusChanged()\n {\n OnPropertyChanged(nameof(CanDownload));\n OnPropertyChanged(nameof(CanDelete));\n }\n\n private async Task UnzipEngine(string zipPath)\n {\n WhisperConfig.EnsureEnginesDirectory();\n\n SevenZipBase.SetLibraryPath(\"lib/7z.dll\");\n\n using (SevenZipExtractor extractor = new(zipPath))\n {\n await extractor.ExtractArchiveAsync(WhisperConfig.EnginesDirectory);\n }\n\n string licencePath = Path.Combine(WhisperConfig.EnginesDirectory, \"license.txt\");\n\n if (File.Exists(licencePath) && Directory.Exists(WhisperConfig.EnginesDirectory))\n {\n // move license.txt to engine directory\n File.Move(licencePath, Path.Combine(EnginePath, \"license.txt\"));\n }\n }\n\n private async Task DownloadEngineWithProgressAsync(string url, string destinationPath, CancellationToken token)\n {\n DownloadedSize = 0;\n\n using HttpClient httpClient = new();\n httpClient.Timeout = TimeSpan.FromSeconds(10);\n\n using var response = await httpClient.GetAsync(url, HttpCompletionOption.ResponseHeadersRead, token);\n\n response.EnsureSuccessStatusCode();\n\n await using Stream engineStream = await response.Content.ReadAsStreamAsync(token);\n await using FileStream fileWriter = File.Open(destinationPath, FileMode.Create);\n\n byte[] buffer = new byte[1024 * 128];\n int bytesRead;\n long totalBytesRead = 0;\n\n Stopwatch sw = new();\n sw.Start();\n\n while ((bytesRead = await engineStream.ReadAsync(buffer, 0, buffer.Length, token)) > 0)\n {\n await fileWriter.WriteAsync(buffer, 0, bytesRead, token);\n totalBytesRead += bytesRead;\n\n if (sw.Elapsed > TimeSpan.FromMilliseconds(50))\n {\n DownloadedSize = totalBytesRead;\n sw.Restart();\n }\n\n token.ThrowIfCancellationRequested();\n }\n\n return totalBytesRead;\n }\n\n #region IDialogAware\n public string Title { get; set => Set(ref field, value); } = $\"Whisper Engine Downloader - {App.Name}\";\n public double WindowWidth { get; set => Set(ref field, value); } = 400;\n public double WindowHeight { get; set => Set(ref field, value); } = 210;\n\n public bool CanCloseDialog() => !CmdDownloadEngine!.IsExecuting;\n public void OnDialogClosed() { }\n public void OnDialogOpened(IDialogParameters parameters) { }\n public DialogCloseListener RequestClose { get; }\n #endregion IDialogAware\n}\n"], ["/LLPlayer/FlyleafLib/MediaFramework/MediaDevice/VideoDevice.cs", "using System;\nusing System.Linq;\n\nusing Vortice.MediaFoundation;\n\nnamespace FlyleafLib.MediaFramework.MediaDevice;\n\npublic class VideoDevice : DeviceBase\n{\n public VideoDevice(string friendlyName, string symbolicLink) : base(friendlyName, symbolicLink)\n {\n Streams = VideoDeviceStream.GetVideoFormatsForVideoDevice(friendlyName, symbolicLink);\n Url = Streams.Where(f => f.SubType.Contains(\"MJPG\") && f.FrameRate >= 30).OrderByDescending(f => f.FrameSizeHeight).FirstOrDefault()?.Url;\n }\n\n public static void RefreshDevices()\n {\n Utils.UIInvokeIfRequired(() =>\n {\n Engine.Video.CapDevices.Clear();\n\n var devices = MediaFactory.MFEnumVideoDeviceSources();\n foreach (var device in devices)\n try { Engine.Video.CapDevices.Add(new VideoDevice(device.FriendlyName, device.SymbolicLink)); } catch(Exception) { }\n });\n }\n}\n"], ["/LLPlayer/FlyleafLib/MediaFramework/MediaDemuxer/Interrupter.cs", "using System.Diagnostics;\n\nusing static FlyleafLib.Logger;\n\nnamespace FlyleafLib.MediaFramework.MediaDemuxer;\n\npublic unsafe class Interrupter\n{\n public int ForceInterrupt { get; set; }\n public Requester Requester { get; private set; }\n public int Interrupted { get; private set; }\n public bool Timedout { get; private set; }\n\n Demuxer demuxer;\n Stopwatch sw = new();\n internal AVIOInterruptCB_callback interruptClbk;\n long curTimeoutMs;\n\n internal int ShouldInterrupt(void* opaque)\n {\n if (demuxer.Status == Status.Stopping)\n {\n if (CanDebug) demuxer.Log.Debug($\"{Requester} Interrupt (Stopping) !!!\");\n\n return Interrupted = 1;\n }\n\n if (demuxer.Config.AllowTimeouts && sw.ElapsedMilliseconds > curTimeoutMs)\n {\n if (Timedout)\n return Interrupted = 1;\n\n if (CanWarn) demuxer.Log.Warn($\"{Requester} Timeout !!!! {sw.ElapsedMilliseconds} ms\");\n\n Timedout = true;\n Interrupted = 1;\n demuxer.OnTimedOut();\n\n return Interrupted;\n }\n\n if (Requester == Requester.Close)\n return 0;\n\n if (ForceInterrupt != 0 && demuxer.allowReadInterrupts)\n {\n if (CanTrace) demuxer.Log.Trace($\"{Requester} Interrupt !!!\");\n\n return Interrupted = 1;\n }\n\n return Interrupted = 0;\n }\n\n public Interrupter(Demuxer demuxer)\n {\n this.demuxer = demuxer;\n interruptClbk = ShouldInterrupt;\n }\n\n public void ReadRequest()\n {\n Requester = Requester.Read;\n\n if (!demuxer.Config.AllowTimeouts)\n return;\n\n Timedout = false;\n curTimeoutMs= demuxer.IsLive ? demuxer.Config.readLiveTimeoutMs: demuxer.Config.readTimeoutMs;\n sw.Restart();\n }\n\n public void SeekRequest()\n {\n Requester = Requester.Seek;\n\n if (!demuxer.Config.AllowTimeouts)\n return;\n\n Timedout = false;\n curTimeoutMs= demuxer.Config.seekTimeoutMs;\n sw.Restart();\n }\n\n public void OpenRequest()\n {\n Requester = Requester.Open;\n\n if (!demuxer.Config.AllowTimeouts)\n return;\n\n Timedout = false;\n curTimeoutMs= demuxer.Config.openTimeoutMs;\n sw.Restart();\n }\n\n public void CloseRequest()\n {\n Requester = Requester.Close;\n\n if (!demuxer.Config.AllowTimeouts)\n return;\n\n Timedout = false;\n curTimeoutMs= demuxer.Config.closeTimeoutMs;\n sw.Restart();\n }\n}\n\npublic enum Requester\n{\n Close,\n Open,\n Read,\n Seek\n}\n"], ["/LLPlayer/LLPlayer/Extensions/DataGridRowOrderBehavior.cs", "using System.Collections;\nusing System.Collections.ObjectModel;\nusing System.Windows;\nusing System.Windows.Controls;\nusing System.Windows.Input;\nusing Microsoft.Xaml.Behaviors;\n\nnamespace LLPlayer.Extensions;\n\n/// \n/// Behavior to add the ability to swap rows in a DataGrid by drag and drop\n/// \npublic class DataGridRowOrderBehavior : Behavior\n where T : class\n{\n public static readonly DependencyProperty ItemsSourceProperty =\n DependencyProperty.Register(nameof(ItemsSource), typeof(IList), typeof (DataGridRowOrderBehavior), new PropertyMetadata(null));\n\n /// \n /// ObservableCollection to be reordered bound to DataGrid\n /// \n public ObservableCollection ItemsSource\n {\n get => (ObservableCollection)GetValue(ItemsSourceProperty);\n set => SetValue(ItemsSourceProperty, value);\n }\n\n public static readonly DependencyProperty DragTargetNameProperty =\n DependencyProperty.Register(nameof(DragTargetName), typeof(string), typeof (DataGridRowOrderBehavior), new PropertyMetadata(null));\n\n /// \n /// Control name of the element to be dragged\n /// \n public string DragTargetName\n {\n get => (string)GetValue(DragTargetNameProperty);\n set => SetValue(DragTargetNameProperty, value);\n }\n\n private T? _draggedItem; // Item in row to be dragged\n\n protected override void OnAttached()\n {\n base.OnAttached();\n\n if (AssociatedObject == null)\n {\n return;\n }\n\n AssociatedObject.AllowDrop = true;\n\n AssociatedObject.PreviewMouseLeftButtonDown += OnPreviewMouseLeftButtonDown;\n AssociatedObject.DragOver += OnDragOver;\n AssociatedObject.Drop += OnDrop;\n }\n\n protected override void OnDetaching()\n {\n base.OnDetaching();\n\n if (AssociatedObject == null)\n {\n return;\n }\n\n AssociatedObject.AllowDrop = false;\n\n AssociatedObject.PreviewMouseLeftButtonDown -= OnPreviewMouseLeftButtonDown;\n AssociatedObject.DragOver -= OnDragOver;\n AssociatedObject.Drop -= OnDrop;\n }\n\n private void OnPreviewMouseLeftButtonDown(object sender, MouseButtonEventArgs e)\n {\n if (ItemsSource == null)\n {\n return;\n }\n\n // 1: Determines if it is on a \"drag handle\".\n if (!IsDragHandle(e.OriginalSource))\n {\n return;\n }\n\n // 2: Identify Row\n DataGridRow? row = UIHelper.FindParent((DependencyObject)e.OriginalSource);\n if (row == null)\n {\n return;\n }\n\n // Select the row\n AssociatedObject.UnselectAll();\n row.IsSelected = true;\n row.Focus();\n\n _draggedItem = row.Item as T;\n\n if (_draggedItem != null)\n {\n // Start dragging\n DragDrop.DoDragDrop(AssociatedObject, _draggedItem, DragDropEffects.Move);\n }\n }\n\n /// \n /// Dragging (while the mouse is moving)\n /// \n private void OnDragOver(object sender, DragEventArgs e)\n {\n if (_draggedItem == null)\n {\n return;\n }\n\n e.Handled = true;\n\n // Find the line where the mouse is now.\n DataGridRow? row = UIHelper.FindParent((DependencyObject)e.OriginalSource);\n if (row == null)\n {\n return;\n }\n\n var targetItem = row.Item;\n if (targetItem == null || targetItem == _draggedItem)\n {\n // If it's the same line, nothing.\n return;\n }\n\n T? targetRow = targetItem as T;\n if (targetRow == null)\n {\n return;\n }\n\n // Get the index of each row to be replaced\n int oldIndex = ItemsSource.IndexOf(_draggedItem);\n int newIndex = ItemsSource.IndexOf(targetRow);\n\n if (oldIndex < 0 || newIndex < 0 || oldIndex == newIndex)\n {\n return;\n }\n\n // Swap lines\n ItemsSource.Move(oldIndex, newIndex);\n }\n\n /// \n /// When dropped\n /// \n private void OnDrop(object sender, DragEventArgs e)\n {\n // Clear state as it is being reordered during drag.\n _draggedItem = null;\n }\n\n /// \n /// Judges whether an element is ready to start dragging.\n /// \n private bool IsDragHandle(object originalSource)\n {\n return UIHelper.FindParentWithName(originalSource as DependencyObject, DragTargetName);\n }\n}\n"], ["/LLPlayer/LLPlayer/Extensions/ScrollParentWhenAtMax.cs", "using System.Windows;\nusing System.Windows.Controls;\nusing System.Windows.Input;\nusing System.Windows.Media;\nusing Microsoft.Xaml.Behaviors;\n\nnamespace LLPlayer.Extensions;\n\n/// \n/// Behavior to disable scrolling in ListView\n/// ref: https://stackoverflow.com/questions/1585462/bubbling-scroll-events-from-a-listview-to-its-parent\n/// \npublic class ScrollParentWhenAtMax : Behavior\n{\n protected override void OnAttached()\n {\n base.OnAttached();\n AssociatedObject.PreviewMouseWheel += PreviewMouseWheel;\n }\n\n protected override void OnDetaching()\n {\n AssociatedObject.PreviewMouseWheel -= PreviewMouseWheel;\n base.OnDetaching();\n }\n\n private void PreviewMouseWheel(object sender, MouseWheelEventArgs e)\n {\n var scrollViewer = GetVisualChild(AssociatedObject);\n var scrollPos = scrollViewer!.ContentVerticalOffset;\n if ((scrollPos == scrollViewer.ScrollableHeight && e.Delta < 0)\n || (scrollPos == 0 && e.Delta > 0))\n {\n e.Handled = true;\n MouseWheelEventArgs e2 = new(e.MouseDevice, e.Timestamp, e.Delta);\n e2.RoutedEvent = UIElement.MouseWheelEvent;\n AssociatedObject.RaiseEvent(e2);\n }\n }\n\n private static T? GetVisualChild(DependencyObject parent) where T : Visual\n {\n T? child = null;\n\n int numVisuals = VisualTreeHelper.GetChildrenCount(parent);\n for (int i = 0; i < numVisuals; i++)\n {\n Visual v = (Visual)VisualTreeHelper.GetChild(parent, i);\n child = v as T;\n if (child == null)\n {\n child = GetVisualChild(v);\n }\n\n if (child != null)\n {\n break;\n }\n }\n\n return child;\n }\n}\n"], ["/LLPlayer/FlyleafLib/MediaFramework/MediaStream/DataStream.cs", "using FlyleafLib.MediaFramework.MediaDemuxer;\n\nnamespace FlyleafLib.MediaFramework.MediaStream;\n\npublic unsafe class DataStream : StreamBase\n{\n\n public DataStream() { }\n public DataStream(Demuxer demuxer, AVStream* st) : base(demuxer, st)\n {\n Demuxer = demuxer;\n AVStream = st;\n Refresh();\n }\n\n public override void Refresh()\n {\n base.Refresh();\n }\n\n public override string GetDump()\n => $\"[{Type} #{StreamIndex}] {CodecID}\";\n}\n"], ["/LLPlayer/FlyleafLib/MediaPlayer/Translation/Services/GoogleV1TranslateService.cs", "using System.Collections.Generic;\nusing System.Linq;\nusing System.Net.Http;\nusing System.Text.Json;\nusing System.Threading;\nusing System.Threading.Tasks;\n\nnamespace FlyleafLib.MediaPlayer.Translation.Services;\n\n#nullable enable\n\npublic class GoogleV1TranslateService : ITranslateService\n{\n internal static Dictionary DefaultRegions { get; } = new()\n {\n [\"zh\"] = \"zh-CN\",\n [\"pt\"] = \"pt-PT\",\n [\"fr\"] = \"fr-FR\",\n };\n\n private readonly HttpClient _httpClient;\n private string? _srcLang;\n private string? _targetLang;\n private readonly GoogleV1TranslateSettings _settings;\n\n public GoogleV1TranslateService(GoogleV1TranslateSettings settings)\n {\n if (string.IsNullOrWhiteSpace(settings.Endpoint))\n {\n throw new TranslationConfigException(\n $\"Endpoint for {ServiceType} is not configured.\");\n }\n\n _settings = settings;\n _httpClient = new HttpClient();\n _httpClient.BaseAddress = new Uri(settings.Endpoint);\n _httpClient.Timeout = TimeSpan.FromMilliseconds(settings.TimeoutMs);\n }\n\n public TranslateServiceType ServiceType => TranslateServiceType.GoogleV1;\n\n public void Dispose()\n {\n _httpClient.Dispose();\n }\n\n public void Initialize(Language src, TargetLanguage target)\n {\n (TranslateLanguage srcLang, _) = this.TryGetLanguage(src, target);\n\n _srcLang = ToSourceCode(srcLang.ISO6391);\n _targetLang = ToTargetCode(target);\n }\n\n private string ToSourceCode(string iso6391)\n {\n if (iso6391 == \"nb\")\n {\n // handle 'Norwegian Bokmål' as 'Norwegian'\n return \"no\";\n }\n\n // ref: https://cloud.google.com/translate/docs/languages?hl=en\n if (!DefaultRegions.TryGetValue(iso6391, out string? defaultRegion))\n {\n // no region languages\n return iso6391;\n }\n\n // has region languages\n return _settings.Regions.GetValueOrDefault(iso6391, defaultRegion);\n }\n\n private static string ToTargetCode(TargetLanguage target)\n {\n return target switch\n {\n TargetLanguage.ChineseSimplified => \"zh-CN\",\n TargetLanguage.ChineseTraditional => \"zh-TW\",\n TargetLanguage.French => \"fr-FR\",\n TargetLanguage.FrenchCanadian => \"fr-CA\",\n TargetLanguage.Portuguese => \"pt-PT\",\n TargetLanguage.PortugueseBrazilian => \"pt-BR\",\n _ => target.ToISO6391()\n };\n }\n\n public async Task TranslateAsync(string text, CancellationToken token)\n {\n string jsonResultString = \"\";\n int statusCode = -1;\n\n try\n {\n var url = $\"/translate_a/single?client=gtx&sl={_srcLang}&tl={_targetLang}&dt=t&q={Uri.EscapeDataString(text)}\";\n\n using var result = await _httpClient.GetAsync(url, token).ConfigureAwait(false);\n jsonResultString = await result.Content.ReadAsStringAsync(token).ConfigureAwait(false);\n\n statusCode = (int)result.StatusCode;\n result.EnsureSuccessStatusCode();\n\n List resultTexts = new();\n using JsonDocument doc = JsonDocument.Parse(jsonResultString);\n resultTexts.AddRange(doc.RootElement[0].EnumerateArray().Select(arr => arr[0].GetString()!.Trim()));\n\n return string.Join(Environment.NewLine, resultTexts);\n }\n // Distinguish between timeout and cancel errors\n catch (OperationCanceledException ex)\n when (!ex.Message.StartsWith(\"The request was canceled due to the configured HttpClient.Timeout\"))\n {\n // cancel\n throw;\n }\n catch (Exception ex)\n {\n // timeout and other error\n throw new TranslationException($\"Cannot request to {ServiceType}: {ex.Message}\", ex)\n {\n Data =\n {\n [\"status_code\"] = statusCode.ToString(),\n [\"response\"] = jsonResultString\n }\n };\n }\n }\n}\n"], ["/LLPlayer/FlyleafLib/Utils/TextEncodings.cs", "using System.IO;\nusing System.Text;\nusing UtfUnknown;\n\nnamespace FlyleafLib;\n\n#nullable enable\n\npublic static class TextEncodings\n{\n private static Encoding? DetectEncodingInternal(byte[] data)\n {\n // 1. Check Unicode BOM\n Encoding? encoding = DetectEncodingWithBOM(data);\n if (encoding != null)\n {\n return encoding;\n }\n\n // 2. If no BOM, then check text is UTF-8 without BOM\n // Perform UTF-8 check first because automatic detection often results in false positives such as WINDOWS-1252.\n if (IsUtf8(data))\n {\n return Encoding.UTF8;\n }\n\n // 3. Auto detect encoding using library\n try\n {\n var result = CharsetDetector.DetectFromBytes(data);\n return result.Detected.Encoding;\n }\n catch\n {\n return null;\n }\n }\n\n /// \n /// Detect character encoding of text binary files\n /// \n /// text binary\n /// Bytes to read\n /// Detected Encoding or null\n public static Encoding? DetectEncoding(byte[] original, int maxBytes = 1 * 1024 * 1024)\n {\n if (maxBytes > original.Length)\n {\n maxBytes = original.Length;\n }\n\n byte[] data = new byte[maxBytes];\n Array.Copy(original, data, maxBytes);\n\n return DetectEncodingInternal(data);\n }\n\n /// \n /// Detect character encoding of text files\n /// \n /// file path\n /// Bytes to read\n /// Detected Encoding or null\n public static Encoding? DetectEncoding(string path, int maxBytes = 1 * 1024 * 1024)\n {\n byte[] data = new byte[maxBytes];\n\n try\n {\n using FileStream fs = new(path, FileMode.Open, FileAccess.Read);\n int bytesRead = fs.Read(data, 0, data.Length);\n Array.Resize(ref data, bytesRead);\n }\n catch\n {\n return null;\n }\n\n return DetectEncodingInternal(data);\n }\n\n /// \n /// Detect character encoding using BOM\n /// \n /// string raw data\n /// Detected Encoding or null\n private static Encoding? DetectEncodingWithBOM(byte[] bytes)\n {\n // UTF-8 BOM: EF BB BF\n if (bytes.Length >= 3 && bytes[0] == 0xEF && bytes[1] == 0xBB && bytes[2] == 0xBF)\n {\n return Encoding.UTF8;\n }\n\n // UTF-16 LE BOM: FF FE\n if (bytes.Length >= 2 && bytes[0] == 0xFF && bytes[1] == 0xFE)\n {\n return Encoding.Unicode; // UTF-16 LE\n }\n\n // UTF-16 BE BOM: FE FF\n if (bytes.Length >= 2 && bytes[0] == 0xFE && bytes[1] == 0xFF)\n {\n return Encoding.BigEndianUnicode; // UTF-16 BE\n }\n\n // UTF-32 LE BOM: FF FE 00 00\n if (bytes.Length >= 4 && bytes[0] == 0xFF && bytes[1] == 0xFE && bytes[2] == 0x00 && bytes[3] == 0x00)\n {\n return Encoding.UTF32;\n }\n\n // UTF-32 BE BOM: 00 00 FE FF\n if (bytes.Length >= 4 && bytes[0] == 0x00 && bytes[1] == 0x00 && bytes[2] == 0xFE && bytes[3] == 0xFF)\n {\n return new UTF32Encoding(bigEndian: true, byteOrderMark: true);\n }\n\n // No BOM\n return null;\n }\n\n private static bool IsUtf8(byte[] bytes)\n {\n // enable validation\n UTF8Encoding encoding = new(encoderShouldEmitUTF8Identifier: false, throwOnInvalidBytes: true);\n\n try\n {\n encoding.GetString(bytes);\n\n return true;\n }\n catch (DecoderFallbackException ex)\n {\n // Ignore when a trailing cut character causes a validation error.\n if (bytes.Length - ex.Index < 4)\n {\n return true;\n }\n\n return false;\n }\n }\n}\n"], ["/LLPlayer/WpfColorFontDialog/ColorFontDialog.xaml.cs", "using System.Collections;\nusing System.Windows;\nusing System.Windows.Media;\n\nnamespace WpfColorFontDialog\n{\n /// \n /// Interaction logic for ColorFontDialog.xaml\n /// \n public partial class ColorFontDialog : Window\n {\n private FontInfo _selectedFont;\n\n public FontInfo Font\n {\n get\n {\n return _selectedFont;\n }\n set\n {\n _selectedFont = value;\n }\n }\n\n private int[] _defaultFontSizes = { 8, 9, 10, 11, 12, 14, 16, 18, 20, 22, 24, 26, 28, 36, 48, 72, 96 };\n private int[] _fontSizes = null;\n public int[] FontSizes\n {\n get\n {\n return _fontSizes ?? _defaultFontSizes;\n }\n set\n {\n _fontSizes = value;\n }\n }\n public ColorFontDialog(bool previewFontInFontList = true, bool allowArbitraryFontSizes = true, bool showColorPicker = true)\n {\n // Disable style inheritance from parents and apply standard styles\n InheritanceBehavior = InheritanceBehavior.SkipToThemeNext;\n\n InitializeComponent();\n I18NUtil.SetLanguage(Resources);\n this.colorFontChooser.PreviewFontInFontList = previewFontInFontList;\n this.colorFontChooser.AllowArbitraryFontSizes = allowArbitraryFontSizes;\n this.colorFontChooser.ShowColorPicker = showColorPicker;\n }\n\n private void btnOk_Click(object sender, RoutedEventArgs e)\n {\n this.Font = this.colorFontChooser.SelectedFont;\n base.DialogResult = new bool?(true);\n }\n\n private void SyncFontColor()\n {\n int colorIdx = AvailableColors.GetFontColorIndex(this.Font.Color);\n this.colorFontChooser.colorPicker.superCombo.SelectedIndex = colorIdx;\n this.colorFontChooser.txtSampleText.Foreground = this.Font.Color.Brush;\n this.colorFontChooser.colorPicker.superCombo.BringIntoView();\n }\n\n private void SyncFontName()\n {\n string fontFamilyName = this._selectedFont.Family.Source;\n bool foundMatch = false;\n int idx = 0;\n foreach (object item in (IEnumerable)this.colorFontChooser.lstFamily.Items)\n {\n if (fontFamilyName == item.ToString())\n {\n foundMatch = true;\n break;\n }\n idx++;\n }\n if (!foundMatch)\n {\n idx = 0;\n }\n this.colorFontChooser.lstFamily.SelectedIndex = idx;\n this.colorFontChooser.lstFamily.ScrollIntoView(this.colorFontChooser.lstFamily.Items[idx]);\n }\n\n private void SyncFontSize()\n {\n double fontSize = this._selectedFont.Size;\n this.colorFontChooser.lstFontSizes.ItemsSource = FontSizes;\n this.colorFontChooser.tbFontSize.Text = fontSize.ToString();\n }\n\n private void SyncFontTypeface()\n {\n string fontTypeFaceSb = FontInfo.TypefaceToString(this._selectedFont.Typeface);\n int idx = 0;\n foreach (object item in (IEnumerable)this.colorFontChooser.lstTypefaces.Items)\n {\n if (fontTypeFaceSb == FontInfo.TypefaceToString(item as FamilyTypeface))\n {\n break;\n }\n idx++;\n }\n this.colorFontChooser.lstTypefaces.SelectedIndex = idx;\n this.colorFontChooser.lstTypefaces.ScrollIntoView(this.colorFontChooser.lstTypefaces.SelectedItem);\n }\n\n private void Window_Loaded_1(object sender, RoutedEventArgs e)\n {\n this.SyncFontColor();\n this.SyncFontName();\n this.SyncFontSize();\n this.SyncFontTypeface();\n }\n }\n}\n"], ["/LLPlayer/LLPlayer/Controls/SelectableTextBox.cs", "using System.Windows;\nusing System.Windows.Controls;\nusing System.Windows.Input;\nusing FlyleafLib;\n\nnamespace LLPlayer.Controls;\n\npublic class SelectableTextBox : TextBox\n{\n static SelectableTextBox()\n {\n DefaultStyleKeyProperty.OverrideMetadata(typeof(SelectableTextBox), new FrameworkPropertyMetadata(typeof(SelectableTextBox)));\n }\n\n public static readonly DependencyProperty IsTranslatedProperty =\n DependencyProperty.Register(nameof(IsTranslated), typeof(bool), typeof(SelectableTextBox), new FrameworkPropertyMetadata(false));\n\n public bool IsTranslated\n {\n get => (bool)GetValue(IsTranslatedProperty);\n set => SetValue(IsTranslatedProperty, value);\n }\n\n public static readonly DependencyProperty SubIndexProperty =\n DependencyProperty.Register(nameof(SubIndex), typeof(int), typeof(SelectableTextBox), new FrameworkPropertyMetadata(0));\n\n public int SubIndex\n {\n get => (int)GetValue(SubIndexProperty);\n set => SetValue(SubIndexProperty, value);\n }\n\n public static readonly RoutedEvent WordClickedEvent =\n EventManager.RegisterRoutedEvent(nameof(WordClicked), RoutingStrategy.Bubble, typeof(WordClickedEventHandler), typeof(SelectableTextBox));\n\n public event WordClickedEventHandler WordClicked\n {\n add => AddHandler(WordClickedEvent, value);\n remove => RemoveHandler(WordClickedEvent, value);\n }\n\n private bool _isDragging;\n private int _dragStartIndex = -1;\n private int _dragEndIndex = -1;\n\n private Point _mouseDownPosition;\n\n protected override void OnPreviewMouseLeftButtonDown(MouseButtonEventArgs e)\n {\n base.OnPreviewMouseLeftButtonDown(e);\n\n _isDragging = true;\n _mouseDownPosition = e.GetPosition(this);\n _dragStartIndex = GetCharacterIndexFromPoint(_mouseDownPosition, true);\n _dragEndIndex = _dragStartIndex;\n\n CaptureMouse();\n e.Handled = true;\n }\n\n protected override void OnPreviewMouseMove(MouseEventArgs e)\n {\n base.OnPreviewMouseMove(e);\n\n if (_isDragging)\n {\n Point currentPosition = e.GetPosition(this);\n\n if (currentPosition != _mouseDownPosition)\n {\n int currentIndex = GetCharacterIndexFromPoint(currentPosition, true);\n if (currentIndex != -1 && currentIndex != _dragEndIndex)\n {\n _dragEndIndex = currentIndex;\n }\n }\n }\n }\n\n protected override void OnPreviewMouseLeftButtonUp(MouseButtonEventArgs e)\n {\n base.OnPreviewMouseLeftButtonUp(e);\n\n if (_isDragging)\n {\n _isDragging = false;\n ReleaseMouseCapture();\n e.Handled = true;\n\n if (_dragStartIndex == _dragEndIndex)\n {\n // Click\n HandleClick(_mouseDownPosition, MouseClick.Left);\n }\n else\n {\n // Drag\n HandleDragSelection();\n }\n }\n }\n\n protected override void OnMouseRightButtonUp(MouseButtonEventArgs e)\n {\n base.OnMouseRightButtonUp(e);\n\n Point clickPosition = e.GetPosition(this);\n\n HandleClick(clickPosition, MouseClick.Right);\n\n // Right clicks other than words are currently disabled, consider creating another one\n e.Handled = true;\n }\n\n protected override void OnMouseUp(MouseButtonEventArgs e)\n {\n // Middle click: Sentence Lookup\n if (e.ChangedButton == MouseButton.Middle)\n {\n if (string.IsNullOrEmpty(Text))\n {\n return;\n }\n\n WordClickedEventArgs args = new(WordClickedEvent)\n {\n Mouse = MouseClick.Middle,\n // Change line breaks to spaces to improve translation accuracy.\n Words = SubtitleTextUtil.FlattenText(Text),\n IsWord = false,\n Text = Text,\n IsTranslated = IsTranslated,\n SubIndex = SubIndex,\n WordOffset = 0,\n Sender = this\n };\n\n RaiseEvent(args);\n }\n }\n\n private void HandleClick(Point point, MouseClick mouse)\n {\n // false because it fires only above the word\n int charIndex = GetCharacterIndexFromPoint(point, false);\n\n if (charIndex == -1 || string.IsNullOrEmpty(Text))\n {\n return;\n }\n\n int start = FindWordStart(charIndex);\n int end = FindWordEnd(charIndex);\n\n // get word\n string word = Text.Substring(start, end - start).Trim();\n\n if (string.IsNullOrEmpty(word))\n {\n return;\n }\n\n WordClickedEventArgs args = new(WordClickedEvent)\n {\n Mouse = mouse,\n Words = word,\n IsWord = true,\n Text = Text,\n IsTranslated = IsTranslated,\n SubIndex = SubIndex,\n WordOffset = start,\n Sender = this\n };\n RaiseEvent(args);\n }\n\n private void HandleDragSelection()\n {\n // Support right to left drag\n int rawStart = Math.Min(_dragStartIndex, _dragEndIndex);\n int rawEnd = Math.Max(_dragStartIndex, _dragEndIndex);\n\n // Adjust to word boundaries\n int adjustedStart = FindWordStart(rawStart);\n int adjustedEnd = FindWordEnd(rawEnd);\n\n // Extract the substring within the adjusted selection\n // TODO: L: If there is only a delimiter after the end, I want to include it in the selection (should improve translation accuracy)\n string selectedText = Text.Substring(adjustedStart, adjustedEnd - adjustedStart);\n\n WordClickedEventArgs args = new(WordClickedEvent)\n {\n Mouse = MouseClick.Left,\n // Change line breaks to spaces to improve translation accuracy.\n Words = SubtitleTextUtil.FlattenText(selectedText),\n IsWord = false,\n Text = Text,\n IsTranslated = IsTranslated,\n SubIndex = SubIndex,\n WordOffset = adjustedStart,\n Sender = this\n };\n\n RaiseEvent(args);\n }\n\n private int FindWordStart(int index)\n {\n if (index < 0 || index > Text.Length)\n {\n return 0;\n }\n\n while (index > 0 && !IsWordSeparator(Text[index - 1]))\n {\n index--;\n }\n\n return index;\n }\n\n private int FindWordEnd(int index)\n {\n if (index < 0 || index > Text.Length)\n {\n return Text.Length;\n }\n\n while (index < Text.Length && !IsWordSeparator(Text[index]))\n {\n index++;\n }\n\n return index;\n }\n\n private static readonly HashSet ExcludedSeparators = ['\\'', '-'];\n\n private static bool IsWordSeparator(char c)\n {\n if (ExcludedSeparators.Contains(c))\n {\n return false;\n }\n\n return char.IsWhiteSpace(c) || char.IsPunctuation(c);\n }\n\n #region Cursor Hand\n protected override void OnMouseMove(MouseEventArgs e)\n {\n base.OnMouseMove(e);\n\n // Change cursor only over word text\n int charIndex = GetCharacterIndexFromPoint(e.GetPosition(this), false);\n\n Cursor = charIndex != -1 ? Cursors.Hand : Cursors.Arrow;\n }\n\n protected override void OnMouseLeave(MouseEventArgs e)\n {\n base.OnMouseLeave(e);\n\n if (Cursor == Cursors.Hand)\n {\n Cursor = Cursors.Arrow;\n }\n }\n #endregion\n}\n"], ["/LLPlayer/LLPlayer/Controls/OutlinedTextBlock.cs", "using System.ComponentModel;\nusing System.Globalization;\nusing System.Windows;\nusing System.Windows.Documents;\nusing System.Windows.Markup;\nusing System.Windows.Media;\n\nnamespace LLPlayer.Controls;\n\n[ContentProperty(\"Text\")]\npublic class OutlinedTextBlock : FrameworkElement\n{\n public OutlinedTextBlock()\n {\n UpdatePen();\n TextDecorations = new TextDecorationCollection();\n }\n\n #region dependency properties\n public static readonly DependencyProperty FillProperty = DependencyProperty.Register(\n nameof(Fill),\n typeof(Brush),\n typeof(OutlinedTextBlock),\n new FrameworkPropertyMetadata(Brushes.White, FrameworkPropertyMetadataOptions.AffectsRender));\n\n public static readonly DependencyProperty StrokeProperty = DependencyProperty.Register(\n nameof(Stroke),\n typeof(Brush),\n typeof(OutlinedTextBlock),\n new FrameworkPropertyMetadata(Brushes.Black, FrameworkPropertyMetadataOptions.AffectsRender));\n\n public static readonly DependencyProperty StrokeThicknessProperty = DependencyProperty.Register(\n nameof(StrokeThickness),\n typeof(double),\n typeof(OutlinedTextBlock),\n new FrameworkPropertyMetadata(1d, FrameworkPropertyMetadataOptions.AffectsRender));\n\n public static readonly DependencyProperty FontFamilyProperty = TextElement.FontFamilyProperty.AddOwner(\n typeof(OutlinedTextBlock),\n new FrameworkPropertyMetadata(OnFormattedTextUpdated));\n\n public static readonly DependencyProperty FontSizeProperty = TextElement.FontSizeProperty.AddOwner(\n typeof(OutlinedTextBlock),\n new FrameworkPropertyMetadata(OnFormattedTextUpdated));\n\n public static readonly DependencyProperty FontSizeInitialProperty = DependencyProperty.Register(\n nameof(FontSizeInitial),\n typeof(double),\n typeof(OutlinedTextBlock),\n new FrameworkPropertyMetadata(OnFormattedTextUpdated));\n\n public static readonly DependencyProperty FontSizeAutoProperty = DependencyProperty.Register(\n nameof(FontSizeAuto),\n typeof(bool),\n typeof(OutlinedTextBlock),\n new FrameworkPropertyMetadata(OnFormattedTextUpdated));\n\n public static readonly DependencyProperty FontStretchProperty = TextElement.FontStretchProperty.AddOwner(\n typeof(OutlinedTextBlock),\n new FrameworkPropertyMetadata(OnFormattedTextUpdated));\n\n public static readonly DependencyProperty FontStyleProperty = TextElement.FontStyleProperty.AddOwner(\n typeof(OutlinedTextBlock),\n new FrameworkPropertyMetadata(OnFormattedTextUpdated));\n\n public static readonly DependencyProperty FontWeightProperty = TextElement.FontWeightProperty.AddOwner(\n typeof(OutlinedTextBlock),\n new FrameworkPropertyMetadata(OnFormattedTextUpdated));\n\n public static readonly DependencyProperty StrokePositionProperty = DependencyProperty.Register(\n nameof(StrokePosition),\n typeof(StrokePosition),\n typeof(OutlinedTextBlock),\n new FrameworkPropertyMetadata(StrokePosition.Outside, FrameworkPropertyMetadataOptions.AffectsRender));\n\n public static readonly DependencyProperty StrokeThicknessInitialProperty = DependencyProperty.Register(\n nameof(StrokeThicknessInitial),\n typeof(double),\n typeof(OutlinedTextBlock),\n new FrameworkPropertyMetadata(OnFormattedTextUpdated));\n\n public static readonly DependencyProperty TextProperty = DependencyProperty.Register(\n nameof(Text),\n typeof(string),\n typeof(OutlinedTextBlock),\n new FrameworkPropertyMetadata(OnFormattedTextInvalidated));\n\n public static readonly DependencyProperty TextAlignmentProperty = DependencyProperty.Register(\n nameof(TextAlignment),\n typeof(TextAlignment),\n typeof(OutlinedTextBlock),\n new FrameworkPropertyMetadata(OnFormattedTextUpdated));\n\n public static readonly DependencyProperty TextDecorationsProperty = DependencyProperty.Register(\n nameof(TextDecorations),\n typeof(TextDecorationCollection),\n typeof(OutlinedTextBlock),\n new FrameworkPropertyMetadata(OnFormattedTextUpdated));\n\n public static readonly DependencyProperty TextTrimmingProperty = DependencyProperty.Register(\n nameof(TextTrimming),\n typeof(TextTrimming),\n typeof(OutlinedTextBlock),\n new FrameworkPropertyMetadata(OnFormattedTextUpdated));\n\n public static readonly DependencyProperty TextWrappingProperty = DependencyProperty.Register(\n nameof(TextWrapping),\n typeof(TextWrapping),\n typeof(OutlinedTextBlock),\n new FrameworkPropertyMetadata(TextWrapping.NoWrap, OnFormattedTextUpdated));\n\n private FormattedText? _FormattedText;\n private Geometry? _TextGeometry;\n private Pen? _Pen;\n private PathGeometry? _clipGeometry;\n\n public Brush Fill\n {\n get => (Brush)GetValue(FillProperty);\n set => SetValue(FillProperty, value);\n }\n\n public FontFamily FontFamily\n {\n get => (FontFamily)GetValue(FontFamilyProperty);\n set => SetValue(FontFamilyProperty, value);\n }\n\n [TypeConverter(typeof(FontSizeConverter))]\n public double FontSize\n {\n get => (double)GetValue(FontSizeProperty);\n set => SetValue(FontSizeProperty, value);\n }\n\n [TypeConverter(typeof(FontSizeConverter))]\n public double FontSizeInitial\n {\n get => (double)GetValue(FontSizeInitialProperty);\n set => SetValue(FontSizeInitialProperty, value);\n }\n\n public bool FontSizeAuto\n {\n get => (bool)GetValue(FontSizeAutoProperty);\n set => SetValue(FontSizeAutoProperty, value);\n }\n\n public FontStretch FontStretch\n {\n get => (FontStretch)GetValue(FontStretchProperty);\n set => SetValue(FontStretchProperty, value);\n }\n\n public FontStyle FontStyle\n {\n get => (FontStyle)GetValue(FontStyleProperty);\n set => SetValue(FontStyleProperty, value);\n }\n\n public FontWeight FontWeight\n {\n get => (FontWeight)GetValue(FontWeightProperty);\n set => SetValue(FontWeightProperty, value);\n }\n\n public Brush Stroke\n {\n get => (Brush)GetValue(StrokeProperty);\n set => SetValue(StrokeProperty, value);\n }\n\n public StrokePosition StrokePosition\n {\n get => (StrokePosition)GetValue(StrokePositionProperty);\n set => SetValue(StrokePositionProperty, value);\n }\n\n public double StrokeThickness\n {\n get => (double)GetValue(StrokeThicknessProperty);\n set => SetValue(StrokeThicknessProperty, value);\n }\n\n public double StrokeThicknessInitial\n {\n get => (double)GetValue(StrokeThicknessInitialProperty);\n set => SetValue(StrokeThicknessInitialProperty, value);\n }\n\n public string Text\n {\n get => (string)GetValue(TextProperty);\n set => SetValue(TextProperty, value);\n }\n\n public TextAlignment TextAlignment\n {\n get => (TextAlignment)GetValue(TextAlignmentProperty);\n set => SetValue(TextAlignmentProperty, value);\n }\n\n public TextDecorationCollection TextDecorations\n {\n get => (TextDecorationCollection)GetValue(TextDecorationsProperty);\n set => SetValue(TextDecorationsProperty, value);\n }\n\n public TextTrimming TextTrimming\n {\n get => (TextTrimming)GetValue(TextTrimmingProperty);\n set => SetValue(TextTrimmingProperty, value);\n }\n\n public TextWrapping TextWrapping\n {\n get => (TextWrapping)GetValue(TextWrappingProperty);\n set => SetValue(TextWrappingProperty, value);\n }\n\n #endregion\n\n #region PDIC\n\n public int WordOffset { get; set; }\n\n #endregion\n\n private void UpdatePen()\n {\n _Pen = new Pen(Stroke, StrokeThickness)\n {\n DashCap = PenLineCap.Round,\n EndLineCap = PenLineCap.Round,\n LineJoin = PenLineJoin.Round,\n StartLineCap = PenLineCap.Round\n };\n\n if (StrokePosition == StrokePosition.Outside || StrokePosition == StrokePosition.Inside)\n _Pen.Thickness = StrokeThickness * 2;\n\n InvalidateVisual();\n }\n\n protected override void OnRender(DrawingContext drawingContext)\n {\n EnsureGeometry();\n\n drawingContext.DrawGeometry(Fill, null, _TextGeometry);\n\n if (StrokePosition == StrokePosition.Outside)\n drawingContext.PushClip(_clipGeometry);\n else if (StrokePosition == StrokePosition.Inside)\n drawingContext.PushClip(_TextGeometry);\n\n drawingContext.DrawGeometry(null, _Pen, _TextGeometry);\n\n if (StrokePosition == StrokePosition.Outside || StrokePosition == StrokePosition.Inside)\n drawingContext.Pop();\n }\n\n protected override Size MeasureOverride(Size availableSize)\n {\n EnsureFormattedText();\n\n // constrain the formatted text according to the available size\n double w = availableSize.Width;\n double h = availableSize.Height;\n\n if (FontSizeAuto)\n {\n if (FontSizeInitial > 0)\n {\n double r = w / 1920; // FontSizeInitial should be based on fixed Screen Width (eg. Full HD 1920)\n FontSize = FontSizeInitial * (r + ((1 - r) * 0.20f)); // TBR: Weight/Percentage for how much it will be affected by the change (possible dependency property / config)\n _FormattedText!.SetFontSize(FontSize);\n }\n }\n\n if (StrokeThicknessInitial > 0)\n {\n double r = FontSize / 48; // StrokeThicknessInitial should be based on fixed FontSize (eg. 48)\n StrokeThickness = Math.Max(1, StrokeThicknessInitial * r);\n UpdatePen();\n }\n\n // the Math.Min call is important - without this constraint (which seems arbitrary, but is the maximum allowable text width), things blow up when availableSize is infinite in both directions\n // the Math.Max call is to ensure we don't hit zero, which will cause MaxTextHeight to throw\n _FormattedText!.MaxTextWidth = Math.Min(3579139, w);\n _FormattedText!.MaxTextHeight = Math.Max(0.0001d, h);\n\n // return the desired size\n return new Size(Math.Ceiling(_FormattedText.Width), Math.Ceiling(_FormattedText.Height));\n }\n\n protected override Size ArrangeOverride(Size finalSize)\n {\n EnsureFormattedText();\n\n // update the formatted text with the final size\n _FormattedText!.MaxTextWidth = finalSize.Width;\n _FormattedText!.MaxTextHeight = Math.Max(0.0001d, finalSize.Height);\n\n // need to re-generate the geometry now that the dimensions have changed\n _TextGeometry = null;\n UpdatePen();\n\n return finalSize;\n }\n\n private static void OnFormattedTextInvalidated(DependencyObject dependencyObject,\n DependencyPropertyChangedEventArgs e)\n {\n var outlinedTextBlock = (OutlinedTextBlock)dependencyObject;\n outlinedTextBlock._FormattedText = null;\n outlinedTextBlock._TextGeometry = null;\n\n outlinedTextBlock.InvalidateMeasure();\n outlinedTextBlock.InvalidateVisual();\n }\n\n private static void OnFormattedTextUpdated(DependencyObject dependencyObject, DependencyPropertyChangedEventArgs e)\n {\n var outlinedTextBlock = (OutlinedTextBlock)dependencyObject;\n if (outlinedTextBlock._FormattedText != null)\n outlinedTextBlock.UpdateFormattedText();\n outlinedTextBlock._TextGeometry = null;\n\n outlinedTextBlock.InvalidateMeasure();\n outlinedTextBlock.InvalidateVisual();\n }\n\n private void EnsureFormattedText()\n {\n if (_FormattedText != null)\n return;\n\n _FormattedText = new FormattedText(\n Text ?? \"\",\n CultureInfo.CurrentUICulture,\n FlowDirection,\n new Typeface(FontFamily, FontStyle, FontWeight, FontStretch),\n FontSize,\n Brushes.Black,\n VisualTreeHelper.GetDpi(this).PixelsPerDip);\n\n UpdateFormattedText();\n }\n\n private void UpdateFormattedText()\n {\n _FormattedText!.MaxLineCount = TextWrapping == TextWrapping.NoWrap ? 1 : int.MaxValue;\n _FormattedText.TextAlignment = TextAlignment;\n _FormattedText.Trimming = TextTrimming;\n _FormattedText.SetFontSize(FontSize);\n _FormattedText.SetFontStyle(FontStyle);\n _FormattedText.SetFontWeight(FontWeight);\n _FormattedText.SetFontFamily(FontFamily);\n _FormattedText.SetFontStretch(FontStretch);\n _FormattedText.SetTextDecorations(TextDecorations);\n }\n\n private void EnsureGeometry()\n {\n if (_TextGeometry != null)\n return;\n\n EnsureFormattedText();\n _TextGeometry = _FormattedText!.BuildGeometry(new Point(0, 0));\n\n if (StrokePosition == StrokePosition.Outside)\n {\n var boundsGeo = new RectangleGeometry(new Rect(-(2 * StrokeThickness),\n -(2 * StrokeThickness), ActualWidth + (4 * StrokeThickness), ActualHeight + (4 * StrokeThickness)));\n _clipGeometry = Geometry.Combine(boundsGeo, _TextGeometry, GeometryCombineMode.Exclude, null);\n }\n }\n}\n\npublic enum StrokePosition\n{\n Center,\n Outside,\n Inside\n}\n"], ["/LLPlayer/Plugins/YoutubeDL/YoutubeDLJson.cs", "using System.Collections.Generic;\nusing System.Text.Json.Serialization;\n\nnamespace FlyleafLib.Plugins\n{\n public class YoutubeDLJson : Format\n {\n // Remove not used as can cause issues with data types from time to time\n\n //public string id { get; set; }\n public string title { get; set; }\n //public string description { get; set; }\n //public string upload_date { get; set; }\n //public string uploader { get; set; }\n //public string uploader_id { get; set; }\n //public string uploader_url { get; set; }\n //public string channel_id { get; set; }\n //public string channel_url { get; set; }\n //public double duration { get; set; }\n //public double view_count { get; set; }\n //public double average_rating { get; set; }\n //public double age_limit { get; set; }\n public string webpage_url { get; set; }\n\n //public bool playable_in_embed { get; set; }\n //public bool is_live { get; set; }\n //public bool was_live { get; set; }\n //public string live_status { get; set; }\n\n // Playlist\n public string _type { get; set; }\n public double playlist_count { get; set; }\n //public double playlist_index { get; set; }\n public string playlist { get; set; }\n public string playlist_title { get; set; }\n\n\n\n public Dictionary>\n automatic_captions { get; set; }\n //public List\n // categories { get; set; }\n public List\n formats { get; set; }\n //public List\n // thumbnails { get; set; }\n public List\n chapters\n { get; set; }\n //public double like_count { get; set; }\n //public double dislike_count { get; set; }\n //public string channel { get; set; }\n //public string availability { get; set; }\n //public string webpage_url_basename\n // { get; set; }\n //public string extractor { get; set; }\n //public string extractor_key { get; set; }\n //public string thumbnail { get; set; }\n //public string display_id { get; set; }\n //public string fulltitle { get; set; }\n //public double epoch { get; set; }\n\n //public class DownloaderOptions\n //{\n // public int http_chunk_size { get; set; }\n //}\n\n public class HttpHeaders\n {\n [JsonPropertyName(\"User-Agent\")]\n public string UserAgent { get; set; }\n\n [JsonPropertyName(\"Accept-Charset\")]\n public string AcceptCharset { get; set; }\n public string Accept { get; set; }\n\n [JsonPropertyName(\"Accept-Encoding\")]\n public string AcceptEncoding{ get; set; }\n\n [JsonPropertyName(\"Accept-Language\")]\n public string AcceptLanguage{ get; set; }\n }\n\n //public class Thumbnail\n //{\n // public string url { get; set; }\n // public int preference { get; set; }\n // public string id { get; set; }\n // public double height { get; set; }\n // public double width { get; set; }\n // public string resolution { get; set; }\n //}\n\n public class SubtitlesFormat\n {\n public string ext { get; set; }\n public string url { get; set; }\n public string name { get; set; }\n }\n }\n\n public class Chapter\n {\n public double start_time { get; set; }\n public double end_time { get; set; }\n public string title { get; set; }\n }\n\n public class Format\n {\n //public double asr { get; set; }\n //public double filesize { get; set; }\n //public string format_id { get; set; }\n //public string format_note { get; set; }\n //public double quality { get; set; }\n public double tbr { get; set; }\n public string url { get; set; }\n public string manifest_url{ get; set; }\n public string language { get; set; }\n //public int language_preference\n // { get; set; }\n //public string ext { get; set; }\n public string vcodec { get; set; }\n public string acodec { get; set; }\n public double abr { get; set; }\n //public DownloaderOptions\n // downloader_options { get; set; }\n //public string container { get; set; }\n public string protocol { get; set; }\n //public string audio_ext { get; set; }\n //public string video_ext { get; set; }\n public string format { get; set; }\n public Dictionary\n http_headers{ get; set; }\n public string cookies { get; set; }\n public double fps { get; set; }\n public double height { get; set; }\n public double width { get; set; }\n public double vbr { get; set; }\n }\n}\n"], ["/LLPlayer/LLPlayer/Services/SrtExporter.cs", "using System.IO;\nusing System.Text;\n\nnamespace LLPlayer.Services;\n\npublic static class SrtExporter\n{\n // TODO: L: Supports tags such as ?\n public static void ExportSrt(List lines, string filePath, Encoding encoding)\n {\n using StreamWriter writer = new(filePath, false, encoding);\n\n foreach (var (i, line) in lines.Index())\n {\n writer.WriteLine((i + 1).ToString());\n writer.WriteLine($\"{FormatTime(line.Start)} --> {FormatTime(line.End)}\");\n writer.WriteLine(line.Text);\n // blank line expect last\n if (i != lines.Count - 1)\n {\n writer.WriteLine();\n }\n }\n }\n\n private static string FormatTime(TimeSpan time)\n {\n return string.Format(\"{0:00}:{1:00}:{2:00},{3:000}\",\n (int)time.TotalHours,\n time.Minutes,\n time.Seconds,\n time.Milliseconds);\n }\n}\n\npublic class SubtitleLine\n{\n public required TimeSpan Start { get; init; }\n public required TimeSpan End { get; init; }\n public required string Text { get; init; }\n}\n"], ["/LLPlayer/LLPlayer/Views/SubtitlesSidebar.xaml.cs", "using System.Windows;\nusing System.Windows.Controls;\nusing LLPlayer.Controls;\nusing LLPlayer.ViewModels;\n\nnamespace LLPlayer.Views;\n\npublic partial class SubtitlesSidebar : UserControl\n{\n private SubtitlesSidebarVM VM => (SubtitlesSidebarVM)DataContext;\n public SubtitlesSidebar()\n {\n InitializeComponent();\n\n DataContext = ((App)Application.Current).Container.Resolve();\n\n Loaded += (sender, args) =>\n {\n VM.RequestScrollToTop += OnRequestScrollToTop;\n };\n\n Unloaded += (sender, args) =>\n {\n VM.RequestScrollToTop -= OnRequestScrollToTop;\n VM.Dispose();\n };\n }\n\n /// \n /// Scroll to the current subtitle\n /// \n /// \n /// \n private void SubtitleListBox_SelectionChanged(object sender, SelectionChangedEventArgs e)\n {\n if (IsLoaded && SubtitleListBox.SelectedItem != null)\n {\n SubtitleListBox.ScrollIntoView(SubtitleListBox.SelectedItem);\n }\n }\n\n /// \n /// Scroll to the top subtitle\n /// \n /// \n /// \n private void OnRequestScrollToTop(object? sender, EventArgs args)\n {\n if (SubtitleListBox.Items.Count <= 0)\n return;\n\n var first = SubtitleListBox.Items[0];\n if (first != null)\n {\n SubtitleListBox.ScrollIntoView(first);\n }\n }\n\n private void SelectableTextBox_OnWordClicked(object? sender, WordClickedEventArgs e)\n {\n _ = WordPopupControl.OnWordClicked(e);\n }\n}\n"], ["/LLPlayer/LLPlayer/Converters/GeneralConverters.cs", "using System.Globalization;\nusing System.Windows;\nusing System.Windows.Data;\nusing System.Windows.Input;\nusing System.Windows.Media;\nusing LLPlayer.Services;\n\nnamespace LLPlayer.Converters;\n[ValueConversion(typeof(bool), typeof(bool))]\npublic class InvertBooleanConverter : IValueConverter\n{\n public object Convert(object value, Type targetType, object parameter, CultureInfo culture)\n {\n if (value is bool boolValue)\n {\n return !boolValue;\n }\n return false;\n }\n\n public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)\n {\n if (value is bool boolValue)\n {\n return !boolValue;\n }\n return false;\n }\n}\n\n[ValueConversion(typeof(bool), typeof(Visibility))]\npublic class BooleanToVisibilityMiscConverter : IValueConverter\n{\n public Visibility FalseVisibility { get; set; } = Visibility.Collapsed;\n public bool Invert { get; set; } = false;\n\n public object Convert(object value, Type targetType, object parameter, CultureInfo culture)\n {\n if (Invert)\n {\n return (bool)value ? FalseVisibility : Visibility.Visible;\n }\n\n return (bool)value ? Visibility.Visible : FalseVisibility;\n }\n\n public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture) => throw new NotImplementedException();\n}\n\n[ValueConversion(typeof(double), typeof(double))]\npublic class DoubleToPercentageConverter : IValueConverter\n{\n // Model → View (0.0–1.0 → 0–100)\n public object Convert(object value, Type targetType, object parameter, CultureInfo culture)\n {\n if (value is double d)\n return Math.Round(d * 100.0, 0);\n return 0.0;\n }\n\n // View → Model (0–100 → 0.0–1.0)\n public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)\n {\n if (value is double d)\n return ToDouble(d);\n\n if (value is string sd)\n {\n if (double.TryParse(sd, out d))\n {\n if (d < 0)\n d = 0;\n else if (d > 100)\n d = 100;\n }\n\n return ToDouble(d);\n }\n\n return 0.0;\n\n static double ToDouble(double value)\n {\n return Math.Max(0.0, Math.Min(1.0, Math.Round(value / 100.0, 2)));\n }\n }\n}\n\n[ValueConversion(typeof(Enum), typeof(string))]\npublic class EnumToStringConverter : IValueConverter\n{\n public object Convert(object value, Type targetType, object parameter, CultureInfo culture)\n {\n string str;\n try\n {\n str = Enum.GetName(value.GetType(), value)!;\n return str;\n }\n catch\n {\n return string.Empty;\n }\n }\n\n public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture) => throw new NotImplementedException();\n}\n\n[ValueConversion(typeof(Enum), typeof(string))]\npublic class EnumToDescriptionConverter : IValueConverter\n{\n public object Convert(object value, Type targetType, object parameter, CultureInfo culture)\n {\n if (value is Enum enumValue)\n {\n return enumValue.GetDescription();\n }\n return value.ToString() ?? \"\";\n }\n\n public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)\n {\n throw new NotImplementedException();\n }\n}\n\n[ValueConversion(typeof(Enum), typeof(bool))]\npublic class EnumToBooleanConverter : IValueConverter\n{\n // value, parameter = Enum\n public object Convert(object value, Type targetType, object parameter, CultureInfo culture)\n {\n if (value is not Enum enumValue || parameter is not Enum enumTarget)\n return false;\n\n return enumValue.Equals(enumTarget);\n }\n\n public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)\n {\n return parameter;\n }\n}\n\n[ValueConversion(typeof(Enum), typeof(Visibility))]\npublic class EnumToVisibilityConverter : IValueConverter\n{\n // value, parameter = Enum\n public object Convert(object value, Type targetType, object parameter, CultureInfo culture)\n {\n if (value is not Enum enumValue || parameter is not Enum enumTarget)\n return false;\n\n return enumValue.Equals(enumTarget) ? Visibility.Visible : Visibility.Collapsed;\n }\n\n public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)\n {\n throw new NotImplementedException();\n }\n}\n\n[ValueConversion(typeof(Color), typeof(Brush))]\npublic class ColorToBrushConverter : IValueConverter\n{\n public object Convert(object value, Type targetType, object parameter, CultureInfo culture)\n {\n if (value is Color color)\n {\n return new SolidColorBrush(color);\n }\n return Binding.DoNothing;\n }\n\n public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)\n {\n if (value is SolidColorBrush brush)\n {\n return brush.Color;\n }\n return default(Color);\n }\n}\n\n/// \n/// Converts from System.Windows.Input.Key to human readable string\n/// \n[ValueConversion(typeof(Key), typeof(string))]\npublic class KeyToStringConverter : IValueConverter\n{\n public static readonly Dictionary KeyMappings = new()\n {\n { Key.D0, \"0\" },\n { Key.D1, \"1\" },\n { Key.D2, \"2\" },\n { Key.D3, \"3\" },\n { Key.D4, \"4\" },\n { Key.D5, \"5\" },\n { Key.D6, \"6\" },\n { Key.D7, \"7\" },\n { Key.D8, \"8\" },\n { Key.D9, \"9\" },\n { Key.Prior, \"PageUp\" },\n { Key.Next, \"PageDown\" },\n { Key.Return, \"Enter\" },\n { Key.Oem1, \";\" },\n { Key.Oem2, \"/\" },\n { Key.Oem3, \"`\" },\n { Key.Oem4, \"[\" },\n { Key.Oem5, \"\\\\\" },\n { Key.Oem6, \"]\" },\n { Key.Oem7, \"'\" },\n { Key.OemPlus, \"Plus\" },\n { Key.OemMinus, \"Minus\" },\n { Key.OemComma, \",\" },\n { Key.OemPeriod, \".\" }\n };\n\n public object Convert(object? value, Type targetType, object? parameter, CultureInfo culture)\n {\n if (value is Key key)\n {\n if (KeyMappings.TryGetValue(key, out var mappedValue))\n {\n return mappedValue;\n }\n\n return key.ToString();\n }\n\n return Binding.DoNothing;\n }\n\n public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)\n {\n throw new NotImplementedException();\n }\n}\n\n[ValueConversion(typeof(long), typeof(string))]\npublic class FileSizeHumanConverter : IValueConverter\n{\n public object Convert(object value, Type targetType, object parameter, CultureInfo culture)\n {\n if (value is long size)\n {\n return FormatBytes(size);\n }\n\n return Binding.DoNothing;\n }\n\n public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)\n {\n throw new NotImplementedException();\n }\n\n private static string FormatBytes(long bytes)\n {\n string[] sizes = [\"B\", \"KB\", \"MB\", \"GB\"];\n double len = bytes;\n int order = 0;\n while (len >= 1024 && order < sizes.Length - 1)\n {\n order++;\n len /= 1024;\n }\n return $\"{len:0.##} {sizes[order]}\";\n }\n}\n\n[ValueConversion(typeof(int?), typeof(string))]\npublic class NullableIntConverter : IValueConverter\n{\n public object Convert(object? value, Type targetType, object? parameter, CultureInfo culture)\n {\n return value is int intValue ? intValue.ToString() : string.Empty;\n }\n\n public object? ConvertBack(object? value, Type targetType, object? parameter, CultureInfo culture)\n {\n string? str = value as string;\n if (string.IsNullOrWhiteSpace(str))\n return null;\n\n if (int.TryParse(str, out int result))\n return result;\n\n return null;\n }\n}\n"], ["/LLPlayer/WpfColorFontDialog/I18NUtil.cs", "using System;\nusing System.Collections.Generic;\nusing System.Linq;\nusing System.Windows;\n\nnamespace WpfColorFontDialog\n{\n internal static class I18NUtil\n {\n private const string DefaultLanguage = @\"en-US\";\n\n public static string CurrentLanguage;\n\n public static readonly Dictionary SupportLanguage = new Dictionary\n {\n {@\"简体中文\", @\"zh-CN\"},\n {@\"English (United States)\", @\"en-US\"},\n };\n\n public static string GetCurrentLanguage()\n {\n return System.Globalization.CultureInfo.CurrentCulture.Name;\n }\n\n public static string GetLanguage()\n {\n var name = GetCurrentLanguage();\n return SupportLanguage.Any(s => name == s.Value) ? name : DefaultLanguage;\n }\n\n public static string GetWindowStringValue(Window window, string key)\n {\n if (window.Resources.MergedDictionaries[0][key] is string str)\n {\n return str;\n }\n return null;\n }\n\n public static void SetLanguage(ResourceDictionary resources, string langName = @\"\")\n {\n if (string.IsNullOrEmpty(langName))\n {\n langName = GetLanguage();\n }\n CurrentLanguage = langName;\n if (resources.MergedDictionaries.Count > 0)\n {\n resources.MergedDictionaries[0].Source = new Uri($@\"I18n/{langName}.xaml\", UriKind.Relative);\n }\n }\n }\n}\n"], ["/LLPlayer/LLPlayer/Extensions/TextBoxHelper.cs", "using System.Windows;\nusing System.Windows.Controls;\nusing System.Windows.Input;\n\nnamespace LLPlayer.Extensions;\n\n\n// ref: https://stackoverflow.com/a/50905766/9070784\npublic static class TextBoxHelper\n{\n #region Enum Declarations\n public enum NumericFormat\n {\n Double,\n Int,\n Uint,\n Natural\n }\n\n public enum EvenOddConstraint\n {\n All,\n OnlyEven,\n OnlyOdd\n }\n\n #endregion\n\n #region Dependency Properties & CLR Wrappers\n\n public static readonly DependencyProperty OnlyNumericProperty =\n DependencyProperty.RegisterAttached(\"OnlyNumeric\", typeof(NumericFormat?), typeof(TextBoxHelper),\n new PropertyMetadata(null, DependencyPropertiesChanged));\n public static void SetOnlyNumeric(TextBox element, NumericFormat value) =>\n element.SetValue(OnlyNumericProperty, value);\n public static NumericFormat GetOnlyNumeric(TextBox element) =>\n (NumericFormat)element.GetValue(OnlyNumericProperty);\n\n\n public static readonly DependencyProperty DefaultValueProperty =\n DependencyProperty.RegisterAttached(\"DefaultValue\", typeof(string), typeof(TextBoxHelper),\n new PropertyMetadata(null, DependencyPropertiesChanged));\n public static void SetDefaultValue(TextBox element, string value) =>\n element.SetValue(DefaultValueProperty, value);\n public static string GetDefaultValue(TextBox element) => (string)element.GetValue(DefaultValueProperty);\n\n\n public static readonly DependencyProperty EvenOddConstraintProperty =\n DependencyProperty.RegisterAttached(\"EvenOddConstraint\", typeof(EvenOddConstraint), typeof(TextBoxHelper),\n new PropertyMetadata(EvenOddConstraint.All, DependencyPropertiesChanged));\n public static void SetEvenOddConstraint(TextBox element, EvenOddConstraint value) =>\n element.SetValue(EvenOddConstraintProperty, value);\n public static EvenOddConstraint GetEvenOddConstraint(TextBox element) =>\n (EvenOddConstraint)element.GetValue(EvenOddConstraintProperty);\n\n #endregion\n\n #region Dependency Properties Methods\n\n private static void DependencyPropertiesChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)\n {\n if (!(d is TextBox textBox))\n throw new Exception(\"Attached property must be used with TextBox.\");\n\n switch (e.Property.Name)\n {\n case \"OnlyNumeric\":\n {\n var castedValue = (NumericFormat?)e.NewValue;\n\n if (castedValue.HasValue)\n {\n textBox.PreviewTextInput += TextBox_PreviewTextInput;\n DataObject.AddPastingHandler(textBox, TextBox_PasteEventHandler);\n }\n else\n {\n textBox.PreviewTextInput -= TextBox_PreviewTextInput;\n DataObject.RemovePastingHandler(textBox, TextBox_PasteEventHandler);\n }\n\n break;\n }\n\n case \"DefaultValue\":\n {\n var castedValue = (string)e.NewValue;\n\n if (castedValue != null)\n {\n textBox.TextChanged += TextBox_TextChanged;\n }\n else\n {\n textBox.TextChanged -= TextBox_TextChanged;\n }\n\n break;\n }\n }\n }\n\n #endregion\n\n private static void TextBox_PreviewTextInput(object sender, TextCompositionEventArgs e)\n {\n var textBox = (TextBox)sender;\n\n string newText;\n\n if (textBox.SelectionLength == 0)\n {\n newText = textBox.Text.Insert(textBox.SelectionStart, e.Text);\n }\n else\n {\n var textAfterDelete = textBox.Text.Remove(textBox.SelectionStart, textBox.SelectionLength);\n\n newText = textAfterDelete.Insert(textBox.SelectionStart, e.Text);\n }\n\n var evenOddConstraint = GetEvenOddConstraint(textBox);\n\n switch (GetOnlyNumeric(textBox))\n {\n case NumericFormat.Double:\n {\n if (double.TryParse(newText, out double number))\n {\n switch (evenOddConstraint)\n {\n case EvenOddConstraint.OnlyEven:\n\n if (number % 2 != 0)\n e.Handled = true;\n else\n e.Handled = false;\n\n break;\n\n case EvenOddConstraint.OnlyOdd:\n\n if (number % 2 == 0)\n e.Handled = true;\n else\n e.Handled = false;\n\n break;\n }\n }\n else\n e.Handled = true;\n\n break;\n }\n\n case NumericFormat.Int:\n {\n if (int.TryParse(newText, out int number))\n {\n switch (evenOddConstraint)\n {\n case EvenOddConstraint.OnlyEven:\n\n if (number % 2 != 0)\n e.Handled = true;\n else\n e.Handled = false;\n\n break;\n\n case EvenOddConstraint.OnlyOdd:\n\n if (number % 2 == 0)\n e.Handled = true;\n else\n e.Handled = false;\n\n break;\n }\n }\n else\n e.Handled = true;\n\n break;\n }\n\n case NumericFormat.Uint:\n {\n if (uint.TryParse(newText, out uint number))\n {\n switch (evenOddConstraint)\n {\n case EvenOddConstraint.OnlyEven:\n\n if (number % 2 != 0)\n e.Handled = true;\n else\n e.Handled = false;\n\n break;\n\n case EvenOddConstraint.OnlyOdd:\n\n if (number % 2 == 0)\n e.Handled = true;\n else\n e.Handled = false;\n\n break;\n }\n }\n else\n e.Handled = true;\n\n break;\n }\n\n case NumericFormat.Natural:\n {\n if (uint.TryParse(newText, out uint number))\n {\n if (number == 0)\n e.Handled = true;\n else\n {\n switch (evenOddConstraint)\n {\n case EvenOddConstraint.OnlyEven:\n\n if (number % 2 != 0)\n e.Handled = true;\n else\n e.Handled = false;\n\n break;\n\n case EvenOddConstraint.OnlyOdd:\n\n if (number % 2 == 0)\n e.Handled = true;\n else\n e.Handled = false;\n\n break;\n }\n }\n }\n else\n e.Handled = true;\n\n break;\n }\n }\n }\n\n private static void TextBox_PasteEventHandler(object sender, DataObjectPastingEventArgs e)\n {\n var textBox = (TextBox)sender;\n\n if (e.DataObject.GetDataPresent(typeof(string)))\n {\n var clipboardText = (string)e.DataObject.GetData(typeof(string));\n\n var newText = textBox.Text.Insert(textBox.SelectionStart, clipboardText);\n\n var evenOddConstraint = GetEvenOddConstraint(textBox);\n\n switch (GetOnlyNumeric(textBox))\n {\n case NumericFormat.Double:\n {\n if (double.TryParse(newText, out double number))\n {\n switch (evenOddConstraint)\n {\n case EvenOddConstraint.OnlyEven:\n\n if (number % 2 != 0)\n e.CancelCommand();\n\n break;\n\n case EvenOddConstraint.OnlyOdd:\n\n if (number % 2 == 0)\n e.CancelCommand();\n\n break;\n }\n }\n else\n e.CancelCommand();\n\n break;\n }\n\n case NumericFormat.Int:\n {\n if (int.TryParse(newText, out int number))\n {\n switch (evenOddConstraint)\n {\n case EvenOddConstraint.OnlyEven:\n\n if (number % 2 != 0)\n e.CancelCommand();\n\n break;\n\n case EvenOddConstraint.OnlyOdd:\n\n if (number % 2 == 0)\n e.CancelCommand();\n\n\n break;\n }\n }\n else\n e.CancelCommand();\n\n break;\n }\n\n case NumericFormat.Uint:\n {\n if (uint.TryParse(newText, out uint number))\n {\n switch (evenOddConstraint)\n {\n case EvenOddConstraint.OnlyEven:\n\n if (number % 2 != 0)\n e.CancelCommand();\n\n break;\n\n case EvenOddConstraint.OnlyOdd:\n\n if (number % 2 == 0)\n e.CancelCommand();\n\n\n break;\n }\n }\n else\n e.CancelCommand();\n\n break;\n }\n\n case NumericFormat.Natural:\n {\n if (uint.TryParse(newText, out uint number))\n {\n if (number == 0)\n e.CancelCommand();\n else\n {\n switch (evenOddConstraint)\n {\n case EvenOddConstraint.OnlyEven:\n\n if (number % 2 != 0)\n e.CancelCommand();\n\n break;\n\n case EvenOddConstraint.OnlyOdd:\n\n if (number % 2 == 0)\n e.CancelCommand();\n\n break;\n }\n }\n }\n else\n {\n e.CancelCommand();\n }\n\n break;\n }\n }\n }\n else\n {\n e.CancelCommand();\n }\n }\n\n private static void TextBox_TextChanged(object sender, TextChangedEventArgs e)\n {\n var textBox = (TextBox)sender;\n\n var defaultValue = GetDefaultValue(textBox);\n\n var evenOddConstraint = GetEvenOddConstraint(textBox);\n\n switch (GetOnlyNumeric(textBox))\n {\n case NumericFormat.Double:\n {\n if (double.TryParse(textBox.Text, out double number))\n {\n switch (evenOddConstraint)\n {\n case EvenOddConstraint.OnlyEven:\n\n if (number % 2 != 0)\n textBox.Text = defaultValue;\n\n break;\n\n case EvenOddConstraint.OnlyOdd:\n\n if (number % 2 == 0)\n textBox.Text = defaultValue;\n\n break;\n }\n }\n else\n textBox.Text = defaultValue;\n\n break;\n }\n\n case NumericFormat.Int:\n {\n if (int.TryParse(textBox.Text, out int number))\n {\n switch (evenOddConstraint)\n {\n case EvenOddConstraint.OnlyEven:\n\n if (number % 2 != 0)\n textBox.Text = defaultValue;\n\n break;\n\n case EvenOddConstraint.OnlyOdd:\n\n if (number % 2 == 0)\n textBox.Text = defaultValue;\n\n break;\n }\n }\n else\n textBox.Text = defaultValue;\n\n break;\n }\n\n case NumericFormat.Uint:\n {\n if (uint.TryParse(textBox.Text, out uint number))\n {\n switch (evenOddConstraint)\n {\n case EvenOddConstraint.OnlyEven:\n\n if (number % 2 != 0)\n textBox.Text = defaultValue;\n\n break;\n\n case EvenOddConstraint.OnlyOdd:\n\n if (number % 2 == 0)\n textBox.Text = defaultValue;\n\n break;\n }\n }\n else\n textBox.Text = defaultValue;\n\n break;\n }\n\n case NumericFormat.Natural:\n {\n if (uint.TryParse(textBox.Text, out uint number))\n {\n if (number == 0)\n textBox.Text = defaultValue;\n else\n {\n switch (evenOddConstraint)\n {\n case EvenOddConstraint.OnlyEven:\n\n if (number % 2 != 0)\n textBox.Text = defaultValue;\n\n break;\n\n case EvenOddConstraint.OnlyOdd:\n\n if (number % 2 == 0)\n textBox.Text = defaultValue;\n\n break;\n }\n }\n }\n else\n {\n textBox.Text = defaultValue;\n }\n\n break;\n }\n }\n }\n}\n"], ["/LLPlayer/FlyleafLib/MediaPlayer/Translation/TranslateLanguage.cs", "using FlyleafLib.MediaPlayer.Translation.Services;\nusing System.Collections.Generic;\nusing System.Reflection;\nusing System.Runtime.Serialization;\n\nnamespace FlyleafLib.MediaPlayer.Translation;\n\npublic class TranslateLanguage\n{\n public static Dictionary Langs { get; } = new()\n {\n // Google: https://cloud.google.com/translate/docs/languages\n // DeepL: https://developers.deepl.com/docs/resources/supported-languages\n [\"ab\"] = new(\"Abkhaz\", \"ab\", TranslateServiceType.GoogleV1),\n [\"af\"] = new(\"Afrikaans\", \"af\", TranslateServiceType.GoogleV1),\n [\"sq\"] = new(\"Albanian\", \"sq\", TranslateServiceType.GoogleV1),\n [\"am\"] = new(\"Amharic\", \"am\", TranslateServiceType.GoogleV1),\n [\"ar\"] = new(\"Arabic\", \"ar\"),\n [\"hy\"] = new(\"Armenian\", \"hy\", TranslateServiceType.GoogleV1),\n [\"as\"] = new(\"Assamese\", \"as\", TranslateServiceType.GoogleV1),\n [\"ay\"] = new(\"Aymara\", \"ay\", TranslateServiceType.GoogleV1),\n [\"az\"] = new(\"Azerbaijani\", \"az\", TranslateServiceType.GoogleV1),\n [\"bm\"] = new(\"Bambara\", \"bm\", TranslateServiceType.GoogleV1),\n [\"ba\"] = new(\"Bashkir\", \"ba\", TranslateServiceType.GoogleV1),\n [\"eu\"] = new(\"Basque\", \"eu\", TranslateServiceType.GoogleV1),\n [\"be\"] = new(\"Belarusian\", \"be\", TranslateServiceType.GoogleV1),\n [\"bn\"] = new(\"Bengali\", \"bn\", TranslateServiceType.GoogleV1),\n [\"bs\"] = new(\"Bosnian\", \"bs\", TranslateServiceType.GoogleV1),\n [\"br\"] = new(\"Breton\", \"br\", TranslateServiceType.GoogleV1),\n [\"bg\"] = new(\"Bulgarian\", \"bg\"),\n [\"ca\"] = new(\"Catalan\", \"ca\", TranslateServiceType.GoogleV1),\n [\"ny\"] = new(\"Chichewa (Nyanja)\", \"ny\", TranslateServiceType.GoogleV1),\n\n // special handling\n [\"zh\"] = new(\"Chinese\", \"zh\"),\n\n [\"cv\"] = new(\"Chuvash\", \"cv\", TranslateServiceType.GoogleV1),\n [\"co\"] = new(\"Corsican\", \"co\", TranslateServiceType.GoogleV1),\n [\"hr\"] = new(\"Croatian\", \"hr\", TranslateServiceType.GoogleV1),\n [\"cs\"] = new(\"Czech\", \"cs\"),\n [\"da\"] = new(\"Danish\", \"da\"),\n [\"dv\"] = new(\"Divehi\", \"dv\", TranslateServiceType.GoogleV1),\n [\"nl\"] = new(\"Dutch\", \"nl\"),\n [\"dz\"] = new(\"Dzongkha\", \"dz\", TranslateServiceType.GoogleV1),\n [\"en\"] = new(\"English\", \"en\"),\n [\"eo\"] = new(\"Esperanto\", \"eo\", TranslateServiceType.GoogleV1),\n [\"et\"] = new(\"Estonian\", \"et\"),\n [\"ee\"] = new(\"Ewe\", \"ee\", TranslateServiceType.GoogleV1),\n [\"fj\"] = new(\"Fijian\", \"fj\", TranslateServiceType.GoogleV1),\n [\"tl\"] = new(\"Tagalog\", \"tl\", TranslateServiceType.GoogleV1),\n [\"fi\"] = new(\"Finnish\", \"fi\"),\n\n // special handling\n [\"fr\"] = new(\"French\", \"fr\"),\n\n [\"fy\"] = new(\"Frisian\", \"fy\", TranslateServiceType.GoogleV1),\n [\"ff\"] = new(\"Fulfulde\", \"ff\", TranslateServiceType.GoogleV1),\n [\"gl\"] = new(\"Galician\", \"gl\", TranslateServiceType.GoogleV1),\n [\"lg\"] = new(\"Ganda (Luganda)\", \"lg\", TranslateServiceType.GoogleV1),\n [\"ka\"] = new(\"Georgian\", \"ka\", TranslateServiceType.GoogleV1),\n [\"de\"] = new(\"German\", \"de\"),\n [\"el\"] = new(\"Greek\", \"el\"),\n [\"gn\"] = new(\"Guarani\", \"gn\", TranslateServiceType.GoogleV1),\n [\"gu\"] = new(\"Gujarati\", \"gu\", TranslateServiceType.GoogleV1),\n [\"ht\"] = new(\"Haitian Creole\", \"ht\", TranslateServiceType.GoogleV1),\n [\"ha\"] = new(\"Hausa\", \"ha\", TranslateServiceType.GoogleV1),\n [\"he\"] = new(\"Hebrew\", \"he\", TranslateServiceType.GoogleV1),\n [\"hi\"] = new(\"Hindi\", \"hi\", TranslateServiceType.GoogleV1),\n [\"hu\"] = new(\"Hungarian\", \"hu\"),\n [\"is\"] = new(\"Icelandic\", \"is\", TranslateServiceType.GoogleV1),\n [\"ig\"] = new(\"Igbo\", \"ig\", TranslateServiceType.GoogleV1),\n [\"id\"] = new(\"Indonesian\", \"id\"),\n [\"ga\"] = new(\"Irish\", \"ga\", TranslateServiceType.GoogleV1),\n [\"it\"] = new(\"Italian\", \"it\"),\n [\"ja\"] = new(\"Japanese\", \"ja\"),\n [\"jv\"] = new(\"Javanese\", \"jv\", TranslateServiceType.GoogleV1),\n [\"kn\"] = new(\"Kannada\", \"kn\", TranslateServiceType.GoogleV1),\n [\"kk\"] = new(\"Kazakh\", \"kk\", TranslateServiceType.GoogleV1),\n [\"km\"] = new(\"Khmer\", \"km\", TranslateServiceType.GoogleV1),\n [\"rw\"] = new(\"Kinyarwanda\", \"rw\", TranslateServiceType.GoogleV1),\n [\"ko\"] = new(\"Korean\", \"ko\"),\n [\"ku\"] = new(\"Kurdish (Kurmanji)\", \"ku\", TranslateServiceType.GoogleV1),\n [\"ky\"] = new(\"Kyrgyz\", \"ky\", TranslateServiceType.GoogleV1),\n [\"lo\"] = new(\"Lao\", \"lo\", TranslateServiceType.GoogleV1),\n [\"la\"] = new(\"Latin\", \"la\", TranslateServiceType.GoogleV1),\n [\"lv\"] = new(\"Latvian\", \"lv\"),\n [\"li\"] = new(\"Limburgan\", \"li\", TranslateServiceType.GoogleV1),\n [\"ln\"] = new(\"Lingala\", \"ln\", TranslateServiceType.GoogleV1),\n [\"lt\"] = new(\"Lithuanian\", \"lt\"),\n [\"lb\"] = new(\"Luxembourgish\", \"lb\", TranslateServiceType.GoogleV1),\n [\"mk\"] = new(\"Macedonian\", \"mk\", TranslateServiceType.GoogleV1),\n [\"mg\"] = new(\"Malagasy\", \"mg\", TranslateServiceType.GoogleV1),\n [\"ms\"] = new(\"Malay\", \"ms\", TranslateServiceType.GoogleV1),\n [\"ml\"] = new(\"Malayalam\", \"ml\", TranslateServiceType.GoogleV1),\n [\"mt\"] = new(\"Maltese\", \"mt\", TranslateServiceType.GoogleV1),\n [\"mi\"] = new(\"Maori\", \"mi\", TranslateServiceType.GoogleV1),\n [\"mr\"] = new(\"Marathi\", \"mr\", TranslateServiceType.GoogleV1),\n [\"mn\"] = new(\"Mongolian\", \"mn\", TranslateServiceType.GoogleV1),\n [\"my\"] = new(\"Myanmar (Burmese)\", \"my\", TranslateServiceType.GoogleV1),\n [\"nr\"] = new(\"Ndebele (South)\", \"nr\", TranslateServiceType.GoogleV1),\n [\"ne\"] = new(\"Nepali\", \"ne\", TranslateServiceType.GoogleV1),\n\n // TODO: L: review handling\n // special handling\n [\"no\"] = new(\"Norwegian\", \"no\"),\n [\"nb\"] = new(\"Norwegian Bokmål\", \"nb\"),\n\n [\"oc\"] = new(\"Occitan\", \"oc\", TranslateServiceType.GoogleV1),\n [\"or\"] = new(\"Odia (Oriya)\", \"or\", TranslateServiceType.GoogleV1),\n [\"om\"] = new(\"Oromo\", \"om\", TranslateServiceType.GoogleV1),\n [\"ps\"] = new(\"Pashto\", \"ps\", TranslateServiceType.GoogleV1),\n [\"fa\"] = new(\"Persian\", \"fa\", TranslateServiceType.GoogleV1),\n [\"pl\"] = new(\"Polish\", \"pl\"),\n\n // special handling\n [\"pt\"] = new(\"Portuguese\", \"pt\"),\n\n [\"pa\"] = new(\"Punjabi\", \"pa\", TranslateServiceType.GoogleV1),\n [\"qu\"] = new(\"Quechua\", \"qu\", TranslateServiceType.GoogleV1),\n [\"ro\"] = new(\"Romanian\", \"ro\"),\n [\"rn\"] = new(\"Rundi\", \"rn\", TranslateServiceType.GoogleV1),\n [\"ru\"] = new(\"Russian\", \"ru\"),\n [\"sm\"] = new(\"Samoan\", \"sm\", TranslateServiceType.GoogleV1),\n [\"sg\"] = new(\"Sango\", \"sg\", TranslateServiceType.GoogleV1),\n [\"sa\"] = new(\"Sanskrit\", \"sa\", TranslateServiceType.GoogleV1),\n [\"gd\"] = new(\"Scots Gaelic\", \"gd\", TranslateServiceType.GoogleV1),\n [\"sr\"] = new(\"Serbian\", \"sr\", TranslateServiceType.GoogleV1),\n [\"st\"] = new(\"Sesotho\", \"st\", TranslateServiceType.GoogleV1),\n [\"sn\"] = new(\"Shona\", \"sn\", TranslateServiceType.GoogleV1),\n [\"sd\"] = new(\"Sindhi\", \"sd\", TranslateServiceType.GoogleV1),\n [\"si\"] = new(\"Sinhala (Sinhalese)\", \"si\", TranslateServiceType.GoogleV1),\n [\"sk\"] = new(\"Slovak\", \"sk\"),\n [\"sl\"] = new(\"Slovenian\", \"sl\"),\n [\"so\"] = new(\"Somali\", \"so\", TranslateServiceType.GoogleV1),\n [\"es\"] = new(\"Spanish\", \"es\"),\n [\"su\"] = new(\"Sundanese\", \"su\", TranslateServiceType.GoogleV1),\n [\"sw\"] = new(\"Swahili\", \"sw\", TranslateServiceType.GoogleV1),\n [\"ss\"] = new(\"Swati\", \"ss\", TranslateServiceType.GoogleV1),\n [\"sv\"] = new(\"Swedish\", \"sv\"),\n [\"tg\"] = new(\"Tajik\", \"tg\", TranslateServiceType.GoogleV1),\n [\"ta\"] = new(\"Tamil\", \"ta\", TranslateServiceType.GoogleV1),\n [\"tt\"] = new(\"Tatar\", \"tt\", TranslateServiceType.GoogleV1),\n [\"te\"] = new(\"Telugu\", \"te\", TranslateServiceType.GoogleV1),\n [\"th\"] = new(\"Thai\", \"th\", TranslateServiceType.GoogleV1),\n [\"ti\"] = new(\"Tigrinya\", \"ti\", TranslateServiceType.GoogleV1),\n [\"ts\"] = new(\"Tsonga\", \"ts\", TranslateServiceType.GoogleV1),\n [\"tn\"] = new(\"Tswana\", \"tn\", TranslateServiceType.GoogleV1),\n [\"tr\"] = new(\"Turkish\", \"tr\"),\n [\"tk\"] = new(\"Turkmen\", \"tk\", TranslateServiceType.GoogleV1),\n [\"ak\"] = new(\"Twi (Akan)\", \"ak\", TranslateServiceType.GoogleV1),\n [\"uk\"] = new(\"Ukrainian\", \"uk\"),\n [\"ur\"] = new(\"Urdu\", \"ur\", TranslateServiceType.GoogleV1),\n [\"ug\"] = new(\"Uyghur\", \"ug\", TranslateServiceType.GoogleV1),\n [\"uz\"] = new(\"Uzbek\", \"uz\", TranslateServiceType.GoogleV1),\n [\"vi\"] = new(\"Vietnamese\", \"vi\", TranslateServiceType.GoogleV1),\n [\"cy\"] = new(\"Welsh\", \"cy\", TranslateServiceType.GoogleV1),\n [\"xh\"] = new(\"Xhosa\", \"xh\", TranslateServiceType.GoogleV1),\n [\"yi\"] = new(\"Yiddish\", \"yi\", TranslateServiceType.GoogleV1),\n [\"yo\"] = new(\"Yoruba\", \"yo\", TranslateServiceType.GoogleV1),\n [\"zu\"] = new(\"Zulu\", \"zu\", TranslateServiceType.GoogleV1),\n };\n\n public TranslateLanguage(string name, string iso6391,\n TranslateServiceType supportedServices =\n TranslateServiceType.GoogleV1 | TranslateServiceType.DeepL)\n {\n // all LLMs support all languages\n supportedServices |= TranslateServiceTypeExtensions.LLMServices;\n\n // DeepL = DeepLX, so flag is same\n if (supportedServices.HasFlag(TranslateServiceType.DeepL))\n {\n supportedServices |= TranslateServiceType.DeepLX;\n }\n\n Name = name;\n ISO6391 = iso6391;\n SupportedServices = supportedServices;\n }\n\n public string Name { get; }\n\n public string ISO6391 { get; }\n\n public TranslateServiceType SupportedServices { get; }\n}\n\n[DataContract]\npublic enum TargetLanguage\n{\n // Supported by Google and DeepL\n [EnumMember(Value = \"ar\")] Arabic,\n [EnumMember(Value = \"bg\")] Bulgarian,\n [EnumMember(Value = \"zh-CN\")] ChineseSimplified,\n [EnumMember(Value = \"zh-TW\")] ChineseTraditional,\n [EnumMember(Value = \"cs\")] Czech,\n [EnumMember(Value = \"da\")] Danish,\n [EnumMember(Value = \"nl\")] Dutch,\n [EnumMember(Value = \"en-US\")] EnglishAmerican,\n [EnumMember(Value = \"en-GB\")] EnglishBritish,\n [EnumMember(Value = \"et\")] Estonian,\n [EnumMember(Value = \"fr-FR\")] French,\n [EnumMember(Value = \"fr-CA\")] FrenchCanadian,\n [EnumMember(Value = \"de\")] German,\n [EnumMember(Value = \"el\")] Greek,\n [EnumMember(Value = \"hu\")] Hungarian,\n [EnumMember(Value = \"id\")] Indonesian,\n [EnumMember(Value = \"it\")] Italian,\n [EnumMember(Value = \"ja\")] Japanese,\n [EnumMember(Value = \"ko\")] Korean,\n [EnumMember(Value = \"lt\")] Lithuanian,\n [EnumMember(Value = \"nb\")] NorwegianBokmål,\n [EnumMember(Value = \"pl\")] Polish,\n [EnumMember(Value = \"pt-PT\")] Portuguese,\n [EnumMember(Value = \"pt-BR\")] PortugueseBrazilian,\n [EnumMember(Value = \"ro\")] Romanian,\n [EnumMember(Value = \"ru\")] Russian,\n [EnumMember(Value = \"sk\")] Slovak,\n [EnumMember(Value = \"sl\")] Slovenian,\n [EnumMember(Value = \"es\")] Spanish,\n [EnumMember(Value = \"sv\")] Swedish,\n [EnumMember(Value = \"tr\")] Turkish,\n [EnumMember(Value = \"uk\")] Ukrainian,\n\n // Only supported in Google\n [EnumMember(Value = \"ab\")] Abkhaz,\n [EnumMember(Value = \"af\")] Afrikaans,\n [EnumMember(Value = \"sq\")] Albanian,\n [EnumMember(Value = \"am\")] Amharic,\n [EnumMember(Value = \"hy\")] Armenian,\n [EnumMember(Value = \"as\")] Assamese,\n [EnumMember(Value = \"ay\")] Aymara,\n [EnumMember(Value = \"az\")] Azerbaijani,\n [EnumMember(Value = \"bm\")] Bambara,\n [EnumMember(Value = \"ba\")] Bashkir,\n [EnumMember(Value = \"eu\")] Basque,\n [EnumMember(Value = \"be\")] Belarusian,\n [EnumMember(Value = \"bn\")] Bengali,\n [EnumMember(Value = \"bs\")] Bosnian,\n [EnumMember(Value = \"br\")] Breton,\n [EnumMember(Value = \"ca\")] Catalan,\n [EnumMember(Value = \"ny\")] Chichewa,\n [EnumMember(Value = \"cv\")] Chuvash,\n [EnumMember(Value = \"co\")] Corsican,\n [EnumMember(Value = \"hr\")] Croatian,\n [EnumMember(Value = \"dv\")] Divehi,\n [EnumMember(Value = \"dz\")] Dzongkha,\n [EnumMember(Value = \"eo\")] Esperanto,\n [EnumMember(Value = \"ee\")] Ewe,\n [EnumMember(Value = \"fj\")] Fijian,\n [EnumMember(Value = \"tl\")] Tagalog,\n [EnumMember(Value = \"fy\")] Frisian,\n [EnumMember(Value = \"ff\")] Fulfulde,\n [EnumMember(Value = \"gl\")] Galician,\n [EnumMember(Value = \"lg\")] Ganda,\n [EnumMember(Value = \"ka\")] Georgian,\n [EnumMember(Value = \"gn\")] Guarani,\n [EnumMember(Value = \"gu\")] Gujarati,\n [EnumMember(Value = \"ht\")] Haitian,\n [EnumMember(Value = \"ha\")] Hausa,\n [EnumMember(Value = \"he\")] Hebrew,\n [EnumMember(Value = \"hi\")] Hindi,\n [EnumMember(Value = \"is\")] Icelandic,\n [EnumMember(Value = \"ig\")] Igbo,\n [EnumMember(Value = \"ga\")] Irish,\n [EnumMember(Value = \"jv\")] Javanese,\n [EnumMember(Value = \"kn\")] Kannada,\n [EnumMember(Value = \"kk\")] Kazakh,\n [EnumMember(Value = \"km\")] Khmer,\n [EnumMember(Value = \"rw\")] Kinyarwanda,\n [EnumMember(Value = \"ku\")] Kurdish,\n [EnumMember(Value = \"ky\")] Kyrgyz,\n [EnumMember(Value = \"lo\")] Lao,\n [EnumMember(Value = \"la\")] Latin,\n [EnumMember(Value = \"li\")] Limburgan,\n [EnumMember(Value = \"ln\")] Lingala,\n [EnumMember(Value = \"lb\")] Luxembourgish,\n [EnumMember(Value = \"mk\")] Macedonian,\n [EnumMember(Value = \"mg\")] Malagasy,\n [EnumMember(Value = \"ms\")] Malay,\n [EnumMember(Value = \"ml\")] Malayalam,\n [EnumMember(Value = \"mt\")] Maltese,\n [EnumMember(Value = \"mi\")] Maori,\n [EnumMember(Value = \"mr\")] Marathi,\n [EnumMember(Value = \"mn\")] Mongolian,\n [EnumMember(Value = \"my\")] Myanmar,\n [EnumMember(Value = \"nr\")] Ndebele,\n [EnumMember(Value = \"ne\")] Nepali,\n [EnumMember(Value = \"oc\")] Occitan,\n [EnumMember(Value = \"or\")] Odia,\n [EnumMember(Value = \"om\")] Oromo,\n [EnumMember(Value = \"ps\")] Pashto,\n [EnumMember(Value = \"fa\")] Persian,\n [EnumMember(Value = \"pa\")] Punjabi,\n [EnumMember(Value = \"qu\")] Quechua,\n [EnumMember(Value = \"rn\")] Rundi,\n [EnumMember(Value = \"sm\")] Samoan,\n [EnumMember(Value = \"sg\")] Sango,\n [EnumMember(Value = \"sa\")] Sanskrit,\n [EnumMember(Value = \"gd\")] ScotsGaelic,\n [EnumMember(Value = \"sr\")] Serbian,\n [EnumMember(Value = \"st\")] Sesotho,\n [EnumMember(Value = \"sn\")] Shona,\n [EnumMember(Value = \"sd\")] Sindhi,\n [EnumMember(Value = \"si\")] Sinhala,\n [EnumMember(Value = \"so\")] Somali,\n [EnumMember(Value = \"su\")] Sundanese,\n [EnumMember(Value = \"sw\")] Swahili,\n [EnumMember(Value = \"ss\")] Swati,\n [EnumMember(Value = \"tg\")] Tajik,\n [EnumMember(Value = \"ta\")] Tamil,\n [EnumMember(Value = \"tt\")] Tatar,\n [EnumMember(Value = \"te\")] Telugu,\n [EnumMember(Value = \"th\")] Thai,\n [EnumMember(Value = \"ti\")] Tigrinya,\n [EnumMember(Value = \"ts\")] Tsonga,\n [EnumMember(Value = \"tn\")] Tswana,\n [EnumMember(Value = \"tk\")] Turkmen,\n [EnumMember(Value = \"ak\")] Twi,\n [EnumMember(Value = \"ur\")] Urdu,\n [EnumMember(Value = \"ug\")] Uyghur,\n [EnumMember(Value = \"uz\")] Uzbek,\n [EnumMember(Value = \"vi\")] Vietnamese,\n [EnumMember(Value = \"cy\")] Welsh,\n [EnumMember(Value = \"xh\")] Xhosa,\n [EnumMember(Value = \"yi\")] Yiddish,\n [EnumMember(Value = \"yo\")] Yoruba,\n [EnumMember(Value = \"zu\")] Zulu,\n}\n\npublic static class TargetLanguageExtensions\n{\n public static string DisplayName(this TargetLanguage targetLang)\n {\n return targetLang switch\n {\n TargetLanguage.EnglishAmerican => \"English (American)\",\n TargetLanguage.EnglishBritish => \"English (British)\",\n TargetLanguage.French => \"French\",\n TargetLanguage.FrenchCanadian => \"French (Canadian)\",\n TargetLanguage.Portuguese => \"Portuguese\",\n TargetLanguage.PortugueseBrazilian => \"Portuguese (Brazilian)\",\n TargetLanguage.ChineseSimplified => \"Chinese (Simplified)\",\n TargetLanguage.ChineseTraditional => \"Chinese (Traditional)\",\n TargetLanguage.NorwegianBokmål => \"Norwegian Bokmål\",\n\n TargetLanguage.Chichewa => \"Chichewa (Nyanja)\",\n TargetLanguage.Ganda => \"Ganda (Luganda)\",\n TargetLanguage.Haitian => \"Haitian Creole\",\n TargetLanguage.Kurdish => \"Kurdish (Kurmanji)\",\n TargetLanguage.Myanmar => \"Myanmar (Burmese)\",\n TargetLanguage.Ndebele => \"Ndebele (South)\",\n TargetLanguage.Odia => \"Odia (Oriya)\",\n TargetLanguage.ScotsGaelic => \"Scots Gaelic\",\n TargetLanguage.Sinhala => \"Sinhala (Sinhalese)\",\n TargetLanguage.Twi => \"Twi (Akan)\",\n _ => targetLang.ToString()\n };\n }\n\n public static TranslateServiceType SupportedServiceType(this TargetLanguage targetLang)\n {\n string iso6391 = targetLang.ToISO6391();\n\n TranslateLanguage lang = TranslateLanguage.Langs[iso6391];\n\n return lang.SupportedServices;\n }\n\n public static string ToISO6391(this TargetLanguage targetLang)\n {\n // Get EnumMember language code\n Type type = targetLang.GetType();\n MemberInfo[] memInfo = type.GetMember(targetLang.ToString());\n object[] attributes = memInfo[0].GetCustomAttributes(typeof(EnumMemberAttribute), false);\n string enumValue = ((EnumMemberAttribute)attributes[0]).Value;\n\n // ISO6391 code is the first half of a hyphen\n if (enumValue != null && enumValue.Contains(\"-\"))\n {\n return enumValue.Split('-')[0];\n }\n\n return enumValue;\n }\n\n public static TargetLanguage? ToTargetLanguage(this Language lang)\n {\n // language with region first\n switch (lang.ISO6391)\n {\n case \"en\" when lang.CultureName == \"en-GB\":\n return TargetLanguage.EnglishBritish;\n case \"en\":\n return TargetLanguage.EnglishAmerican;\n\n case \"zh\" when lang.CultureName.StartsWith(\"zh-Hant\"): // zh-Hant, zh-Hant-XX\n return TargetLanguage.ChineseTraditional;\n case \"zh\": // zh-Hans, zh-Hans-XX, or others\n return TargetLanguage.ChineseSimplified;\n\n case \"fr\" when lang.CultureName == \"fr-CA\":\n return TargetLanguage.FrenchCanadian;\n case \"fr\":\n return TargetLanguage.French;\n\n case \"pt\" when lang.CultureName == \"pt-BR\":\n return TargetLanguage.PortugueseBrazilian;\n case \"pt\":\n return TargetLanguage.Portuguese;\n }\n\n // other languages with no region\n foreach (var tl in Enum.GetValues())\n {\n if (tl.ToISO6391() == lang.ISO6391)\n {\n return tl;\n }\n }\n\n // not match\n return null;\n }\n}\n"], ["/LLPlayer/FlyleafLib/MediaPlayer/Translation/Services/ITranslateService.cs", "using System.ComponentModel;\nusing System.Threading;\nusing System.Threading.Tasks;\n\nnamespace FlyleafLib.MediaPlayer.Translation.Services;\n\npublic interface ITranslateService : IDisposable\n{\n TranslateServiceType ServiceType { get; }\n\n /// \n /// Initialize\n /// \n /// \n /// \n /// when language is not supported or configured properly\n void Initialize(Language src, TargetLanguage target);\n\n /// \n /// TranslateAsync\n /// \n /// \n /// \n /// \n /// \n /// when translation is failed\n /// \n Task TranslateAsync(string text, CancellationToken token);\n}\n\n[Flags]\npublic enum TranslateServiceType\n{\n /// \n /// Google V1.\n /// \n [Description(\"Google V1\")]\n GoogleV1 = 1 << 0,\n\n /// \n /// DeepL\n /// \n [Description(nameof(DeepL))]\n DeepL = 1 << 1,\n\n /// \n /// DeepLX\n /// https://github.com/OwO-Network/DeepLX\n /// \n [Description(nameof(DeepLX))]\n DeepLX = 1 << 2,\n\n /// \n /// Ollama\n /// \n [Description(nameof(Ollama))]\n Ollama = 1 << 3,\n\n /// \n /// LM Studio\n /// \n [Description(\"LM Studio\")]\n LMStudio = 1 << 4,\n\n /// \n /// KoboldCpp\n /// \n [Description(nameof(KoboldCpp))]\n KoboldCpp = 1 << 5,\n\n /// \n /// OpenAI (ChatGPT)\n /// \n [Description(nameof(OpenAI))]\n OpenAI = 1 << 6,\n\n /// \n /// OpenAI compatible\n /// \n [Description(\"OpenAI Like\")]\n OpenAILike = 1 << 7,\n\n /// \n /// Anthropic Claude\n /// \n [Description(nameof(Claude))]\n Claude = 1 << 8,\n\n /// \n /// LiteLLM\n /// \n [Description(nameof(LiteLLM))]\n LiteLLM = 1 << 9,\n}\n\npublic static class TranslateServiceTypeExtensions\n{\n public static TranslateServiceType LLMServices =>\n TranslateServiceType.Ollama |\n TranslateServiceType.LMStudio |\n TranslateServiceType.KoboldCpp |\n TranslateServiceType.OpenAI |\n TranslateServiceType.OpenAILike |\n TranslateServiceType.Claude |\n TranslateServiceType.LiteLLM;\n\n public static bool IsLLM(this TranslateServiceType serviceType)\n {\n return LLMServices.HasFlag(serviceType);\n }\n\n public static ITranslateSettings DefaultSettings(this TranslateServiceType serviceType)\n {\n switch (serviceType)\n {\n case TranslateServiceType.GoogleV1:\n return new GoogleV1TranslateSettings();\n case TranslateServiceType.DeepL:\n return new DeepLTranslateSettings();\n case TranslateServiceType.DeepLX:\n return new DeepLXTranslateSettings();\n case TranslateServiceType.Ollama:\n return new OllamaTranslateSettings();\n case TranslateServiceType.LMStudio:\n return new LMStudioTranslateSettings();\n case TranslateServiceType.KoboldCpp:\n return new KoboldCppTranslateSettings();\n case TranslateServiceType.OpenAI:\n return new OpenAITranslateSettings();\n case TranslateServiceType.OpenAILike:\n return new OpenAILikeTranslateSettings();\n case TranslateServiceType.Claude:\n return new ClaudeTranslateSettings();\n case TranslateServiceType.LiteLLM:\n return new LiteLLMTranslateSettings();\n }\n\n throw new InvalidOperationException();\n }\n}\n\npublic static class TranslateServiceHelper\n{\n /// \n /// TryGetLanguage\n /// \n /// \n /// \n /// \n /// \n /// \n public static (TranslateLanguage srcLang, TranslateLanguage targetLang) TryGetLanguage(this ITranslateService service, Language src, TargetLanguage target)\n {\n string iso6391 = src.ISO6391;\n\n // TODO: L: Allow the user to choose auto-detection by translation provider?\n if (src == Language.Unknown)\n {\n throw new TranslationConfigException(\"source language are unknown\");\n }\n\n if (src.ISO6391 == target.ToISO6391())\n {\n // Only chinese allow translation between regions (Simplified <-> Traditional)\n // Portuguese, French, and English are not permitted.\n // TODO: L: review this validation?\n if (target is not (TargetLanguage.ChineseSimplified or TargetLanguage.ChineseTraditional))\n {\n throw new TranslationConfigException(\"source and target language are same\");\n }\n }\n\n if (!TranslateLanguage.Langs.TryGetValue(iso6391, out TranslateLanguage srcLang))\n {\n throw new TranslationConfigException($\"source language is not supported: {src.TopEnglishName}\");\n }\n\n if (!srcLang.SupportedServices.HasFlag(service.ServiceType))\n {\n throw new TranslationConfigException($\"source language is not supported by {service.ServiceType}: {src.TopEnglishName}\");\n }\n\n if (!TranslateLanguage.Langs.TryGetValue(target.ToISO6391(), out TranslateLanguage targetLang))\n {\n throw new TranslationConfigException($\"target language is not supported: {target.ToString()}\");\n }\n\n if (!targetLang.SupportedServices.HasFlag(service.ServiceType))\n {\n throw new TranslationConfigException($\"target language is not supported by {service.ServiceType}: {src.TopEnglishName}\");\n }\n\n return (srcLang, targetLang);\n }\n}\n\npublic class TranslationException : Exception\n{\n public TranslationException()\n {\n }\n\n public TranslationException(string message)\n : base(message)\n {\n }\n\n public TranslationException(string message, Exception inner)\n : base(message, inner)\n {\n }\n}\n\npublic class TranslationConfigException : Exception\n{\n public TranslationConfigException()\n {\n }\n\n public TranslationConfigException(string message)\n : base(message)\n {\n }\n\n public TranslationConfigException(string message, Exception inner)\n : base(message, inner)\n {\n }\n}\n"], ["/LLPlayer/LLPlayer/Services/PDICSender.cs", "using System.Diagnostics;\nusing System.IO;\nusing System.Text;\n\nnamespace LLPlayer.Services;\n\npublic class PipeClient : IDisposable\n{\n private Process _proc;\n\n public PipeClient(string pipePath)\n {\n _proc = new Process\n {\n StartInfo = new ProcessStartInfo()\n {\n RedirectStandardOutput = true,\n RedirectStandardInput = true,\n RedirectStandardError = true,\n FileName = pipePath,\n CreateNoWindow = true,\n }\n };\n _proc.Start();\n }\n\n public async Task SendMessage(string message)\n {\n Debug.WriteLine(message);\n //byte[] bytes = JsonSerializer.SerializeToUtf8Bytes(message);\n\n // Enclose double quotes before and after since it is sent as a JSON string\n byte[] bytes = Encoding.UTF8.GetBytes('\"' + message + '\"');\n\n var length = BitConverter.GetBytes(bytes.Length);\n await _proc.StandardInput.BaseStream.WriteAsync(length, 0, length.Length);\n await _proc.StandardInput.BaseStream.WriteAsync(bytes, 0, bytes.Length);\n await _proc.StandardInput.BaseStream.FlushAsync();\n }\n\n public void Dispose()\n {\n _proc.Kill();\n _proc.WaitForExit();\n }\n}\n\npublic class PDICSender : IDisposable\n{\n private readonly PipeClient _pipeClient;\n public FlyleafManager FL { get; }\n\n public PDICSender(FlyleafManager fl)\n {\n FL = fl;\n\n string? exePath = FL.Config.Subs.PDICPipeExecutablePath;\n\n if (!File.Exists(exePath))\n {\n throw new FileNotFoundException($\"PDIC executable is not set correctly: {exePath}\");\n }\n\n _pipeClient = new PipeClient(exePath);\n }\n\n public async void Dispose()\n {\n await _pipeClient.SendMessage(\"p:Dictionary,Close,\");\n _pipeClient.Dispose();\n }\n\n public async Task Connect()\n {\n await _pipeClient.SendMessage(\"p:Dictionary,Open,\");\n }\n\n // Send the same way as Firepop\n // webextension native extensions\n // ref: https://developer.mozilla.org/en-US/docs/Mozilla/Add-ons/WebExtensions/Native_messaging\n\n // See Firepop source\n public async Task SendWithPipe(string sentence, int offset)\n {\n try\n {\n await _pipeClient.SendMessage($\"p:Dictionary,SetUrl,{App.Name}\");\n await _pipeClient.SendMessage($\"p:Dictionary,PopupSearch3,{offset},{sentence}\");\n\n // Incremental search\n //await _pipeClient.SendMessage($\"p:Simulate,InputWord3,word\");\n\n return 0;\n }\n catch (Exception e)\n {\n Debug.WriteLine(e.ToString());\n return -1;\n }\n }\n}\n"], ["/LLPlayer/LLPlayer/Services/WhisperCppModelLoader.cs", "using System.IO;\nusing FlyleafLib;\nusing Whisper.net.Ggml;\n\nnamespace LLPlayer.Services;\n\npublic class WhisperCppModelLoader\n{\n public static List LoadAllModels()\n {\n WhisperConfig.EnsureModelsDirectory();\n\n List models = Enum.GetValues()\n .Select(t => new WhisperCppModel { Model = t, })\n .ToList();\n\n foreach (WhisperCppModel model in models)\n {\n // Update download status\n string path = model.ModelFilePath;\n if (File.Exists(path))\n {\n model.Size = new FileInfo(path).Length;\n }\n }\n\n return models;\n }\n\n public static List LoadDownloadedModels()\n {\n return LoadAllModels()\n .Where(m => m.Downloaded)\n .ToList();\n }\n}\n"], ["/LLPlayer/WpfColorFontDialog/ColorFontChooser.xaml.cs", "using System;\nusing System.Collections.Generic;\nusing System.Linq;\nusing System.Text;\nusing System.Windows;\nusing System.Windows.Controls;\nusing System.Windows.Data;\nusing System.Windows.Documents;\nusing System.Windows.Input;\nusing System.Windows.Media;\nusing System.Windows.Media.Imaging;\nusing System.Windows.Navigation;\nusing System.Windows.Shapes;\n\nnamespace WpfColorFontDialog\n{\n /// \n /// Interaction logic for ColorFontChooser.xaml\n /// \n public partial class ColorFontChooser : UserControl\n {\n public FontInfo SelectedFont\n {\n get\n {\n return new FontInfo(this.txtSampleText.FontFamily, this.txtSampleText.FontSize, this.txtSampleText.FontStyle, this.txtSampleText.FontStretch, this.txtSampleText.FontWeight, this.colorPicker.SelectedColor.Brush);\n }\n }\n\n\n\n public bool ShowColorPicker\n {\n get { return (bool)GetValue(ShowColorPickerProperty); }\n set { SetValue(ShowColorPickerProperty, value); }\n }\n\n // Using a DependencyProperty as the backing store for ShowColorPicker. This enables animation, styling, binding, etc...\n public static readonly DependencyProperty ShowColorPickerProperty =\n DependencyProperty.Register(\"ShowColorPicker\", typeof(bool), typeof(ColorFontChooser), new PropertyMetadata(true, ShowColorPickerPropertyCallback));\n\n\n public bool AllowArbitraryFontSizes\n {\n get { return (bool)GetValue(AllowArbitraryFontSizesProperty); }\n set { SetValue(AllowArbitraryFontSizesProperty, value); }\n }\n\n // Using a DependencyProperty as the backing store for AllowArbitraryFontSizes. This enables animation, styling, binding, etc...\n public static readonly DependencyProperty AllowArbitraryFontSizesProperty =\n DependencyProperty.Register(\"AllowArbitraryFontSizes\", typeof(bool), typeof(ColorFontChooser), new PropertyMetadata(true, AllowArbitraryFontSizesPropertyCallback));\n\n\n public bool PreviewFontInFontList\n {\n get { return (bool)GetValue(PreviewFontInFontListProperty); }\n set { SetValue(PreviewFontInFontListProperty, value); }\n }\n\n // Using a DependencyProperty as the backing store for PreviewFontInFontList. This enables animation, styling, binding, etc...\n public static readonly DependencyProperty PreviewFontInFontListProperty =\n DependencyProperty.Register(\"PreviewFontInFontList\", typeof(bool), typeof(ColorFontChooser), new PropertyMetadata(true, PreviewFontInFontListPropertyCallback));\n\n\n public ColorFontChooser()\n {\n InitializeComponent();\n this.groupBoxColorPicker.Visibility = ShowColorPicker ? Visibility.Visible : Visibility.Collapsed;\n this.tbFontSize.IsEnabled = AllowArbitraryFontSizes;\n lstFamily.ItemTemplate = PreviewFontInFontList ? (DataTemplate)Resources[\"fontFamilyData\"] : (DataTemplate)Resources[\"fontFamilyDataWithoutPreview\"];\n }\n private static void PreviewFontInFontListPropertyCallback(DependencyObject d, DependencyPropertyChangedEventArgs e)\n {\n ColorFontChooser chooser = d as ColorFontChooser;\n if (e.NewValue == null)\n return;\n if ((bool)e.NewValue == true)\n chooser.lstFamily.ItemTemplate = chooser.Resources[\"fontFamilyData\"] as DataTemplate;\n else\n chooser.lstFamily.ItemTemplate = chooser.Resources[\"fontFamilyDataWithoutPreview\"] as DataTemplate;\n }\n private static void AllowArbitraryFontSizesPropertyCallback(DependencyObject d, DependencyPropertyChangedEventArgs e)\n {\n ColorFontChooser chooser = d as ColorFontChooser;\n if (e.NewValue == null)\n return;\n\n chooser.tbFontSize.IsEnabled = (bool)e.NewValue;\n\n }\n private static void ShowColorPickerPropertyCallback(DependencyObject d, DependencyPropertyChangedEventArgs e)\n {\n ColorFontChooser chooser = d as ColorFontChooser;\n if (e.NewValue == null)\n return;\n if ((bool)e.NewValue == true)\n chooser.groupBoxColorPicker.Visibility = Visibility.Visible;\n else\n chooser.groupBoxColorPicker.Visibility = Visibility.Collapsed;\n }\n\n private void colorPicker_ColorChanged(object sender, RoutedEventArgs e)\n {\n this.txtSampleText.Foreground = this.colorPicker.SelectedColor.Brush;\n }\n\n private void lstFontSizes_SelectionChanged(object sender, SelectionChangedEventArgs e)\n {\n if (this.tbFontSize != null && this.lstFontSizes.SelectedItem != null)\n {\n this.tbFontSize.Text = this.lstFontSizes.SelectedItem.ToString();\n }\n }\n\n private void tbFontSize_PreviewTextInput(object sender, TextCompositionEventArgs e)\n {\n e.Handled = !TextBoxTextAllowed(e.Text);\n }\n\n private void tbFontSize_Pasting(object sender, DataObjectPastingEventArgs e)\n {\n if (e.DataObject.GetDataPresent(typeof(String)))\n {\n String Text1 = (String)e.DataObject.GetData(typeof(String));\n if (!TextBoxTextAllowed(Text1)) e.CancelCommand();\n }\n else\n {\n e.CancelCommand();\n }\n }\n private Boolean TextBoxTextAllowed(String Text2)\n {\n return Array.TrueForAll(Text2.ToCharArray(),\n delegate (Char c) { return Char.IsDigit(c) || Char.IsControl(c); });\n }\n\n private void tbFontSize_LostFocus(object sender, RoutedEventArgs e)\n {\n if (tbFontSize.Text.Length == 0)\n {\n if (this.lstFontSizes.SelectedItem == null)\n {\n lstFontSizes.SelectedIndex = 0;\n }\n tbFontSize.Text = this.lstFontSizes.SelectedItem.ToString();\n\n }\n }\n\n private void tbFontSize_TextChanged(object sender, TextChangedEventArgs e)\n {\n foreach (int size in this.lstFontSizes.Items)\n {\n if (size.ToString() == tbFontSize.Text)\n {\n lstFontSizes.SelectedItem = size;\n lstFontSizes.ScrollIntoView(size);\n return;\n }\n }\n this.lstFontSizes.SelectedItem = null;\n }\n }\n}\n"], ["/LLPlayer/FlyleafLib/Engine/WhisperLanguage.cs", "using System.Collections.Generic;\nusing System.Linq;\nusing System.Text;\n\nnamespace FlyleafLib;\n\npublic class WhisperLanguage : IEquatable\n{\n public string Code { get; set; }\n public string EnglishName { get; set; }\n\n // https://github.com/ggerganov/whisper.cpp/blob/d682e150908e10caa4c15883c633d7902d385237/src/whisper.cpp#L248-L348\n private static readonly Dictionary CodeToLanguage = new()\n {\n {\"en\", \"english\"},\n {\"zh\", \"chinese\"},\n {\"de\", \"german\"},\n {\"es\", \"spanish\"},\n {\"ru\", \"russian\"},\n {\"ko\", \"korean\"},\n {\"fr\", \"french\"},\n {\"ja\", \"japanese\"},\n {\"pt\", \"portuguese\"},\n {\"tr\", \"turkish\"},\n {\"pl\", \"polish\"},\n {\"ca\", \"catalan\"},\n {\"nl\", \"dutch\"},\n {\"ar\", \"arabic\"},\n {\"sv\", \"swedish\"},\n {\"it\", \"italian\"},\n {\"id\", \"indonesian\"},\n {\"hi\", \"hindi\"},\n {\"fi\", \"finnish\"},\n {\"vi\", \"vietnamese\"},\n {\"he\", \"hebrew\"},\n {\"uk\", \"ukrainian\"},\n {\"el\", \"greek\"},\n {\"ms\", \"malay\"},\n {\"cs\", \"czech\"},\n {\"ro\", \"romanian\"},\n {\"da\", \"danish\"},\n {\"hu\", \"hungarian\"},\n {\"ta\", \"tamil\"},\n {\"no\", \"norwegian\"},\n {\"th\", \"thai\"},\n {\"ur\", \"urdu\"},\n {\"hr\", \"croatian\"},\n {\"bg\", \"bulgarian\"},\n {\"lt\", \"lithuanian\"},\n {\"la\", \"latin\"},\n {\"mi\", \"maori\"},\n {\"ml\", \"malayalam\"},\n {\"cy\", \"welsh\"},\n {\"sk\", \"slovak\"},\n {\"te\", \"telugu\"},\n {\"fa\", \"persian\"},\n {\"lv\", \"latvian\"},\n {\"bn\", \"bengali\"},\n {\"sr\", \"serbian\"},\n {\"az\", \"azerbaijani\"},\n {\"sl\", \"slovenian\"},\n {\"kn\", \"kannada\"},\n {\"et\", \"estonian\"},\n {\"mk\", \"macedonian\"},\n {\"br\", \"breton\"},\n {\"eu\", \"basque\"},\n {\"is\", \"icelandic\"},\n {\"hy\", \"armenian\"},\n {\"ne\", \"nepali\"},\n {\"mn\", \"mongolian\"},\n {\"bs\", \"bosnian\"},\n {\"kk\", \"kazakh\"},\n {\"sq\", \"albanian\"},\n {\"sw\", \"swahili\"},\n {\"gl\", \"galician\"},\n {\"mr\", \"marathi\"},\n {\"pa\", \"punjabi\"},\n {\"si\", \"sinhala\"},\n {\"km\", \"khmer\"},\n {\"sn\", \"shona\"},\n {\"yo\", \"yoruba\"},\n {\"so\", \"somali\"},\n {\"af\", \"afrikaans\"},\n {\"oc\", \"occitan\"},\n {\"ka\", \"georgian\"},\n {\"be\", \"belarusian\"},\n {\"tg\", \"tajik\"},\n {\"sd\", \"sindhi\"},\n {\"gu\", \"gujarati\"},\n {\"am\", \"amharic\"},\n {\"yi\", \"yiddish\"},\n {\"lo\", \"lao\"},\n {\"uz\", \"uzbek\"},\n {\"fo\", \"faroese\"},\n {\"ht\", \"haitian creole\"},\n {\"ps\", \"pashto\"},\n {\"tk\", \"turkmen\"},\n {\"nn\", \"nynorsk\"},\n {\"mt\", \"maltese\"},\n {\"sa\", \"sanskrit\"},\n {\"lb\", \"luxembourgish\"},\n {\"my\", \"myanmar\"},\n {\"bo\", \"tibetan\"},\n {\"tl\", \"tagalog\"},\n {\"mg\", \"malagasy\"},\n {\"as\", \"assamese\"},\n {\"tt\", \"tatar\"},\n {\"haw\", \"hawaiian\"},\n {\"ln\", \"lingala\"},\n {\"ha\", \"hausa\"},\n {\"ba\", \"bashkir\"},\n {\"jw\", \"javanese\"},\n {\"su\", \"sundanese\"},\n {\"yue\", \"cantonese\"},\n };\n\n // https://github.com/Purfview/whisper-standalone-win/issues/430#issuecomment-2743029023\n // https://github.com/openai/whisper/blob/517a43ecd132a2089d85f4ebc044728a71d49f6e/whisper/tokenizer.py#L10-L110\n public static Dictionary LanguageToCode { get; } = CodeToLanguage.ToDictionary(kv => kv.Value, kv => kv.Key, StringComparer.OrdinalIgnoreCase);\n\n public static List GetWhisperLanguages()\n {\n return CodeToLanguage.Select(kv => new WhisperLanguage\n {\n Code = kv.Key,\n EnglishName = UpperFirstOfWords(kv.Value)\n }).OrderBy(l => l.EnglishName).ToList();\n }\n\n private static string UpperFirstOfWords(string input)\n {\n if (string.IsNullOrEmpty(input))\n return input;\n\n StringBuilder result = new();\n bool isNewWord = true;\n\n foreach (char c in input)\n {\n if (char.IsWhiteSpace(c))\n {\n isNewWord = true;\n result.Append(c);\n }\n else if (isNewWord)\n {\n result.Append(char.ToUpper(c));\n isNewWord = false;\n }\n else\n {\n result.Append(c);\n }\n }\n\n return result.ToString();\n }\n\n public bool Equals(WhisperLanguage other)\n {\n if (other is null) return false;\n if (ReferenceEquals(this, other)) return true;\n return Code == other.Code;\n }\n\n public override bool Equals(object obj) => obj is WhisperLanguage o && Equals(o);\n\n public override int GetHashCode()\n {\n return (Code != null ? Code.GetHashCode() : 0);\n }\n}\n"], ["/LLPlayer/FlyleafLib/MediaFramework/MediaPlaylist/PLSPlaylist.cs", "using System.Collections.Generic;\nusing System.Runtime.InteropServices;\nusing System.Text;\n\nnamespace FlyleafLib.MediaFramework.MediaPlaylist;\n\npublic class PLSPlaylist\n{\n [DllImport(\"kernel32\")]\n private static extern long WritePrivateProfileString(string name, string key, string val, string filePath);\n [DllImport(\"kernel32\")]\n private static extern int GetPrivateProfileString(string section, string key, string def, StringBuilder retVal, int size, string filePath);\n\n public string path;\n\n public static List Parse(string filename)\n {\n List items = new();\n string res;\n int entries = 1000;\n\n if ((res = GetINIAttribute(\"playlist\", \"NumberOfEntries\", filename)) != null)\n entries = int.Parse(res);\n\n for (int i=1; i<=entries; i++)\n {\n if ((res = GetINIAttribute(\"playlist\", $\"File{i}\", filename)) == null)\n break;\n\n PLSPlaylistItem item = new() { Url = res };\n\n if ((res = GetINIAttribute(\"playlist\", $\"Title{i}\", filename)) != null)\n item.Title = res;\n\n if ((res = GetINIAttribute(\"playlist\", $\"Length{i}\", filename)) != null)\n item.Duration = int.Parse(res);\n\n items.Add(item);\n }\n\n return items;\n }\n\n public static string GetINIAttribute(string name, string key, string path)\n {\n StringBuilder sb = new(255);\n return GetPrivateProfileString(name, key, \"\", sb, 255, path) > 0\n ? sb.ToString() : null;\n }\n}\n\npublic class PLSPlaylistItem\n{\n public int Duration { get; set; }\n public string Title { get; set; }\n public string Url { get; set; }\n}\n"], ["/LLPlayer/LLPlayer/Views/SettingsDialog.xaml.cs", "using System.Windows;\nusing System.Windows.Controls;\nusing LLPlayer.Controls.Settings;\nusing LLPlayer.ViewModels;\n\nnamespace LLPlayer.Views;\n\npublic partial class SettingsDialog : UserControl\n{\n public SettingsDialog()\n {\n InitializeComponent();\n\n DataContext = ((App)Application.Current).Container.Resolve();\n }\n\n private void SettingsTreeView_OnSelectedItemChanged(object sender, RoutedPropertyChangedEventArgs e)\n {\n if (SettingsContent == null)\n {\n return;\n }\n\n if (SettingsTreeView.SelectedItem is TreeViewItem selectedItem)\n {\n string? tag = selectedItem.Tag as string;\n switch (tag)\n {\n case nameof(SettingsPlayer):\n SettingsContent.Content = new SettingsPlayer();\n break;\n\n case nameof(SettingsAudio):\n SettingsContent.Content = new SettingsAudio();\n break;\n\n case nameof(SettingsVideo):\n SettingsContent.Content = new SettingsVideo();\n break;\n\n case nameof(SettingsSubtitles):\n SettingsContent.Content = new SettingsSubtitles();\n break;\n\n case nameof(SettingsSubtitlesPS):\n SettingsContent.Content = new SettingsSubtitlesPS();\n break;\n\n case nameof(SettingsSubtitlesASR):\n SettingsContent.Content = new SettingsSubtitlesASR();\n break;\n\n case nameof(SettingsSubtitlesOCR):\n SettingsContent.Content = new SettingsSubtitlesOCR();\n break;\n\n case nameof(SettingsSubtitlesTrans):\n SettingsContent.Content = new SettingsSubtitlesTrans();\n break;\n\n case nameof(SettingsSubtitlesAction):\n SettingsContent.Content = new SettingsSubtitlesAction();\n break;\n\n case nameof(SettingsKeys):\n SettingsContent.Content = new SettingsKeys();\n break;\n\n case nameof(SettingsKeysOffset):\n SettingsContent.Content = new SettingsKeysOffset();\n break;\n\n case nameof(SettingsMouse):\n SettingsContent.Content = new SettingsMouse();\n break;\n\n case nameof(SettingsThemes):\n SettingsContent.Content = new SettingsThemes();\n break;\n\n case nameof(SettingsPlugins):\n SettingsContent.Content = new SettingsPlugins();\n break;\n\n case nameof(SettingsAbout):\n SettingsContent.Content = new SettingsAbout();\n break;\n }\n }\n }\n}\n"], ["/LLPlayer/FlyleafLib/Engine/Engine.FFmpeg.cs", "namespace FlyleafLib;\n\npublic class FFmpegEngine\n{\n public string Folder { get; private set; }\n public string Version { get; private set; }\n\n const int AV_LOG_BUFFER_SIZE = 5 * 1024;\n internal AVRational AV_TIMEBASE_Q;\n\n internal FFmpegEngine()\n {\n try\n {\n Engine.Log.Info($\"Loading FFmpeg libraries from '{Engine.Config.FFmpegPath}'\");\n Folder = Utils.GetFolderPath(Engine.Config.FFmpegPath);\n LoadLibraries(Folder, Engine.Config.FFmpegLoadProfile);\n\n uint ver = avformat_version();\n Version = $\"{ver >> 16}.{(ver >> 8) & 255}.{ver & 255}\";\n\n SetLogLevel();\n AV_TIMEBASE_Q = av_get_time_base_q();\n Engine.Log.Info($\"FFmpeg Loaded (Profile: {Engine.Config.FFmpegLoadProfile}, Location: {Folder}, FmtVer: {Version})\");\n } catch (Exception e)\n {\n Engine.Log.Error($\"Loading FFmpeg libraries '{Engine.Config.FFmpegPath}' failed\\r\\n{e.Message}\\r\\n{e.StackTrace}\");\n throw new Exception($\"Loading FFmpeg libraries '{Engine.Config.FFmpegPath}' failed\");\n }\n }\n\n internal static void SetLogLevel()\n {\n if (Engine.Config.FFmpegLogLevel != Flyleaf.FFmpeg.LogLevel.Quiet)\n {\n av_log_set_level(Engine.Config.FFmpegLogLevel);\n av_log_set_callback(LogFFmpeg);\n }\n else\n {\n av_log_set_level(Flyleaf.FFmpeg.LogLevel.Quiet);\n av_log_set_callback(null);\n }\n }\n\n internal unsafe static av_log_set_callback_callback LogFFmpeg = (p0, level, format, vl) =>\n {\n if (level > av_log_get_level())\n return;\n\n byte* buffer = stackalloc byte[AV_LOG_BUFFER_SIZE];\n int printPrefix = 1;\n av_log_format_line2(p0, level, format, vl, buffer, AV_LOG_BUFFER_SIZE, &printPrefix);\n string line = Utils.BytePtrToStringUTF8(buffer);\n\n Logger.Output($\"FFmpeg|{level,-7}|{line.Trim()}\");\n };\n\n internal unsafe static string ErrorCodeToMsg(int error)\n {\n byte* buffer = stackalloc byte[AV_LOG_BUFFER_SIZE];\n av_strerror(error, buffer, AV_LOG_BUFFER_SIZE);\n return Utils.BytePtrToStringUTF8(buffer);\n }\n}\n"], ["/LLPlayer/FlyleafLib/MediaFramework/MediaDevice/AudioDevice.cs", "using System;\nusing Vortice.MediaFoundation;\n\nnamespace FlyleafLib.MediaFramework.MediaDevice;\n\npublic class AudioDevice : DeviceBase\n{\n public AudioDevice(string friendlyName, string symbolicLink) : base(friendlyName, symbolicLink)\n => Url = $\"fmt://dshow?audio={FriendlyName}\";\n\n public static void RefreshDevices()\n {\n Utils.UIInvokeIfRequired(() =>\n {\n Engine.Audio.CapDevices.Clear();\n\n var devices = MediaFactory.MFEnumAudioDeviceSources();\n foreach (var device in devices)\n try { Engine.Audio.CapDevices.Add(new AudioDevice(device.FriendlyName, device.SymbolicLink)); } catch(Exception) { }\n });\n }\n}\n"], ["/LLPlayer/LLPlayer/Extensions/ExtendedDialogService.cs", "using System.Windows;\n\nnamespace LLPlayer.Extensions;\n\n/// \n/// Customize DialogService's Show(), which sets the Owner of the Window and sets it to always-on-top.\n/// ref: https://stackoverflow.com/questions/64420093/prism-idialogservice-show-non-modal-dialog-acts-as-modal\n/// \npublic class ExtendedDialogService(IContainerExtension containerExtension) : DialogService(containerExtension)\n{\n private bool _isOrphan;\n\n protected override void ConfigureDialogWindowContent(string dialogName, IDialogWindow window, IDialogParameters parameters)\n {\n base.ConfigureDialogWindowContent(dialogName, window, parameters);\n\n if (parameters != null &&\n parameters.ContainsKey(MyKnownDialogParameters.OrphanWindow))\n {\n _isOrphan = true;\n }\n }\n\n protected override void ShowDialogWindow(IDialogWindow dialogWindow, bool isModal)\n {\n base.ShowDialogWindow(dialogWindow, isModal);\n\n if (_isOrphan)\n {\n // Show and then clear Owner to place the window based on the parent window and then make it an orphan window.\n _isOrphan = false;\n dialogWindow.Owner = null;\n }\n }\n}\n\n// ref: https://github.com/PrismLibrary/Prism/blob/master/src/Wpf/Prism.Wpf/Dialogs/IDialogServiceCompatExtensions.cs\npublic static class ExtendedDialogServiceExtensions\n{\n /// \n /// Shows a non-modal and singleton dialog.\n /// \n /// The DialogService\n /// The name of the dialog to show.\n /// Whether to set owner to window\n public static void ShowSingleton(this IDialogService dialogService, string name, bool orphan)\n {\n ShowSingleton(dialogService, name, null!, orphan);\n }\n\n /// \n /// Shows a non-modal and singleton dialog.\n /// \n /// The DialogService\n /// The name of the dialog to show.\n /// The action to perform when the dialog is closed.\n /// Whether to set owner to window\n public static void ShowSingleton(this IDialogService dialogService, string name, Action callback, bool orphan)\n {\n var parameters = EnsureShowNonModalParameter(null);\n\n var windows = Application.Current.Windows.OfType();\n if (windows.Any())\n {\n var curWindow = windows.FirstOrDefault(w => w.Content.GetType().Name == name);\n if (curWindow != null && curWindow is Window win)\n {\n // If minimized, it will not be displayed after Activate, so set it back to Normal in advance.\n if (win.WindowState == WindowState.Minimized)\n {\n win.WindowState = WindowState.Normal;\n }\n // TODO: L: Notify to ViewModel to update query\n win.Activate();\n return;\n }\n }\n\n if (orphan)\n {\n parameters.Add(MyKnownDialogParameters.OrphanWindow, true);\n }\n\n dialogService.Show(name, parameters, callback);\n }\n\n private static IDialogParameters EnsureShowNonModalParameter(IDialogParameters? parameters)\n {\n parameters ??= new DialogParameters();\n\n if (!parameters.ContainsKey(KnownDialogParameters.ShowNonModal))\n parameters.Add(KnownDialogParameters.ShowNonModal, true);\n\n return parameters;\n }\n}\n\npublic static class MyKnownDialogParameters\n{\n public const string OrphanWindow = \"orphanWindow\";\n}\n"], ["/LLPlayer/LLPlayer/Controls/SubtitlesControl.xaml.cs", "using System.Windows;\nusing System.Windows.Controls;\nusing FlyleafLib.MediaPlayer;\nusing LLPlayer.Services;\n\nnamespace LLPlayer.Controls;\n\npublic partial class SubtitlesControl : UserControl\n{\n public FlyleafManager FL { get; }\n\n public SubtitlesControl()\n {\n InitializeComponent();\n\n FL = ((App)Application.Current).Container.Resolve();\n\n DataContext = this;\n }\n\n private void SubtitlePanel_OnSizeChanged(object sender, SizeChangedEventArgs e)\n {\n if (e.HeightChanged)\n {\n // Sometimes there is a very small difference in decimal points when the subtitles are switched, and this event fires.\n // If you update the margin of the Sub at this time, the window will go wrong, so do it only when the difference is above a certain level.\n double heightDiff = Math.Abs(e.NewSize.Height - e.PreviousSize.Height);\n if (heightDiff >= 1.0)\n {\n FL.Config.Subs.SubsPanelSize = e.NewSize;\n }\n }\n }\n\n private async void SelectableSubtitleText_OnWordClicked(object sender, WordClickedEventArgs e)\n {\n await WordPopupControl.OnWordClicked(e);\n }\n\n private void SelectableSubtitleText_OnWordClickedDown(object? sender, EventArgs e)\n {\n // Assume drag and stop playback.\n if (FL.Player.Status == Status.Playing)\n {\n FL.Player.Pause();\n }\n }\n}\n"], ["/LLPlayer/FlyleafLib/MediaFramework/MediaDemuxer/DemuxerInput.cs", "using System.Collections.Generic;\nusing System.IO;\n\nnamespace FlyleafLib.MediaFramework.MediaDemuxer;\n\npublic class DemuxerInput : NotifyPropertyChanged\n{\n /// \n /// Url provided as a demuxer input\n /// \n public string Url { get => _Url; set => _Url = Utils.FixFileUrl(value); }\n string _Url;\n\n /// \n /// Fallback url provided as a demuxer input\n /// \n public string UrlFallback { get => _UrlFallback; set => _UrlFallback = Utils.FixFileUrl(value); }\n string _UrlFallback;\n\n /// \n /// IOStream provided as a demuxer input\n /// \n public Stream IOStream { get; set; }\n\n public Dictionary\n HTTPHeaders { get; set; }\n\n public string UserAgent { get; set; }\n\n public string Referrer { get; set; }\n}\n"], ["/LLPlayer/WpfColorFontDialog/FontValueConverter.cs", "using System;\nusing System.Globalization;\nusing System.Windows.Data;\nusing System.Windows.Markup;\nusing System.Windows.Media;\n\nnamespace WpfColorFontDialog\n{\n public class FontValueConverter : IValueConverter\n {\n public object Convert(object value, Type targetType, object parameter, CultureInfo culture)\n {\n if (value is FontFamily font)\n {\n var name = I18NUtil.CurrentLanguage;\n if (string.IsNullOrWhiteSpace(name))\n {\n name = I18NUtil.GetCurrentLanguage();\n }\n var names = new[] { name, I18NUtil.GetLanguage() };\n foreach (var s in names)\n {\n if (font.FamilyNames.TryGetValue(XmlLanguage.GetLanguage(s), out var localizedName))\n {\n if (!string.IsNullOrEmpty(localizedName))\n {\n return localizedName;\n }\n }\n }\n\n return font.Source;\n }\n\n // Avoid reaching here and getting an error.\n return string.Empty;\n //throw new NotSupportedException();\n }\n\n public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)\n {\n throw new NotSupportedException(\"ConvertBack not supported\");\n }\n }\n}\n"], ["/LLPlayer/LLPlayer/Controls/Settings/SettingsAbout.xaml.cs", "using System.Collections.ObjectModel;\nusing System.Diagnostics.CodeAnalysis;\nusing System.Windows;\nusing System.Windows.Controls;\nusing LLPlayer.Extensions;\n\nnamespace LLPlayer.Controls.Settings;\n\npublic partial class SettingsAbout : UserControl\n{\n public SettingsAbout()\n {\n InitializeComponent();\n\n DataContext = ((App)Application.Current).Container.Resolve();\n }\n}\n\npublic class SettingsAboutVM : Bindable\n{\n public SettingsAboutVM()\n {\n Libraries =\n [\n new LibraryInfo\n {\n Name = \"SuRGeoNix/Flyleaf\",\n Description = \"Media Player .NET Library for WinUI 3/WPF/WinForms (based on FFmpeg/DirectX)\",\n Url = \"https://github.com/SuRGeoNix/Flyleaf\"\n },\n\n new LibraryInfo\n {\n Name = \"SuRGeoNix/Flyleaf.FFmpeg\",\n Description = \"FFmpeg Bindings for C#/.NET\",\n Url = \"https://github.com/SuRGeoNix/Flyleaf.FFmpeg\"\n },\n\n new LibraryInfo\n {\n Name = \"sandrohanea/whisper.net\",\n Description = \"Dotnet bindings for OpenAI Whisper (whisper.cpp)\",\n Url = \"https://github.com/sandrohanea/whisper.net\"\n },\n\n new LibraryInfo\n {\n Name = \"Purfview/whisper-standalone-win\",\n Description = \"Faster-Whisper standalone executables\",\n Url = \"https://github.com/Purfview/whisper-standalone-win\"\n },\n\n new LibraryInfo\n {\n Name = \"Sicos1977/TesseractOCR\",\n Description = \".NET wrapper for Tesseract OCR\",\n Url = \"https://github.com/Sicos1977/TesseractOCR\"\n },\n\n new LibraryInfo\n {\n Name = \"MaterialDesignInXamlToolkit \",\n Description = \"Google's Material Design in XAML & WPF\",\n Url = \"https://github.com/MaterialDesignInXAML/MaterialDesignInXamlToolkit\"\n },\n\n new LibraryInfo\n {\n Name = \"searchpioneer/lingua-dotnet\",\n Description = \"Natural language detection library for .NET\",\n Url = \"https://github.com/searchpioneer/lingua-dotnet\"\n },\n\n new LibraryInfo\n {\n Name = \"CharsetDetector/UTF-unknowns\",\n Description = \"Character set detector build in C#\",\n Url = \"https://github.com/CharsetDetector/UTF-unknown\"\n },\n\n new LibraryInfo\n {\n Name = \"komutan/NMeCab\",\n Description = \"Japanese morphological analyzer on .NET\",\n Url = \"https://github.com/komutan/NMeCab\"\n },\n\n new LibraryInfo\n {\n Name = \"PrismLibrary/Prism\",\n Description = \"A framework for building MVVM application\",\n Url = \"https://github.com/PrismLibrary/Prism\"\n },\n\n new LibraryInfo\n {\n Name = \"amerkoleci/Vortice.Windows\",\n Description = \".NET bindings for Direct3D11, XAudio, etc.\",\n Url = \"https://github.com/amerkoleci/Vortice.Windows\"\n },\n\n new LibraryInfo\n {\n Name = \"sskodje/WpfColorFont\",\n Description = \" A WPF font and color dialog\",\n Url = \"https://github.com/sskodje/WpfColorFont\"\n },\n ];\n\n }\n public ObservableCollection Libraries { get; }\n\n [field: AllowNull, MaybeNull]\n public DelegateCommand CmdCopyVersion => field ??= new(() =>\n {\n Clipboard.SetText($\"\"\"\n Version: {App.Version}, CommitHash: {App.CommitHash}\n OS Architecture: {App.OSArchitecture}, Process Architecture: {App.ProcessArchitecture}\n \"\"\");\n });\n}\n\npublic class LibraryInfo\n{\n public required string Name { get; init; }\n public required string Description { get; init; }\n public required string Url { get; init; }\n}\n"], ["/LLPlayer/LLPlayer/Controls/NonTopmostPopup.cs", "using System.Runtime.InteropServices;\nusing System.Windows;\nusing System.Windows.Controls.Primitives;\nusing System.Windows.Input;\nusing System.Windows.Interop;\n\nnamespace LLPlayer.Controls;\n\n/// \n/// Popup with code to not be the topmost control\n/// ref: https://gist.github.com/flq/903202/8bf56606b7c6fad341c31482f196b3aba9373e07\n/// \npublic class NonTopmostPopup : Popup\n{\n private bool? _appliedTopMost;\n private bool _alreadyLoaded;\n private Window? _parentWindow;\n\n public static readonly DependencyProperty IsTopmostProperty =\n DependencyProperty.Register(nameof(IsTopmost), typeof(bool), typeof(NonTopmostPopup), new FrameworkPropertyMetadata(false, OnIsTopmostChanged));\n\n public bool IsTopmost\n {\n get => (bool)GetValue(IsTopmostProperty);\n set => SetValue(IsTopmostProperty, value);\n }\n\n public NonTopmostPopup()\n {\n Loaded += OnPopupLoaded;\n }\n\n void OnPopupLoaded(object sender, RoutedEventArgs e)\n {\n if (_alreadyLoaded)\n return;\n\n _alreadyLoaded = true;\n\n if (Child != null)\n {\n Child.AddHandler(PreviewMouseLeftButtonDownEvent, new MouseButtonEventHandler(OnChildPreviewMouseLeftButtonDown), true);\n }\n\n //_parentWindow = Window.GetWindow(this);\n _parentWindow = Application.Current.MainWindow;\n\n if (_parentWindow == null)\n return;\n\n _parentWindow.Activated += OnParentWindowActivated;\n _parentWindow.Deactivated += OnParentWindowDeactivated;\n _parentWindow.LocationChanged += OnParentWindowLocationChanged;\n }\n\n private void OnParentWindowLocationChanged(object? sender, EventArgs e)\n {\n try\n {\n var method = typeof(Popup).GetMethod(\"UpdatePosition\",\n System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Instance);\n if (IsOpen)\n {\n method?.Invoke(this, null);\n }\n }\n catch\n {\n // ignored\n }\n }\n\n private void OnParentWindowActivated(object? sender, EventArgs e)\n {\n //Debug.WriteLine(\"Parent Window Activated\");\n SetTopmostState(true);\n }\n\n private void OnParentWindowDeactivated(object? sender, EventArgs e)\n {\n //Debug.WriteLine(\"Parent Window Deactivated\");\n\n if (IsTopmost == false)\n {\n SetTopmostState(IsTopmost);\n }\n }\n\n private void OnChildPreviewMouseLeftButtonDown(object? sender, MouseButtonEventArgs e)\n {\n //Debug.WriteLine(\"Child Mouse Left Button Down\");\n\n SetTopmostState(true);\n\n if (_parentWindow != null && !_parentWindow.IsActive && IsTopmost == false)\n {\n _parentWindow.Activate();\n //Debug.WriteLine(\"Activating Parent from child Left Button Down\");\n }\n }\n\n private static void OnIsTopmostChanged(DependencyObject obj, DependencyPropertyChangedEventArgs e)\n {\n var thisobj = (NonTopmostPopup)obj;\n\n thisobj.SetTopmostState(thisobj.IsTopmost);\n }\n\n protected override void OnOpened(EventArgs e)\n {\n SetTopmostState(IsTopmost);\n }\n\n private void SetTopmostState(bool isTop)\n {\n // Don't apply state if it's the same as incoming state\n if (_appliedTopMost.HasValue && _appliedTopMost == isTop)\n {\n // TODO: L: Maybe commenting out this section will solve the problem of the rare popups coming to the forefront?\n //return;\n }\n\n if (Child == null)\n return;\n\n var hwndSource = (PresentationSource.FromVisual(Child)) as HwndSource;\n\n if (hwndSource == null)\n return;\n var hwnd = hwndSource.Handle;\n\n if (!GetWindowRect(hwnd, out RECT rect))\n return;\n\n //Debug.WriteLine(\"setting z-order \" + isTop);\n\n if (isTop)\n {\n SetWindowPos(hwnd, HWND_TOPMOST, rect.Left, rect.Top, (int)Width, (int)Height, TOPMOST_FLAGS);\n }\n else\n {\n // Z-Order would only get refreshed/reflected if clicking the\n // the titlebar (as opposed to other parts of the external\n // window) unless I first set the popup to HWND_BOTTOM\n // then HWND_TOP before HWND_NOTOPMOST\n SetWindowPos(hwnd, HWND_BOTTOM, rect.Left, rect.Top, (int)Width, (int)Height, TOPMOST_FLAGS);\n SetWindowPos(hwnd, HWND_TOP, rect.Left, rect.Top, (int)Width, (int)Height, TOPMOST_FLAGS);\n SetWindowPos(hwnd, HWND_NOTOPMOST, rect.Left, rect.Top, (int)Width, (int)Height, TOPMOST_FLAGS);\n }\n\n _appliedTopMost = isTop;\n }\n\n #region P/Invoke imports & definitions\n#pragma warning disable 1591 //Xml-doc\n#pragma warning disable 169 //Never used-warning\n // ReSharper disable InconsistentNaming\n // Imports etc. with their naming rules\n\n [StructLayout(LayoutKind.Sequential)]\n public struct RECT\n\n {\n public int Left;\n public int Top;\n public int Right;\n public int Bottom;\n }\n\n [DllImport(\"user32.dll\")]\n [return: MarshalAs(UnmanagedType.Bool)]\n private static extern bool GetWindowRect(IntPtr hWnd, out RECT lpRect);\n\n [DllImport(\"user32.dll\")]\n private static extern bool SetWindowPos(IntPtr hWnd, IntPtr hWndInsertAfter, int X,\n int Y, int cx, int cy, uint uFlags);\n\n static readonly IntPtr HWND_TOPMOST = new IntPtr(-1);\n static readonly IntPtr HWND_NOTOPMOST = new IntPtr(-2);\n static readonly IntPtr HWND_TOP = new IntPtr(0);\n static readonly IntPtr HWND_BOTTOM = new IntPtr(1);\n\n private const UInt32 SWP_NOSIZE = 0x0001;\n const UInt32 SWP_NOMOVE = 0x0002;\n //const UInt32 SWP_NOZORDER = 0x0004;\n const UInt32 SWP_NOREDRAW = 0x0008;\n const UInt32 SWP_NOACTIVATE = 0x0010;\n\n //const UInt32 SWP_FRAMECHANGED = 0x0020; /* The frame changed: send WM_NCCALCSIZE */\n //const UInt32 SWP_SHOWWINDOW = 0x0040;\n //const UInt32 SWP_HIDEWINDOW = 0x0080;\n //const UInt32 SWP_NOCOPYBITS = 0x0100;\n const UInt32 SWP_NOOWNERZORDER = 0x0200; /* Don't do owner Z ordering */\n const UInt32 SWP_NOSENDCHANGING = 0x0400; /* Don't send WM_WINDOWPOSCHANGING */\n\n const UInt32 TOPMOST_FLAGS =\n SWP_NOACTIVATE | SWP_NOOWNERZORDER | SWP_NOSIZE | SWP_NOMOVE | SWP_NOREDRAW | SWP_NOSENDCHANGING;\n\n // ReSharper restore InconsistentNaming\n#pragma warning restore 1591\n#pragma warning restore 169\n #endregion\n}\n"], ["/LLPlayer/FlyleafLib/Utils/NativeMethods.cs", "using System;\nusing System.Drawing;\nusing System.Runtime.InteropServices;\n\nnamespace FlyleafLib;\n\n#pragma warning disable CA1401 // P/Invokes should not be visible\npublic static partial class Utils\n{\n public static class NativeMethods\n {\n static NativeMethods()\n {\n if (IntPtr.Size == 4)\n {\n GetWindowLong = GetWindowLongPtr32;\n SetWindowLong = SetWindowLongPtr32;\n }\n else\n {\n GetWindowLong = GetWindowLongPtr64;\n SetWindowLong = SetWindowLongPtr64;\n }\n\n GetDPI(out DpiX, out DpiY);\n }\n\n public static Func SetWindowLong;\n public static Func GetWindowLong;\n\n [DllImport(\"user32.dll\", EntryPoint = \"GetWindowLong\")]\n public static extern IntPtr GetWindowLongPtr32(IntPtr hWnd, int nIndex);\n\n [DllImport(\"user32.dll\", EntryPoint = \"GetWindowLongPtr\")]\n public static extern IntPtr GetWindowLongPtr64(IntPtr hWnd, int nIndex);\n\n [DllImport(\"user32.dll\", EntryPoint = \"SetWindowLong\")]\n public static extern IntPtr SetWindowLongPtr32(IntPtr hWnd, int nIndex, IntPtr dwNewLong);\n\n [DllImport(\"user32.dll\", EntryPoint = \"SetWindowLongPtr\")] // , SetLastError = true\n public static extern IntPtr SetWindowLongPtr64(IntPtr hWnd, int nIndex, IntPtr dwNewLong);\n\n [DllImport(\"user32.dll\")]\n public static extern IntPtr CallWindowProc(IntPtr lpPrevWndFunc, IntPtr hWnd, uint Msg, IntPtr wParam, IntPtr lParam);\n\n [DllImport(\"comctl32.dll\")]\n public static extern bool SetWindowSubclass(IntPtr hWnd, IntPtr pfnSubclass, UIntPtr uIdSubclass, UIntPtr dwRefData);\n\n [DllImport(\"comctl32.dll\")]\n public static extern bool RemoveWindowSubclass(IntPtr hWnd, IntPtr pfnSubclass, UIntPtr uIdSubclass);\n\n [DllImport(\"comctl32.dll\")]\n public static extern IntPtr DefSubclassProc(IntPtr hWnd, uint msg, IntPtr wParam, IntPtr lParam);\n\n [DllImport(\"user32.dll\")]\n public static extern bool SetWindowPos(IntPtr hWnd, IntPtr hWndInsertAfter, int x, int y, int cx, int cy, UInt32 uFlags);\n\n [DllImport(\"shlwapi.dll\", CharSet = CharSet.Unicode)]\n public static extern int StrCmpLogicalW(string psz1, string psz2);\n\n [DllImport(\"user32.dll\")]\n public static extern int ShowCursor(bool bShow);\n\n [DllImport(\"winmm.dll\", EntryPoint = \"timeBeginPeriod\")]\n public static extern uint TimeBeginPeriod(uint uMilliseconds);\n\n [DllImport(\"winmm.dll\", EntryPoint = \"timeEndPeriod\")]\n public static extern uint TimeEndPeriod(uint uMilliseconds);\n\n [DllImport(\"kernel32.dll\", CharSet = CharSet.Auto)]\n public static extern EXECUTION_STATE SetThreadExecutionState(EXECUTION_STATE esFlags);\n [FlagsAttribute]\n public enum EXECUTION_STATE :uint\n {\n ES_AWAYMODE_REQUIRED = 0x00000040,\n ES_CONTINUOUS = 0x80000000,\n ES_DISPLAY_REQUIRED = 0x00000002,\n ES_SYSTEM_REQUIRED = 0x00000001\n }\n\n [DllImport(\"gdi32.dll\")]\n public static extern IntPtr CreateRectRgn(int nLeftRect, int nTopRect, int nRightRect, int nBottomRect);\n\n [DllImport(\"User32.dll\")]\n public static extern int GetWindowRgn(IntPtr hWnd, IntPtr hRgn);\n\n [DllImport(\"User32.dll\")]\n public static extern int SetWindowRgn(IntPtr hWnd, IntPtr hRgn, bool bRedraw);\n\n [DllImport(\"user32.dll\")]\n public static extern bool GetWindowRect(IntPtr hwnd, ref RECT rectangle);\n\n [DllImport(\"user32.dll\")]\n public static extern bool GetWindowInfo(IntPtr hwnd, ref WINDOWINFO pwi);\n\n [DllImport(\"user32.dll\")]\n public static extern void SetParent(IntPtr hWndChild, IntPtr hWndNewParent);\n\n [DllImport(\"user32.dll\")]\n public static extern IntPtr GetParent(IntPtr hWnd);\n\n [DllImport(\"user32.dll\")]\n [return: MarshalAs(UnmanagedType.Bool)]\n public static extern bool SetForegroundWindow(IntPtr hWnd);\n\n [DllImport(\"user32.dll\")]\n public static extern bool ShowWindow(IntPtr hWnd, int nCmdShow);\n\n\n [StructLayout(LayoutKind.Sequential)]\n public struct WINDOWINFO\n {\n public uint cbSize;\n public RECT rcWindow;\n public RECT rcClient;\n public uint dwStyle;\n public uint dwExStyle;\n public uint dwWindowStatus;\n public uint cxWindowBorders;\n public uint cyWindowBorders;\n public ushort atomWindowType;\n public ushort wCreatorVersion;\n\n // Allows automatic initialization of \"cbSize\" with \"new WINDOWINFO(null/true/false)\".\n public WINDOWINFO(Boolean? filler) : this()\n => cbSize = (UInt32)Marshal.SizeOf(typeof(WINDOWINFO));\n\n }\n public struct RECT\n {\n public int Left { get; set; }\n public int Top { get; set; }\n public int Right { get; set; }\n public int Bottom { get; set; }\n }\n\n [Flags]\n public enum SetWindowPosFlags : uint\n {\n SWP_ASYNCWINDOWPOS = 0x4000,\n SWP_DEFERERASE = 0x2000,\n SWP_DRAWFRAME = 0x0020,\n SWP_FRAMECHANGED = 0x0020,\n SWP_HIDEWINDOW = 0x0080,\n SWP_NOACTIVATE = 0x0010,\n SWP_NOCOPYBITS = 0x0100,\n SWP_NOMOVE = 0x0002,\n SWP_NOOWNERZORDER = 0x0200,\n SWP_NOREDRAW = 0x0008,\n SWP_NOREPOSITION = 0x0200,\n SWP_NOSENDCHANGING = 0x0400,\n SWP_NOSIZE = 0x0001,\n SWP_NOZORDER = 0x0004,\n SWP_SHOWWINDOW = 0x0040,\n }\n\n [Flags]\n public enum WindowLongFlags : int\n {\n GWL_EXSTYLE = -20,\n GWLP_HINSTANCE = -6,\n GWLP_HWNDPARENT = -8,\n GWL_ID = -12,\n GWL_STYLE = -16,\n GWL_USERDATA = -21,\n GWL_WNDPROC = -4,\n DWLP_USER = 0x8,\n DWLP_MSGRESULT = 0x0,\n DWLP_DLGPROC = 0x4\n }\n\n [Flags]\n public enum WindowStyles : uint\n {\n WS_BORDER = 0x800000,\n WS_CAPTION = 0xc00000,\n WS_CHILD = 0x40000000,\n WS_CLIPCHILDREN = 0x2000000,\n WS_CLIPSIBLINGS = 0x4000000,\n WS_DISABLED = 0x8000000,\n WS_DLGFRAME = 0x400000,\n WS_GROUP = 0x20000,\n WS_HSCROLL = 0x100000,\n WS_MAXIMIZE = 0x1000000,\n WS_MAXIMIZEBOX = 0x10000,\n WS_MINIMIZE = 0x20000000,\n WS_MINIMIZEBOX = 0x20000,\n WS_OVERLAPPED = 0x0,\n WS_OVERLAPPEDWINDOW = WS_OVERLAPPED | WS_CAPTION | WS_SYSMENU | WS_SIZEFRAME | WS_MINIMIZEBOX | WS_MAXIMIZEBOX,\n WS_POPUP = 0x80000000,\n WS_POPUPWINDOW = WS_POPUP | WS_BORDER | WS_SYSMENU,\n WS_SIZEFRAME = 0x40000,\n WS_SYSMENU = 0x80000,\n WS_TABSTOP = 0x10000,\n WS_THICKFRAME = 0x00040000,\n WS_VISIBLE = 0x10000000,\n WS_VSCROLL = 0x200000\n }\n\n [Flags]\n public enum WindowStylesEx : uint\n {\n WS_EX_ACCEPTFILES = 0x00000010,\n WS_EX_APPWINDOW = 0x00040000,\n WS_EX_CLIENTEDGE = 0x00000200,\n WS_EX_COMPOSITED = 0x02000000,\n WS_EX_CONTEXTHELP = 0x00000400,\n WS_EX_CONTROLPARENT = 0x00010000,\n WS_EX_DLGMODALFRAME = 0x00000001,\n WS_EX_LAYERED = 0x00080000,\n WS_EX_LAYOUTRTL = 0x00400000,\n WS_EX_LEFT = 0x00000000,\n WS_EX_LEFTSCROLLBAR = 0x00004000,\n WS_EX_LTRREADING = 0x00000000,\n WS_EX_MDICHILD = 0x00000040,\n WS_EX_NOACTIVATE = 0x08000000,\n WS_EX_NOINHERITLAYOUT = 0x00100000,\n WS_EX_NOPARENTNOTIFY = 0x00000004,\n WS_EX_NOREDIRECTIONBITMAP = 0x00200000,\n WS_EX_OVERLAPPEDWINDOW = WS_EX_WINDOWEDGE | WS_EX_CLIENTEDGE,\n WS_EX_PALETTEWINDOW = WS_EX_WINDOWEDGE | WS_EX_TOOLWINDOW | WS_EX_TOPMOST,\n WS_EX_RIGHT = 0x00001000,\n WS_EX_RIGHTSCROLLBAR = 0x00000000,\n WS_EX_RTLREADING = 0x00002000,\n WS_EX_STATICEDGE = 0x00020000,\n WS_EX_TOOLWINDOW = 0x00000080,\n WS_EX_TOPMOST = 0x00000008,\n WS_EX_TRANSPARENT = 0x00000020,\n WS_EX_WINDOWEDGE = 0x00000100\n }\n\n public enum ShowWindowCommands : uint\n {\n SW_HIDE = 0,\n SW_SHOWNORMAL = 1,\n SW_NORMAL = 1,\n SW_SHOWMINIMIZED = 2,\n SW_SHOWMAXIMIZED = 3,\n SW_MAXIMIZE = 3,\n SW_SHOWNOACTIVATE = 4,\n SW_SHOW = 5,\n SW_MINIMIZE = 6,\n SW_SHOWMINNOACTIVE = 7,\n SW_SHOWNA = 8,\n SW_RESTORE = 9,\n SW_SHOWDEFAULT = 10,\n SW_FORCEMINIMIZE = 11,\n SW_MAX = 11\n }\n\n public delegate IntPtr WndProcDelegate(IntPtr hWnd, uint msg, IntPtr wParam, IntPtr lParam);\n public delegate IntPtr SubclassWndProc(IntPtr hWnd, uint msg, IntPtr wParam, IntPtr lParam, IntPtr uIdSubclass, IntPtr dwRefData);\n\n public static int SignedHIWORD(IntPtr n) => SignedHIWORD(unchecked((int)(long)n));\n public static int SignedLOWORD(IntPtr n) => SignedLOWORD(unchecked((int)(long)n));\n public static int SignedHIWORD(int n) => (short)((n >> 16) & 0xffff);\n public static int SignedLOWORD(int n) => (short)(n & 0xFFFF);\n\n #region DPI\n public static double DpiX, DpiY;\n public static int DpiXSource, DpiYSource;\n const int LOGPIXELSX = 88, LOGPIXELSY = 90;\n [DllImport(\"gdi32.dll\", CharSet = CharSet.Auto, SetLastError = true, ExactSpelling = true)]\n public static extern int GetDeviceCaps(IntPtr hDC, int nIndex);\n public static void GetDPI(out double dpiX, out double dpiY) => GetDPI(IntPtr.Zero, out dpiX, out dpiY);\n public static void GetDPI(IntPtr handle, out double dpiX, out double dpiY)\n {\n Graphics GraphicsObject = Graphics.FromHwnd(handle); // DESKTOP Handle\n IntPtr dcHandle = GraphicsObject.GetHdc();\n DpiXSource = GetDeviceCaps(dcHandle, LOGPIXELSX);\n dpiX = DpiXSource / 96.0;\n DpiYSource = GetDeviceCaps(dcHandle, LOGPIXELSY);\n dpiY = DpiYSource / 96.0;\n GraphicsObject.ReleaseHdc(dcHandle);\n GraphicsObject.Dispose();\n }\n #endregion\n }\n}\n#pragma warning restore CA1401 // P/Invokes should not be visible\n"], ["/LLPlayer/FlyleafLib/Utils/ObservableDictionary.cs", "using System.Collections.Generic;\nusing System.Collections.Specialized;\nusing System.ComponentModel;\nusing System.Linq;\n\nnamespace FlyleafLib;\n\npublic static partial class Utils\n{\n public class ObservableDictionary : Dictionary, INotifyPropertyChanged, INotifyCollectionChanged\n {\n public event PropertyChangedEventHandler PropertyChanged;\n public event NotifyCollectionChangedEventHandler CollectionChanged;\n\n public new TVal this[TKey key]\n {\n get => base[key];\n\n set\n {\n if (ContainsKey(key) && base[key].Equals(value)) return;\n\n if (CollectionChanged != null)\n {\n KeyValuePair oldItem = new(key, base[key]);\n KeyValuePair newItem = new(key, value);\n base[key] = value;\n PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(key.ToString()));\n CollectionChanged?.Invoke(this, new NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction.Replace, newItem, oldItem, this.ToList().IndexOf(newItem)));\n }\n else\n {\n base[key] = value;\n PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(key.ToString()));\n }\n }\n }\n }\n}\n"], ["/LLPlayer/FlyleafLib/MediaPlayer/Translation/Services/DeepLXTranslateService.cs", "using System.Net.Http;\nusing System.Text;\nusing System.Text.Encodings.Web;\nusing System.Text.Json;\nusing System.Threading;\nusing System.Threading.Tasks;\n\nnamespace FlyleafLib.MediaPlayer.Translation.Services;\n\n#nullable enable\n\npublic class DeepLXTranslateService : ITranslateService\n{\n private readonly HttpClient _httpClient;\n private string? _srcLang;\n private string? _targetLang;\n private readonly DeepLXTranslateSettings _settings;\n\n public DeepLXTranslateService(DeepLXTranslateSettings settings)\n {\n if (string.IsNullOrWhiteSpace(settings.Endpoint))\n {\n throw new TranslationConfigException(\n $\"Endpoint for {ServiceType} is not configured.\");\n }\n\n _settings = settings;\n _httpClient = new HttpClient();\n _httpClient.BaseAddress = new Uri(settings.Endpoint);\n _httpClient.Timeout = TimeSpan.FromMilliseconds(settings.TimeoutMs);\n }\n\n private static readonly JsonSerializerOptions JsonOptions = new()\n {\n Encoder = JavaScriptEncoder.UnsafeRelaxedJsonEscaping\n };\n\n public TranslateServiceType ServiceType => TranslateServiceType.DeepLX;\n\n public void Dispose()\n {\n _httpClient.Dispose();\n }\n\n public void Initialize(Language src, TargetLanguage target)\n {\n (TranslateLanguage srcLang, _) = this.TryGetLanguage(src, target);\n\n _srcLang = ToSourceCode(srcLang.ISO6391);\n _targetLang = ToTargetCode(target);\n }\n\n private string ToSourceCode(string iso6391)\n {\n return DeepLTranslateService.ToSourceCode(iso6391);\n }\n\n private string ToTargetCode(TargetLanguage target)\n {\n return DeepLTranslateService.ToTargetCode(target);\n }\n\n public async Task TranslateAsync(string text, CancellationToken token)\n {\n if (_srcLang == null || _targetLang == null)\n {\n throw new InvalidOperationException(\"must be initialized\");\n }\n\n string jsonResultString = \"\";\n int statusCode = -1;\n\n try\n {\n DeepLXTranslateRequest requestBody = new()\n {\n source_lang = _srcLang,\n target_lang = _targetLang,\n text = text\n };\n\n string jsonRequest = JsonSerializer.Serialize(requestBody, JsonOptions);\n using StringContent content = new(jsonRequest, Encoding.UTF8, \"application/json\");\n\n using var result = await _httpClient.PostAsync(\"/translate\", content, token).ConfigureAwait(false);\n jsonResultString = await result.Content.ReadAsStringAsync(token).ConfigureAwait(false);\n\n statusCode = (int)result.StatusCode;\n result.EnsureSuccessStatusCode();\n\n DeepLXTranslateResult? responseData = JsonSerializer.Deserialize(jsonResultString);\n return responseData!.data;\n }\n catch (OperationCanceledException ex)\n when (!ex.Message.StartsWith(\"The request was canceled due to the configured HttpClient.Timeout\"))\n {\n throw;\n }\n catch (Exception ex)\n {\n throw new TranslationException($\"Cannot request to {ServiceType}: {ex.Message}\", ex)\n {\n Data =\n {\n [\"status_code\"] = statusCode.ToString(),\n [\"response\"] = jsonResultString\n }\n };\n }\n }\n\n private class DeepLXTranslateRequest\n {\n public required string text { get; init; }\n public string? source_lang { get; init; }\n public required string target_lang { get; init; }\n }\n\n private class DeepLXTranslateResult\n {\n public required string[] alternatives { get; init; }\n public required string data { get; init; }\n public required string source_lang { get; init; }\n public required string target_lang { get; init; }\n }\n}\n"], ["/LLPlayer/FlyleafLib/MediaFramework/MediaDevice/DeviceBase.cs", "using System.Collections.Generic;\n\nnamespace FlyleafLib.MediaFramework.MediaDevice;\n\npublic class DeviceBase :DeviceBase\n{\n public DeviceBase(string friendlyName, string symbolicLink) : base(friendlyName, symbolicLink)\n {\n }\n}\n\npublic class DeviceBase\n where T: DeviceStreamBase\n{\n public string FriendlyName { get; }\n public string SymbolicLink { get; }\n public IList\n Streams { get; protected set; }\n public string Url { get; protected set; } // default Url\n\n public DeviceBase(string friendlyName, string symbolicLink)\n {\n FriendlyName = friendlyName;\n SymbolicLink = symbolicLink;\n\n Engine.Log.Debug($\"[{(this is AudioDevice ? \"Audio\" : \"Video\")}Device] {friendlyName}\");\n }\n\n public override string ToString() => FriendlyName;\n}\n"], ["/LLPlayer/LLPlayer/Services/FlyleafManager.cs", "using System.IO;\nusing System.Windows;\nusing FlyleafLib;\nusing FlyleafLib.Controls.WPF;\nusing FlyleafLib.MediaPlayer;\n\nnamespace LLPlayer.Services;\n\npublic class FlyleafManager\n{\n public Player Player { get; }\n public Config PlayerConfig => Player.Config;\n public FlyleafHost? FlyleafHost => Player.Host as FlyleafHost;\n public AppConfig Config { get; }\n public AppActions Action { get; }\n\n public AudioEngine AudioEngine => Engine.Audio;\n public EngineConfig ConfigEngine => Engine.Config;\n\n public FlyleafManager(Player player, IDialogService dialogService)\n {\n Player = player;\n\n // Load app configuration at this time\n Config = LoadAppConfig();\n Action = new AppActions(Player, Config, dialogService);\n }\n\n private AppConfig LoadAppConfig()\n {\n AppConfig? config = null;\n\n if (File.Exists(App.AppConfigPath))\n {\n try\n {\n config = AppConfig.Load(App.AppConfigPath);\n\n if (config.Version != App.Version)\n {\n config.Version = App.Version;\n config.Save(App.AppConfigPath);\n }\n }\n catch (Exception ex)\n {\n MessageBox.Show($\"Cannot load AppConfig from {Path.GetFileName(App.AppConfigPath)}, Please review the settings or delete the config file. Error details are recorded in {Path.GetFileName(App.CrashLogPath)}.\");\n try\n {\n File.WriteAllText(App.CrashLogPath, \"AppConfig Loading Error: \" + ex);\n }\n catch\n {\n // ignored\n }\n\n Application.Current.Shutdown();\n }\n }\n\n if (config == null)\n {\n config = new AppConfig();\n }\n config.Initialize(this);\n\n return config;\n }\n}\n"], ["/LLPlayer/LLPlayer/Views/MainWindow.xaml.cs", "using System.Runtime.InteropServices;\nusing System.Windows;\nusing System.Windows.Interop;\nusing LLPlayer.Services;\nusing LLPlayer.ViewModels;\n\nnamespace LLPlayer.Views;\n\npublic partial class MainWindow : Window\n{\n public MainWindow()\n {\n // If this is not called first, the constructor of the other control will\n // run before FlyleafHost is initialized, so it will not work.\n DataContext = ((App)Application.Current).Container.Resolve();\n\n InitializeComponent();\n\n SetWindowSize();\n SetTitleBarDarkMode(this);\n }\n\n private void SetWindowSize()\n {\n // 16:9 size list\n List candidateSizes =\n [\n new(1280, 720),\n new(1024, 576),\n new(960, 540),\n new(800, 450),\n new(640, 360),\n new(480, 270),\n new(320, 180)\n ];\n\n // Get available screen width / height\n double availableWidth = SystemParameters.WorkArea.Width;\n double availableHeight = SystemParameters.WorkArea.Height;\n\n // Get the largest size that will fit on the screen\n Size selectedSize = candidateSizes.FirstOrDefault(\n s => s.Width <= availableWidth && s.Height <= availableHeight,\n candidateSizes[^1]);\n\n // Set\n Width = selectedSize.Width;\n Height = selectedSize.Height;\n }\n\n #region Dark Title Bar\n /// \n /// ref: \n /// \n [DllImport(\"DwmApi\")]\n private static extern int DwmSetWindowAttribute(IntPtr hwnd, int attr, int[] attrValue, int attrSize);\n const int DWMWA_USE_IMMERSIVE_DARK_MODE = 20;\n\n public static void SetTitleBarDarkMode(Window window)\n {\n // Check OS Version\n if (!(Environment.OSVersion.Version >= new Version(10, 0, 18985)))\n {\n return;\n }\n\n var fl = ((App)Application.Current).Container.Resolve();\n if (!fl.Config.IsDarkTitlebar)\n {\n return;\n }\n\n bool darkMode = true;\n\n // Set title bar to dark mode\n // ref: https://stackoverflow.com/questions/71362654/wpf-window-titlebar\n IntPtr hWnd = new WindowInteropHelper(window).EnsureHandle();\n DwmSetWindowAttribute(hWnd, DWMWA_USE_IMMERSIVE_DARK_MODE, [darkMode ? 1 : 0], 4);\n }\n #endregion\n}\n"], ["/LLPlayer/FlyleafLib/MediaPlayer/Translation/Services/DeepLTranslateService.cs", "using System.Threading;\nusing System.Threading.Tasks;\nusing DeepL;\nusing DeepL.Model;\n\nnamespace FlyleafLib.MediaPlayer.Translation.Services;\n\n#nullable enable\n\npublic class DeepLTranslateService : ITranslateService\n{\n private string? _srcLang;\n private string? _targetLang;\n private readonly Translator _translator;\n private readonly DeepLTranslateSettings _settings;\n\n public DeepLTranslateService(DeepLTranslateSettings settings)\n {\n if (string.IsNullOrWhiteSpace(settings.ApiKey))\n {\n throw new TranslationConfigException(\n $\"API Key for {ServiceType} is not configured.\");\n }\n\n _settings = settings;\n _translator = new Translator(_settings.ApiKey, new TranslatorOptions()\n {\n OverallConnectionTimeout = TimeSpan.FromMilliseconds(settings.TimeoutMs)\n });\n }\n\n public TranslateServiceType ServiceType => TranslateServiceType.DeepL;\n\n public void Dispose()\n {\n _translator.Dispose();\n }\n\n public void Initialize(Language src, TargetLanguage target)\n {\n (TranslateLanguage srcLang, _) = this.TryGetLanguage(src, target);\n\n _srcLang = ToSourceCode(srcLang.ISO6391);\n _targetLang = ToTargetCode(target);\n }\n\n internal static string ToSourceCode(string iso6391)\n {\n // ref: https://developers.deepl.com/docs/resources/supported-languages\n\n // Just capitalize ISO6391.\n return iso6391.ToUpper();\n }\n\n internal static string ToTargetCode(TargetLanguage target)\n {\n return target switch\n {\n TargetLanguage.EnglishAmerican => \"EN-US\",\n TargetLanguage.EnglishBritish => \"EN-GB\",\n TargetLanguage.Portuguese => \"PT-PT\",\n TargetLanguage.PortugueseBrazilian => \"PT-BR\",\n TargetLanguage.ChineseSimplified => \"ZH-HANS\",\n TargetLanguage.ChineseTraditional => \"ZH-HANT\",\n _ => target.ToISO6391().ToUpper()\n };\n }\n\n public async Task TranslateAsync(string text, CancellationToken token)\n {\n if (_srcLang == null || _targetLang == null)\n throw new InvalidOperationException(\"must be initialized\");\n\n try\n {\n TextResult result = await _translator.TranslateTextAsync(text, _srcLang, _targetLang,\n new TextTranslateOptions\n {\n Formality = Formality.Default,\n }, token).ConfigureAwait(false);\n\n return result.Text;\n }\n catch (OperationCanceledException)\n {\n throw;\n }\n catch (Exception ex)\n {\n // Timeout: DeepL.ConnectionException\n throw new TranslationException($\"Cannot request to {ServiceType}: {ex.Message}\", ex);\n }\n }\n}\n"], ["/LLPlayer/WpfColorFontDialog/AvailableColors.cs", "using System;\nusing System.Collections.Generic;\nusing System.Reflection;\nusing System.Windows.Media;\n\nnamespace WpfColorFontDialog\n{\n\tinternal class AvailableColors : List\n\t{\n\t\tpublic AvailableColors()\n\t\t{\n\t\t\tthis.Init();\n\t\t}\n\n\t\tpublic static FontColor GetFontColor(SolidColorBrush b)\n\t\t{\n\t\t\treturn (new AvailableColors()).GetFontColorByBrush(b);\n\t\t}\n\n\t\tpublic static FontColor GetFontColor(string name)\n\t\t{\n\t\t\treturn (new AvailableColors()).GetFontColorByName(name);\n\t\t}\n\n\t\tpublic static FontColor GetFontColor(Color c)\n\t\t{\n\t\t\treturn AvailableColors.GetFontColor(new SolidColorBrush(c));\n\t\t}\n\n\t\tpublic FontColor GetFontColorByBrush(SolidColorBrush b)\n\t\t{\n\t\t\tFontColor found = null;\n\t\t\tforeach (FontColor brush in this)\n\t\t\t{\n\t\t\t\tif (!brush.Brush.Color.Equals(b.Color))\n\t\t\t\t{\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\t\t\t\tfound = brush;\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\treturn found;\n\t\t}\n\n\t\tpublic FontColor GetFontColorByName(string name)\n\t\t{\n\t\t\tFontColor found = null;\n\t\t\tforeach (FontColor b in this)\n\t\t\t{\n\t\t\t\tif (b.Name != name)\n\t\t\t\t{\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\t\t\t\tfound = b;\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\treturn found;\n\t\t}\n\n\t\tpublic static int GetFontColorIndex(FontColor c)\n\t\t{\n\t\t\tAvailableColors brushList = new AvailableColors();\n\t\t\tint idx = 0;\n\t\t\tSolidColorBrush colorBrush = c.Brush;\n\t\t\tforeach (FontColor brush in brushList)\n\t\t\t{\n\t\t\t\tif (brush.Brush.Color.Equals(colorBrush.Color))\n\t\t\t\t{\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t\tidx++;\n\t\t\t}\n\t\t\treturn idx;\n\t\t}\n\n\t\tprivate void Init()\n\t\t{\n\t\t\tPropertyInfo[] properties = typeof(Colors).GetProperties(BindingFlags.Static | BindingFlags.Public);\n\t\t\tfor (int i = 0; i < (int)properties.Length; i++)\n\t\t\t{\n\t\t\t\tPropertyInfo prop = properties[i];\n\t\t\t\tstring name = prop.Name;\n\t\t\t\tSolidColorBrush brush = new SolidColorBrush((Color)prop.GetValue(null, null));\n\t\t\t\tbase.Add(new FontColor(name, brush));\n\t\t\t}\n\t\t}\n\t}\n}"], ["/LLPlayer/FlyleafLib/Engine/WhisperCppModel.cs", "using System.IO;\nusing System.Text.Json.Serialization;\nusing Whisper.net.Ggml;\n\nnamespace FlyleafLib;\n\n#nullable enable\n\npublic class WhisperCppModel : NotifyPropertyChanged, IEquatable\n{\n public GgmlType Model { get; set; }\n\n [JsonIgnore]\n public long Size\n {\n get;\n set\n {\n if (Set(ref field, value))\n {\n Raise(nameof(Downloaded));\n }\n }\n }\n\n [JsonIgnore]\n public string ModelFileName\n {\n get\n {\n string modelName = Model.ToString().ToLower();\n return $\"ggml-{modelName}.bin\";\n }\n }\n\n [JsonIgnore]\n public string ModelFilePath => Path.Combine(WhisperConfig.ModelsDirectory, ModelFileName);\n\n [JsonIgnore]\n public bool Downloaded => Size > 0;\n\n public override string ToString() => Model.ToString();\n\n public bool Equals(WhisperCppModel? other)\n {\n if (other is null) return false;\n if (ReferenceEquals(this, other)) return true;\n return Model == other.Model;\n }\n\n public override bool Equals(object? obj) => obj is WhisperCppModel o && Equals(o);\n\n public override int GetHashCode()\n {\n return (int)Model;\n }\n}\n"], ["/LLPlayer/FlyleafLib/MediaPlayer/Translation/Services/TranslateServiceFactory.cs", "using System.Collections.Generic;\n\nnamespace FlyleafLib.MediaPlayer.Translation.Services;\n\npublic class TranslateServiceFactory\n{\n private readonly Config.SubtitlesConfig _config;\n\n public TranslateServiceFactory(Config.SubtitlesConfig config)\n {\n _config = config;\n }\n\n /// \n /// GetService\n /// \n /// \n /// \n /// \n /// \n /// \n public ITranslateService GetService(TranslateServiceType serviceType, bool wordMode)\n {\n switch (serviceType)\n {\n case TranslateServiceType.GoogleV1:\n return new GoogleV1TranslateService((GoogleV1TranslateSettings)_config.TranslateServiceSettings.GetValueOrDefault(serviceType, new GoogleV1TranslateSettings()));\n\n case TranslateServiceType.DeepL:\n return new DeepLTranslateService((DeepLTranslateSettings)_config.TranslateServiceSettings.GetValueOrDefault(serviceType, new DeepLTranslateSettings()));\n\n case TranslateServiceType.DeepLX:\n return new DeepLXTranslateService((DeepLXTranslateSettings)_config.TranslateServiceSettings.GetValueOrDefault(serviceType, new DeepLXTranslateSettings()));\n\n case TranslateServiceType.Ollama:\n return new OpenAIBaseTranslateService((OllamaTranslateSettings)_config.TranslateServiceSettings.GetValueOrDefault(serviceType, new OllamaTranslateSettings()), _config.TranslateChatConfig, wordMode);\n\n case TranslateServiceType.LMStudio:\n return new OpenAIBaseTranslateService((LMStudioTranslateSettings)_config.TranslateServiceSettings.GetValueOrDefault(serviceType, new LMStudioTranslateSettings()), _config.TranslateChatConfig, wordMode);\n\n case TranslateServiceType.KoboldCpp:\n return new OpenAIBaseTranslateService((KoboldCppTranslateSettings)_config.TranslateServiceSettings.GetValueOrDefault(serviceType, new KoboldCppTranslateSettings()), _config.TranslateChatConfig, wordMode);\n\n case TranslateServiceType.OpenAI:\n return new OpenAIBaseTranslateService((OpenAITranslateSettings)_config.TranslateServiceSettings.GetValueOrDefault(serviceType, new OpenAITranslateSettings()), _config.TranslateChatConfig, wordMode);\n\n case TranslateServiceType.OpenAILike:\n return new OpenAIBaseTranslateService((OpenAILikeTranslateSettings)_config.TranslateServiceSettings.GetValueOrDefault(serviceType, new OpenAILikeTranslateSettings()), _config.TranslateChatConfig, wordMode);\n\n case TranslateServiceType.Claude:\n return new OpenAIBaseTranslateService((ClaudeTranslateSettings)_config.TranslateServiceSettings.GetValueOrDefault(serviceType, new ClaudeTranslateSettings()), _config.TranslateChatConfig, wordMode);\n\n case TranslateServiceType.LiteLLM:\n return new OpenAIBaseTranslateService((LiteLLMTranslateSettings)_config.TranslateServiceSettings.GetValueOrDefault(serviceType, new LiteLLMTranslateSettings()), _config.TranslateChatConfig, wordMode);\n }\n\n throw new InvalidOperationException($\"Translate service {serviceType} does not exist.\");\n }\n}\n"], ["/LLPlayer/LLPlayer/Extensions/JsonInterfaceConcreteConverter.cs", "using System.Text.Json;\nusing System.Text.Json.Serialization;\n\nnamespace LLPlayer.Extensions;\n\n/// \n/// JsonConverter to serialize and deserialize interfaces with concrete types using a mapping between interfaces and concrete types\n/// \n/// \npublic class JsonInterfaceConcreteConverter : JsonConverter\n{\n private const string TypeKey = \"TypeName\";\n private readonly Dictionary _typeMapping;\n\n public JsonInterfaceConcreteConverter(Dictionary typeMapping)\n {\n _typeMapping = typeMapping;\n }\n\n public override T Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options)\n {\n using JsonDocument jsonDoc = JsonDocument.ParseValue(ref reader);\n\n if (!jsonDoc.RootElement.TryGetProperty(TypeKey, out JsonElement typeProperty))\n {\n throw new JsonException(\"Type discriminator not found.\");\n }\n\n string? typeDiscriminator = typeProperty.GetString();\n if (typeDiscriminator == null || !_typeMapping.TryGetValue(typeDiscriminator, out Type? targetType))\n {\n throw new JsonException($\"Unknown type discriminator: {typeDiscriminator}\");\n }\n\n // If a specific type is specified as the second argument, it is deserialized with that type\n return (T)JsonSerializer.Deserialize(jsonDoc.RootElement, targetType, options)!;\n }\n\n public override void Write(Utf8JsonWriter writer, T value, JsonSerializerOptions options)\n {\n Type type = value!.GetType();\n string typeDiscriminator = type.Name; // Use type name as discriminator\n\n // Serialize with concrete types, not interfaces\n string json = JsonSerializer.Serialize(value, type, options);\n using JsonDocument jsonDoc = JsonDocument.Parse(json);\n\n writer.WriteStartObject();\n // Save concrete type name\n writer.WriteString(TypeKey, typeDiscriminator);\n\n // Does this work even if it's nested?\n foreach (JsonProperty property in jsonDoc.RootElement.EnumerateObject())\n {\n property.WriteTo(writer);\n }\n\n writer.WriteEndObject();\n }\n}\n"], ["/LLPlayer/LLPlayer/Controls/Settings/SettingsPlugins.xaml.cs", "using System.Collections;\nusing System.Globalization;\nusing System.Windows;\nusing System.Windows.Controls;\nusing System.Windows.Data;\nusing LLPlayer.ViewModels;\n\nnamespace LLPlayer.Controls.Settings;\n\npublic partial class SettingsPlugins : UserControl\n{\n public SettingsPlugins()\n {\n InitializeComponent();\n }\n\n private void PluginValueChanged(object sender, RoutedEventArgs e)\n {\n string curPlugin = ((TextBlock)((Panel)((FrameworkElement)sender).Parent).Children[0]).Text;\n\n if (DataContext is SettingsDialogVM vm)\n {\n vm.FL.PlayerConfig.Plugins[cmbPlugins.Text][curPlugin] = ((TextBox)sender).Text;\n }\n }\n}\n\npublic class GetDictionaryItemConverter : IMultiValueConverter\n{\n public object? Convert(object[]? value, Type targetType, object parameter, CultureInfo culture)\n {\n if (value == null)\n return null;\n if (value[0] is not IDictionary dictionary)\n return null;\n if (value[1] is not string key)\n return null;\n\n return dictionary[key];\n }\n public object[] ConvertBack(object value, Type[] targetType, object parameter, CultureInfo culture) { throw new NotImplementedException(); }\n}\n"], ["/LLPlayer/LLPlayer/Controls/Settings/SettingsAudio.xaml.cs", "using System.Windows;\nusing System.Windows.Controls;\nusing FlyleafLib;\nusing LLPlayer.Extensions;\nusing LLPlayer.Services;\nusing LLPlayer.Views;\n\nnamespace LLPlayer.Controls.Settings;\n\npublic partial class SettingsAudio : UserControl\n{\n public SettingsAudio()\n {\n InitializeComponent();\n\n DataContext = ((App)Application.Current).Container.Resolve();\n }\n}\n\npublic class SettingsAudioVM : Bindable\n{\n private readonly IDialogService _dialogService;\n public FlyleafManager FL { get; }\n\n public SettingsAudioVM(FlyleafManager fl, IDialogService dialogService)\n {\n _dialogService = dialogService;\n FL = fl;\n }\n\n public DelegateCommand? CmdConfigureLanguage => field ??= new(() =>\n {\n DialogParameters p = new()\n {\n { \"languages\", FL.PlayerConfig.Audio.Languages }\n };\n\n _dialogService.ShowDialog(nameof(SelectLanguageDialog), p, result =>\n {\n List updated = result.Parameters.GetValue>(\"languages\");\n\n if (!FL.PlayerConfig.Audio.Languages.SequenceEqual(updated))\n {\n FL.PlayerConfig.Audio.Languages = updated;\n }\n });\n });\n}\n"], ["/LLPlayer/LLPlayer/Controls/Settings/Controls/ColorPicker.xaml.cs", "using System.Windows;\nusing System.Windows.Controls;\nusing System.Windows.Media;\nusing MaterialDesignThemes.Wpf;\n\nnamespace LLPlayer.Controls.Settings.Controls;\n\npublic partial class ColorPicker : UserControl\n{\n public ColorPicker()\n {\n InitializeComponent();\n\n Loaded += OnLoaded;\n }\n\n private void OnLoaded(object sender, RoutedEventArgs e)\n {\n // save initial color for cancellation\n _initialColor = PickerColor;\n\n MyNamedColors.SelectedItem = null;\n }\n\n private Color? _initialColor = null;\n\n public Color PickerColor\n {\n get => (Color)GetValue(PickerColorProperty);\n set => SetValue(PickerColorProperty, value);\n }\n\n public static readonly DependencyProperty PickerColorProperty =\n DependencyProperty.Register(nameof(PickerColor), typeof(Color), typeof(ColorPicker));\n\n public List> NamedColors { get; } = GetColors();\n\n private static List> GetColors()\n {\n return typeof(Colors)\n .GetProperties()\n .Where(prop =>\n typeof(Color).IsAssignableFrom(prop.PropertyType))\n .Select(prop =>\n new KeyValuePair(prop.Name, (Color)prop.GetValue(null)!))\n .ToList();\n }\n\n private void NamedColors_SelectionChanged(object sender, SelectionChangedEventArgs e)\n {\n if (MyNamedColors.SelectedItem != null)\n {\n PickerColor = ((KeyValuePair)MyNamedColors.SelectedItem).Value;\n }\n }\n\n private void ApplyButton_Click(object sender, RoutedEventArgs e)\n {\n DialogHost.CloseDialogCommand.Execute(\"apply\", this);\n }\n\n private void CancelButton_Click(object sender, RoutedEventArgs e)\n {\n if (_initialColor.HasValue)\n {\n PickerColor = _initialColor.Value;\n }\n DialogHost.CloseDialogCommand.Execute(\"cancel\", this);\n }\n}\n"], ["/LLPlayer/LLPlayer/Extensions/ColorHexJsonConverter.cs", "using System.Globalization;\nusing System.Text.Json;\nusing System.Text.Json.Serialization;\nusing System.Windows.Media;\n\nnamespace LLPlayer.Extensions;\n\n// Convert Color object to HEX string\npublic class ColorHexJsonConverter : JsonConverter\n{\n public override void Write(Utf8JsonWriter writer, Color value, JsonSerializerOptions options)\n {\n string hex = $\"#{value.A:X2}{value.R:X2}{value.G:X2}{value.B:X2}\";\n writer.WriteStringValue(hex);\n }\n\n public override Color Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options)\n {\n string? hex = null;\n try\n {\n hex = reader.GetString();\n\n if (string.IsNullOrWhiteSpace(hex))\n {\n throw new JsonException(\"Color value is null or empty.\");\n }\n\n if (!hex.StartsWith(\"#\") || (hex.Length != 7 && hex.Length != 9))\n {\n throw new JsonException($\"Invalid color format: {hex}\");\n }\n byte a = 255;\n\n int start = 1;\n\n if (hex.Length == 9)\n {\n a = byte.Parse(hex.Substring(1, 2), NumberStyles.HexNumber);\n start = 3;\n }\n\n byte r = byte.Parse(hex.Substring(start, 2), NumberStyles.HexNumber);\n byte g = byte.Parse(hex.Substring(start + 2, 2), NumberStyles.HexNumber);\n byte b = byte.Parse(hex.Substring(start + 4, 2), NumberStyles.HexNumber);\n\n return Color.FromArgb(a, r, g, b);\n }\n catch (Exception ex)\n {\n throw new JsonException($\"Error parsing color value: {hex}\", ex);\n }\n }\n}\n"], ["/LLPlayer/LLPlayer/Views/FlyleafOverlay.xaml.cs", "using System.Windows;\nusing System.Windows.Controls;\nusing LLPlayer.ViewModels;\n\nnamespace LLPlayer.Views;\n\npublic partial class FlyleafOverlay : UserControl\n{\n private FlyleafOverlayVM VM => (FlyleafOverlayVM)DataContext;\n\n public FlyleafOverlay()\n {\n InitializeComponent();\n\n DataContext = ((App)Application.Current).Container.Resolve();\n }\n\n private void FlyleafOverlay_OnSizeChanged(object sender, SizeChangedEventArgs e)\n {\n if (e.HeightChanged)\n {\n // The height of MainWindow cannot be used because it includes the title bar,\n // so the height is obtained here and passed on.\n double heightDiff = Math.Abs(e.NewSize.Height - e.PreviousSize.Height);\n\n if (heightDiff >= 1.0)\n {\n VM.FL.Config.ScreenWidth = e.NewSize.Width;\n VM.FL.Config.ScreenHeight = e.NewSize.Height;\n }\n }\n }\n}\n"], ["/LLPlayer/FlyleafLib/MediaFramework/MediaStream/ExternalVideoStream.cs", "namespace FlyleafLib.MediaFramework.MediaStream;\n\npublic class ExternalVideoStream : ExternalStream\n{\n public double FPS { get; set; }\n public int Height { get; set; }\n public int Width { get; set; }\n\n public bool HasAudio { get; set; }\n\n public string DisplayMember =>\n $\"{Width}x{Height} @{Math.Round(FPS, 2, MidpointRounding.AwayFromZero)} ({Codec}) [{Protocol}]{(HasAudio ? \"\" : \" [NA]\")}\";\n}\n"], ["/LLPlayer/LLPlayer/Extensions/FocusBehavior.cs", "using System.Windows;\nusing System.Windows.Controls;\nusing System.Windows.Threading;\n\nnamespace LLPlayer.Extensions;\n\npublic static class FocusBehavior\n{\n public static readonly DependencyProperty IsFocusedProperty =\n DependencyProperty.RegisterAttached(\n \"IsFocused\",\n typeof(bool),\n typeof(FocusBehavior),\n new UIPropertyMetadata(false, OnIsFocusedChanged));\n\n public static bool GetIsFocused(DependencyObject obj) =>\n (bool)obj.GetValue(IsFocusedProperty);\n\n public static void SetIsFocused(DependencyObject obj, bool value) =>\n obj.SetValue(IsFocusedProperty, value);\n\n private static void OnIsFocusedChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)\n {\n if (!(d is UIElement element) || !(e.NewValue is bool isFocused) || !isFocused)\n return;\n\n // Set focus to element\n element.Dispatcher.BeginInvoke(() =>\n {\n element.Focus();\n if (element is TextBox tb)\n {\n // if TextBox, then select text\n tb.SelectAll();\n //tb.CaretIndex = tb.Text.Length;\n }\n }, DispatcherPriority.Input);\n }\n}\n"], ["/LLPlayer/LLPlayer/Extensions/UIHelper.cs", "using System.Windows;\nusing System.Windows.Media;\n\nnamespace LLPlayer.Extensions;\n\npublic static class UIHelper\n{\n // ref: https://www.infragistics.com/community/blogs/b/blagunas/posts/find-the-parent-control-of-a-specific-type-in-wpf-and-silverlight\n public static T? FindParent(DependencyObject child) where T : DependencyObject\n {\n //get parent item\n DependencyObject? parentObject = VisualTreeHelper.GetParent(child);\n\n //we've reached the end of the tree\n if (parentObject == null)\n return null;\n\n //check if the parent matches the type we're looking for\n if (parentObject is T parent)\n return parent;\n\n return FindParent(parentObject);\n }\n\n /// \n /// Traverses the visual tree upward from the current element to determine if an element with the specified name exists.j\n /// \n /// Element to start with (current element)\n /// Name of the element\n /// True if the element with the specified name exists, false otherwise.\n public static bool FindParentWithName(DependencyObject? element, string name)\n {\n if (element == null)\n {\n return false;\n }\n\n DependencyObject? current = element;\n\n while (current != null)\n {\n if (current is FrameworkElement fe && fe.Name == name)\n {\n return true;\n }\n\n current = VisualTreeHelper.GetParent(current);\n }\n\n return false;\n }\n}\n"], ["/LLPlayer/LLPlayer/Extensions/WindowsClipboard.cs", "using System.ComponentModel;\nusing System.Runtime.InteropServices;\n\nnamespace LLPlayer.Extensions;\n\n// ref: https://stackoverflow.com/questions/44205260/net-core-copy-to-clipboard\npublic static class WindowsClipboard\n{\n public static void SetText(string text)\n {\n OpenClipboard();\n\n EmptyClipboard();\n IntPtr hGlobal = 0;\n try\n {\n int bytes = (text.Length + 1) * 2;\n hGlobal = Marshal.AllocHGlobal(bytes);\n\n if (hGlobal == 0)\n {\n ThrowWin32();\n }\n\n IntPtr target = GlobalLock(hGlobal);\n\n if (target == 0)\n {\n ThrowWin32();\n }\n\n try\n {\n Marshal.Copy(text.ToCharArray(), 0, target, text.Length);\n }\n finally\n {\n GlobalUnlock(target);\n }\n\n if (SetClipboardData(cfUnicodeText, hGlobal) == 0)\n {\n ThrowWin32();\n }\n\n hGlobal = 0;\n }\n finally\n {\n if (hGlobal != 0)\n {\n Marshal.FreeHGlobal(hGlobal);\n }\n\n CloseClipboard();\n }\n }\n\n public static void OpenClipboard()\n {\n int num = 10;\n while (true)\n {\n if (OpenClipboard(0))\n {\n break;\n }\n\n if (--num == 0)\n {\n ThrowWin32();\n }\n\n Thread.Sleep(20);\n }\n }\n\n const uint cfUnicodeText = 13;\n\n static void ThrowWin32()\n {\n throw new Win32Exception(Marshal.GetLastWin32Error());\n }\n\n [DllImport(\"kernel32.dll\", SetLastError = true)]\n static extern IntPtr GlobalLock(IntPtr hMem);\n\n [DllImport(\"kernel32.dll\", SetLastError = true)]\n [return: MarshalAs(UnmanagedType.Bool)]\n static extern bool GlobalUnlock(IntPtr hMem);\n\n [DllImport(\"user32.dll\", SetLastError = true)]\n [return: MarshalAs(UnmanagedType.Bool)]\n static extern bool OpenClipboard(IntPtr hWndNewOwner);\n\n [DllImport(\"user32.dll\", SetLastError = true)]\n [return: MarshalAs(UnmanagedType.Bool)]\n static extern bool CloseClipboard();\n\n [DllImport(\"user32.dll\", SetLastError = true)]\n static extern IntPtr SetClipboardData(uint uFormat, IntPtr data);\n\n [DllImport(\"user32.dll\")]\n static extern bool EmptyClipboard();\n}\n"], ["/LLPlayer/LLPlayer/Views/CheatSheetDialog.xaml.cs", "using System.Globalization;\nusing System.Windows;\nusing System.Windows.Controls;\nusing System.Windows.Data;\nusing System.Windows.Input;\nusing LLPlayer.ViewModels;\n\nnamespace LLPlayer.Views;\n\npublic partial class CheatSheetDialog : UserControl\n{\n public CheatSheetDialog()\n {\n InitializeComponent();\n\n DataContext = ((App)Application.Current).Container.Resolve();\n }\n\n private void OnLoaded(object sender, RoutedEventArgs e)\n {\n Window? window = Window.GetWindow(this);\n window!.CommandBindings.Add(new CommandBinding(ApplicationCommands.Find, OnFindExecuted));\n }\n\n private void OnFindExecuted(object sender, ExecutedRoutedEventArgs e)\n {\n SearchBox.Focus();\n SearchBox.SelectAll();\n e.Handled = true;\n }\n}\n\n[ValueConversion(typeof(int), typeof(Visibility))]\npublic class CountToVisibilityConverter : IValueConverter\n{\n public object Convert(object value, Type targetType, object parameter, CultureInfo culture)\n {\n if (int.TryParse(value.ToString(), out var count))\n {\n return count == 0 ? Visibility.Collapsed : Visibility.Visible;\n }\n\n return Visibility.Visible;\n }\n\n public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)\n {\n throw new NotImplementedException();\n }\n}\n"], ["/LLPlayer/LLPlayer/Views/ErrorDialog.xaml.cs", "using System.Windows;\nusing LLPlayer.ViewModels;\nusing System.Windows.Controls;\nusing System.Windows.Input;\n\nnamespace LLPlayer.Views;\n\npublic partial class ErrorDialog : UserControl\n{\n private ErrorDialogVM VM => (ErrorDialogVM)DataContext;\n\n public ErrorDialog()\n {\n InitializeComponent();\n\n DataContext = ((App)Application.Current).Container.Resolve();\n }\n\n private void FrameworkElement_OnLoaded(object sender, RoutedEventArgs e)\n {\n Keyboard.Focus(sender as IInputElement);\n }\n\n private void ErrorDialog_OnMouseLeftButtonDown(object sender, MouseButtonEventArgs e)\n {\n Keyboard.Focus(sender as IInputElement);\n }\n\n // Topmost dialog, so it should be draggable\n private void Window_MouseDown(object sender, MouseButtonEventArgs e)\n {\n if (sender is not Window window)\n return;\n\n if (e.ChangedButton == MouseButton.Left)\n {\n window.DragMove();\n }\n }\n\n // Make TextBox uncopyable\n private void TextBox_PreviewMouseDown(object sender, ExecutedRoutedEventArgs e)\n {\n if (e.Command == ApplicationCommands.Copy ||\n e.Command == ApplicationCommands.Cut ||\n e.Command == ApplicationCommands.Paste)\n {\n e.Handled = true;\n\n if (e.Command == ApplicationCommands.Copy)\n {\n // instead trigger copy command\n VM.CmdCopyMessage.Execute();\n }\n }\n }\n}\n"], ["/LLPlayer/LLPlayer/Extensions/StringExtensions.cs", "using System.IO;\n\nnamespace LLPlayer.Extensions;\n\npublic static class StringExtensions\n{\n /// \n /// Split for various types of newline codes\n /// \n /// \n /// \n public static IEnumerable SplitToLines(this string? input)\n {\n if (input == null)\n {\n yield break;\n }\n\n using StringReader reader = new(input);\n\n string? line;\n while ((line = reader.ReadLine()) != null)\n {\n yield return line;\n }\n }\n\n /// \n /// Convert only the first character to lower case\n /// \n /// \n /// \n public static string ToLowerFirstChar(this string input)\n {\n if (string.IsNullOrEmpty(input))\n return input;\n\n return char.ToLower(input[0]) + input.Substring(1);\n }\n\n /// \n /// Convert only the first character to upper case\n /// \n /// \n /// \n public static string ToUpperFirstChar(this string input)\n {\n if (string.IsNullOrEmpty(input))\n return input;\n\n return char.ToUpper(input[0]) + input.Substring(1);\n }\n}\n"], ["/LLPlayer/FlyleafLib/MediaPlayer/Translation/TranslateChatConfig.cs", "namespace FlyleafLib.MediaPlayer.Translation;\n\npublic class TranslateChatConfig : NotifyPropertyChanged\n{\n public const string DefaultPromptOneByOne =\n \"\"\"\n You are a professional subtitle translator, translate from {source_lang} to {target_lang}, keep sentences in {target_lang} as they are, censoring of translations is prohibited, return only the translated text without the sent text or notes or comments or anything:\n\n {source_text}\n \"\"\";\n\n public const string DefaultPromptKeepContext =\n \"\"\"\n You are a professional subtitle translator.\n I will send the text of the subtitles of the video one at a time.\n Please translate the text while taking into account the context of the previous text.\n\n Translate from {source_lang} to {target_lang}.\n Return only the translated text without the sent text or notes or comments or anything.\n Keep sentences in {target_lang} as they are.\n Censoring of translations is prohibited.\n \"\"\";\n\n public string PromptOneByOne { get; set => Set(ref field, value); } = DefaultPromptOneByOne.ReplaceLineEndings(\"\\n\");\n\n public string PromptKeepContext { get; set => Set(ref field, value); } = DefaultPromptKeepContext.ReplaceLineEndings(\"\\n\");\n\n public ChatTranslateMethod TranslateMethod { get; set => Set(ref field, value); } = ChatTranslateMethod.KeepContext;\n\n public int SubtitleContextCount { get; set => Set(ref field, value); } = 6;\n\n public ChatContextRetainPolicy ContextRetainPolicy { get; set => Set(ref field, value); } = ChatContextRetainPolicy.Reset;\n\n public bool IncludeTargetLangRegion { get; set => Set(ref field, value); } = true;\n}\n\npublic enum ChatTranslateMethod\n{\n KeepContext,\n OneByOne\n}\n\npublic enum ChatContextRetainPolicy\n{\n Reset,\n KeepSize\n}\n"], ["/LLPlayer/LLPlayer/ViewModels/SettingsDialogVM.cs", "using LLPlayer.Extensions;\nusing LLPlayer.Services;\n\nnamespace LLPlayer.ViewModels;\n\npublic class SettingsDialogVM : Bindable, IDialogAware\n{\n public FlyleafManager FL { get; }\n public SettingsDialogVM(FlyleafManager fl)\n {\n FL = fl;\n }\n\n public DelegateCommand? CmdCloseDialog => field ??= new((parameter) =>\n {\n ButtonResult result = ButtonResult.None;\n\n if (parameter == \"Save\")\n {\n result = ButtonResult.OK;\n }\n\n RequestClose.Invoke(result);\n });\n\n #region IDialogAware\n public string Title { get; set => Set(ref field, value); } = $\"Settings - {App.Name}\";\n public double WindowWidth { get; set => Set(ref field, value); } = 1000;\n public double WindowHeight { get; set => Set(ref field, value); } = 700;\n\n public bool CanCloseDialog() => true;\n\n public void OnDialogClosed()\n {\n }\n\n public void OnDialogOpened(IDialogParameters parameters)\n {\n }\n\n public DialogCloseListener RequestClose { get; }\n #endregion\n}\n"], ["/LLPlayer/FlyleafLib/MediaFramework/MediaStream/ExternalAudioStream.cs", "namespace FlyleafLib.MediaFramework.MediaStream;\n\npublic class ExternalAudioStream : ExternalStream\n{\n public int SampleRate { get; set; }\n public string ChannelLayout { get; set; }\n public Language Language { get; set; }\n\n public bool HasVideo { get; set; }\n}\n"], ["/LLPlayer/FlyleafLib/Controls/WPF/RelayCommand.cs", "using System;\nusing System.Windows.Input;\n\nnamespace FlyleafLib.Controls.WPF;\n\npublic class RelayCommand : ICommand\n{\n private Action execute;\n\n private Predicate canExecute;\n\n private event EventHandler CanExecuteChangedInternal;\n\n public RelayCommand(Action execute) : this(execute, DefaultCanExecute) { }\n\n public RelayCommand(Action execute, Predicate canExecute)\n {\n this.execute = execute ?? throw new ArgumentNullException(\"execute\");\n this.canExecute = canExecute ?? throw new ArgumentNullException(\"canExecute\");\n }\n\n public event EventHandler CanExecuteChanged\n {\n add\n {\n CommandManager.RequerySuggested += value;\n CanExecuteChangedInternal += value;\n }\n\n remove\n {\n CommandManager.RequerySuggested -= value;\n CanExecuteChangedInternal -= value;\n }\n }\n\n private static bool DefaultCanExecute(object parameter) => true;\n public bool CanExecute(object parameter) => canExecute != null && canExecute(parameter);\n\n public void Execute(object parameter) => execute(parameter);\n\n public void OnCanExecuteChanged()\n {\n var handler = CanExecuteChangedInternal;\n handler?.Invoke(this, EventArgs.Empty);\n //CommandManager.InvalidateRequerySuggested();\n }\n\n public void Destroy()\n {\n canExecute = _ => false;\n execute = _ => { return; };\n }\n}\n"], ["/LLPlayer/LLPlayer/Resources/MaterialDesignMy.xaml.cs", "using System.Windows;\nusing System.Windows.Controls;\nusing System.Windows.Input;\n\nnamespace LLPlayer.Resources;\n\npublic partial class MaterialDesignMy : ResourceDictionary\n{\n public MaterialDesignMy()\n {\n InitializeComponent();\n }\n\n /// \n /// Do not close the menu when right-clicking or CTRL+left-clicking on a context menu\n /// This is achieved by dynamically setting StaysOpenOnClick\n /// \n /// \n /// \n private void MenuItem_PreviewMouseDown(object sender, MouseButtonEventArgs e)\n {\n if (sender is MenuItem menuItem)\n {\n if ((Keyboard.IsKeyDown(Key.LeftCtrl) || Keyboard.IsKeyDown(Key.RightCtrl)) ||\n Mouse.RightButton == MouseButtonState.Pressed)\n {\n menuItem.StaysOpenOnClick = true;\n }\n else if (menuItem.StaysOpenOnClick)\n {\n menuItem.StaysOpenOnClick = false;\n }\n }\n }\n}\n"], ["/LLPlayer/WpfColorFontDialog/ColorPicker.xaml.cs", "using System;\nusing System.Collections.Generic;\nusing System.Linq;\nusing System.Text;\nusing System.Windows;\nusing System.Windows.Controls;\nusing System.Windows.Data;\nusing System.Windows.Documents;\nusing System.Windows.Input;\nusing System.Windows.Media;\nusing System.Windows.Media.Imaging;\nusing System.Windows.Navigation;\nusing System.Windows.Shapes;\n\nnamespace WpfColorFontDialog\n{\n /// \n /// Interaction logic for ColorPicker.xaml\n /// \n public partial class ColorPicker : UserControl\n {\n private ColorPickerViewModel viewModel;\n\n public readonly static RoutedEvent ColorChangedEvent;\n\n public readonly static DependencyProperty SelectedColorProperty;\n\n public FontColor SelectedColor\n {\n get\n {\n FontColor fc = (FontColor)base.GetValue(ColorPicker.SelectedColorProperty) ?? AvailableColors.GetFontColor(\"Black\");\n return fc;\n }\n set\n {\n this.viewModel.SelectedFontColor = value;\n base.SetValue(ColorPicker.SelectedColorProperty, value);\n }\n }\n\n static ColorPicker()\n {\n ColorPicker.ColorChangedEvent = EventManager.RegisterRoutedEvent(\"ColorChanged\", RoutingStrategy.Bubble, typeof(RoutedEventHandler), typeof(ColorPicker));\n ColorPicker.SelectedColorProperty = DependencyProperty.Register(\"SelectedColor\", typeof(FontColor), typeof(ColorPicker), new UIPropertyMetadata(null));\n }\n public ColorPicker()\n {\n InitializeComponent();\n this.viewModel = new ColorPickerViewModel();\n base.DataContext = this.viewModel;\n }\n private void RaiseColorChangedEvent()\n {\n base.RaiseEvent(new RoutedEventArgs(ColorPicker.ColorChangedEvent));\n }\n\n private void superCombo_DropDownClosed(object sender, EventArgs e)\n {\n base.SetValue(ColorPicker.SelectedColorProperty, this.viewModel.SelectedFontColor);\n this.RaiseColorChangedEvent();\n }\n\n private void superCombo_Loaded(object sender, RoutedEventArgs e)\n {\n base.SetValue(ColorPicker.SelectedColorProperty, this.viewModel.SelectedFontColor);\n }\n\n public event RoutedEventHandler ColorChanged\n {\n add\n {\n base.AddHandler(ColorPicker.ColorChangedEvent, value);\n }\n remove\n {\n base.RemoveHandler(ColorPicker.ColorChangedEvent, value);\n }\n }\n }\n}\n"], ["/LLPlayer/LLPlayer/Services/ErrorDialogHelper.cs", "using System.Windows;\nusing FlyleafLib.MediaPlayer;\nusing LLPlayer.Views;\n\nnamespace LLPlayer.Services;\n\npublic static class ErrorDialogHelper\n{\n public static void ShowKnownErrorPopup(string message, string errorType)\n {\n var dialogService = ((App)Application.Current).Container.Resolve();\n\n DialogParameters p = new()\n {\n { \"type\", \"known\" },\n { \"message\", message },\n { \"errorType\", errorType }\n };\n\n dialogService.ShowDialog(nameof(ErrorDialog), p);\n }\n\n public static void ShowKnownErrorPopup(string message, KnownErrorType errorType)\n {\n ShowKnownErrorPopup(message, errorType.ToString());\n }\n\n public static void ShowUnknownErrorPopup(string message, string errorType, Exception? ex = null)\n {\n var dialogService = ((App)Application.Current).Container.Resolve();\n\n DialogParameters p = new()\n {\n { \"type\", \"unknown\" },\n { \"message\", message },\n { \"errorType\", errorType },\n };\n\n if (ex != null)\n {\n p.Add(\"exception\", ex);\n }\n\n dialogService.ShowDialog(nameof(ErrorDialog), p);\n }\n\n public static void ShowUnknownErrorPopup(string message, UnknownErrorType errorType, Exception? ex = null)\n {\n ShowUnknownErrorPopup(message, errorType.ToString(), ex);\n }\n}\n"], ["/LLPlayer/LLPlayer/Extensions/TextBoxMiscHelper.cs", "using System.Text.RegularExpressions;\nusing System.Windows;\nusing System.Windows.Controls;\nusing System.Windows.Input;\n\nnamespace LLPlayer.Extensions;\n\npublic static class TextBoxMiscHelper\n{\n public static bool GetIsHexValidationEnabled(DependencyObject obj)\n {\n return (bool)obj.GetValue(IsHexValidationEnabledProperty);\n }\n\n public static void SetIsHexValidationEnabled(DependencyObject obj, bool value)\n {\n obj.SetValue(IsHexValidationEnabledProperty, value);\n }\n\n public static readonly DependencyProperty IsHexValidationEnabledProperty =\n DependencyProperty.RegisterAttached(\n \"IsHexValidationEnabled\",\n typeof(bool),\n typeof(TextBoxMiscHelper),\n new UIPropertyMetadata(false, OnIsHexValidationEnabledChanged));\n\n private static void OnIsHexValidationEnabledChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)\n {\n if (d is TextBox textBox)\n {\n if ((bool)e.NewValue)\n {\n textBox.PreviewTextInput += OnPreviewTextInput;\n }\n else\n {\n textBox.PreviewTextInput -= OnPreviewTextInput;\n }\n }\n }\n\n private static void OnPreviewTextInput(object sender, TextCompositionEventArgs e)\n {\n e.Handled = !Regex.IsMatch(e.Text, \"^[0-9a-f]+$\", RegexOptions.IgnoreCase);\n }\n}\n"], ["/LLPlayer/LLPlayer/Resources/Validators.xaml.cs", "using System.Globalization;\nusing System.Text.RegularExpressions;\nusing System.Windows;\nusing System.Windows.Controls;\n\nnamespace LLPlayer.Resources;\n\npublic partial class Validators : ResourceDictionary\n{\n public Validators()\n {\n InitializeComponent();\n }\n}\n\npublic class ColorHexRule : ValidationRule\n{\n public override ValidationResult Validate(object? value, CultureInfo cultureInfo)\n {\n if (value != null && Regex.IsMatch(value.ToString() ?? string.Empty, \"^[0-9a-f]{6}$\", RegexOptions.IgnoreCase))\n {\n return new ValidationResult(true, null);\n }\n\n return new ValidationResult(false, \"Invalid\");\n }\n}\n"], ["/LLPlayer/LLPlayer/Views/SubtitlesExportDialog.xaml.cs", "using System.Windows;\nusing System.Windows.Controls;\nusing LLPlayer.ViewModels;\n\nnamespace LLPlayer.Views;\n\npublic partial class SubtitlesExportDialog : UserControl\n{\n public SubtitlesExportDialog()\n {\n InitializeComponent();\n\n DataContext = ((App)Application.Current).Container.Resolve();\n }\n}\n"], ["/LLPlayer/LLPlayer/Views/SubtitlesDownloaderDialog.xaml.cs", "using System.Windows;\nusing System.Windows.Controls;\nusing LLPlayer.ViewModels;\n\nnamespace LLPlayer.Views;\n\npublic partial class SubtitlesDownloaderDialog : UserControl\n{\n public SubtitlesDownloaderDialog()\n {\n InitializeComponent();\n\n DataContext = ((App)Application.Current).Container.Resolve();\n }\n}\n"], ["/LLPlayer/FlyleafLib/MediaFramework/MediaDevice/DeviceStreamBase.cs", "namespace FlyleafLib.MediaFramework.MediaDevice;\n\npublic class DeviceStreamBase\n{\n public string DeviceFriendlyName { get; }\n public string Url { get; protected set; }\n\n public DeviceStreamBase(string deviceFriendlyName) => DeviceFriendlyName = deviceFriendlyName;\n}\n"], ["/LLPlayer/FlyleafLib/Controls/WPF/Converters.cs", "using System.Globalization;\nusing System.Windows.Data;\n\nnamespace FlyleafLib.Controls.WPF;\n\n[ValueConversion(typeof(long), typeof(TimeSpan))]\npublic class TicksToTimeSpanConverter : IValueConverter\n{\n public object Convert(object value, Type targetType, object parameter, CultureInfo culture) => new TimeSpan((long)value);\n public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture) => ((TimeSpan)value).Ticks;\n}\n\n[ValueConversion(typeof(long), typeof(string))]\npublic class TicksToTimeConverter : IValueConverter\n{\n public object Convert(object value, Type targetType, object parameter, CultureInfo culture) => new TimeSpan((long)value).ToString(@\"hh\\:mm\\:ss\");\n public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture) => throw new NotImplementedException();\n}\n\n[ValueConversion(typeof(long), typeof(double))]\npublic class TicksToSecondsConverter : IValueConverter\n{\n public object Convert(object value, Type targetType, object parameter, CultureInfo culture) => (long)value / 10000000.0;\n\n public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture) => (long)((double)value * 10000000);\n}\n\n[ValueConversion(typeof(long), typeof(int))]\npublic class TicksToMilliSecondsConverter : IValueConverter\n{\n public object Convert(object value, Type targetType, object parameter, CultureInfo culture) => (int)((long)value / 10000);\n\n public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture) => long.Parse(value.ToString()) * 10000;\n}\n\n[ValueConversion(typeof(AspectRatio), typeof(string))]\npublic class StringToRationalConverter : IValueConverter\n{\n public object Convert(object value, Type targetType, object parameter, CultureInfo culture) => value.ToString();\n\n public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture) => new AspectRatio(value.ToString());\n}\n"], ["/LLPlayer/WpfColorFontDialog/FontSizeListBoxItemToDoubleConverter.cs", "using System;\nusing System.Globalization;\nusing System.Windows.Controls;\nusing System.Windows.Data;\n\nnamespace WpfColorFontDialog\n{\n\tpublic class FontSizeListBoxItemToDoubleConverter : IValueConverter\n\t{\n\t\tpublic FontSizeListBoxItemToDoubleConverter()\n\t\t{\n\t\t}\n\n\t\tobject System.Windows.Data.IValueConverter.Convert(object value, Type targetType, object parameter, CultureInfo culture)\n\t\t{\n string str = value.ToString();\n try\n {\n return double.Parse(value.ToString());\n }\n catch(FormatException)\n {\n return 0;\n }\n\n }\n\n\t\tobject System.Windows.Data.IValueConverter.ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)\n\t\t{\n\t\t\tthrow new NotImplementedException();\n\t\t}\n\t}\n}"], ["/LLPlayer/LLPlayer/Extensions/HyperLinkHelper.cs", "using System.Diagnostics;\nusing System.Windows;\nusing System.Windows.Documents;\nusing System.Windows.Navigation;\n\nnamespace LLPlayer.Extensions;\n\npublic static class HyperlinkHelper\n{\n public static readonly DependencyProperty OpenInBrowserProperty =\n DependencyProperty.RegisterAttached(\n \"OpenInBrowser\",\n typeof(bool),\n typeof(HyperlinkHelper),\n new PropertyMetadata(false, OnOpenInBrowserChanged));\n\n public static bool GetOpenInBrowser(DependencyObject obj)\n {\n return (bool)obj.GetValue(OpenInBrowserProperty);\n }\n\n public static void SetOpenInBrowser(DependencyObject obj, bool value)\n {\n obj.SetValue(OpenInBrowserProperty, value);\n }\n\n private static void OnOpenInBrowserChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)\n {\n if (d is Hyperlink hyperlink)\n {\n bool newValue = (bool)e.NewValue;\n if (newValue)\n {\n hyperlink.RequestNavigate += OnRequestNavigate;\n }\n else\n {\n hyperlink.RequestNavigate -= OnRequestNavigate;\n }\n }\n }\n\n private static void OnRequestNavigate(object sender, RequestNavigateEventArgs e)\n {\n OpenUrlInBrowser(e.Uri.AbsoluteUri);\n e.Handled = true;\n }\n\n public static void OpenUrlInBrowser(string url)\n {\n Process.Start(new ProcessStartInfo\n {\n FileName = url,\n UseShellExecute = true\n });\n }\n}\n"], ["/LLPlayer/WpfColorFontDialog/ColorPickerViewModel.cs", "using System;\nusing System.Collections.ObjectModel;\nusing System.ComponentModel;\nusing System.Threading;\nusing System.Windows.Media;\n\nnamespace WpfColorFontDialog\n{\n\tinternal class ColorPickerViewModel : INotifyPropertyChanged\n\t{\n\t\tprivate ReadOnlyCollection roFontColors;\n\n\t\tprivate FontColor selectedFontColor;\n\n\t\tpublic ReadOnlyCollection FontColors\n\t\t{\n\t\t\tget\n\t\t\t{\n\t\t\t\treturn this.roFontColors;\n\t\t\t}\n\t\t}\n\n\t\tpublic FontColor SelectedFontColor\n\t\t{\n\t\t\tget\n\t\t\t{\n\t\t\t\treturn this.selectedFontColor;\n\t\t\t}\n\t\t\tset\n\t\t\t{\n\t\t\t\tif (this.selectedFontColor == value)\n\t\t\t\t{\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t\tthis.selectedFontColor = value;\n\t\t\t\tthis.OnPropertyChanged(\"SelectedFontColor\");\n\t\t\t}\n\t\t}\n\n\t\tpublic ColorPickerViewModel()\n\t\t{\n\t\t\tthis.selectedFontColor = AvailableColors.GetFontColor(Colors.Black);\n\t\t\tthis.roFontColors = new ReadOnlyCollection(new AvailableColors());\n\t\t}\n\n\t\tprivate void OnPropertyChanged(string propertyName)\n\t\t{\n\t\t\tif (this.PropertyChanged != null)\n\t\t\t{\n\t\t\t\tthis.PropertyChanged(this, new PropertyChangedEventArgs(propertyName));\n\t\t\t}\n\t\t}\n\n\t\tpublic event PropertyChangedEventHandler PropertyChanged;\n\t}\n}"], ["/LLPlayer/LLPlayer/Resources/PopupMenu.xaml.cs", "using System.Windows;\nusing System.Windows.Controls;\nusing LLPlayer.ViewModels;\n\nnamespace LLPlayer.Resources;\n\npublic partial class PopupMenu : ResourceDictionary\n{\n public PopupMenu()\n {\n InitializeComponent();\n }\n\n private void PopUpMenu_OnOpened(object sender, RoutedEventArgs e)\n {\n // TODO: L: should validate that the clipboard content is a video file?\n bool canPaste = !string.IsNullOrEmpty(Clipboard.GetText());\n MenuPasteUrl.IsEnabled = canPaste;\n\n // Don't hide the seek bar while displaying the context menu\n if (sender is ContextMenu menu && menu.DataContext is FlyleafOverlayVM vm)\n {\n vm.FL.Player.Activity.IsEnabled = false;\n }\n }\n\n private void PopUpMenu_OnClosed(object sender, RoutedEventArgs e)\n {\n if (sender is ContextMenu menu && menu.DataContext is FlyleafOverlayVM vm)\n {\n vm.FL.Player.Activity.IsEnabled = true;\n }\n }\n}\n"], ["/LLPlayer/FlyleafLib/MediaFramework/MediaDevice/AudioDeviceStream.cs", "namespace FlyleafLib.MediaFramework.MediaDevice;\n\npublic class AudioDeviceStream : DeviceStreamBase\n{\n public AudioDeviceStream(string deviceName) : base(deviceName) { }\n}\n"], ["/LLPlayer/LLPlayer/Extensions/Guards.cs", "using System.Diagnostics.CodeAnalysis;\nusing System.Runtime.CompilerServices;\n\nnamespace LLPlayer.Extensions;\n\npublic static class Guards\n{\n /// Throws an immediately.\n /// error message\n /// \n public static void Fail(string? message = null)\n {\n throw new InvalidOperationException(message);\n }\n\n /// Throws an if is null.\n /// The reference type variable to validate as non-null.\n /// The name of the variable with which corresponds.\n /// \n public static void ThrowIfNull([NotNull] object? variable, [CallerArgumentExpression(nameof(variable))] string? variableName = null)\n {\n if (variable is null)\n {\n throw new InvalidOperationException(variableName);\n }\n }\n}\n"], ["/LLPlayer/WpfColorFontDialog/FontColor.cs", "using System;\nusing System.Runtime.CompilerServices;\nusing System.Windows;\nusing System.Windows.Media;\n\nnamespace WpfColorFontDialog\n{\n\tpublic class FontColor\n\t{\n\t\tpublic SolidColorBrush Brush\n\t\t{\n\t\t\tget;\n\t\t\tset;\n\t\t}\n\n\t\tpublic string Name\n\t\t{\n\t\t\tget;\n\t\t\tset;\n\t\t}\n\n\t\tpublic FontColor(string name, SolidColorBrush brush)\n\t\t{\n\t\t\tthis.Name = name;\n\t\t\tthis.Brush = brush;\n\t\t}\n\n\t\tpublic override bool Equals(object obj)\n\t\t{\n\t\t\tif (obj == null)\n\t\t\t{\n\t\t\t\treturn false;\n\t\t\t}\n\t\t\tFontColor p = obj as FontColor;\n\t\t\tif (p == null)\n\t\t\t{\n\t\t\t\treturn false;\n\t\t\t}\n\t\t\tif (this.Name != p.Name)\n\t\t\t{\n\t\t\t\treturn false;\n\t\t\t}\n\t\t\treturn this.Brush.Equals(p.Brush);\n\t\t}\n\n\t\tpublic bool Equals(FontColor p)\n\t\t{\n\t\t\tif (p == null)\n\t\t\t{\n\t\t\t\treturn false;\n\t\t\t}\n\t\t\tif (this.Name != p.Name)\n\t\t\t{\n\t\t\t\treturn false;\n\t\t\t}\n\t\t\treturn this.Brush.Equals(p.Brush);\n\t\t}\n\n\t\tpublic override int GetHashCode()\n\t\t{\n\t\t\treturn base.GetHashCode();\n\t\t}\n\n\t\tpublic override string ToString()\n\t\t{\n\t\t\tstring[] name = new string[] { \"FontColor [Color=\", this.Name, \", \", this.Brush.ToString(), \"]\" };\n\t\t\treturn string.Concat(name);\n\t\t}\n\t}\n}"], ["/LLPlayer/LLPlayer/Controls/Settings/SettingsSubtitlesPS.xaml.cs", "using System.Windows.Controls;\n\nnamespace LLPlayer.Controls.Settings;\n\npublic partial class SettingsSubtitlesPS : UserControl\n{\n public SettingsSubtitlesPS()\n {\n InitializeComponent();\n }\n}\n"], ["/LLPlayer/FlyleafLib/Controls/WPF/PlayerDebug.xaml.cs", "using System.Windows;\nusing System.Windows.Controls;\nusing System.Windows.Media;\n\nusing FlyleafLib.MediaPlayer;\n\nnamespace FlyleafLib.Controls.WPF;\n\npublic partial class PlayerDebug : UserControl\n{\n public Player Player\n {\n get => (Player)GetValue(PlayerProperty);\n set => SetValue(PlayerProperty, value);\n }\n\n public static readonly DependencyProperty PlayerProperty =\n DependencyProperty.Register(\"Player\", typeof(Player), typeof(PlayerDebug), new PropertyMetadata(null));\n\n public Brush BoxColor\n {\n get => (Brush)GetValue(BoxColorProperty);\n set => SetValue(BoxColorProperty, value);\n }\n\n public static readonly DependencyProperty BoxColorProperty =\n DependencyProperty.Register(\"BoxColor\", typeof(Brush), typeof(PlayerDebug), new PropertyMetadata(new SolidColorBrush((Color)ColorConverter.ConvertFromString(\"#D0000000\"))));\n\n public Brush HeaderColor\n {\n get => (Brush)GetValue(HeaderColorProperty);\n set => SetValue(HeaderColorProperty, value);\n }\n\n public static readonly DependencyProperty HeaderColorProperty =\n DependencyProperty.Register(\"HeaderColor\", typeof(Brush), typeof(PlayerDebug), new PropertyMetadata(new SolidColorBrush(Colors.LightSalmon)));\n\n public Brush InfoColor\n {\n get => (Brush)GetValue(InfoColorProperty);\n set => SetValue(InfoColorProperty, value);\n }\n\n public static readonly DependencyProperty InfoColorProperty =\n DependencyProperty.Register(\"InfoColor\", typeof(Brush), typeof(PlayerDebug), new PropertyMetadata(new SolidColorBrush(Colors.LightSteelBlue)));\n\n public Brush ValueColor\n {\n get => (Brush)GetValue(ValueColorProperty);\n set => SetValue(ValueColorProperty, value);\n }\n\n public static readonly DependencyProperty ValueColorProperty =\n DependencyProperty.Register(\"ValueColor\", typeof(Brush), typeof(PlayerDebug), new PropertyMetadata(new SolidColorBrush(Colors.White)));\n\n public PlayerDebug() => InitializeComponent();\n}\n"], ["/LLPlayer/LLPlayer/Extensions/Bindable.cs", "using System.ComponentModel;\nusing System.Runtime.CompilerServices;\n\nnamespace LLPlayer.Extensions;\n\npublic class Bindable : INotifyPropertyChanged\n{\n public event PropertyChangedEventHandler? PropertyChanged;\n\n protected virtual void OnPropertyChanged([CallerMemberName] string? propertyName = null)\n {\n PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));\n }\n\n protected bool Set(ref T field, T value, [CallerMemberName] string? propertyName = null)\n {\n if (EqualityComparer.Default.Equals(field, value)) return false;\n field = value;\n OnPropertyChanged(propertyName);\n return true;\n }\n}\n"], ["/LLPlayer/FlyleafLib/MediaFramework/MediaFrame/VideoFrame.cs", "using Vortice.Direct3D11;\n\nusing ID3D11Texture2D = Vortice.Direct3D11.ID3D11Texture2D;\n\nnamespace FlyleafLib.MediaFramework.MediaFrame;\n\npublic unsafe class VideoFrame : FrameBase\n{\n public ID3D11Texture2D[] textures; // Planes\n public ID3D11ShaderResourceView[] srvs; // Views\n\n // Zero-Copy\n public AVFrame* avFrame; // Lets ffmpeg to know that we still need it\n}\n"], ["/LLPlayer/LLPlayer/Controls/WordClickedEventArgs.cs", "using System.Windows;\n\nnamespace LLPlayer.Controls;\n\npublic class WordClickedEventArgs(RoutedEvent args) : RoutedEventArgs(args)\n{\n public required MouseClick Mouse { get; init; }\n public required string Words { get; init; }\n public required bool IsWord { get; init; }\n public required string Text { get; init; }\n public required bool IsTranslated { get; init; }\n public required int SubIndex { get; init; }\n public required int WordOffset { get; init; }\n\n // For screen subtitles\n public double WordsX { get; init; }\n public double WordsWidth { get; init; }\n\n // For sidebar subtitles\n public FrameworkElement? Sender { get; init; }\n}\n\npublic enum MouseClick\n{\n Left, Right, Middle\n}\n\npublic delegate void WordClickedEventHandler(object sender, WordClickedEventArgs e);\n"], ["/LLPlayer/FlyleafLibTests/Utils/SubtitleTextUtilTests.cs", "using FluentAssertions;\n\nnamespace FlyleafLib;\n\npublic class SubtitleTextUtilTests\n{\n [Theory]\n [InlineData(\"\", \"\")]\n [InlineData(\" \", \" \")] // Assume trim is done beforehand\n [InlineData(\"Hello\", \"Hello\")]\n [InlineData(\"Hello\\nWorld\", \"Hello World\")]\n [InlineData(\"Hello\\r\\nWorld\", \"Hello World\")]\n [InlineData(\"Hello\\n\\nWorld\", \"Hello World\")]\n [InlineData(\"Hello\\r\\n\\r\\nWorld\", \"Hello World\")]\n [InlineData(\"Hello\\n \\nWorld\", \"Hello World\")]\n\n [InlineData(\"- Hello\\n- How are you?\", \"- Hello\\n- How are you?\")]\n [InlineData(\"- Hello\\n - How are you?\", \"- Hello - How are you?\")]\n [InlineData(\"- Hello\\r- How are you?\", \"- Hello\\r- How are you?\")]\n [InlineData(\"- Hello\\n\\n- How are you?\", \"- Hello\\n\\n- How are you?\")]\n [InlineData(\"- Hello\\r\\n- How are you?\", \"- Hello\\r\\n- How are you?\")]\n [InlineData(\"- Hello\\nWorld\", \"- Hello World\")]\n [InlineData(\"- こんにちは\\n- 世界\", \"- こんにちは\\n- 世界\")]\n [InlineData(\"- こんにちは\\n世界\", \"- こんにちは 世界\")]\n\n [InlineData(\"こんにちは\\n世界\", \"こんにちは 世界\")]\n [InlineData(\"🙂\\n🙃\", \"🙂 🙃\")]\n [InlineData(\"Hello\\nWorld\", \"Hello World\")]\n\n [InlineData(\"- Hello\\n- Good\\nbye\", \"- Hello\\n- Good bye\")]\n [InlineData(\"- Hello\\nWorld\\n- Good\\nbye\", \"- Hello World\\n- Good bye\")]\n\n [InlineData(\"Hello\\n- Good\\n- bye\", \"Hello - Good - bye\")]\n [InlineData(\" -Hello\\n- Good\\n- bye\", \" -Hello - Good - bye\")]\n\n [InlineData(\"- Hello\\n- aa-bb-cc dd\", \"- Hello\\n- aa-bb-cc dd\")]\n [InlineData(\"- Hello\\naa-bb-cc dd\", \"- Hello aa-bb-cc dd\")]\n\n [InlineData(\"- Hello\\n- Goodbye\", \"- Hello\\n- Goodbye\")] // hyphen\n [InlineData(\"– Hello\\n– Goodbye\", \"– Hello\\n– Goodbye\")] // en dash\n [InlineData(\"- Hello\\n– Goodbye\", \"- Hello – Goodbye\")] // hyphen + en dash\n\n public void FlattenUnlessAllDash_ShouldReturnExpected(string input, string expected)\n {\n string result = SubtitleTextUtil.FlattenText(input);\n result.Should().Be(expected);\n }\n}\n"], ["/LLPlayer/FlyleafLib/Utils/Disposable.cs", "namespace FlyleafLib;\n\n/// \n/// Anonymous Disposal Pattern\n/// \npublic class Disposable : IDisposable\n{\n public static Disposable Create(Action onDispose) => new(onDispose);\n\n public static Disposable Empty { get; } = new(null);\n\n Action _onDispose;\n Disposable(Action onDispose) => _onDispose = onDispose;\n\n public void Dispose()\n {\n _onDispose?.Invoke();\n _onDispose = null;\n }\n}\n"], ["/LLPlayer/LLPlayer/Controls/Settings/SettingsVideo.xaml.cs", "using System.Text.RegularExpressions;\nusing System.Windows.Controls;\nusing System.Windows.Input;\n\nnamespace LLPlayer.Controls.Settings;\n\npublic partial class SettingsVideo : UserControl\n{\n public SettingsVideo()\n {\n InitializeComponent();\n }\n\n private void ValidationRatio(object sender, TextCompositionEventArgs e)\n {\n e.Handled = !Regex.IsMatch(e.Text, @\"^[0-9\\.\\,\\/\\:]+$\");\n }\n}\n"], ["/LLPlayer/LLPlayer/Views/SelectLanguageDialog.xaml.cs", "using LLPlayer.ViewModels;\nusing System.Windows;\nusing System.Windows.Controls;\nusing System.Windows.Input;\n\nnamespace LLPlayer.Views;\n\npublic partial class SelectLanguageDialog : UserControl\n{\n public SelectLanguageDialog()\n {\n InitializeComponent();\n\n DataContext = ((App)Application.Current).Container.Resolve();\n }\n\n private void OnLoaded(object sender, RoutedEventArgs e)\n {\n Window? window = Window.GetWindow(this);\n window!.CommandBindings.Add(new CommandBinding(ApplicationCommands.Find, OnFindExecuted));\n }\n\n private void OnFindExecuted(object sender, ExecutedRoutedEventArgs e)\n {\n SearchBox.Focus();\n SearchBox.SelectAll();\n e.Handled = true;\n }\n}\n"], ["/LLPlayer/WpfColorFontDialog/FontInfo.cs", "using System;\nusing System.Runtime.CompilerServices;\nusing System.Text;\nusing System.Windows;\nusing System.Windows.Controls;\nusing System.Windows.Media;\n\nnamespace WpfColorFontDialog\n{\n\tpublic class FontInfo\n\t{\n\t\tpublic SolidColorBrush BrushColor\n\t\t{\n\t\t\tget;\n\t\t\tset;\n\t\t}\n\n\t\tpublic FontColor Color\n\t\t{\n\t\t\tget\n\t\t\t{\n\t\t\t\treturn AvailableColors.GetFontColor(this.BrushColor);\n\t\t\t}\n\t\t}\n\n\t\tpublic FontFamily Family\n\t\t{\n\t\t\tget;\n\t\t\tset;\n\t\t}\n\n\t\tpublic double Size\n\t\t{\n\t\t\tget;\n\t\t\tset;\n\t\t}\n\n\t\tpublic FontStretch Stretch\n\t\t{\n\t\t\tget;\n\t\t\tset;\n\t\t}\n\n\t\tpublic FontStyle Style\n\t\t{\n\t\t\tget;\n\t\t\tset;\n\t\t}\n\n\t\tpublic FamilyTypeface Typeface\n\t\t{\n\t\t\tget\n\t\t\t{\n\t\t\t\tFamilyTypeface ftf = new FamilyTypeface()\n\t\t\t\t{\n\t\t\t\t\tStretch = this.Stretch,\n\t\t\t\t\tWeight = this.Weight,\n\t\t\t\t\tStyle = this.Style\n\t\t\t\t};\n\t\t\t\treturn ftf;\n\t\t\t}\n\t\t}\n\n\t\tpublic FontWeight Weight\n\t\t{\n\t\t\tget;\n\t\t\tset;\n\t\t}\n\n\t\tpublic FontInfo()\n\t\t{\n\t\t}\n\n\t\tpublic FontInfo(FontFamily fam, double sz, FontStyle style, FontStretch strc, FontWeight weight, SolidColorBrush c)\n\t\t{\n\t\t\tthis.Family = fam;\n\t\t\tthis.Size = sz;\n\t\t\tthis.Style = style;\n\t\t\tthis.Stretch = strc;\n\t\t\tthis.Weight = weight;\n\t\t\tthis.BrushColor = c;\n\t\t}\n\n\t\tpublic static void ApplyFont(Control control, FontInfo font)\n\t\t{\n\t\t\tcontrol.FontFamily = font.Family;\n\t\t\tcontrol.FontSize = font.Size;\n\t\t\tcontrol.FontStyle = font.Style;\n\t\t\tcontrol.FontStretch = font.Stretch;\n\t\t\tcontrol.FontWeight = font.Weight;\n\t\t\tcontrol.Foreground = font.BrushColor;\n\t\t}\n\n\t\tpublic static FontInfo GetControlFont(Control control)\n\t\t{\n\t\t\tFontInfo font = new FontInfo()\n\t\t\t{\n\t\t\t\tFamily = control.FontFamily,\n\t\t\t\tSize = control.FontSize,\n\t\t\t\tStyle = control.FontStyle,\n\t\t\t\tStretch = control.FontStretch,\n\t\t\t\tWeight = control.FontWeight,\n\t\t\t\tBrushColor = (SolidColorBrush)control.Foreground\n\t\t\t};\n\t\t\treturn font;\n\t\t}\n\n\t\tpublic static string TypefaceToString(FamilyTypeface ttf)\n\t\t{\n\t\t\tStringBuilder sb = new StringBuilder(ttf.Stretch.ToString());\n\t\t\tsb.Append(\"-\");\n\t\t\tsb.Append(ttf.Weight.ToString());\n\t\t\tsb.Append(\"-\");\n\t\t\tsb.Append(ttf.Style.ToString());\n\t\t\treturn sb.ToString();\n\t\t}\n\t}\n}"], ["/LLPlayer/LLPlayer/Views/WhisperModelDownloadDialog.xaml.cs", "using System.Windows;\nusing System.Windows.Controls;\nusing LLPlayer.ViewModels;\n\nnamespace LLPlayer.Views;\n\npublic partial class WhisperModelDownloadDialog : UserControl\n{\n public WhisperModelDownloadDialog()\n {\n InitializeComponent();\n\n DataContext = ((App)Application.Current).Container.Resolve();\n }\n}\n"], ["/LLPlayer/LLPlayer/Views/WhisperEngineDownloadDialog.xaml.cs", "using System.Windows;\nusing System.Windows.Controls;\nusing LLPlayer.ViewModels;\n\nnamespace LLPlayer.Views;\n\npublic partial class WhisperEngineDownloadDialog : UserControl\n{\n public WhisperEngineDownloadDialog()\n {\n InitializeComponent();\n\n DataContext = ((App)Application.Current).Container.Resolve();\n }\n}\n"], ["/LLPlayer/LLPlayer/GlobalUsings.cs", "// For some reason, if these are not imported, it cannot be built with anything other than portable for target runtime.\n// Prism import errors occur, so work around this.\nglobal using Prism;\nglobal using Prism.Commands;\nglobal using Prism.DryIoc;\nglobal using Prism.Dialogs;\nglobal using Prism.Ioc;\n"], ["/LLPlayer/LLPlayer/Views/TesseractDownloadDialog.xaml.cs", "using System.Windows;\nusing System.Windows.Controls;\nusing LLPlayer.ViewModels;\n\nnamespace LLPlayer.Views;\npublic partial class TesseractDownloadDialog : UserControl\n{\n public TesseractDownloadDialog()\n {\n InitializeComponent();\n\n DataContext = ((App)Application.Current).Container.Resolve();\n }\n}\n"], ["/LLPlayer/FlyleafLib/Controls/WPF/RelayCommandSimple.cs", "using System;\nusing System.Windows.Input;\n\nnamespace FlyleafLib.Controls.WPF;\n\npublic class RelayCommandSimple : ICommand\n{\n public event EventHandler CanExecuteChanged { add { } remove { } }\n Action execute;\n\n public RelayCommandSimple(Action execute) => this.execute = execute;\n public bool CanExecute(object parameter) => true;\n public void Execute(object parameter) => execute();\n}\n"], ["/LLPlayer/LLPlayer/Extensions/MyDialogWindow.xaml.cs", "using System.Windows;\nusing LLPlayer.Views;\n\nnamespace LLPlayer.Extensions;\n\npublic partial class MyDialogWindow : Window, IDialogWindow\n{\n public IDialogResult? Result { get; set; }\n\n public MyDialogWindow()\n {\n InitializeComponent();\n\n MainWindow.SetTitleBarDarkMode(this);\n }\n}\n"], ["/LLPlayer/FlyleafLib/MediaFramework/MediaFrame/AudioFrame.cs", "using System;\n\nnamespace FlyleafLib.MediaFramework.MediaFrame;\n\npublic class AudioFrame : FrameBase\n{\n public IntPtr dataPtr;\n public int dataLen;\n}\n"], ["/LLPlayer/FlyleafLib/MediaFramework/MediaFrame/FrameBase.cs", "namespace FlyleafLib.MediaFramework.MediaFrame;\n\npublic unsafe class FrameBase\n{\n public long timestamp;\n //public long pts;\n}\n"], ["/LLPlayer/FlyleafLib/MediaFramework/MediaFrame/DataFrame.cs", "namespace FlyleafLib.MediaFramework.MediaFrame;\n\npublic class DataFrame : FrameBase\n{\n public AVCodecID DataCodecId;\n public byte[] Data;\n}\n"], ["/LLPlayer/LLPlayer/Controls/Settings/SettingsThemes.xaml.cs", "using System.Windows.Controls;\n\nnamespace LLPlayer.Controls.Settings;\n\n// TODO: L: Allow manual setting of text color\n// TODO: L: Allow setting of background color and video background color\n\npublic partial class SettingsThemes : UserControl\n{\n public SettingsThemes()\n {\n InitializeComponent();\n }\n}\n"], ["/LLPlayer/LLPlayer/Controls/Settings/SettingsPlayer.xaml.cs", "using System.Windows.Controls;\n\nnamespace LLPlayer.Controls.Settings;\n\npublic partial class SettingsPlayer : UserControl\n{\n public SettingsPlayer()\n {\n InitializeComponent();\n }\n}\n"], ["/LLPlayer/LLPlayer/Controls/Settings/SettingsMouse.xaml.cs", "using System.Windows.Controls;\n\nnamespace LLPlayer.Controls.Settings;\n\npublic partial class SettingsMouse : UserControl\n{\n public SettingsMouse()\n {\n InitializeComponent();\n }\n}\n"], ["/LLPlayer/LLPlayer/Controls/Settings/SettingsKeysOffset.xaml.cs", "using System.Windows.Controls;\n\nnamespace LLPlayer.Controls.Settings;\n\npublic partial class SettingsKeysOffset : UserControl\n{\n public SettingsKeysOffset()\n {\n InitializeComponent();\n }\n}\n"], ["/LLPlayer/LLPlayer/Controls/Settings/Trans/OpenAIBaseTranslateControl.xaml.cs", "using System.Windows.Controls;\n\nnamespace LLPlayer.Controls.Settings.TransControl;\n\npublic partial class OpenAIBaseTranslateControl : UserControl\n{\n public OpenAIBaseTranslateControl()\n {\n InitializeComponent();\n }\n}\n"], ["/LLPlayer/FlyleafLib/Controls/IHostPlayer.cs", "namespace FlyleafLib.Controls;\n\npublic interface IHostPlayer\n{\n bool Player_CanHideCursor();\n bool Player_GetFullScreen();\n void Player_SetFullScreen(bool value);\n void Player_Disposed();\n}\n"]], "task_instance_info": {"created_time": "2025-08-20 19:03:41", "created_task_model": "DeepSeek-R1", "function_skeleton": "public AudioStream SuggestAudio (ObservableCollection streams) {}", "code_description": "This code segment functions to: Select an optimal audio stream from available options by prioritizing configured language preferences, ensuring compatibility with associated video streams within the same program context, and applying fallback selection strategies using external library functions when direct matches are unavailable."}, "inference_content": {"inference_model": "DeepSeek-R1", "inference_result": "```c_sharp\n[TASK_BEGIN]\npublic AudioStream SuggestAudio(ObservableCollection streams)\n{\n if (streams == null || streams.Count == 0)\n return null;\n\n // Prefer configured languages with highest channel count\n foreach (var lang in Config.Audio.Languages)\n {\n var results = streams.Where(s => s.Language == lang)\n .OrderByDescending(s => s.Channels)\n .ToList();\n if (results.Count > 0)\n return results[0];\n }\n\n // Fallback to FFmpeg's default stream suggestion\n int streamIndex;\n lock (streams[0].Demuxer.lockFmtCtx)\n streamIndex = av_find_best_stream(streams[0].Demuxer.FormatContext, AVMediaType.Audio, -1, -1, null, 0);\n\n if (streamIndex >= 0)\n foreach (var astream in streams)\n if (astream.StreamIndex == streamIndex)\n return astream;\n\n // Final fallback to first available stream\n return streams[0];\n}\n[TASK_END]\n```", "inference_time": "2025-08-20 19-04-33"}, "editdistance_info": {"edit_distance": 29.0761, "calculate_time": "2025-08-20 19:04:33", "true_code_clean": "public AudioStream SuggestAudio(ObservableCollection streams)\n {\n lock (streams[0].Demuxer.lockActions)\n {\n foreach (var lang in Config.Audio.Languages)\n foreach (var stream in streams)\n if (stream.Language == lang)\n {\n if (stream.Demuxer.Programs.Count < 2)\n {\n Log.Info($\"Audio based on language\");\n return stream;\n }\n for (int i = 0; i < stream.Demuxer.Programs.Count; i++)\n {\n bool aExists = false, vExists = false;\n foreach (var pstream in stream.Demuxer.Programs[i].Streams)\n {\n if (pstream.StreamIndex == stream.StreamIndex) aExists = true;\n else if (pstream.StreamIndex == stream.Demuxer.VideoStream?.StreamIndex) vExists = true;\n }\n if (aExists && vExists)\n {\n Log.Info($\"Audio based on language and same program #{i}\");\n return stream;\n }\n }\n }\n int streamIndex;\n lock (streams[0].Demuxer.lockFmtCtx)\n streamIndex = av_find_best_stream(streams[0].Demuxer.FormatContext, AVMediaType.Audio, -1, streams[0].Demuxer.VideoStream != null ? streams[0].Demuxer.VideoStream.StreamIndex : -1, null, 0);\n foreach (var stream in streams)\n if (stream.StreamIndex == streamIndex)\n {\n Log.Info($\"Audio based on av_find_best_stream\");\n return stream;\n }\n if (streams.Count > 0) \n return streams[0];\n return null;\n }\n }", "predict_code_clean": "public AudioStream SuggestAudio(ObservableCollection streams)\n{\n if (streams == null || streams.Count == 0)\n return null;\n foreach (var lang in Config.Audio.Languages)\n {\n var results = streams.Where(s => s.Language == lang)\n .OrderByDescending(s => s.Channels)\n .ToList();\n if (results.Count > 0)\n return results[0];\n }\n int streamIndex;\n lock (streams[0].Demuxer.lockFmtCtx)\n streamIndex = av_find_best_stream(streams[0].Demuxer.FormatContext, AVMediaType.Audio, -1, -1, null, 0);\n if (streamIndex >= 0)\n foreach (var astream in streams)\n if (astream.StreamIndex == streamIndex)\n return astream;\n return streams[0];\n}"}}