Compare commits

...

7 Commits
1.4 ... 1.7

Author SHA1 Message Date
Frank Skare
e7d41ff626 - 2019-03-23 15:42:57 +01:00
Frank Skare
f2c526348d - 2019-03-23 04:24:33 +01:00
Frank Skare
b4d2a7e86d - 2019-03-23 04:21:45 +01:00
Frank Skare
98f8e7090a - 2019-03-23 04:10:26 +01:00
Frank Skare
aeb5958be6 - 2019-03-23 04:07:47 +01:00
Frank Skare
1d16861b0b 1.5 2019-03-21 18:31:18 +01:00
Frank Skare
4366c47a09 - 2019-03-21 18:30:10 +01:00
15 changed files with 408 additions and 262 deletions

View File

@@ -1,5 +1,6 @@
Imports System.ComponentModel.Composition Imports System.ComponentModel.Composition
Imports System.IO Imports System.IO
Imports System.Windows.Forms
Imports mpvnet Imports mpvnet
Imports mpvnet.StaticUsing Imports mpvnet.StaticUsing
@@ -13,7 +14,8 @@ Public Class CSScriptAddon
Sub New() Sub New()
Dim scriptDir = mp.mpvConfFolderPath + "scripts" Dim scriptDir = mp.mpvConfFolderPath + "scripts"
If Not Directory.Exists(scriptDir) Then Return If Not Directory.Exists(scriptDir) Then Return
Dim csFiles = Directory.GetFiles(scriptDir, "*.cs") Dim csFiles = Directory.GetFiles(scriptDir, "*.cs").ToList
csFiles.AddRange(Directory.GetFiles(Application.StartupPath + "\\Scripts", "*.cs"))
If csFiles.Count = 0 Then Return If csFiles.Count = 0 Then Return
CSScriptLibrary.CSScript.EvaluatorConfig.Engine = EvaluatorEngine.CodeDom CSScriptLibrary.CSScript.EvaluatorConfig.Engine = EvaluatorEngine.CodeDom

View File

@@ -55,6 +55,7 @@
<Reference Include="System" /> <Reference Include="System" />
<Reference Include="System.ComponentModel.Composition" /> <Reference Include="System.ComponentModel.Composition" />
<Reference Include="System.Data" /> <Reference Include="System.Data" />
<Reference Include="System.Windows.Forms" />
<Reference Include="System.Xml" /> <Reference Include="System.Xml" />
<Reference Include="System.Core" /> <Reference Include="System.Core" />
<Reference Include="System.Xml.Linq" /> <Reference Include="System.Xml.Linq" />

113
README.md
View File

@@ -18,23 +18,33 @@ mpv manual: https://mpv.io/manual/master/
### Context Menu ### Context Menu
The context menu can be customized via input.conf file located at: The context menu can be customized via input.conf file located at:
```
C:\Users\username\AppData\Roaming\mpv\input.conf
```
if it's missing mpv.net generates it with the following defaults:
C:\Users\Frank\AppData\Roaming\mpv\input.conf https://github.com/stax76/mpv.net/blob/master/mpv.net/Resources/input.conf.txt
if it misses mpv.net generates it with the following defaults: ### Settings
https://github.com/stax76/mpv.net/blob/master/mpv.net/Resources/input_conf.txt mpv.net shares the settings with mpv, settings have to be edited in a config file called mpv.conf located at:
```
C:\Users\username\AppData\Roaming\mpv\mpv.conf
```
if it's missing mpv.net generates it with the following defaults:
https://github.com/stax76/mpv.net/blob/master/mpv.net/Resources/mpv.conf.txt
### C# Scripting ### C# Scripting
A simple C# script located at: A simple C# script located at:
```
C:\Users\Frank\AppData\Roaming\mpv\scripts\test.cs C:\Users\username\AppData\Roaming\mpv\scripts\fullscreen.cs
```
or or
```
startup\scripts\test.cs startup\scripts\fullscreen.cs
```
``` ```
using mpvnet; using mpvnet;
@@ -42,14 +52,14 @@ class Script
{ {
public Script() public Script()
{ {
var fs = mpv.GetStringProp("fullscreen"); var fs = mp.get_property_string("fullscreen");
mpv.Command("show-text", "fullscreen: " + fs); mp.commandv("show-text", "fullscreen: " + fs);
mpv.ObserveBoolProp("fullscreen", FullscreenChange); mp.observe_property_bool("fullscreen", FullscreenChange);
} }
void FullscreenChange(bool val) void FullscreenChange(bool val)
{ {
mpv.Command("show-text", "fullscreen: " + val.ToString()); mp.commandv("show-text", "fullscreen: " + val.ToString());
} }
} }
``` ```
@@ -57,13 +67,13 @@ class Script
### Python Scripting ### Python Scripting
A simple Python script located at: A simple Python script located at:
```
C:\Users\user\AppData\Roaming\mpv\scripts C:\Users\user\AppData\Roaming\mpv\scripts\seek-show-position.py
```
or or
```
startup\scripts startup\scripts\seek-show-position.py
```
``` ```
# when seeking displays position and # when seeking displays position and
# duration like so: 70:00 / 80:00 # duration like so: 70:00 / 80:00
@@ -96,22 +106,45 @@ mp.register_event("seek", seek) # or use: mp.Seek += seek
### PowerShell Scripting ### PowerShell Scripting
A simple PowerShell script located at: A simple PowerShell script located at:
```
C:\Users\user\AppData\Roaming\mpv\scripts C:\Users\user\AppData\Roaming\mpv\scripts\seek.ps1
```
or or
```
startup\scripts startup\scripts\seek.ps1
```
Please note that PowerShell don't allow assigning to events and mpv.net uses as workaround the script filename.
``` ```
$position = [mp]::get_property_number("time-pos"); $position = [mp]::get_property_number("time-pos");
[mp]::commandv("show-text", $position.ToString() + " seconds") [mp]::commandv("show-text", $position.ToString() + " seconds")
``` ```
Please note that PowerShell don't allow assigning to events and mpv.net uses as workaround a matching script filename, a list of available events can be found in the mpv manual or in the file mp.cs in the mpv.net source code.
### Changes ### Changes
### 1.7
- showing the conf files mpv.net uses now the app that is registered for txt files, before it just shell executed the conf file which only worked if conf files were associated with an application
- leaving fullscreen mode the previous window size and position wasn't restored
- when the source video aspect ratio changes the height is kept and the width is adjusted and a check is performed to assure the window is within screen bounds
### 1.6
- a crash caused by WM_APPCOMMAND (multimedia keyboards) commands was fixed
- support for the 'screen' property was added, it should work both from mpv.conf (screen = 1) and from command line (--screen=1)
- per monitor DPI awareness and better multi monitor support was added
### 1.5
- the info command supports now info for music files instead of showing an exception on music files
- added support for WM_APPCOMMAND API to support media keyboards
- fixed Alt key input not working
- mpv.net API methods renamed to match the names used in the Lua/JS API
### 1.4
- the last thread sync fix wasn't working well, the delayed shutdown should be gone for good now
- libmpv updated
### 1.3 ### 1.3
- besides Lua/JavaScript/C#/Python there is now PowerShell supported as fifth scripting language - besides Lua/JavaScript/C#/Python there is now PowerShell supported as fifth scripting language
@@ -130,29 +163,3 @@ $position = [mp]::get_property_number("time-pos");
### 1.0 ### 1.0
- much more feature packed context menu - much more feature packed context menu
### 0.2.5
- mpv lib updated to 2019-02-24
- UI glitch fixed the appeared when started in fullscreen mode
- fixed default video output mode which caused video playback to fail
### 0.2.4
- changed minimum runtime to .NET 4.7.2
- fixed mpv.net not working with new mpv lib
- the track name in the title bar was sometimes wrong
- mpv lib updated to 2018-12-16
- quit-watch-later added to context menu (Shift+Q) to exit and resume at the last position
- ab loop added to menu
- added the possibility to modify mpv.conf settings using the context menu
- added link to the manual and default keys to the menu
### 0.2.2
- history feature added
- mpv lib updated
### 0.2.1
- right-click in fullscreen in the right-left corner closes the app

View File

@@ -51,8 +51,8 @@ namespace RatingAddon
if (args?.Length != 2 || args[0] != "rate-file" || ! int.TryParse(args[1], out rating)) if (args?.Length != 2 || args[0] != "rate-file" || ! int.TryParse(args[1], out rating))
return; return;
Dic[mp.GetStringProp("path")] = rating; Dic[mp.get_property_string("path")] = rating;
mp.Command("show-text", $"Rating: {rating}"); mp.commandv("show-text", $"Rating: {rating}");
} }
} }
} }

View File

@@ -62,24 +62,12 @@ namespace mpvnet
public static void show_keys(string[] args) public static void show_keys(string[] args)
{ {
Process.Start(mp.InputConfPath); Process.Start(NativeHelp.GetAssociatedApplication(".txt"), mp.InputConfPath);
}
private static void CreateMpvConf()
{
if (!File.Exists(mp.mpvConfPath))
{
if (!Directory.Exists(mp.mpvConfFolderPath))
Directory.CreateDirectory(mp.mpvConfFolderPath);
File.WriteAllText(mp.mpvConfPath, "# https://mpv.io/manual/master/#configuration-files");
}
} }
public static void show_prefs(string[] args) public static void show_prefs(string[] args)
{ {
CreateMpvConf(); Process.Start(NativeHelp.GetAssociatedApplication(".txt"), mp.mpvConfPath);
Process.Start(mp.mpvConfPath);
} }
public static void history(string[] args) public static void history(string[] args)
@@ -89,7 +77,7 @@ namespace mpvnet
if (File.Exists(fp)) if (File.Exists(fp))
Process.Start(fp); Process.Start(fp);
else else
if (MsgQuestion("Create history.txt file in config folder?\r\n\r\nmpv.net will write the date, time and filename of opened files to it.") == DialogResult.OK) if (MsgQuestion("Create history.txt file in config folder?\n\nmpv.net will write the date, time and filename of opened files to it.") == DialogResult.OK)
File.WriteAllText(fp, ""); File.WriteAllText(fp, "");
} }
@@ -100,8 +88,6 @@ namespace mpvnet
public static void set_setting(string[] args) public static void set_setting(string[] args)
{ {
CreateMpvConf();
bool changed = false; bool changed = false;
string fp = mp.mpvConfPath; string fp = mp.mpvConfPath;
var confLines = File.ReadAllLines(fp); var confLines = File.ReadAllLines(fp);
@@ -116,51 +102,67 @@ namespace mpvnet
} }
if (changed) if (changed)
{
File.WriteAllText(fp, String.Join(Environment.NewLine, confLines)); File.WriteAllText(fp, String.Join(Environment.NewLine, confLines));
}
else else
{ File.WriteAllText(fp, File.ReadAllText(fp) + Environment.NewLine + args[0] + "=" + args[1]);
File.WriteAllText(fp,
File.ReadAllText(fp) + Environment.NewLine + args[0] + "=" + args[1]);
}
MsgInfo("Please restart mpv.net"); MsgInfo("Please restart mpv.net");
} }
public static void show_info(string[] args) public static void show_info(string[] args)
{ {
var fi = new FileInfo(mp.GetStringProp("path")); var fileInfo = new FileInfo(mp.get_property_string("path"));
using (var mi = new MediaInfo(fi.FullName)) using (var mediaInfo = new MediaInfo(fileInfo.FullName))
{ {
var w = mi.GetInfo(MediaInfoStreamKind.Video, "Width"); string width = mediaInfo.GetInfo(MediaInfoStreamKind.Video, "Width");
var h = mi.GetInfo(MediaInfoStreamKind.Video, "Height");
var pos = TimeSpan.FromSeconds(mp.GetIntProp("time-pos"));
var dur = TimeSpan.FromSeconds(mp.GetIntProp("duration"));
string mibr = mi.GetInfo(MediaInfoStreamKind.Video, "BitRate");
if (mibr == "") if (width == "")
mibr = "0"; {
string performer = mediaInfo.GetInfo(MediaInfoStreamKind.General, "Performer");
string title = mediaInfo.GetInfo(MediaInfoStreamKind.General, "Title");
string album = mediaInfo.GetInfo(MediaInfoStreamKind.General, "Album");
string genre = mediaInfo.GetInfo(MediaInfoStreamKind.General, "Genre");
string date = mediaInfo.GetInfo(MediaInfoStreamKind.General, "Recorded_Date");
string duration = mediaInfo.GetInfo(MediaInfoStreamKind.Audio, "Duration/String");
var br = Convert.ToInt32(mibr) / 1000.0 / 1000.0; string text = "";
var vf = mp.GetStringProp("video-format").ToUpper();
var fn = fi.Name;
if (fn.Length > 60) if (performer != "") text += "Artist: " + performer + "\n";
fn = fn.Insert(59, "\r\n"); if (title != "") text += "Title: " + title + "\n";
if (album != "") text += "Album: " + album + "\n";
if (genre != "") text += "Genre: " + genre + "\n";
if (date != "") text += "Year: " + date + "\n";
if (duration != "") text += "Length: " + duration + "\n";
var info = mp.commandv("show-text", text, "5000");
FormatTime(pos.TotalMinutes) + ":" + }
FormatTime(pos.Seconds) + " / " + else
FormatTime(dur.TotalMinutes) + ":" + {
FormatTime(dur.Seconds) + "\n" + string height = mediaInfo.GetInfo(MediaInfoStreamKind.Video, "Height");
((int)(fi.Length / 1024 / 1024)).ToString() + TimeSpan position = TimeSpan.FromSeconds(mp.get_property_number("time-pos"));
$" MB - {w} x {h}\n{vf} - {br.ToString("f1")} Mb/s" + "\n" + fn; TimeSpan duration = TimeSpan.FromSeconds(mp.get_property_number("duration"));
string bitrate = mediaInfo.GetInfo(MediaInfoStreamKind.Video, "BitRate");
mp.Command("show-text", info, "5000"); if (bitrate == "")
bitrate = "0";
string FormatTime(double value) => ((int)(Math.Floor(value))).ToString("00"); var bitrate2 = Convert.ToDouble(bitrate) / 1000.0 / 1000.0;
var videoCodec = mp.get_property_string("video-format").ToUpper();
var filename = fileInfo.Name;
var text =
FormatTime(position.TotalMinutes) + ":" +
FormatTime(position.Seconds) + " / " +
FormatTime(duration.TotalMinutes) + ":" +
FormatTime(duration.Seconds) + "\n" +
Convert.ToInt32(fileInfo.Length / 1024 / 1024).ToString() +
$" MB - {width} x {height}\n{videoCodec} - {bitrate2.ToString("f1")} Mb/s" + "\n" + filename;
mp.commandv("show-text", text, "5000");
}
string FormatTime(double value) => ((int)value).ToString("00");
} }
} }
} }

View File

@@ -42,10 +42,10 @@
// MainForm // MainForm
// //
this.AllowDrop = true; this.AllowDrop = true;
this.AutoScaleDimensions = new System.Drawing.SizeF(10F, 25F); this.AutoScaleDimensions = new System.Drawing.SizeF(288F, 288F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.None; this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Dpi;
this.BackColor = System.Drawing.Color.Black; this.BackColor = System.Drawing.Color.Black;
this.ClientSize = new System.Drawing.Size(1553, 1000); this.ClientSize = new System.Drawing.Size(1012, 615);
this.Font = new System.Drawing.Font("Segoe UI", 9F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.Font = new System.Drawing.Font("Segoe UI", 9F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.Icon = ((System.Drawing.Icon)(resources.GetObject("$this.Icon"))); this.Icon = ((System.Drawing.Icon)(resources.GetObject("$this.Icon")));
this.Margin = new System.Windows.Forms.Padding(3, 4, 3, 4); this.Margin = new System.Windows.Forms.Padding(3, 4, 3, 4);

View File

@@ -6,6 +6,8 @@ using System.Threading;
using System.Windows.Forms; using System.Windows.Forms;
using System.Diagnostics; using System.Diagnostics;
using static mpvnet.StaticUsing; using static mpvnet.StaticUsing;
using System.Linq;
using System.Collections.Generic;
namespace mpvnet namespace mpvnet
{ {
@@ -16,7 +18,7 @@ namespace mpvnet
private Point LastCursorPosChanged; private Point LastCursorPosChanged;
private int LastCursorChangedTickCount; private int LastCursorChangedTickCount;
private bool IsClosed; private bool IgnoreDpiChanged = true;
public ContextMenuStripEx CMS; public ContextMenuStripEx CMS;
@@ -27,15 +29,110 @@ namespace mpvnet
try try
{ {
Application.ThreadException += Application_ThreadException; Application.ThreadException += Application_ThreadException;
SetFormPosSize();
Instance = this; Instance = this;
Hwnd = Handle; Hwnd = Handle;
Text += " " + Application.ProductVersion; Text += " " + Application.ProductVersion;
ChangeFullscreen((mp.mpvConv.ContainsKey("fullscreen") && mp.mpvConv["fullscreen"] == "yes") || (mp.mpvConv.ContainsKey("fs") && mp.mpvConv["fs"] == "yes"));
if (mp.mpvConf.ContainsKey("screen"))
SetScreen(Convert.ToInt32(mp.mpvConf["screen"]));
else
SetScreen(Screen.PrimaryScreen);
ChangeFullscreen((mp.mpvConf.ContainsKey("fullscreen") && mp.mpvConf["fullscreen"] == "yes") ||
(mp.mpvConf.ContainsKey("fs") && mp.mpvConf["fs"] == "yes"));
ProcessCommandLineEarly();
} }
catch (Exception ex) catch (Exception e)
{ {
HandleException(ex); MsgError(e.ToString());
}
}
protected void SetScreen(int targetIndex)
{
Screen[] screens = Screen.AllScreens;
if (targetIndex < 0 || targetIndex > screens.Length - 1) return;
SetScreen(screens[Array.IndexOf(screens, screens[targetIndex])]);
}
protected void SetScreen(Screen screen)
{
Rectangle target = screen.Bounds;
Left = target.X + Convert.ToInt32((target.Width - Width) / 2.0);
Top = target.Y + Convert.ToInt32((target.Height - Height) / 2.0);
SetStartFormPositionAndSize();
}
void SetStartFormPositionAndSize()
{
if (IsFullscreen || mp.VideoSize.Width == 0) return;
Screen screen = Screen.FromControl(this);
int height = Convert.ToInt32(screen.Bounds.Height * 0.6);
int width = Convert.ToInt32(height * mp.VideoSize.Width / (double)mp.VideoSize.Height);
Point middlePos = new Point(Left + Width / 2, Top + Height / 2);
var rect = new Native.RECT(new Rectangle(screen.Bounds.X, screen.Bounds.Y, width, height));
NativeHelp.AddWindowBorders(Handle, ref rect);
int left = middlePos.X - rect.Width / 2;
int top = middlePos.Y - rect.Height / 2;
Native.SetWindowPos(Handle, IntPtr.Zero /* HWND_TOP */, left, top, rect.Width, rect.Height, 4 /* SWP_NOZORDER */);
}
void SetFormPositionAndSizeKeepHeight()
{
if (IsFullscreen || mp.VideoSize.Width == 0) return;
Screen screen = Screen.FromControl(this);
int height = ClientSize.Height;
int width = Convert.ToInt32(height * mp.VideoSize.Width / (double)mp.VideoSize.Height);
Point middlePos = new Point(Left + Width / 2, Top + Height / 2);
var rect = new Native.RECT(new Rectangle(screen.Bounds.X, screen.Bounds.Y, width, height));
NativeHelp.AddWindowBorders(Handle, ref rect);
int left = middlePos.X - rect.Width / 2;
int top = middlePos.Y - rect.Height / 2;
Screen[] screens = Screen.AllScreens;
if (left < screens[0].Bounds.Left)
left = screens[0].Bounds.Left;
int maxLeft = screens[0].Bounds.Left + screens.Select((sc) => sc.Bounds.Width).Sum() - rect.Width - SystemInformation.CaptionHeight;
if (left > maxLeft)
left = maxLeft;
Native.SetWindowPos(Handle, IntPtr.Zero /* HWND_TOP */, left, top, rect.Width, rect.Height, 4 /* SWP_NOZORDER */);
}
protected void ProcessCommandLineEarly()
{
var args = Environment.GetCommandLineArgs().Skip(1);
foreach (string i in args)
{
if (i.StartsWith("--"))
{
if (i.Contains("="))
{
string left = i.Substring(2, i.IndexOf("=") - 2);
string right = i.Substring(left.Length + 3);
if (left == "screen")
SetScreen(Convert.ToInt32(right));
ChangeFullscreen((left == "fs" || left == "fullscreen") && right == "yes");
}
else
{
string switchName = i.Substring(2);
switch (switchName)
{
case "fs":
case "fullscreen":
ChangeFullscreen(true);
break;
}
}
}
} }
} }
@@ -62,7 +159,7 @@ namespace mpvnet
var menuItem = CMS.Add(path, () => { var menuItem = CMS.Add(path, () => {
try try
{ {
mp.CommandString(cmd, false); mp.command_string(cmd);
} }
catch (Exception e) catch (Exception e)
{ {
@@ -84,17 +181,23 @@ namespace mpvnet
private void mp_PlaybackRestart() private void mp_PlaybackRestart()
{ {
var fn = mp.GetStringProp("filename"); var filename = mp.get_property_string("filename");
BeginInvoke(new Action(() => { Text = fn + " - mpv.net " + Application.ProductVersion; })); BeginInvoke(new Action(() => { Text = filename + " - mpv.net " + Application.ProductVersion; }));
var fp = mp.mpvConfFolderPath + "history.txt"; var historyFilepath = mp.mpvConfFolderPath + "history.txt";
if (LastHistory != fn && File.Exists(fp)) if (LastHistory != filename && File.Exists(historyFilepath))
{ {
File.AppendAllText(fp, DateTime.Now.ToString() + " " + Path.GetFileNameWithoutExtension(fn) + "\r\n"); File.AppendAllText(historyFilepath, DateTime.Now.ToString() + " " +
LastHistory = fn; Path.GetFileNameWithoutExtension(filename) + "\r\n");
LastHistory = filename;
} }
} }
private void Mp_Idle()
{
BeginInvoke(new Action(() => { Text = "mpv.net " + Application.ProductVersion; }));
}
private void CM_Popup(object sender, EventArgs e) private void CM_Popup(object sender, EventArgs e)
{ {
CursorHelp.Show(); CursorHelp.Show();
@@ -102,23 +205,17 @@ namespace mpvnet
private void Application_ThreadException(object sender, ThreadExceptionEventArgs e) private void Application_ThreadException(object sender, ThreadExceptionEventArgs e)
{ {
HandleException(e.Exception); MsgError(e.Exception.ToString());
}
void HandleException(Exception e)
{
MsgError(e.ToString());
} }
private void mp_VideoSizeChanged() private void mp_VideoSizeChanged()
{ {
BeginInvoke(new Action(() => SetFormPosSize())); BeginInvoke(new Action(() => SetFormPositionAndSizeKeepHeight()));
} }
private void mp_Shutdown() private void mp_Shutdown()
{ {
if (!IsClosed) BeginInvoke(new Action(() => Close()));
BeginInvoke(new Action(() => Close()));
} }
public bool IsFullscreen public bool IsFullscreen
@@ -135,14 +232,17 @@ namespace mpvnet
{ {
if (value) if (value)
{ {
FormBorderStyle = FormBorderStyle.None; if (FormBorderStyle != FormBorderStyle.None)
WindowState = FormWindowState.Maximized; {
FormBorderStyle = FormBorderStyle.None;
WindowState = FormWindowState.Maximized;
}
} }
else else
{ {
WindowState = FormWindowState.Normal; WindowState = FormWindowState.Normal;
FormBorderStyle = FormBorderStyle.Sizable; FormBorderStyle = FormBorderStyle.Sizable;
SetFormPosSize(); SetFormPositionAndSizeKeepHeight();
} }
} }
@@ -158,9 +258,26 @@ namespace mpvnet
if (mp.MpvWindowHandle != IntPtr.Zero) if (mp.MpvWindowHandle != IntPtr.Zero)
Native.SendMessage(mp.MpvWindowHandle, m.Msg, m.WParam, m.LParam); Native.SendMessage(mp.MpvWindowHandle, m.Msg, m.WParam, m.LParam);
break; break;
case 0x319: // WM_APPCOMMAND
if (mp.MpvWindowHandle != IntPtr.Zero)
Native.PostMessage(mp.MpvWindowHandle, m.Msg, m.WParam, m.LParam);
break;
case 0x0104: // WM_SYSKEYDOWN:
if (mp.MpvWindowHandle != IntPtr.Zero)
Native.SendMessage(mp.MpvWindowHandle, m.Msg, m.WParam, m.LParam);
break;
case 0x0105: // WM_SYSKEYUP:
if (mp.MpvWindowHandle != IntPtr.Zero)
Native.SendMessage(mp.MpvWindowHandle, m.Msg, m.WParam, m.LParam);
break;
case 0x203: // Native.WM.LBUTTONDBLCLK case 0x203: // Native.WM.LBUTTONDBLCLK
if (!IsMouseInOSC()) if (!IsMouseInOSC())
mp.CommandString("cycle fullscreen"); mp.command_string("cycle fullscreen");
break;
case 0x02E0: // WM_DPICHANGED
if (IgnoreDpiChanged) break;
var r2 = Marshal.PtrToStructure<Native.RECT>(m.LParam);
Native.SetWindowPos(Handle, IntPtr.Zero, r2.Left, r2.Top, r2.Width, r2.Height, 0);
break; break;
case 0x0214: // WM_SIZING case 0x0214: // WM_SIZING
var rc = Marshal.PtrToStructure<Native.RECT>(m.LParam); var rc = Marshal.PtrToStructure<Native.RECT>(m.LParam);
@@ -168,8 +285,8 @@ namespace mpvnet
NativeHelp.SubtractWindowBorders(Handle, ref r); NativeHelp.SubtractWindowBorders(Handle, ref r);
int c_w = r.Right - r.Left, c_h = r.Bottom - r.Top; int c_w = r.Right - r.Left, c_h = r.Bottom - r.Top;
float aspect = mp.VideoSize.Width / (float)mp.VideoSize.Height; float aspect = mp.VideoSize.Width / (float)mp.VideoSize.Height;
int d_w = (int)(c_h * aspect - c_w); int d_w = Convert.ToInt32(c_h * aspect - c_w);
int d_h = (int)(c_w / aspect - c_h); int d_h = Convert.ToInt32(c_w / aspect - c_h);
int[] d_corners = { d_w, d_h, -d_w, -d_h }; int[] d_corners = { d_w, d_h, -d_w, -d_h };
int[] corners = { rc.Left, rc.Top, rc.Right, rc.Bottom }; int[] corners = { rc.Left, rc.Top, rc.Right, rc.Bottom };
int corner = NativeHelp.GetResizeBorder(m.WParam.ToInt32()); int corner = NativeHelp.GetResizeBorder(m.WParam.ToInt32());
@@ -185,24 +302,6 @@ namespace mpvnet
base.WndProc(ref m); base.WndProc(ref m);
} }
void SetFormPosSize()
{
if (IsFullscreen || mp.VideoSize.Width == 0) return;
var wa = Screen.GetWorkingArea(this);
int h = (int)(wa.Height * 0.6);
int w = (int)(h * mp.VideoSize.Width / (float)mp.VideoSize.Height);
Point middlePos = new Point(Left + Width / 2, Top + Height / 2);
var r = new Native.RECT(new Rectangle(0, 0, w, h));
NativeHelp.AddWindowBorders(Handle, ref r);
int l = middlePos.X - r.Width / 2;
int t = middlePos.Y - r.Height / 2;
if (l < 0) l = 0;
if (t < 0) t = 0;
if (l + r.Width > wa.Width ) l = wa.Width - r.Width;
if (t + r.Height > wa.Height ) t = wa.Height - r.Height;
Native.SetWindowPos(Handle, IntPtr.Zero /* HWND_TOP */, l, t, r.Width, r.Height, 4 /* SWP_NOZORDER */);
}
protected override void OnDragEnter(DragEventArgs e) protected override void OnDragEnter(DragEventArgs e)
{ {
base.OnDragEnter(e); base.OnDragEnter(e);
@@ -223,7 +322,6 @@ namespace mpvnet
{ {
base.OnMouseDown(e); base.OnMouseDown(e);
// window-dragging
if (WindowState == FormWindowState.Normal && if (WindowState == FormWindowState.Normal &&
e.Button == MouseButtons.Left && e.Button == MouseButtons.Left &&
e.Y < ClientSize.Height * 0.9) e.Y < ClientSize.Height * 0.9)
@@ -238,15 +336,13 @@ namespace mpvnet
var p2 = PointToScreen(e.Location); var p2 = PointToScreen(e.Location);
if (Math.Abs(p1.X - p2.X) < 10 && Math.Abs(p1.Y - p2.Y) < 10) if (Math.Abs(p1.X - p2.X) < 10 && Math.Abs(p1.Y - p2.Y) < 10)
mp.Command("quit"); mp.commandv("quit");
} }
protected override void OnMouseMove(MouseEventArgs e) protected override void OnMouseMove(MouseEventArgs e)
{ {
base.OnMouseMove(e); base.OnMouseMove(e);
mp.command_string($"mouse {e.X} {e.Y}");
// send mouse command to make OSC show
mp.CommandString($"mouse {e.X} {e.Y}");
if (CursorHelp.IsPosDifferent(LastCursorPosChanged)) if (CursorHelp.IsPosDifferent(LastCursorPosChanged))
CursorHelp.Show(); CursorHelp.Show();
@@ -276,10 +372,11 @@ namespace mpvnet
{ {
base.OnLoad(e); base.OnLoad(e);
mp.Init(); mp.Init();
mp.ObserveBoolProp("fullscreen", mp_ChangeFullscreen); mp.observe_property_bool("fullscreen", mp_ChangeFullscreen);
mp.Shutdown += mp_Shutdown; mp.Shutdown += mp_Shutdown;
mp.VideoSizeChanged += mp_VideoSizeChanged; mp.VideoSizeChanged += mp_VideoSizeChanged;
mp.PlaybackRestart += mp_PlaybackRestart; mp.PlaybackRestart += mp_PlaybackRestart;
mp.Idle += Mp_Idle;
} }
protected override void OnShown(EventArgs e) protected override void OnShown(EventArgs e)
@@ -289,19 +386,14 @@ namespace mpvnet
CMS.Opened += CMS_Opened; CMS.Opened += CMS_Opened;
ContextMenuStrip = CMS; ContextMenuStrip = CMS;
BuildMenu(); BuildMenu();
IgnoreDpiChanged = false;
} }
protected override void OnFormClosed(FormClosedEventArgs e) protected override void OnFormClosed(FormClosedEventArgs e)
{ {
base.OnFormClosed(e); base.OnFormClosed(e);
IsClosed = true; mp.commandv("quit");
mp.Command("quit"); mp.AutoResetEvent.WaitOne(3000);
for (int i = 0; i < 99; i++)
{
if (mp.IsShutdownComplete) break;
Thread.Sleep(100);
}
} }
} }
} }

View File

@@ -1,4 +1,5 @@
using System.Collections; using System;
using System.Collections;
using System.Collections.Generic; using System.Collections.Generic;
using System.Runtime.InteropServices; using System.Runtime.InteropServices;
using System.Windows.Forms; using System.Windows.Forms;
@@ -43,4 +44,17 @@ namespace mpvnet
return MessageBox.Show(message, Application.ProductName, MessageBoxButtons.OKCancel, MessageBoxIcon.Question); return MessageBox.Show(message, Application.ProductName, MessageBoxButtons.OKCancel, MessageBoxIcon.Question);
} }
} }
//public class OSVersion
//{
// public static float Windows7 { get; set; } = 6.1f;
// public static float Windows8 { get; set; } = 6.2f;
// public static float Windows81 { get; set; } = 6.3f;
// public static float Windows10 { get; set; } = 10f;
// public static float Current
// {
// get => Environment.OSVersion.Version.Major + Environment.OSVersion.Version.Minor / 10f;
// }
//}
} }

View File

@@ -1,6 +1,8 @@
using System; using System;
using System.Drawing; using System.Drawing;
using System.IO;
using System.Runtime.InteropServices; using System.Runtime.InteropServices;
using System.Text;
namespace mpvnet namespace mpvnet
{ {
@@ -30,6 +32,9 @@ namespace mpvnet
[DllImport("user32.dll", SetLastError = true)] [DllImport("user32.dll", SetLastError = true)]
public static extern bool SetWindowPos(IntPtr hWnd, IntPtr hWndInsertAfter, int X, int Y, int cx, int cy, int uFlags); public static extern bool SetWindowPos(IntPtr hWnd, IntPtr hWndInsertAfter, int X, int Y, int cx, int cy, int uFlags);
[DllImport("Shlwapi.dll", SetLastError = true, CharSet = CharSet.Unicode)]
public static extern uint AssocQueryString(uint flags, uint str, string pszAssoc, string pszExtra, StringBuilder pszOut, ref uint pcchOut);
[StructLayout(LayoutKind.Sequential)] [StructLayout(LayoutKind.Sequential)]
public struct RECT public struct RECT
{ {

View File

@@ -1,4 +1,6 @@
using System; using System;
using System.IO;
using System.Text;
namespace mpvnet namespace mpvnet
{ {
@@ -34,5 +36,25 @@ namespace mpvnet
{ {
Native.AdjustWindowRect(ref rc, (uint)Native.GetWindowLongPtrW(hwnd, -16 /* GWL_STYLE */), false); Native.AdjustWindowRect(ref rc, (uint)Native.GetWindowLongPtrW(hwnd, -16 /* GWL_STYLE */), false);
} }
public static string GetAssociatedApplication(string ext)
{
uint returnValue = 0U;
// ASSOCF_VERIFY, ASSOCSTR_EXECUTABLE
if (1 == Native.AssocQueryString(0x40, 2, ext, null, null, ref returnValue))
{
if (returnValue > 0)
{
StringBuilder sb = new StringBuilder(Convert.ToInt32(returnValue));
// ASSOCF_VERIFY, ASSOCSTR_EXECUTABLE
if (0 == Native.AssocQueryString(0x40, 2, ext, null, sb, ref returnValue))
{
var ret = sb.ToString();
if (File.Exists(ret)) return ret;
}
}
}
return "";
}
} }
} }

View File

@@ -6,7 +6,7 @@ using System.Runtime.InteropServices;
// set of attributes. Change these attribute values to modify the information // set of attributes. Change these attribute values to modify the information
// associated with an assembly. // associated with an assembly.
[assembly: AssemblyTitle("mpv.net")] [assembly: AssemblyTitle("mpv.net")]
[assembly: AssemblyDescription("mpv/libmpv based player with pure mpv experience")] [assembly: AssemblyDescription("libmpv based player with pure mpv experience")]
[assembly: AssemblyConfiguration("")] [assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")] [assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("mpv.net")] [assembly: AssemblyProduct("mpv.net")]
@@ -32,5 +32,5 @@ using System.Runtime.InteropServices;
// You can specify all the values or you can default the Build and Revision Numbers // You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below: // by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")] // [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.3.0.0")] [assembly: AssemblyVersion("1.7.0.0")]
[assembly: AssemblyFileVersion("1.3.0.0")] [assembly: AssemblyFileVersion("1.7.0.0")]

View File

@@ -1,9 +1,10 @@
using System; using System;
using System.Reflection;
using IronPython.Hosting; using IronPython.Hosting;
using Microsoft.Scripting.Hosting; using Microsoft.Scripting.Hosting;
using static mpvnet.StaticUsing; using static mpvnet.StaticUsing;
using PyRT = IronPython.Runtime;
namespace mpvnet namespace mpvnet
{ {
@@ -30,4 +31,26 @@ namespace mpvnet
} }
} }
} }
public class PythonEventObject
{
public PyRT.PythonFunction PythonFunction { get; set; }
public EventInfo EventInfo { get; set; }
public Delegate Delegate { get; set; }
public void Invoke()
{
PyRT.Operations.PythonCalls.Call(PythonFunction);
}
public void InvokeEndFileEventMode(EndFileEventMode arg)
{
PyRT.Operations.PythonCalls.Call(PythonFunction, new[] { arg });
}
public void InvokeStrings(string[] arg)
{
PyRT.Operations.PythonCalls.Call(PythonFunction, new[] { arg });
}
}
} }

View File

@@ -29,16 +29,16 @@
Ctrl++ add video-zoom 0.1 #menu: Ctrl++ ; Pan && Scan > Increase Size Ctrl++ add video-zoom 0.1 #menu: Ctrl++ ; Pan && Scan > Increase Size
Ctrl+- add video-zoom -0.1 #menu: Ctrl+- ; Pan && Scan > Decrease Size Ctrl+- add video-zoom -0.1 #menu: Ctrl+- ; Pan && Scan > Decrease Size
_ ignore #menu: _ ; Pan && Scan > - _ ignore #menu: _ ; Pan && Scan > -
Shift+Left add video-pan-x -0.01 #menu: Shift+Left ; Pan && Scan > Move Left Ctrl+KP4 add video-pan-x -0.01 #menu: Ctrl+Numpad 4 ; Pan && Scan > Move Left
Shift+Right add video-pan-x 0.01 #menu: Shift+Right ; Pan && Scan > Move Right Ctrl+KP6 add video-pan-x 0.01 #menu: Ctrl+Numpad 6 ; Pan && Scan > Move Right
_ ignore #menu: _ ; Pan && Scan > - _ ignore #menu: _ ; Pan && Scan > -
Shift+Up add video-pan-y -0.01 #menu: Shift+Up ; Pan && Scan > Move Up Ctrl+KP8 add video-pan-y -0.01 #menu: Ctrl+Numpad 8 ; Pan && Scan > Move Up
Shift+Down add video-pan-y 0.01 #menu: Shift+Down ; Pan && Scan > Move Down Ctrl+KP2 add video-pan-y 0.01 #menu: Ctrl+Numpad 2 ; Pan && Scan > Move Down
_ ignore #menu: _ ; Pan && Scan > - _ ignore #menu: _ ; Pan && Scan > -
w add panscan -0.1 #menu: W ; Pan && Scan > Decrease Height w add panscan -0.1 #menu: W ; Pan && Scan > Decrease Height
W add panscan +0.1 #menu: Shift+W ; Pan && Scan > Increase Height W add panscan +0.1 #menu: Shift+W ; Pan && Scan > Increase Height
_ ignore #menu: _ ; Pan && Scan > - _ ignore #menu: _ ; Pan && Scan > -
Shift+BS set video-zoom 0 ; set video-pan-x 0 ; set video-pan-y 0 #menu: Shift+Backspace ; Pan && Scan > Reset Ctrl+BS set video-zoom 0 ; set video-pan-x 0 ; set video-pan-y 0 #menu: Ctrl+Backspace ; Pan && Scan > Reset
Ctrl+1 add contrast -1 #menu: Ctrl+1 ; Video > Decrease Contrast Ctrl+1 add contrast -1 #menu: Ctrl+1 ; Video > Decrease Contrast
Ctrl+2 add contrast 1 #menu: Ctrl+2 ; Video > Increase Contrast Ctrl+2 add contrast 1 #menu: Ctrl+2 ; Video > Increase Contrast
@@ -115,9 +115,10 @@
F8 show-text ${playlist} 5000 #menu: F8 ; Tools > Show Playlist F8 show-text ${playlist} 5000 #menu: F8 ; Tools > Show Playlist
F9 show-text ${track-list} 5000 #menu: F9 ; Tools > Show Audio/Video/Subtitle List F9 show-text ${track-list} 5000 #menu: F9 ; Tools > Show Audio/Video/Subtitle List
_ script-message mpv.net shell-execute https://mpv.io/manual/stable/ #menu: _ ; Tools > Web > Show mpv manual _ script-message mpv.net shell-execute https://mpv.io/manual/stable/ #menu: _ ; Help > Show mpv manual
_ script-message mpv.net shell-execute https://github.com/mpv-player/mpv/blob/master/etc/input.conf #menu: _ ; Tools > Web > Show mpv default keys _ script-message mpv.net shell-execute https://github.com/mpv-player/mpv/blob/master/etc/input.conf #menu: _ ; Help > Show mpv default keys
_ script-message mpv.net shell-execute https://github.com/stax76/mpvnet #menu: _ ; Tools > Web > Show mpv.net web site _ script-message mpv.net shell-execute https://github.com/stax76/mpv.net/blob/master/mpv.net/Resources/input.conf.txt #menu: _ ; Help > Show mpv.net default keys
_ script-message mpv.net shell-execute https://github.com/stax76/mpvnet #menu: _ ; Help > Show mpv.net web site
_ ignore #menu: _ ; - _ ignore #menu: _ ; -
Esc quit #menu: Escape ; Exit Esc quit #menu: Escape ; Exit
Q quit-watch-later #menu: Shift+Q ; Exit Watch Later Q quit-watch-later #menu: Shift+Q ; Exit Watch Later
@@ -135,5 +136,3 @@
VOLUME_UP add volume 2 VOLUME_UP add volume 2
VOLUME_DOWN add volume -2 VOLUME_DOWN add volume -2
MUTE cycle mute MUTE cycle mute
CLOSE_WIN quit
CLOSE_WIN {encode} quit 4

View File

@@ -25,7 +25,9 @@
</compatibility> </compatibility>
<application> <application>
<windowsSettings> <windowsSettings>
<longPathAware xmlns="http://schemas.microsoft.com/SMI/2016/WindowsSettings">true</longPathAware>
<dpiAware xmlns="http://schemas.microsoft.com/SMI/2005/WindowsSettings">true</dpiAware> <dpiAware xmlns="http://schemas.microsoft.com/SMI/2005/WindowsSettings">true</dpiAware>
<dpiAwareness xmlns="http://schemas.microsoft.com/SMI/2016/WindowsSettings">PerMonitorV2</dpiAwareness>
</windowsSettings> </windowsSettings>
</application> </application>
<dependency> <dependency>

View File

@@ -1,5 +1,6 @@
using System; using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.Diagnostics;
using System.Drawing; using System.Drawing;
using System.IO; using System.IO;
using System.Linq; using System.Linq;
@@ -61,28 +62,22 @@ namespace mpvnet
public static string InputConfPath = Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData) + "\\mpv\\input.conf"; public static string InputConfPath = Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData) + "\\mpv\\input.conf";
public static string mpvConfPath = Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData) + "\\mpv\\mpv.conf"; public static string mpvConfPath = Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData) + "\\mpv\\mpv.conf";
public static List<PythonScript> PythonScripts { get; } = new List<PythonScript>(); public static List<PythonScript> PythonScripts { get; } = new List<PythonScript>();
public static bool IsShutdownComplete { get; set; } public static AutoResetEvent AutoResetEvent = new AutoResetEvent(false);
private static Dictionary<string, string> _mpvConv; private static Dictionary<string, string> _mpvConf;
public static Dictionary<string, string> mpvConv { public static Dictionary<string, string> mpvConf {
get { get {
if (_mpvConv == null) if (_mpvConf == null)
{ {
_mpvConv = new Dictionary<string, string>(); _mpvConf = new Dictionary<string, string>();
if (File.Exists(mpvConfPath)) if (File.Exists(mpvConfPath))
{
foreach (var i in File.ReadAllLines(mpvConfPath)) foreach (var i in File.ReadAllLines(mpvConfPath))
{
if (i.Contains("=") && ! i.StartsWith("#")) if (i.Contains("=") && ! i.StartsWith("#"))
{ _mpvConf[i.Left("=").Trim()] = i.Right("=").Trim();
_mpvConv[i.Left("=").Trim()] = i.Right("=").Trim();
}
}
}
} }
return _mpvConv; return _mpvConf;
} }
} }
@@ -99,11 +94,12 @@ namespace mpvnet
LoadLibrary("mpv-1.dll"); LoadLibrary("mpv-1.dll");
MpvHandle = mpv_create(); MpvHandle = mpv_create();
SetStringProp("input-default-bindings", "yes"); set_property_string("input-default-bindings", "yes");
SetStringProp("osc", "yes"); set_property_string("osc", "yes");
SetStringProp("config", "yes"); set_property_string("config", "yes");
SetStringProp("wid", MainForm.Hwnd.ToString()); set_property_string("wid", MainForm.Hwnd.ToString());
SetStringProp("force-window", "yes"); set_property_string("force-window", "yes");
set_property_string("input-media-keys", "yes");
mpv_initialize(MpvHandle); mpv_initialize(MpvHandle);
ProcessCommandLine(); ProcessCommandLine();
Task.Run(() => { LoadScripts(); }); Task.Run(() => { LoadScripts(); });
@@ -118,7 +114,7 @@ namespace mpvnet
foreach (var scriptPath in startupScripts) foreach (var scriptPath in startupScripts)
if (jsLua.Contains(Path.GetExtension(scriptPath).ToLower())) if (jsLua.Contains(Path.GetExtension(scriptPath).ToLower()))
mp.Command("load-script", $"{scriptPath}"); mp.commandv("load-script", $"{scriptPath}");
foreach (var scriptPath in startupScripts) foreach (var scriptPath in startupScripts)
if (Path.GetExtension(scriptPath) == ".py") if (Path.GetExtension(scriptPath) == ".py")
@@ -147,11 +143,13 @@ namespace mpvnet
if (MpvWindowHandle == IntPtr.Zero) if (MpvWindowHandle == IntPtr.Zero)
MpvWindowHandle = FindWindowEx(MainForm.Hwnd, IntPtr.Zero, "mpv", null); MpvWindowHandle = FindWindowEx(MainForm.Hwnd, IntPtr.Zero, "mpv", null);
//Debug.WriteLine(evt.event_id.ToString());
switch (evt.event_id) switch (evt.event_id)
{ {
case mpv_event_id.MPV_EVENT_SHUTDOWN: case mpv_event_id.MPV_EVENT_SHUTDOWN:
Shutdown?.Invoke(); Shutdown?.Invoke();
IsShutdownComplete = true; AutoResetEvent.Set();
return; return;
case mpv_event_id.MPV_EVENT_LOG_MESSAGE: case mpv_event_id.MPV_EVENT_LOG_MESSAGE:
LogMessage?.Invoke(); LogMessage?.Invoke();
@@ -239,7 +237,7 @@ namespace mpvnet
break; break;
case mpv_event_id.MPV_EVENT_PLAYBACK_RESTART: case mpv_event_id.MPV_EVENT_PLAYBACK_RESTART:
PlaybackRestart?.Invoke(); PlaybackRestart?.Invoke();
Size s = new Size(GetIntProp("dwidth", false), GetIntProp("dheight", false)); Size s = new Size(get_property_int("dwidth"), get_property_int("dheight"));
if (VideoSize != s && s != Size.Empty) if (VideoSize != s && s != Size.Empty)
{ {
@@ -260,28 +258,6 @@ namespace mpvnet
} }
} }
public class PythonEventObject
{
public PyRT.PythonFunction PythonFunction { get; set; }
public EventInfo EventInfo { get; set; }
public Delegate Delegate { get; set; }
public void Invoke()
{
PyRT.Operations.PythonCalls.Call(PythonFunction);
}
public void InvokeEndFileEventMode(EndFileEventMode arg)
{
PyRT.Operations.PythonCalls.Call(PythonFunction, new[] { arg });
}
public void InvokeStrings(string[] arg)
{
PyRT.Operations.PythonCalls.Call(PythonFunction, new[] { arg });
}
}
private static List<PythonEventObject> PythonEventObjects = new List<PythonEventObject>(); private static List<PythonEventObject> PythonEventObjects = new List<PythonEventObject>();
public static void register_event(string name, PyRT.PythonFunction pyFunc) public static void register_event(string name, PyRT.PythonFunction pyFunc)
@@ -327,11 +303,6 @@ namespace mpvnet
} }
public static void commandv(params string[] args) public static void commandv(params string[] args)
{
Command(args);
}
public static void Command(params string[] args)
{ {
if (MpvHandle == IntPtr.Zero) if (MpvHandle == IntPtr.Zero)
return; return;
@@ -349,7 +320,7 @@ namespace mpvnet
Marshal.FreeHGlobal(mainPtr); Marshal.FreeHGlobal(mainPtr);
} }
public static void CommandString(string command, bool throwException = true) public static void command_string(string command, bool throwException = false)
{ {
if (MpvHandle == IntPtr.Zero) if (MpvHandle == IntPtr.Zero)
return; return;
@@ -360,21 +331,21 @@ namespace mpvnet
throw new Exception($"{(mpv_error)err}\r\n\r\n" + command); throw new Exception($"{(mpv_error)err}\r\n\r\n" + command);
} }
public static void SetStringProp(string name, string value, bool throwException = true) public static void set_property_string(string name, string value, bool throwOnException = false)
{ {
var bytes = GetUtf8Bytes(value); var bytes = GetUtf8Bytes(value);
int err = mpv_set_property(MpvHandle, GetUtf8Bytes(name), mpv_format.MPV_FORMAT_STRING, ref bytes); int err = mpv_set_property(MpvHandle, GetUtf8Bytes(name), mpv_format.MPV_FORMAT_STRING, ref bytes);
if (err < 0 && throwException) if (err < 0 && throwOnException)
throw new Exception($"{name}: {(mpv_error)err}"); throw new Exception($"{name}: {(mpv_error)err}");
} }
public static string GetStringProp(string name) public static string get_property_string(string name, bool throwOnException = false)
{ {
var lpBuffer = IntPtr.Zero; var lpBuffer = IntPtr.Zero;
int err = mpv_get_property(MpvHandle, GetUtf8Bytes(name), mpv_format.MPV_FORMAT_STRING, ref lpBuffer); int err = mpv_get_property(MpvHandle, GetUtf8Bytes(name), mpv_format.MPV_FORMAT_STRING, ref lpBuffer);
if (err < 0) if (err < 0 && throwOnException)
throw new Exception($"{name}: {(mpv_error)err}"); throw new Exception($"{name}: {(mpv_error)err}");
var ret = StringFromNativeUtf8(lpBuffer); var ret = StringFromNativeUtf8(lpBuffer);
@@ -383,43 +354,49 @@ namespace mpvnet
return ret; return ret;
} }
public static int GetIntProp(string name, bool throwException = true) public static int get_property_int(string name, bool throwOnException = false)
{ {
var lpBuffer = IntPtr.Zero; var lpBuffer = IntPtr.Zero;
int err = mpv_get_property(MpvHandle, GetUtf8Bytes(name), mpv_format.MPV_FORMAT_INT64, ref lpBuffer); int err = mpv_get_property(MpvHandle, GetUtf8Bytes(name), mpv_format.MPV_FORMAT_INT64, ref lpBuffer);
if (err < 0 && throwException) if (err < 0 && throwOnException)
throw new Exception($"{name}: {(mpv_error)err}"); throw new Exception($"{name}: {(mpv_error)err}");
else else
return lpBuffer.ToInt32(); return lpBuffer.ToInt32();
} }
public static double get_property_number(string name) public static double get_property_number(string name, bool throwOnException = false)
{
return GetDoubleProp(name);
}
public static double GetDoubleProp(string name, bool throwException = true)
{ {
double val = 0; double val = 0;
int err = mpv_get_property(MpvHandle, GetUtf8Bytes(name), mpv_format.MPV_FORMAT_DOUBLE, ref val); int err = mpv_get_property(MpvHandle, GetUtf8Bytes(name), mpv_format.MPV_FORMAT_DOUBLE, ref val);
if (err < 0 && throwException) if (err < 0 && throwOnException)
throw new Exception($"{name}: {(mpv_error)err}"); throw new Exception($"{name}: {(mpv_error)err}");
else else
return val; return val;
} }
public static void SetIntProp(string name, int value) public static bool get_property_bool(string name, bool throwOnException = false)
{
var lpBuffer = IntPtr.Zero;
int err = mpv_get_property(MpvHandle, GetUtf8Bytes(name), mpv_format.MPV_FORMAT_FLAG, ref lpBuffer);
if (err < 0 && throwOnException)
throw new Exception($"{name}: {(mpv_error)err}");
else
return lpBuffer.ToInt32() == 1;
}
public static void set_property_int(string name, int value, bool throwOnException = false)
{ {
Int64 val = value; Int64 val = value;
int err = mpv_set_property(MpvHandle, GetUtf8Bytes(name), mpv_format.MPV_FORMAT_INT64, ref val); int err = mpv_set_property(MpvHandle, GetUtf8Bytes(name), mpv_format.MPV_FORMAT_INT64, ref val);
if (err < 0) if (err < 0 && throwOnException)
throw new Exception($"{name}: {(mpv_error)err}"); throw new Exception($"{name}: {(mpv_error)err}");
} }
public static void ObserveBoolProp(string name, Action<bool> action) public static void observe_property_bool(string name, Action<bool> action)
{ {
int err = mpv_observe_property(MpvHandle, (ulong)action.GetHashCode(), name, mpv_format.MPV_FORMAT_FLAG); int err = mpv_observe_property(MpvHandle, (ulong)action.GetHashCode(), name, mpv_format.MPV_FORMAT_FLAG);
@@ -429,7 +406,7 @@ namespace mpvnet
BoolPropChangeActions.Add(new KeyValuePair<string, Action<bool>>(name, action)); BoolPropChangeActions.Add(new KeyValuePair<string, Action<bool>>(name, action));
} }
public static void UnobserveBoolProp(string name, Action<bool> action) public static void unobserve_property_bool(string name, Action<bool> action)
{ {
foreach (var i in BoolPropChangeActions.ToArray()) foreach (var i in BoolPropChangeActions.ToArray())
if (i.Value == action) if (i.Value == action)
@@ -441,15 +418,15 @@ namespace mpvnet
throw new Exception($"{name}: {(mpv_error)err}"); throw new Exception($"{name}: {(mpv_error)err}");
} }
public static void ProcessCommandLine() protected static void ProcessCommandLine()
{ {
var args = Environment.GetCommandLineArgs().Skip(1); var args = Environment.GetCommandLineArgs().Skip(1);
foreach (string i in args) foreach (string i in args)
if (!i.StartsWith("--") && File.Exists(i)) if (!i.StartsWith("--") && File.Exists(i))
mp.Command("loadfile", i, "append"); mp.commandv("loadfile", i, "append");
mp.SetStringProp("playlist-pos", "0", false); mp.set_property_string("playlist-pos", "0");
foreach (string i in args) foreach (string i in args)
{ {
@@ -459,25 +436,25 @@ namespace mpvnet
{ {
string left = i.Substring(2, i.IndexOf("=") - 2); string left = i.Substring(2, i.IndexOf("=") - 2);
string right = i.Substring(left.Length + 3); string right = i.Substring(left.Length + 3);
mp.SetStringProp(left, right); mp.set_property_string(left, right);
} }
else else
mp.SetStringProp(i.Substring(2), "yes"); mp.set_property_string(i.Substring(2), "yes");
} }
} }
} }
public static void LoadFiles(string[] files) public static void LoadFiles(string[] files)
{ {
int count = mp.GetIntProp("playlist-count"); int count = mp.get_property_int("playlist-count");
foreach (string file in files) foreach (string file in files)
mp.Command("loadfile", file, "append"); mp.commandv("loadfile", file, "append");
mp.SetIntProp("playlist-pos", count); mp.set_property_int("playlist-pos", count);
for (int i = 0; i < count; i++) for (int i = 0; i < count; i++)
mp.Command("playlist-remove", "0"); mp.commandv("playlist-remove", "0");
mp.LoadFolder(); mp.LoadFolder();
} }
@@ -489,10 +466,10 @@ namespace mpvnet
if (WasFolderLoaded) if (WasFolderLoaded)
return; return;
if (GetIntProp("playlist-count") == 1) if (get_property_int("playlist-count") == 1)
{ {
string[] types = "264 265 3gp aac ac3 avc avi avs bmp divx dts dtshd dtshr dtsma eac3 evo flac flv h264 h265 hevc hvc jpg jpeg m2t m2ts m2v m4a m4v mka mkv mlp mov mp2 mp3 mp4 mpa mpeg mpg mpv mts ogg ogm opus pcm png pva raw rmvb thd thd+ac3 true-hd truehd ts vdr vob vpy w64 wav webm wmv y4m".Split(' '); string[] types = "264 265 3gp aac ac3 avc avi avs bmp divx dts dtshd dtshr dtsma eac3 evo flac flv h264 h265 hevc hvc jpg jpeg m2t m2ts m2v m4a m4v mka mkv mlp mov mp2 mp3 mp4 mpa mpeg mpg mpv mts ogg ogm opus pcm png pva raw rmvb thd thd+ac3 true-hd truehd ts vdr vob vpy w64 wav webm wmv y4m".Split(' ');
string path = GetStringProp("path"); string path = get_property_string("path");
List<string> files = Directory.GetFiles(Path.GetDirectoryName(path)).ToList(); List<string> files = Directory.GetFiles(Path.GetDirectoryName(path)).ToList();
files = files.Where((file) => types.Contains(file.Ext())).ToList(); files = files.Where((file) => types.Contains(file.Ext())).ToList();
files.Sort(new StringLogicalComparer()); files.Sort(new StringLogicalComparer());
@@ -500,10 +477,10 @@ namespace mpvnet
files.Remove(path); files.Remove(path);
foreach (string i in files) foreach (string i in files)
Command("loadfile", i, "append"); commandv("loadfile", i, "append");
if (index > 0) if (index > 0)
Command("playlist-move", "0", (index + 1).ToString()); commandv("playlist-move", "0", (index + 1).ToString());
} }
WasFolderLoaded = true; WasFolderLoaded = true;