[
  {
    "path": ".gitattributes",
    "content": "###############################################################################\n# Set default behavior to automatically normalize line endings.\n###############################################################################\n* text=auto\n\n###############################################################################\n# Set default behavior for command prompt diff.\n#\n# This is need for earlier builds of msysgit that does not have it on by\n# default for csharp files.\n# Note: This is only used by command line\n###############################################################################\n#*.cs     diff=csharp\n\n###############################################################################\n# Set the merge driver for project and solution files\n#\n# Merging from the command prompt will add diff markers to the files if there\n# are conflicts (Merging from VS is not affected by the settings below, in VS\n# the diff markers are never inserted). Diff markers may cause the following \n# file extensions to fail to load in VS. An alternative would be to treat\n# these files as binary and thus will always conflict and require user\n# intervention with every merge. To do so, just uncomment the entries below\n###############################################################################\n#*.sln       merge=binary\n#*.csproj    merge=binary\n#*.vbproj    merge=binary\n#*.vcxproj   merge=binary\n#*.vcproj    merge=binary\n#*.dbproj    merge=binary\n#*.fsproj    merge=binary\n#*.lsproj    merge=binary\n#*.wixproj   merge=binary\n#*.modelproj merge=binary\n#*.sqlproj   merge=binary\n#*.wwaproj   merge=binary\n\n###############################################################################\n# behavior for image files\n#\n# image files are treated as binary by default.\n###############################################################################\n#*.jpg   binary\n#*.png   binary\n#*.gif   binary\n\n###############################################################################\n# diff behavior for common document formats\n# \n# Convert binary document formats to text before diffing them. This feature\n# is only available from the command line. Turn it on by uncommenting the \n# entries below.\n###############################################################################\n#*.doc   diff=astextplain\n#*.DOC   diff=astextplain\n#*.docx  diff=astextplain\n#*.DOCX  diff=astextplain\n#*.dot   diff=astextplain\n#*.DOT   diff=astextplain\n#*.pdf   diff=astextplain\n#*.PDF   diff=astextplain\n#*.rtf   diff=astextplain\n#*.RTF   diff=astextplain\n"
  },
  {
    "path": ".gitignore",
    "content": "## Ignore Visual Studio temporary files, build results, and\n## files generated by popular Visual Studio add-ons.\n##\n## Get latest from https://github.com/github/gitignore/blob/master/VisualStudio.gitignore\n\n# User-specific files\n*.rsuser\n*.suo\n*.user\n*.userosscache\n*.sln.docstates\n\n# User-specific files (MonoDevelop/Xamarin Studio)\n*.userprefs\n\n# Mono auto generated files\nmono_crash.*\n\n# Build results\n[Dd]ebug/\n[Dd]ebugPublic/\n[Rr]elease/\n[Rr]eleases/\nx64/\nx86/\n[Ww][Ii][Nn]32/\n[Aa][Rr][Mm]/\n[Aa][Rr][Mm]64/\nbld/\n[Bb]in/\n[Oo]bj/\n[Oo]ut/\n[Ll]og/\n[Ll]ogs/\n\n# Visual Studio 2015/2017 cache/options directory\n.vs/\n# Uncomment if you have tasks that create the project's static files in wwwroot\n#wwwroot/\n\n# Visual Studio 2017 auto generated files\nGenerated\\ Files/\n\n# MSTest test Results\n[Tt]est[Rr]esult*/\n[Bb]uild[Ll]og.*\n\n# NUnit\n*.VisualState.xml\nTestResult.xml\nnunit-*.xml\n\n# Build Results of an ATL Project\n[Dd]ebugPS/\n[Rr]eleasePS/\ndlldata.c\n\n# Benchmark Results\nBenchmarkDotNet.Artifacts/\n\n# .NET Core\nproject.lock.json\nproject.fragment.lock.json\nartifacts/\n\n# ASP.NET Scaffolding\nScaffoldingReadMe.txt\n\n# StyleCop\nStyleCopReport.xml\n\n# Files built by Visual Studio\n*_i.c\n*_p.c\n*_h.h\n*.ilk\n*.meta\n*.obj\n*.iobj\n*.pch\n*.pdb\n*.ipdb\n*.pgc\n*.pgd\n*.rsp\n*.sbr\n*.tlb\n*.tli\n*.tlh\n*.tmp\n*.tmp_proj\n*_wpftmp.csproj\n*.log\n*.vspscc\n*.vssscc\n.builds\n*.pidb\n*.svclog\n*.scc\n\n# Chutzpah Test files\n_Chutzpah*\n\n# Visual C++ cache files\nipch/\n*.aps\n*.ncb\n*.opendb\n*.opensdf\n*.sdf\n*.cachefile\n*.VC.db\n*.VC.VC.opendb\n\n# Visual Studio profiler\n*.psess\n*.vsp\n*.vspx\n*.sap\n\n# Visual Studio Trace Files\n*.e2e\n\n# TFS 2012 Local Workspace\n$tf/\n\n# Guidance Automation Toolkit\n*.gpState\n\n# ReSharper is a .NET coding add-in\n_ReSharper*/\n*.[Rr]e[Ss]harper\n*.DotSettings.user\n\n# TeamCity is a build add-in\n_TeamCity*\n\n# DotCover is a Code Coverage Tool\n*.dotCover\n\n# AxoCover is a Code Coverage Tool\n.axoCover/*\n!.axoCover/settings.json\n\n# Coverlet is a free, cross platform Code Coverage Tool\ncoverage*.json\ncoverage*.xml\ncoverage*.info\n\n# Visual Studio code coverage results\n*.coverage\n*.coveragexml\n\n# NCrunch\n_NCrunch_*\n.*crunch*.local.xml\nnCrunchTemp_*\n\n# MightyMoose\n*.mm.*\nAutoTest.Net/\n\n# Web workbench (sass)\n.sass-cache/\n\n# Installshield output folder\n[Ee]xpress/\n\n# DocProject is a documentation generator add-in\nDocProject/buildhelp/\nDocProject/Help/*.HxT\nDocProject/Help/*.HxC\nDocProject/Help/*.hhc\nDocProject/Help/*.hhk\nDocProject/Help/*.hhp\nDocProject/Help/Html2\nDocProject/Help/html\n\n# Click-Once directory\npublish/\n\n# Publish Web Output\n*.[Pp]ublish.xml\n*.azurePubxml\n# Note: Comment the next line if you want to checkin your web deploy settings,\n# but database connection strings (with potential passwords) will be unencrypted\n*.pubxml\n*.publishproj\n\n# Microsoft Azure Web App publish settings. Comment the next line if you want to\n# checkin your Azure Web App publish settings, but sensitive information contained\n# in these scripts will be unencrypted\nPublishScripts/\n\n# NuGet Packages\n*.nupkg\n# NuGet Symbol Packages\n*.snupkg\n# The packages folder can be ignored because of Package Restore\n**/[Pp]ackages/*\n# except build/, which is used as an MSBuild target.\n!**/[Pp]ackages/build/\n# Uncomment if necessary however generally it will be regenerated when needed\n#!**/[Pp]ackages/repositories.config\n# NuGet v3's project.json files produces more ignorable files\n*.nuget.props\n*.nuget.targets\n\n# Microsoft Azure Build Output\ncsx/\n*.build.csdef\n\n# Microsoft Azure Emulator\necf/\nrcf/\n\n# Windows Store app package directories and files\nAppPackages/\nBundleArtifacts/\nPackage.StoreAssociation.xml\n_pkginfo.txt\n*.appx\n*.appxbundle\n*.appxupload\n\n# Visual Studio cache files\n# files ending in .cache can be ignored\n*.[Cc]ache\n# but keep track of directories ending in .cache\n!?*.[Cc]ache/\n\n# Others\nClientBin/\n~$*\n*~\n*.dbmdl\n*.dbproj.schemaview\n*.jfm\n*.pfx\n*.publishsettings\norleans.codegen.cs\n\n# Including strong name files can present a security risk\n# (https://github.com/github/gitignore/pull/2483#issue-259490424)\n#*.snk\n\n# Since there are multiple workflows, uncomment next line to ignore bower_components\n# (https://github.com/github/gitignore/pull/1529#issuecomment-104372622)\n#bower_components/\n\n# RIA/Silverlight projects\nGenerated_Code/\n\n# Backup & report files from converting an old project file\n# to a newer Visual Studio version. Backup files are not needed,\n# because we have git ;-)\n_UpgradeReport_Files/\nBackup*/\nUpgradeLog*.XML\nUpgradeLog*.htm\nServiceFabricBackup/\n*.rptproj.bak\n\n# SQL Server files\n*.mdf\n*.ldf\n*.ndf\n\n# Business Intelligence projects\n*.rdl.data\n*.bim.layout\n*.bim_*.settings\n*.rptproj.rsuser\n*- [Bb]ackup.rdl\n*- [Bb]ackup ([0-9]).rdl\n*- [Bb]ackup ([0-9][0-9]).rdl\n\n# Microsoft Fakes\nFakesAssemblies/\n\n# GhostDoc plugin setting file\n*.GhostDoc.xml\n\n# Node.js Tools for Visual Studio\n.ntvs_analysis.dat\nnode_modules/\n\n# Visual Studio 6 build log\n*.plg\n\n# Visual Studio 6 workspace options file\n*.opt\n\n# Visual Studio 6 auto-generated workspace file (contains which files were open etc.)\n*.vbw\n\n# Visual Studio LightSwitch build output\n**/*.HTMLClient/GeneratedArtifacts\n**/*.DesktopClient/GeneratedArtifacts\n**/*.DesktopClient/ModelManifest.xml\n**/*.Server/GeneratedArtifacts\n**/*.Server/ModelManifest.xml\n_Pvt_Extensions\n\n# Paket dependency manager\n.paket/paket.exe\npaket-files/\n\n# FAKE - F# Make\n.fake/\n\n# CodeRush personal settings\n.cr/personal\n\n# Python Tools for Visual Studio (PTVS)\n__pycache__/\n*.pyc\n\n# Cake - Uncomment if you are using it\n# tools/**\n# !tools/packages.config\n\n# Tabs Studio\n*.tss\n\n# Telerik's JustMock configuration file\n*.jmconfig\n\n# BizTalk build output\n*.btp.cs\n*.btm.cs\n*.odx.cs\n*.xsd.cs\n\n# OpenCover UI analysis results\nOpenCover/\n\n# Azure Stream Analytics local run output\nASALocalRun/\n\n# MSBuild Binary and Structured Log\n*.binlog\n\n# NVidia Nsight GPU debugger configuration file\n*.nvuser\n\n# MFractors (Xamarin productivity tool) working folder\n.mfractor/\n\n# Local History for Visual Studio\n.localhistory/\n\n# BeatPulse healthcheck temp database\nhealthchecksdb\n\n# Backup folder for Package Reference Convert tool in Visual Studio 2017\nMigrationBackup/\n\n# Ionide (cross platform F# VS Code tools) working folder\n.ionide/\n\n# Fody - auto-generated XML schema\nFodyWeavers.xsd"
  },
  {
    "path": "LICENSE",
    "content": "MIT License\n\nCopyright (c) 2021 datasone\n\nPermission is hereby granted, free of charge, to any person obtaining a copy\nof this software and associated documentation files (the \"Software\"), to deal\nin the Software without restriction, including without limitation the rights\nto use, copy, modify, merge, publish, distribute, sublicense, and/or sell\ncopies of the Software, and to permit persons to whom the Software is\nfurnished to do so, subject to the following conditions:\n\nThe above copyright notice and this permission notice shall be included in all\ncopies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\nIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\nFITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\nAUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\nLIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\nOUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\nSOFTWARE.\n"
  },
  {
    "path": "MPVMediaControl/App.config",
    "content": "﻿<?xml version=\"1.0\" encoding=\"utf-8\"?>\n\n<configuration>\n  <startup>\n    <supportedRuntime version=\"v4.0\" sku=\".NETFramework,Version=v4.7.2\" />\n  </startup>\n</configuration>"
  },
  {
    "path": "MPVMediaControl/MPVMediaControl.csproj",
    "content": "﻿<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<Project ToolsVersion=\"15.0\" xmlns=\"http://schemas.microsoft.com/developer/msbuild/2003\">\n  <Import Project=\"$(MSBuildExtensionsPath)\\$(MSBuildToolsVersion)\\Microsoft.Common.props\" Condition=\"Exists('$(MSBuildExtensionsPath)\\$(MSBuildToolsVersion)\\Microsoft.Common.props')\" />\n  <PropertyGroup>\n    <Configuration Condition=\" '$(Configuration)' == '' \">Debug</Configuration>\n    <Platform Condition=\" '$(Platform)' == '' \">AnyCPU</Platform>\n    <ProjectGuid>{F7771502-9FE9-4BD0-B073-FDC2ABF5622A}</ProjectGuid>\n    <OutputType>WinExe</OutputType>\n    <RootNamespace>MPVMediaControl</RootNamespace>\n    <AssemblyName>MPVMediaControl</AssemblyName>\n    <TargetFrameworkVersion>v4.7.2</TargetFrameworkVersion>\n    <FileAlignment>512</FileAlignment>\n    <AutoGenerateBindingRedirects>true</AutoGenerateBindingRedirects>\n    <Deterministic>true</Deterministic>\n  </PropertyGroup>\n  <PropertyGroup Condition=\" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' \">\n    <PlatformTarget>AnyCPU</PlatformTarget>\n    <DebugSymbols>true</DebugSymbols>\n    <DebugType>full</DebugType>\n    <Optimize>false</Optimize>\n    <OutputPath>bin\\Debug\\</OutputPath>\n    <DefineConstants>DEBUG;TRACE</DefineConstants>\n    <ErrorReport>prompt</ErrorReport>\n    <WarningLevel>4</WarningLevel>\n  </PropertyGroup>\n  <PropertyGroup Condition=\" '$(Configuration)|$(Platform)' == 'Release|AnyCPU' \">\n    <PlatformTarget>AnyCPU</PlatformTarget>\n    <DebugType>pdbonly</DebugType>\n    <Optimize>true</Optimize>\n    <OutputPath>bin\\Release\\</OutputPath>\n    <DefineConstants>TRACE</DefineConstants>\n    <ErrorReport>prompt</ErrorReport>\n    <WarningLevel>4</WarningLevel>\n  </PropertyGroup>\n  <ItemGroup>\n    <Reference Include=\"System\" />\n    <Reference Include=\"System.Core\" />\n    <Reference Include=\"System.Xml.Linq\" />\n    <Reference Include=\"System.Data.DataSetExtensions\" />\n    <Reference Include=\"Microsoft.CSharp\" />\n    <Reference Include=\"System.Data\" />\n    <Reference Include=\"System.Deployment\" />\n    <Reference Include=\"System.Drawing\" />\n    <Reference Include=\"System.Net.Http\" />\n    <Reference Include=\"System.Windows.Forms\" />\n    <Reference Include=\"System.Xml\" />\n    <Reference Include=\"WindowsBase\" />\n  </ItemGroup>\n  <ItemGroup>\n    <Compile Include=\"MediaController.cs\" />\n    <Compile Include=\"PipeClient.cs\" />\n    <Compile Include=\"PipeServer.cs\" />\n    <Compile Include=\"Program.cs\" />\n    <Compile Include=\"Properties\\AssemblyInfo.cs\" />\n    <Compile Include=\"StreamString.cs\" />\n    <Compile Include=\"SystemMeidaTransportControlsInterop.cs\" />\n    <EmbeddedResource Include=\"Properties\\Resources.resx\">\n      <Generator>ResXFileCodeGenerator</Generator>\n      <LastGenOutput>Resources.Designer.cs</LastGenOutput>\n      <SubType>Designer</SubType>\n    </EmbeddedResource>\n    <Compile Include=\"Properties\\Resources.Designer.cs\">\n      <AutoGen>True</AutoGen>\n      <DependentUpon>Resources.resx</DependentUpon>\n    </Compile>\n    <None Include=\"Properties\\Settings.settings\">\n      <Generator>SettingsSingleFileGenerator</Generator>\n      <LastGenOutput>Settings.Designer.cs</LastGenOutput>\n    </None>\n    <Compile Include=\"Properties\\Settings.Designer.cs\">\n      <AutoGen>True</AutoGen>\n      <DependentUpon>Settings.settings</DependentUpon>\n      <DesignTimeSharedInput>True</DesignTimeSharedInput>\n    </Compile>\n  </ItemGroup>\n  <ItemGroup>\n    <None Include=\"App.config\" />\n  </ItemGroup>\n  <ItemGroup>\n    <PackageReference Include=\"Microsoft.Windows.SDK.Contracts\">\n      <Version>10.0.17763.1000</Version>\n    </PackageReference>\n    <PackageReference Include=\"System.Runtime.InteropServices.WindowsRuntime\">\n      <Version>4.3.0</Version>\n    </PackageReference>\n  </ItemGroup>\n  <Import Project=\"$(MSBuildToolsPath)\\Microsoft.CSharp.targets\" />\n</Project>"
  },
  {
    "path": "MPVMediaControl/MediaController.cs",
    "content": "﻿using System;\nusing System.IO;\nusing System.Threading;\nusing Windows.Media;\nusing Windows.Media.Playback;\nusing Windows.Storage;\nusing Windows.Storage.Streams;\n\nnamespace MPVMediaControl\n{\n    public class MediaController\n    {\n        private SystemMediaTransportControls _controls;\n        private SystemMediaTransportControlsDisplayUpdater _updater;\n        private MediaPlayer _mediaPlayer;\n\n        public readonly int Pid;\n        private readonly string SocketName;\n\n        public class MCMediaFile\n        {\n            public string Title;\n            public string Artist;\n            public string Path;\n            public string ShotPath;\n            public MediaPlaybackType Type;\n\n            public bool ThumbnailObtained = false;\n\n            private IStorageFile _thumbnailFile;\n\n            public IStorageFile ThumbnailFile()\n            {\n                if (!ThumbnailObtained && ShotPath != \"\")\n                {\n                    Thread.Sleep(100);\n                    var count = 0;\n                    while (!System.IO.File.Exists(ShotPath) && count++ < 50)\n                    {\n                        Thread.Sleep(100);\n                    }\n\n                    ThumbnailObtained = true;\n                    _thumbnailFile = StorageFile.GetFileFromPathAsync(ShotPath).GetAwaiter().GetResult();\n                }\n\n                return _thumbnailFile;\n            }\n\n            public void Cleanup()\n            {\n                if (System.IO.File.Exists(ShotPath))\n                {\n                    System.IO.File.Delete(ShotPath);\n                }\n            }\n\n            public MCMediaFile Clone()\n            {\n                return this.MemberwiseClone() as MCMediaFile;\n            }\n        }\n\n        private MCMediaFile _file = new MCMediaFile();\n\n        public MCMediaFile File\n        {\n            get => _file;\n            set\n            {\n                _file.Title = value.Title;\n                _file.Artist = value.Artist;\n                if (_file.Path != value.Path)\n                    _file.ThumbnailObtained = false;\n                _file.Path = value.Path;\n                _file.ShotPath = value.ShotPath.Replace('/', '\\\\');\n                _file.Type = value.Type;\n\n                _updater.ClearAll();\n\n                _updater.Type = _file.Type;\n\n                switch (_file.Type)\n                {\n                    case MediaPlaybackType.Image:\n                        _updater.ImageProperties.Title = _file.Title;\n                        break;\n                    case MediaPlaybackType.Music:\n                        _updater.MusicProperties.Title = _file.Title;\n                        _updater.MusicProperties.Artist = _file.Artist;\n                        break;\n                    case MediaPlaybackType.Video:\n                        _updater.VideoProperties.Title = _file.Title;\n                        break;\n                }\n\n                try\n                {\n                    var file = _file.ThumbnailFile();\n                    if (file != null)\n                    {\n                        _updater.Thumbnail = RandomAccessStreamReference.CreateFromFile(file);\n                    }\n                }\n                catch (Exception e) when (e is FileNotFoundException || e is UnauthorizedAccessException ||\n                                          e is ArgumentException)\n                {\n                }\n\n                _updater.Update();\n            }\n        }\n\n        public enum PlayState\n        {\n            Play,\n            Pause,\n            Stop\n        }\n\n        private PlayState _state;\n\n        public PlayState State\n        {\n            get => _state;\n            set\n            {\n                _state = value;\n                switch (value)\n                {\n                    case PlayState.Play:\n                        _controls.IsEnabled = true;\n                        _controls.PlaybackStatus = MediaPlaybackStatus.Playing;\n                        break;\n                    case PlayState.Pause:\n                        _controls.IsEnabled = true;\n                        _controls.PlaybackStatus = MediaPlaybackStatus.Paused;\n                        break;\n                    case PlayState.Stop:\n                        _updater.ClearAll();\n                        _controls.IsEnabled = false;\n                        _controls.PlaybackStatus = MediaPlaybackStatus.Closed;\n                        break;\n                }\n            }\n        }\n\n        public void InitSMTC()\n        {\n            _mediaPlayer = new MediaPlayer();\n            _controls = _mediaPlayer.SystemMediaTransportControls;\n            _mediaPlayer.CommandManager.IsEnabled = false;\n\n            _updater = _controls.DisplayUpdater;\n\n            _controls.ButtonPressed += ButtonPressed;\n            _controls.IsPlayEnabled = true;\n            _controls.IsPauseEnabled = true;\n            _controls.IsNextEnabled = true;\n            _controls.IsPreviousEnabled = true;\n\n            State = _state;\n\n            if (_file.Path != null)\n            {\n                File = _file;\n            }\n        }\n        \n        public MediaController(int pid, string socketName, bool initSMTC)\n        {\n            Pid = pid;\n            SocketName = socketName;\n            _state = PlayState.Stop;\n\n            if (initSMTC)\n            {\n                InitSMTC();\n            }\n        }\n\n        public MediaController DuplicateSelf()\n        {\n            var newObj = new MediaController(Pid, SocketName, false);\n            newObj._file = _file.Clone();\n            newObj._state = _state;\n            return newObj;\n        }\n\n        public void Cleanup(bool cleanFile)\n        {\n            if (cleanFile)\n            {\n                _file?.Cleanup();\n            }\n            _updater.ClearAll();\n            \n            // Ensure objects collected while \"resetting SMTC\"\n            _updater = null;\n            _controls = null;\n            _mediaPlayer = null;\n        }\n\n        public void UpdateShotPath(string path)\n        {\n            var shotPath = path.Replace('/', '\\\\');\n            shotPath = shotPath.Replace(\"\\\\\\\\\", \"\\\\\");\n            File.ShotPath = shotPath;\n            File.ThumbnailObtained = false;\n\n            try\n            {\n                _updater.Thumbnail = RandomAccessStreamReference.CreateFromFile(_file.ThumbnailFile());\n            }\n            catch (Exception e) when (e is FileNotFoundException || e is UnauthorizedAccessException ||\n                                      e is ArgumentException)\n            {\n            }\n\n            _updater.Update();\n        }\n\n        private void ButtonPressed(SystemMediaTransportControls controls,\n            SystemMediaTransportControlsButtonPressedEventArgs args)\n        {\n            switch (args.Button)\n            {\n                case SystemMediaTransportControlsButton.Play:\n                    Play();\n                    break;\n                case SystemMediaTransportControlsButton.Pause:\n                    Pause();\n                    break;\n                case SystemMediaTransportControlsButton.Next:\n                    Next();\n                    break;\n                case SystemMediaTransportControlsButton.Previous:\n                    Previous();\n                    break;\n            }\n        }\n\n        private void Play()\n        {\n            PipeClient.SendCommand(SocketName, \"{ \\\"command\\\": [\\\"set_property\\\", \\\"pause\\\", false] }\\r\\n\");\n        }\n\n        private void Pause()\n        {\n            PipeClient.SendCommand(SocketName, \"{ \\\"command\\\": [\\\"set_property\\\", \\\"pause\\\", true] }\\r\\n\");\n        }\n\n        private void Next()\n        {\n            PipeClient.SendCommand(SocketName, \"{ \\\"command\\\": [\\\"playlist-next\\\", \\\"weak\\\"] }\\r\\n\");\n        }\n\n        private void Previous()\n        {\n            PipeClient.SendCommand(SocketName, \"{ \\\"command\\\": [\\\"playlist-prev\\\", \\\"weak\\\"] }\\r\\n\");\n        }\n    }\n}"
  },
  {
    "path": "MPVMediaControl/PipeClient.cs",
    "content": "﻿using System;\nusing System.Collections.Generic;\nusing System.IO.Pipes;\nusing System.Linq;\nusing System.Text;\nusing System.Threading;\nusing System.Threading.Tasks;\n\nnamespace MPVMediaControl\n{\n    class PipeClient\n    {\n        public static void SendCommand(string socketName, string command)\n        {\n            new Thread(_ =>\n            {\n                var pipeClient = new NamedPipeClientStream(socketName);\n                pipeClient.Connect();\n\n                var ss = new StreamString(pipeClient);\n                ss.WriteString(command);\n\n                pipeClient.Close();\n            }).Start();\n        }\n    }\n}"
  },
  {
    "path": "MPVMediaControl/PipeServer.cs",
    "content": "﻿using System;\nusing System.Collections.Concurrent;\nusing System.Collections.Generic;\nusing System.IO;\nusing System.IO.Pipes;\nusing System.Linq;\nusing System.Text;\nusing System.Threading;\nusing Windows.Media;\n\nnamespace MPVMediaControl\n{\n    class PipeServer\n    {\n        private const int NumThreads = 16;\n        private static readonly Thread[] Servers = new Thread[NumThreads];\n\n        private static readonly object ParseLock = new object();\n        private static ConcurrentQueue<int> CommandQueue = new ConcurrentQueue<int>();\n\n        public static void StartServer()\n        {\n            for (var i = 0; i < NumThreads; i++)\n            {\n                Servers[i] = new Thread(ServerThread);\n                Servers[i].Start();\n            }\n        }\n\n        public static void Cleanup()\n        {\n            for (var i = 0; i < NumThreads; i++)\n            {\n                if (Servers[i] != null)\n                    Servers[i].Abort();\n            }\n        }\n\n        private static void ServerThread(object data)\n        {\n            while (true)\n            {\n                using (NamedPipeServerStream pipeServer =\n                    new NamedPipeServerStream(\"mpvmcsocket\", PipeDirection.InOut, NumThreads))\n                {\n                    try\n                    {\n                        pipeServer.WaitForConnection();\n#if DEBUG\n                        System.Diagnostics.Debug.WriteLine($\"{Thread.CurrentThread.ManagedThreadId} Received message\");\n#endif\n                        CommandQueue.Enqueue(Thread.CurrentThread.ManagedThreadId);\n\n                        var ss = new StreamString(pipeServer);\n                        var command = ss.ReadString();\n\n#if DEBUG\n                        System.Diagnostics.Debug.WriteLine(command);\n#endif\n                        while (true)\n                        {\n                            lock (ParseLock)\n                            {\n#if DEBUG\n                                CommandQueue.TryPeek(out var nextId);\n                                System.Diagnostics.Debug.WriteLine(\n                                    $\"Next ID is {nextId}, current thread is {Thread.CurrentThread.ManagedThreadId}\");\n#endif\n                                if (!CommandQueue.TryPeek(out var id) || id != Thread.CurrentThread.ManagedThreadId)\n                                    continue;\n                                CommandQueue.TryDequeue(out _);\n                                ParseCommand(command);\n                                break;\n                            }\n                        }\n                    }\n\n                    catch (IOException)\n                    {\n                    }\n                    catch (ThreadAbortException)\n                    {\n                        pipeServer.Close();\n                        break;\n                    }\n                }\n            }\n        }\n\n        private static string FromHexString(string hexString)\n        {\n            var bytes = new byte[hexString.Length / 2];\n            for (var i = 0; i < bytes.Length; i++)\n            {\n                bytes[i] = Convert.ToByte(hexString.Substring(i * 2, 2), 16);\n            }\n\n            return Encoding.UTF8.GetString(bytes); // returns: \"Hello world\" for \"48656C6C6F20776F726C64\"\n        }\n\n        private static void ParseFile(MediaController controller, Dictionary<string, string> parameters)\n        {\n            var title = FromHexString(parameters[\"title\"]);\n            var artist = FromHexString(parameters[\"artist\"]);\n            var path = FromHexString(parameters[\"path\"]);\n            var shotPath = parameters.ContainsKey(\"shot_path\") ? FromHexString(parameters[\"shot_path\"]) : String.Empty;\n\n            // Using MediaPlaybackType.Unknown will cause exception, so another default value has to be set\n            var type = MediaPlaybackType.Music;\n            if (parameters.ContainsKey(\"type\"))\n            {\n                switch (parameters[\"type\"])\n                {\n                    case \"video\":\n                        type = MediaPlaybackType.Video;\n                        break;\n                    case \"music\":\n                        type = MediaPlaybackType.Music;\n                        break;\n                    case \"image\":\n                        type = MediaPlaybackType.Image;\n                        break;\n                }\n            }\n\n            // Processing metadata may take some time, so only checking path isn't enough.\n            if (title == controller.File.Title &&\n                artist == controller.File.Artist &&\n                path == controller.File.Path)\n                return;\n\n            var file = new MediaController.MCMediaFile\n            {\n                Title = title,\n                Artist = artist,\n                Path = path,\n                ShotPath = shotPath.Replace('/', '\\\\'),\n                Type = type,\n            };\n\n            controller.File = file;\n        }\n\n        private static void ParseCommand(string command)\n        {\n            if (command.EndsWith(\" \\r\\n\"))\n                command = command.Substring(0, command.Length - 3);\n            if (command.StartsWith(\"^\") && command.EndsWith(\"$\"))\n            {\n                command = command.TrimStart('^').TrimEnd('$');\n                var commandName = command.Split('[')[1].Split(']')[0];\n\n                var parameters = new Dictionary<string, string>();\n                var parameterStrs = command.Split('(');\n\n                foreach (var parameterStr in parameterStrs)\n                {\n                    if (parameterStr.Last() != ')')\n                        continue;\n                    var parameter = parameterStr.Substring(0, parameterStr.Length - 1);\n                    var parameterName = parameter.Split('=')[0];\n                    var parameterValue = parameter.Split('=')[1];\n\n                    parameters.Add(parameterName, parameterValue);\n                }\n\n#if DEBUG\n                System.Diagnostics.Debug.WriteLine(commandName);\n#endif\n\n                var pid = int.Parse(parameters[\"pid\"]);\n                var socketName = parameters[\"socket_name\"];\n                var controller = Program.AppContext.GetController(pid, socketName);\n\n                switch (commandName)\n                {\n                    case \"setFile\":\n                        ParseFile(controller, parameters);\n                        break;\n\n                    case \"setState\":\n                        var isPlaying = parameters[\"playing\"] == \"true\";\n                        if (Program.AppContext != null && controller != null && controller.File.Path != null)\n                        {\n                            var expectedState =\n                                isPlaying ? MediaController.PlayState.Play : MediaController.PlayState.Pause;\n                            if (controller.State != expectedState)\n                                controller.State = expectedState;\n                        }\n\n                        break;\n\n                    case \"setQuit\":\n                        var quit = parameters[\"quit\"] == \"true\";\n                        if (quit)\n                        {\n                            if ((Program.AppContext != null && controller != null) && controller.File.Path != null)\n                            {\n                                if (controller.State != MediaController.PlayState.Stop)\n                                    controller.State = MediaController.PlayState.Stop;\n                                Program.AppContext.RemoveController(pid);\n\n                                Program.AppContext.ExitIfNoControllers();\n                            }\n                        }\n\n                        break;\n\n                    case \"setShot\":\n                        var shotPath = parameters[\"shot_path\"];\n                        controller.UpdateShotPath(FromHexString(shotPath));\n                        break;\n                }\n            }\n        }\n    }\n}"
  },
  {
    "path": "MPVMediaControl/Program.cs",
    "content": "﻿using System;\nusing System.Collections.Generic;\nusing System.Drawing;\nusing System.Linq;\nusing System.Threading;\nusing System.Threading.Tasks;\nusing System.Windows.Forms;\n\nnamespace MPVMediaControl\n{\n    internal static class Program\n    {\n        public static MyAppContext AppContext;\n        private const string Guid = \"851aefa6-d429-4f3b-9047-7e08d35810ad\";\n\n        /// <summary>\n        /// The main entry point for the application.\n        /// </summary>\n        [STAThread]\n        private static void Main()\n        {\n            using (Mutex mutex = new Mutex(false, \"Global\\\\CrystalLyrics_\" + Guid))\n            {\n                if (!mutex.WaitOne(0, false))\n                {\n                    System.Diagnostics.Debug.WriteLine(\"Another instance of this application is already running.\");\n                    return;\n                }\n\n                Application.EnableVisualStyles();\n                Application.SetCompatibleTextRenderingDefault(false);\n                AppContext = new MyAppContext();\n                Application.Run(AppContext);\n            }\n        }\n    }\n\n    public class MyAppContext : ApplicationContext\n    {\n        private readonly NotifyIcon _trayIcon;\n        private static List<MediaController> _controllers;\n\n        public MyAppContext()\n        {\n            _trayIcon = new NotifyIcon\n            {\n                Text = \"MPV Media Control\",\n                Icon = new Icon(SystemIcons.Application, 32, 32),\n                ContextMenu = new ContextMenu(new []\n                {\n                    new MenuItem(\"Reset SMTC\", ResetControllers),\n                    new MenuItem(\"Exit\", Exit)\n                }),\n                Visible = true\n            };\n\n            PipeServer.StartServer();\n\n            _controllers = new List<MediaController>();\n        }\n\n        public MediaController GetController(int pid, string socketName)\n        {\n            if (_controllers.FindIndex(c => c.Pid == pid) == -1)\n            {\n                _controllers.Add(new MediaController(pid, socketName, true));\n                return _controllers.Last();\n            }\n\n            return _controllers.Find(c => c.Pid == pid);\n        }\n\n        public void RemoveController(int pid)\n        {\n            var controller = _controllers.Find(c => c.Pid == pid);\n            controller.Cleanup(true);\n            _controllers.Remove(controller);\n        }\n\n        private async void ResetControllers(object sender, EventArgs e)\n        {\n            var newControllers = _controllers.Select(c => c.DuplicateSelf()).ToList();\n\n            _controllers.ForEach(c => c.Cleanup(false));\n            _controllers.Clear();\n            \n            // We need to manually trigger GC to remove MusicPlayer instances and prevent duplicate SMTC controls\n            GC.Collect();\n            \n            _controllers.AddRange(newControllers);\n            \n            // There is a bug in Windows where the control is not visible (but exists and is able to interact) if the info is updated too fast\n            // Sleep for a bit to prevent this\n            foreach (var controller in _controllers)\n            {\n                await Task.Delay(400);\n                controller.InitSMTC();\n            }\n        }\n\n        private void Exit(object sender, EventArgs e)\n        {\n            _trayIcon.Visible = false;\n\n            PipeServer.Cleanup();\n\n            _controllers.ForEach(i => i.Cleanup(true));\n\n            Application.Exit();\n            Environment.Exit(0);\n        }\n\n        public async void ExitIfNoControllers()\n        {\n            if (_controllers.Count == 0)\n            {\n                await Task.Run(() => Exit(null, null));\n            }\n        }\n    }\n}"
  },
  {
    "path": "MPVMediaControl/Properties/AssemblyInfo.cs",
    "content": "﻿using System.Reflection;\nusing System.Runtime.InteropServices;\n\n// General Information about an assembly is controlled through the following\n// set of attributes. Change these attribute values to modify the information\n// associated with an assembly.\n[assembly: AssemblyTitle(\"MPVMediaControl\")]\n[assembly: AssemblyDescription(\"\")]\n[assembly: AssemblyConfiguration(\"\")]\n[assembly: AssemblyCompany(\"\")]\n[assembly: AssemblyProduct(\"MPVMediaControl\")]\n[assembly: AssemblyCopyright(\"Copyright ©  2021\")]\n[assembly: AssemblyTrademark(\"\")]\n[assembly: AssemblyCulture(\"\")]\n\n// Setting ComVisible to false makes the types in this assembly not visible\n// to COM components.  If you need to access a type in this assembly from\n// COM, set the ComVisible attribute to true on that type.\n[assembly: ComVisible(false)]\n\n// The following GUID is for the ID of the typelib if this project is exposed to COM\n[assembly: Guid(\"f7771502-9fe9-4bd0-b073-fdc2abf5622a\")]\n\n// Version information for an assembly consists of the following four values:\n//\n//      Major Version\n//      Minor Version\n//      Build Number\n//      Revision\n//\n// You can specify all the values or you can default the Build and Revision Numbers\n// by using the '*' as shown below:\n// [assembly: AssemblyVersion(\"1.0.*\")]\n[assembly: AssemblyVersion(\"1.0.0.0\")]\n[assembly: AssemblyFileVersion(\"1.0.0.0\")]"
  },
  {
    "path": "MPVMediaControl/Properties/Resources.Designer.cs",
    "content": "﻿//------------------------------------------------------------------------------\n// <auto-generated>\n//     This code was generated by a tool.\n//     Runtime Version:4.0.30319.42000\n//\n//     Changes to this file may cause incorrect behavior and will be lost if\n//     the code is regenerated.\n// </auto-generated>\n//------------------------------------------------------------------------------\n\n\nnamespace MPVMediaControl.Properties\n{\n    /// <summary>\n    ///   A strongly-typed resource class, for looking up localized strings, etc.\n    /// </summary>\n    // This class was auto-generated by the StronglyTypedResourceBuilder\n    // class via a tool like ResGen or Visual Studio.\n    // To add or remove a member, edit your .ResX file then rerun ResGen\n    // with the /str option, or rebuild your VS project.\n    [global::System.CodeDom.Compiler.GeneratedCodeAttribute(\"System.Resources.Tools.StronglyTypedResourceBuilder\", \"4.0.0.0\")]\n    [global::System.Diagnostics.DebuggerNonUserCodeAttribute()]\n    [global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()]\n    internal class Resources\n    {\n\n        private static global::System.Resources.ResourceManager resourceMan;\n\n        private static global::System.Globalization.CultureInfo resourceCulture;\n\n        [global::System.Diagnostics.CodeAnalysis.SuppressMessageAttribute(\"Microsoft.Performance\", \"CA1811:AvoidUncalledPrivateCode\")]\n        internal Resources()\n        {\n        }\n\n        /// <summary>\n        ///   Returns the cached ResourceManager instance used by this class.\n        /// </summary>\n        [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)]\n        internal static global::System.Resources.ResourceManager ResourceManager\n        {\n            get\n            {\n                if ((resourceMan == null))\n                {\n                    global::System.Resources.ResourceManager temp = new global::System.Resources.ResourceManager(\"MPVMediaControl.Properties.Resources\", typeof(Resources).Assembly);\n                    resourceMan = temp;\n                }\n                return resourceMan;\n            }\n        }\n\n        /// <summary>\n        ///   Overrides the current thread's CurrentUICulture property for all\n        ///   resource lookups using this strongly typed resource class.\n        /// </summary>\n        [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)]\n        internal static global::System.Globalization.CultureInfo Culture\n        {\n            get\n            {\n                return resourceCulture;\n            }\n            set\n            {\n                resourceCulture = value;\n            }\n        }\n    }\n}\n"
  },
  {
    "path": "MPVMediaControl/Properties/Resources.resx",
    "content": "﻿<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<root>\n  <!-- \n    Microsoft ResX Schema \n    \n    Version 2.0\n    \n    The primary goals of this format is to allow a simple XML format \n    that is mostly human readable. The generation and parsing of the \n    various data types are done through the TypeConverter classes \n    associated with the data types.\n    \n    Example:\n    \n    ... ado.net/XML headers & schema ...\n    <resheader name=\"resmimetype\">text/microsoft-resx</resheader>\n    <resheader name=\"version\">2.0</resheader>\n    <resheader name=\"reader\">System.Resources.ResXResourceReader, System.Windows.Forms, ...</resheader>\n    <resheader name=\"writer\">System.Resources.ResXResourceWriter, System.Windows.Forms, ...</resheader>\n    <data name=\"Name1\"><value>this is my long string</value><comment>this is a comment</comment></data>\n    <data name=\"Color1\" type=\"System.Drawing.Color, System.Drawing\">Blue</data>\n    <data name=\"Bitmap1\" mimetype=\"application/x-microsoft.net.object.binary.base64\">\n        <value>[base64 mime encoded serialized .NET Framework object]</value>\n    </data>\n    <data name=\"Icon1\" type=\"System.Drawing.Icon, System.Drawing\" mimetype=\"application/x-microsoft.net.object.bytearray.base64\">\n        <value>[base64 mime encoded string representing a byte array form of the .NET Framework object]</value>\n        <comment>This is a comment</comment>\n    </data>\n                \n    There are any number of \"resheader\" rows that contain simple \n    name/value pairs.\n    \n    Each data row contains a name, and value. The row also contains a \n    type or mimetype. Type corresponds to a .NET class that support \n    text/value conversion through the TypeConverter architecture. \n    Classes that don't support this are serialized and stored with the \n    mimetype set.\n    \n    The mimetype is used for serialized objects, and tells the \n    ResXResourceReader how to depersist the object. This is currently not \n    extensible. For a given mimetype the value must be set accordingly:\n    \n    Note - application/x-microsoft.net.object.binary.base64 is the format \n    that the ResXResourceWriter will generate, however the reader can \n    read any of the formats listed below.\n    \n    mimetype: application/x-microsoft.net.object.binary.base64\n    value   : The object must be serialized with \n            : System.Serialization.Formatters.Binary.BinaryFormatter\n            : and then encoded with base64 encoding.\n    \n    mimetype: application/x-microsoft.net.object.soap.base64\n    value   : The object must be serialized with \n            : System.Runtime.Serialization.Formatters.Soap.SoapFormatter\n            : and then encoded with base64 encoding.\n\n    mimetype: application/x-microsoft.net.object.bytearray.base64\n    value   : The object must be serialized into a byte array \n            : using a System.ComponentModel.TypeConverter\n            : and then encoded with base64 encoding.\n    -->\n  <xsd:schema id=\"root\" xmlns=\"\" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\" xmlns:msdata=\"urn:schemas-microsoft-com:xml-msdata\">\n    <xsd:element name=\"root\" msdata:IsDataSet=\"true\">\n      <xsd:complexType>\n        <xsd:choice maxOccurs=\"unbounded\">\n          <xsd:element name=\"metadata\">\n            <xsd:complexType>\n              <xsd:sequence>\n                <xsd:element name=\"value\" type=\"xsd:string\" minOccurs=\"0\" />\n              </xsd:sequence>\n              <xsd:attribute name=\"name\" type=\"xsd:string\" />\n              <xsd:attribute name=\"type\" type=\"xsd:string\" />\n              <xsd:attribute name=\"mimetype\" type=\"xsd:string\" />\n            </xsd:complexType>\n          </xsd:element>\n          <xsd:element name=\"assembly\">\n            <xsd:complexType>\n              <xsd:attribute name=\"alias\" type=\"xsd:string\" />\n              <xsd:attribute name=\"name\" type=\"xsd:string\" />\n            </xsd:complexType>\n          </xsd:element>\n          <xsd:element name=\"data\">\n            <xsd:complexType>\n              <xsd:sequence>\n                <xsd:element name=\"value\" type=\"xsd:string\" minOccurs=\"0\" msdata:Ordinal=\"1\" />\n                <xsd:element name=\"comment\" type=\"xsd:string\" minOccurs=\"0\" msdata:Ordinal=\"2\" />\n              </xsd:sequence>\n              <xsd:attribute name=\"name\" type=\"xsd:string\" msdata:Ordinal=\"1\" />\n              <xsd:attribute name=\"type\" type=\"xsd:string\" msdata:Ordinal=\"3\" />\n              <xsd:attribute name=\"mimetype\" type=\"xsd:string\" msdata:Ordinal=\"4\" />\n            </xsd:complexType>\n          </xsd:element>\n          <xsd:element name=\"resheader\">\n            <xsd:complexType>\n              <xsd:sequence>\n                <xsd:element name=\"value\" type=\"xsd:string\" minOccurs=\"0\" msdata:Ordinal=\"1\" />\n              </xsd:sequence>\n              <xsd:attribute name=\"name\" type=\"xsd:string\" use=\"required\" />\n            </xsd:complexType>\n          </xsd:element>\n        </xsd:choice>\n      </xsd:complexType>\n    </xsd:element>\n  </xsd:schema>\n  <resheader name=\"resmimetype\">\n    <value>text/microsoft-resx</value>\n  </resheader>\n  <resheader name=\"version\">\n    <value>2.0</value>\n  </resheader>\n  <resheader name=\"reader\">\n    <value>System.Resources.ResXResourceReader, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>\n  </resheader>\n  <resheader name=\"writer\">\n    <value>System.Resources.ResXResourceWriter, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>\n  </resheader>\n</root>"
  },
  {
    "path": "MPVMediaControl/Properties/Settings.Designer.cs",
    "content": "﻿//------------------------------------------------------------------------------\n// <auto-generated>\n//     This code was generated by a tool.\n//     Runtime Version:4.0.30319.42000\n//\n//     Changes to this file may cause incorrect behavior and will be lost if\n//     the code is regenerated.\n// </auto-generated>\n//------------------------------------------------------------------------------\n\n\nnamespace MPVMediaControl.Properties\n{\n    [global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()]\n    [global::System.CodeDom.Compiler.GeneratedCodeAttribute(\"Microsoft.VisualStudio.Editors.SettingsDesigner.SettingsSingleFileGenerator\", \"11.0.0.0\")]\n    internal sealed partial class Settings : global::System.Configuration.ApplicationSettingsBase\n    {\n\n        private static Settings defaultInstance = ((Settings)(global::System.Configuration.ApplicationSettingsBase.Synchronized(new Settings())));\n\n        public static Settings Default\n        {\n            get\n            {\n                return defaultInstance;\n            }\n        }\n    }\n}\n"
  },
  {
    "path": "MPVMediaControl/Properties/Settings.settings",
    "content": "﻿<?xml version='1.0' encoding='utf-8'?>\n<SettingsFile xmlns=\"http://schemas.microsoft.com/VisualStudio/2004/01/settings\" CurrentProfile=\"(Default)\">\n  <Profiles>\n    <Profile Name=\"(Default)\" />\n  </Profiles>\n  <Settings />\n</SettingsFile>\n"
  },
  {
    "path": "MPVMediaControl/StreamString.cs",
    "content": "﻿using System;\nusing System.IO;\nusing System.Text;\n\nnamespace MPVMediaControl\n{\n    // Defines the data protocol for reading and writing strings on our stream\n    public class StreamString\n    {\n        private Stream ioStream;\n        private Encoding streamEncoding;\n\n        public StreamString(Stream ioStream)\n        {\n            this.ioStream = ioStream;\n            streamEncoding = new UTF8Encoding();\n        }\n\n        public string ReadString()\n        {\n            int len = 1024;\n\n            byte[] inBuffer = new byte[len];\n            ioStream.Read(inBuffer, 0, len);\n\n            return streamEncoding.GetString(inBuffer).TrimEnd('\\0');\n        }\n\n        public int WriteString(string outString)\n        {\n            byte[] outBuffer = streamEncoding.GetBytes(outString);\n            int len = outBuffer.Length;\n            if (len > UInt16.MaxValue)\n            {\n                len = (int)UInt16.MaxValue;\n            }\n\n            ioStream.Write(outBuffer, 0, len);\n            ioStream.Flush();\n\n            return outBuffer.Length;\n        }\n    }\n}"
  },
  {
    "path": "MPVMediaControl/SystemMeidaTransportControlsInterop.cs",
    "content": "﻿// From https://github.com/AdamBraden/WindowsInteropWrappers/blob/master/CoreWindowInterop/SystemMediaTransportControlsInterop.cs\n\nusing System;\nusing System.Runtime.InteropServices.WindowsRuntime;\nusing Windows.Media;\n\nnamespace UWPInterop\n{\n    //MIDL_INTERFACE(\"ddb0472d-c911-4a1f-86d9-dc3d71a95f5a\")\n    //ISystemMediaTransportControlsInterop : public IInspectable\n    //{\n    //public:\n    //    virtual HRESULT STDMETHODCALLTYPE GetForWindow(\n    //        /* [in] */ __RPC__in HWND appWindow,\n    //        /* [in] */ __RPC__in REFIID riid,\n    //        /* [iid_is][retval][out] */ __RPC__deref_out_opt void** mediaTransportControl) = 0;\n\n    //};\n    [System.Runtime.InteropServices.Guid(\"ddb0472d-c911-4a1f-86d9-dc3d71a95f5a\")]\n    [System.Runtime.InteropServices.InterfaceType(System.Runtime.InteropServices.ComInterfaceType\n        .InterfaceIsIInspectable)]\n    interface ISystemMediaTransportControlsInterop\n    {\n        SystemMediaTransportControls GetForWindow(IntPtr appWindow, [System.Runtime.InteropServices.In] ref Guid riid);\n    }\n\n    //Helper to initialize SystemMediaTransportControls\n    public static class SystemMediaTransportControlsInterop\n    {\n        public static SystemMediaTransportControls GetForWindow(IntPtr hWnd)\n        {\n            ISystemMediaTransportControlsInterop systemMediaTransportControlsInterop =\n                (ISystemMediaTransportControlsInterop)WindowsRuntimeMarshal.GetActivationFactory(\n                    typeof(SystemMediaTransportControls));\n            Guid guid = new Guid(\"99FA3FF4-1742-42A6-902E-087D41F965EC\");\n\n            return systemMediaTransportControlsInterop.GetForWindow(hWnd, ref guid);\n        }\n    }\n}"
  },
  {
    "path": "MPVMediaControl.sln",
    "content": "﻿\nMicrosoft Visual Studio Solution File, Format Version 12.00\n# Visual Studio Version 16\nVisualStudioVersion = 16.0.30907.101\nMinimumVisualStudioVersion = 10.0.40219.1\nProject(\"{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}\") = \"MPVMediaControl\", \"MPVMediaControl\\MPVMediaControl.csproj\", \"{F7771502-9FE9-4BD0-B073-FDC2ABF5622A}\"\nEndProject\nGlobal\n\tGlobalSection(SolutionConfigurationPlatforms) = preSolution\n\t\tDebug|Any CPU = Debug|Any CPU\n\t\tRelease|Any CPU = Release|Any CPU\n\tEndGlobalSection\n\tGlobalSection(ProjectConfigurationPlatforms) = postSolution\n\t\t{F7771502-9FE9-4BD0-B073-FDC2ABF5622A}.Debug|Any CPU.ActiveCfg = Debug|Any CPU\n\t\t{F7771502-9FE9-4BD0-B073-FDC2ABF5622A}.Debug|Any CPU.Build.0 = Debug|Any CPU\n\t\t{F7771502-9FE9-4BD0-B073-FDC2ABF5622A}.Release|Any CPU.ActiveCfg = Release|Any CPU\n\t\t{F7771502-9FE9-4BD0-B073-FDC2ABF5622A}.Release|Any CPU.Build.0 = Release|Any CPU\n\tEndGlobalSection\n\tGlobalSection(SolutionProperties) = preSolution\n\t\tHideSolutionNode = FALSE\n\tEndGlobalSection\n\tGlobalSection(ExtensibilityGlobals) = postSolution\n\t\tSolutionGuid = {3FE63DFA-48B1-403D-809A-BEE2A06C3D7E}\n\tEndGlobalSection\nEndGlobal\n"
  },
  {
    "path": "README.md",
    "content": "# MPVMediaControl\nThis tool adds SMTC feature to mpv player, it communicates with mpv by named pipe, and can be controlled by any other programs.\n\n<img src=\"https://github.com/datasone/MPVMediaControl/blob/master/img/screenshot.png?raw=true\" height=\"175px\" />\n\n*Screenshot on Windows 11 22000 (It's much more useable than the one in 10)*\n\n## Features\n- Media metadata display including title and artist information\n- Thumbnail generated from mpv screenshot or youtube cover image\n- Media controls (play/pause, prev, next)\n\n## Usage\nPut `notify_media.lua` in mpv's `scripts` directory and place `MPVMediaControl.exe` to `~~/bin`.\n\nYou can change the default settings via the `notify_media.conf` file.\n\nA `Reset SMTC` item in menu will reset the state of SMTC, useful when Windows is glitched and controls are not working properly (e.g. not displaying or disappearing).\n\nFor retrieving youtube cover image, `curl.exe` is used. It has been bundled in Windows 10 since [1803, or actually build 17063](https://devblogs.microsoft.com/commandline/tar-and-curl-come-to-windows/). So if you are using older versions of Windows, you may need to manually download and put `curl.exe` into $PATH.\n\n## Protocol\nThis tool listens on a named pipe called `mpvmcsocket`, and receives commands through this protocol:\n```\n[commandName](param1=value1)(param2=value2)...\n```\n\ne.g. \n\n```\n[setState](pid=1000)(playing=true)\n```\n\n### Commands\n- `setFile`: set currently playing file\n- `setShot`: set screenshot file path\n- `setState`: set player state (playing or not)\n- `setQuit`: notify the tool that player has quit, and the SMTC should be cleared\n\n### Parameters\n- Common parameters\n  - `pid={num}`: the player's pid. This is a mandatory parameter for every command, it is used to identify different instances.\n  - `socket_name={String}`: the name of MPV's input-ipc-server socket. This is mandatory for every command, and the value is **directly** the name string.\n    - Though Windows allows Unicode named pipes, it will make things more complex and I didn't see any benefits to use non-ASCII characters.\n- Parameters for `setFile`\n  - `title={hexString}`: the title of the media file\n  - `artist={hexString}`: the artist of the media file, music files only. The value can be empty.\n  - `path={hexString}`: the path of the media file\n  - `type={music,video,image}`: the type of the media file\n- Parameters for `setShot`\n  - `shot_path={hexString}`: the path of the thumbnail image file. The value can be empty.\n\nThe `hexString` mentioned above means the original string should be encoded to hex, e.g. `Hello <=> 48656C6C6F`\n- Parameters for `setState`\n  - `playing={bool}`: if the media is being played, `true` for playing, `false` for pausing\n- Parameters for `setQuit`\n  - `quit=true`: this is always true if you want to quit\n\nThe media control part works by sending commands to mpv's ipc socket, which `notify_media.lua` will set mpv to listen on, with the configured `socket_name` in `notify_media.conf`.\n"
  },
  {
    "path": "notify_media.conf",
    "content": "### Default config for notify_media.lua\n\ndebug=no\n# Path to executable (MPVMediaControl.exe)\nbinary_path=~~/bin/MPVMediaControl.exe\n# Path for storing temporary screenshots\nshot_path=~~/\n# If you want to delay taking screenshot for videos, set this to the number of delayed seconds\ndelayed_sec=3\n# Name of mpv's input-ipc-server (defaults to mpvsocket_{pid}), it shall be useful when multiple scripts set up the IPC socket for controls.\n# String \"{pid}\" in this config value will be automatically convert to the ID of mpv process to prevent conflicts between multiple instances.\nsocket_name=mpvsocket_{pid}\n# Should we kill MPVMediaControl when mpv exits, as sometimes the program won't exit properly with mpv\nkill_mc=no\n"
  },
  {
    "path": "notify_media.lua",
    "content": "local mp = require 'mp'\nlocal utils = require 'mp.utils'\nlocal opt = require 'mp.options'\n\nlocal o = {\n    debug = false,\n    -- Path to executable (MPVMediaControl.exe)\n    binary_path = \"~~/bin/MPVMediaControl.exe\",\n    -- Path for storing temporary screenshots\n    shot_path = \"~~/\",\n    -- If you want to delay taking screenshot for videos, set this to the number of delayed seconds\n    delayed_sec = 3,\n    -- Name of mpv's input-ipc-server (defaults to mpvsocket_{pid}), string \"{pid}\" in the value will be automatically replaced with the ID of mpv process\n    socket_name = \"mpvsocket_{pid}\",\n    -- Should we kill MPVMediaControl when mpv exits, as sometimes the program won't exit properly with mpv\n    kill_mc = false,\n}\n\nopt.read_options(o, \"notify_media\")\n\no.binary_path = mp.command_native({ \"expand-path\", o.binary_path })\n\nlocal pid = utils.getpid()\nlocal start_of_file = true\nlocal new_file = false\nlocal yt_thumbnail = false\nlocal yt_failed = false\nlocal mpv_socket_name = o.socket_name:gsub(\"{pid}\", tostring(pid))\n\n-- Print contents of `tbl`, with indentation.\n-- `indent` sets the initial level of indentation.\nfunction tprint (tbl, indent)\n    if not indent then indent = 0 end\n    for k, v in pairs(tbl) do\n        formatting = string.rep(\"  \", indent) .. k .. \": \"\n        if type(v) == \"table\" then\n            print(formatting)\n            tprint(v, indent+1)\n        elseif type(v) == 'boolean' then\n            print(formatting .. tostring(v))\n        else\n            print(formatting .. v)\n        end\n    end\nend\n\nfunction debug_log(message)\n    if o.debug then\n        if not message then\n            print(\"DEBUG: nil\")\n            return\n        end\n        if \"table\" == type(message) then\n            print(\"DEBUG: \")\n            tprint(message)\n        else\n            print(\"DEBUG: \" .. message)\n        end\n    end\nend\n\nipc_socket_file = \"\\\\\\\\.\\\\pipe\\\\mpvmcsocket\"\n\nfunction write_to_socket(message)\n    _, pipe = pcall(io.open, ipc_socket_file, \"w\")\n    if pipe then\n        pcall(pipe.write, pipe, message)\n        pcall(pipe.flush, pipe)\n        pcall(pipe.close, pipe)\n        debug_log(message)\n    end\nend\n\nfunction get_metadata(data, keys)\n    for _, v in pairs(keys) do\n        if data[v] and string.len(data[v]) > 0 then\n            return data[v]\n        end\n    end\n    return \"\"\nend\n\nfunction encode_element(str)\n    -- return str:gsub(\"%(\", \"\\\\\\\\[\"):gsub(\"%)\", \"\\\\\\\\]\")\n    return tohex(str)\nend\n\nfunction tohex(str)\n    return (str:gsub('.', function (c)\n        return string.format('%02X', string.byte(c))\n    end))\nend\n\nfunction save_shot(path)\n    if youtube_thumbail(path) then\n        local shot_path_encoded = encode_element(shot_path)\n        message_content = \"^[setShot](pid=\" .. pid .. \")(shot_path=\" .. shot_path_encoded .. \")(socket_name=\" .. mpv_socket_name .. \")$\"\n        write_to_socket(message_content)\n        return\n    end\n    if start_of_file and media_type() == \"video\" and o.delayed_sec ~= 0 then\n        mp.add_timeout(o.delayed_sec, function() save_shot(path) end)\n        start_of_file = false\n        return\n    end\n    result = mp.commandv(\"screenshot-to-file\", path)\n    if not result then\n        mp.add_timeout(0.5, function() save_shot(path) end)\n    else\n        local shot_path_encoded = encode_element(shot_path)\n        message_content = \"^[setShot](pid=\" .. pid .. \")(shot_path=\" .. shot_path_encoded .. \")(socket_name=\" .. mpv_socket_name .. \")$\"\n        write_to_socket(message_content)\n    end\nend\n\nfunction youtube_thumbail(path)\n    if not yt_thumbnail then\n        debug_log(mp.get_property(\"path\"))\n        if not yt_failed and string.find(mp.get_property(\"path\"), \"www.youtube.com\") then\n        \t-- generate a url to the thumbnail file\n        \tvid_id = mp.get_property(\"filename\")\n        \tvid_id = string.gsub(vid_id, \"watch%?v=\", \"\") -- Strip possible prefix.\n        \tvid_id = string.sub(vid_id, 1, 11) -- Strip possible suffix.\n        \t\n        \tthumb_url = \"https://i.ytimg.com/vi/\" .. vid_id .. \"/maxresdefault.jpg\"\n        \t\n        \tlocal dl_process = mp.command_native({\n        \t    name = \"subprocess\",\n        \t    playback_only = true,\n        \t    args = {\"curl\", \"-L\", \"-s\", \"-o\", shot_path, thumb_url},\n        \t})\n        \t\n        \tif dl_process.status == 0 then\n        \t    yt_thumbnail = true\n                return true\n        \tend\n        end\n        yt_failed = true\n        return false\n    end\n    return true\nend\n\nfunction media_type()\n    fps = mp.get_property_native(\"estimated-vf-fps\")\n\n    if fps and fps > 1 then\n        return \"video\"\n    else\n        return \"music\"\n    end\nend\n\nfunction notify_metadata_updated()\n    metadata = mp.get_property_native(\"metadata\")\n    debug_log(metadata)\n    if not metadata then\n        return\n    end\n\n    artist = get_metadata(metadata, { \"artist\", \"ARTIST\", \"Artist\" })\n    title = get_metadata(metadata, { \"title\", \"TITLE\", \"Title\", \"icy-title\" })\n\n    if media_type() == \"music\" and (not artist or artist == \"\" or not title or title == \"\") then\n        chapter_metadata = mp.get_property_native(\"chapter-metadata\")\n\n        if chapter_metadata then\n            chapter_artist = chapter_metadata[\"performer\"]\n            if not artist or artist == \"\" then\n                artist = chapter_artist\n            end\n\n            chapter_title = chapter_metadata[\"title\"]\n            if not title or title == \"\" then\n                title = chapter_title\n            end\n        end\n    end\n\n    if not title or title == \"\" then\n        title = mp.get_property_native(\"media-title\")\n    end\n\n    path = mp.get_property_native(\"path\")\n    if path:sub(2, 3) ~= \":\\\\\" and path:sub(2, 3) ~= \":/\" then\n        dir = mp.get_property_native(\"working-directory\")\n        path = dir .. \"\\\\\" .. path\n    end\n\n    if not artist then\n        artist = \"\"\n    end\n\n    if title then\n        title = encode_element(title)\n    end\n    if artist then\n        artist = encode_element(artist)\n    end\n    path = encode_element(path)\n\n    local shot_dir = mp.command_native({ \"expand-path\", o.shot_path })\n    shot_path = shot_dir .. \"\\\\\" .. pid .. \".jpg\"\n    if mp.get_property(\"video-codec\") then\n        save_shot(shot_path)\n    end\n\n    message_content = \"^[setFile](pid=\" .. pid .. \")(title=\" .. title .. \")(artist=\" .. artist .. \")(path=\" .. path .. \")(type=\" .. media_type() .. \")(socket_name=\" .. mpv_socket_name .. \")$\"\n    write_to_socket(message_content)\nend\n\nfunction play_state_changed()\n    idle = mp.get_property_native(\"core-idle\")\n    is_playing = not idle\n\n    message_content = \"^[setState](pid=\" .. pid .. \")(playing=\" .. tostring(is_playing) .. \")(socket_name=\" .. mpv_socket_name .. \")$\"\n    write_to_socket(message_content)\n\n    if not idle then\n        mp.add_timeout(10, play_state_changed)\n    end\nend\n\nfunction notify_current_file()\n    -- Even all things are right in MPVMediaControl, there may be native crash caused by Windows itself (SHCORE.dll).\n    -- This line let mpv run the program again when a new file is loaded, help mitigating the problem.\n    -- It won't cost much as MPVMC will not allow multiple instances to be started. But if you don't want this, comment out the line below.\n    run_mpvmc_program()\n    notify_metadata_updated()\nend\n\nfunction run_mpvmc_program()\n    mp.command_native({\n        name = \"subprocess\",\n        playback_only = false,\n        capture_stdout = false,\n        capture_stderr = false,\n        detach = true,\n        args = { o.binary_path },\n    })\nend\n\nmp.set_property(\"options/input-ipc-server\", \"\\\\\\\\.\\\\pipe\\\\\" .. mpv_socket_name)\n\nfunction start_register_event()\n    if new_file then\n        notify_current_file()\n        start_of_file = true\n        new_file = false\n        yt_thumbnail = false\n        yt_failed = false\n        mp.observe_property(\"media-title\", nil, notify_metadata_updated)\n        mp.observe_property(\"metadata\", nil, notify_metadata_updated)\n        mp.observe_property(\"chapter\", nil, notify_metadata_updated)\n        mp.register_event(\"end-file\", play_state_changed)\n        mp.observe_property(\"core-idle\", nil, play_state_changed)\n    end\nend\n\nmp.register_event(\"file-loaded\", function() new_file = true end)\nmp.register_event(\"playback-restart\", start_register_event)\n\nfunction on_quit()\n    if shot_path then\n        os.remove(shot_path)\n    end\n    write_to_socket(\"^[setQuit](pid=\" .. pid .. \")(quit=true)(socket_name=\" .. mpv_socket_name .. \")$\")\n    \n    if o.kill_mc then\n        -- Force kill MPVMediaControl.exe\n        mp.command_native({\n            name = \"subprocess\",\n            playback_only = false,\n            args = {\"taskkill\", \"/F\", \"/IM\", \"MPVMediaControl.exe\"},\n        })\n    end\nend\n\nmp.register_event(\"shutdown\", on_quit)\n"
  }
]