109 lines
5.8 KiB
C#
109 lines
5.8 KiB
C#
#if WINDOWS
|
|
using System.Security.Cryptography;
|
|
using System.Text.Json;
|
|
using Windows.Media.Control;
|
|
|
|
namespace PlotDirector.Companion.Agent;
|
|
|
|
internal sealed record NativeMediaSource(string Key, string Application, string Title, string Artist,
|
|
string State, double? Position, double? Duration, double Rate, string[] Operations);
|
|
|
|
internal sealed class WindowsMediaControl
|
|
{
|
|
private GlobalSystemMediaTransportControlsSessionManager? manager;
|
|
|
|
private async Task<GlobalSystemMediaTransportControlsSessionManager> Manager(CancellationToken cancellation)
|
|
{
|
|
if (!OperatingSystem.IsWindowsVersionAtLeast(10, 0, 17763))
|
|
throw new PlatformNotSupportedException("Windows media sessions require Windows 10 version 1809 or later.");
|
|
return manager ??= await GlobalSystemMediaTransportControlsSessionManager.RequestAsync().AsTask(cancellation);
|
|
}
|
|
|
|
public async Task<IReadOnlyList<NativeMediaSource>> Discover(CancellationToken cancellation)
|
|
{
|
|
using var timeout = CancellationTokenSource.CreateLinkedTokenSource(cancellation);
|
|
timeout.CancelAfter(TimeSpan.FromSeconds(2));
|
|
var sources = new List<NativeMediaSource>();
|
|
foreach (var session in (await Manager(timeout.Token)).GetSessions())
|
|
{
|
|
timeout.Token.ThrowIfCancellationRequested();
|
|
try
|
|
{
|
|
if (await Observe(session, timeout.Token) is { } source)
|
|
sources.Add(source);
|
|
}
|
|
catch (System.Runtime.InteropServices.COMException)
|
|
{
|
|
// A player may disappear while Windows enumerates sessions.
|
|
}
|
|
}
|
|
return sources.GroupBy(source => source.Key).Where(group => group.Count() == 1)
|
|
.Select(group => group.Single()).ToArray();
|
|
}
|
|
|
|
public async Task<bool> Execute(string key, string operation, DateTime expiresUtc, CancellationToken cancellation)
|
|
{
|
|
using var timeout = CancellationTokenSource.CreateLinkedTokenSource(cancellation);
|
|
timeout.CancelAfter(TimeSpan.FromSeconds(2));
|
|
var token = timeout.Token;
|
|
var current = await Manager(token);
|
|
GlobalSystemMediaTransportControlsSession? selected = null;
|
|
foreach (var session in current.GetSessions())
|
|
{
|
|
if ((await Observe(session, token))?.Key != key) continue;
|
|
if (selected != null) return false;
|
|
selected = session;
|
|
}
|
|
if (selected == null || !current.GetSessions().Contains(selected)) return false;
|
|
var source = await Observe(selected, token);
|
|
if (source?.Key != key || !source.Operations.Contains(operation) ||
|
|
!current.GetSessions().Contains(selected) || DateTime.UtcNow >= expiresUtc) return false;
|
|
token.ThrowIfCancellationRequested();
|
|
if (operation == "play") return await selected.TryPlayAsync().AsTask(token);
|
|
if (operation == "pause") return await selected.TryPauseAsync().AsTask(token);
|
|
var timeline = selected.GetTimelineProperties();
|
|
if (timeline.MaxSeekTime <= timeline.MinSeekTime || source.Position is not double position) return false;
|
|
var offset = operation == "back15" ? -15 : 15;
|
|
var target = Math.Clamp(timeline.StartTime.Ticks + TimeSpan.FromSeconds(position + offset).Ticks,
|
|
timeline.MinSeekTime.Ticks, timeline.MaxSeekTime.Ticks);
|
|
return await selected.TryChangePlaybackPositionAsync(target).AsTask(token);
|
|
}
|
|
|
|
private static async Task<NativeMediaSource?> Observe(GlobalSystemMediaTransportControlsSession session,
|
|
CancellationToken cancellation)
|
|
{
|
|
var metadata = await session.TryGetMediaPropertiesAsync().AsTask(cancellation);
|
|
var application = session.SourceAppUserModelId;
|
|
if (string.IsNullOrWhiteSpace(application) || string.IsNullOrWhiteSpace(metadata?.Title)) return null;
|
|
// GSMTC exposes application and metadata identity. It does not expose a Chrome tab ID.
|
|
var key = Convert.ToHexString(SHA256.HashData(JsonSerializer.SerializeToUtf8Bytes(
|
|
new[] { application, metadata.Title, metadata.Artist, metadata.AlbumTitle, metadata.Subtitle })));
|
|
var playback = session.GetPlaybackInfo();
|
|
var timeline = session.GetTimelineProperties();
|
|
var state = playback?.PlaybackStatus switch
|
|
{
|
|
GlobalSystemMediaTransportControlsSessionPlaybackStatus.Playing => "playing",
|
|
GlobalSystemMediaTransportControlsSessionPlaybackStatus.Paused => "paused",
|
|
GlobalSystemMediaTransportControlsSessionPlaybackStatus.Stopped => "stopped",
|
|
_ => "unavailable"
|
|
};
|
|
var rate = playback?.PlaybackRate ?? 1;
|
|
var duration = (timeline.EndTime - timeline.StartTime).TotalSeconds;
|
|
var position = (timeline.Position - timeline.StartTime).TotalSeconds;
|
|
if (state == "playing" && timeline.LastUpdatedTime != default)
|
|
position += Math.Max(0, (DateTimeOffset.UtcNow - timeline.LastUpdatedTime).TotalSeconds) * rate;
|
|
var hasTimeline = duration is > 0 and <= 86400 && timeline.LastUpdatedTime != default &&
|
|
(timeline.Position - timeline.StartTime).TotalSeconds >= 0 && double.IsFinite(position);
|
|
var operations = new List<string>(4);
|
|
var controls = playback?.Controls;
|
|
if (controls?.IsPlayEnabled == true) operations.Add("play");
|
|
if (controls?.IsPauseEnabled == true) operations.Add("pause");
|
|
if (controls?.IsPlaybackPositionEnabled == true && hasTimeline && timeline.MaxSeekTime > timeline.MinSeekTime)
|
|
operations.AddRange(["back15", "forward15"]);
|
|
return new(key, application, metadata.Title, metadata.Artist, state, hasTimeline ? Math.Clamp(position, 0, duration) : null,
|
|
hasTimeline ? duration : null, double.IsFinite(rate) && rate is >= 0.25 and <= 4 ? rate : 1,
|
|
state == "unavailable" ? [] : operations.ToArray());
|
|
}
|
|
}
|
|
#endif
|