Voice-to-text dictation app with local (Nvidia Parakeet/Whisper) and cloud models (BYOK). Privacy-first and available cross-platform.
JavaScript aianthropiccross-platformgeminigroqlinuxmacosnvidiaopen-sourceopenaiparakeetspeech-to-texttranscribewhisperwindows
fix(media): pause/resume on macOS 15.4+ via vendored mediaremote-adapter (#806)
St John Grimblyf94079978fed
diff --git a/electron-builder.json b/electron-builder.jsonindex e6228d136..15c3e40bb 100644--- a/electron-builder.json+++ b/electron-builder.json@@ -112,6 +112,7 @@"macos-mic-listener","macos-text-monitor","macos-media-remote",+ "MediaRemoteAdapter.framework/**","linux-fast-paste","linux-system-audio-helper","linux-text-monitor",@@ -129,6 +130,14 @@"*.dll","*.so*"]+ },+ {+ "from": "resources/mediaremote-adapter/bin/mediaremote-adapter.pl",+ "to": "bin/mediaremote-adapter.pl"+ },+ {+ "from": "resources/mediaremote-adapter/LICENSE",+ "to": "bin/mediaremote-adapter.LICENSE"}],"mac": {diff --git a/package.json b/package.jsonindex 9ac51521b..2394c0ec1 100644--- a/package.json+++ b/package.json@@ -17,9 +17,10 @@"compile:linux-paste": "node scripts/build-linux-fast-paste.js","compile:linux-system-audio": "node scripts/build-linux-system-audio.js","compile:media-remote": "node scripts/build-media-remote.js",+ "compile:mediaremote-adapter": "node scripts/build-mediaremote-adapter.js","compile:mic-listener": "node scripts/build-macos-mic-listener.js","compile:audio-tap": "node scripts/build-macos-audio-tap.js",- "compile:native": "npm run compile:globe && npm run compile:fast-paste && npm run compile:winkeys && npm run compile:linuxkeys && npm run compile:winpaste && npm run compile:linux-paste && npm run compile:linux-system-audio && npm run compile:text-monitor && npm run compile:media-remote && npm run compile:mic-listener && npm run compile:audio-tap",+ "compile:native": "npm run compile:globe && npm run compile:fast-paste && npm run compile:winkeys && npm run compile:linuxkeys && npm run compile:winpaste && npm run compile:linux-paste && npm run compile:linux-system-audio && npm run compile:text-monitor && npm run compile:media-remote && npm run compile:mediaremote-adapter && npm run compile:mic-listener && npm run compile:audio-tap","prestart": "npm run compile:native && npm run download:meeting-aec-helper && npm run download:sherpa-onnx && npm run download:yt-dlp && npm run download:qdrant && npm run download:embedding-model && npm run download:whisper-vad-model","start": "electron .","predev": "npm run compile:native && npm run download:meeting-aec-helper && npm run download:sherpa-onnx && npm run download:yt-dlp && npm run download:qdrant && npm run download:embedding-model && npm run download:whisper-vad-model",diff --git a/resources/macos-media-remote.swift b/resources/macos-media-remote.swiftindex 6a698a84f..576db7888 100644--- a/resources/macos-media-remote.swift+++ b/resources/macos-media-remote.swift@@ -1,98 +1,54 @@-import CoreFoundation+import AppKitimport Foundation-let kMRPlay: UInt32 = 0-let kMRPause: UInt32 = 1-let usage = "Usage: macos-media-remote --is-playing|--pause|--play"-let playbackRateKey = "kMRMediaRemoteNowPlayingInfoPlaybackRate"+// Posts a media play/pause NSEvent (NSEventSubtypeMediaKey / NX_KEYTYPE_PLAY),+// the only event class media apps (Spotify, Music, browser tabs) listen for —+// synthetic F-key codes are not media keys.+//+// State-aware pause/resume is handled by the vendored mediaremote-adapter+// loaded through /usr/bin/perl; this helper is the fallback when the adapter+// is unavailable.-typealias MRSendCommand = @convention(c) (UInt32, Optional<AnyObject>) -> Bool-typealias MRRegister = @convention(c) (DispatchQueue) -> Void-// The get-callback is an Objective-C block, not a C function pointer;-// @convention(c) here would silently misroute the callback.-typealias MRGetInfo = @convention(c) (- DispatchQueue, @escaping @convention(block) ([AnyHashable: Any]?) -> Void-) -> Void--struct MediaRemote {- let send: MRSendCommand- let register: MRRegister?- let getInfo: MRGetInfo-}--func loadMediaRemote() -> MediaRemote? {- let url = URL(fileURLWithPath: "/System/Library/PrivateFrameworks/MediaRemote.framework")- guard let bundle = CFBundleCreate(kCFAllocatorDefault, url as CFURL),- let sendPtr = CFBundleGetFunctionPointerForName(bundle, "MRMediaRemoteSendCommand" as CFString),- let infoPtr = CFBundleGetFunctionPointerForName(bundle, "MRMediaRemoteGetNowPlayingInfo" as CFString) else {- return nil- }- let regPtr = CFBundleGetFunctionPointerForName(- bundle, "MRMediaRemoteRegisterForNowPlayingNotifications" as CFString)- return MediaRemote(- send: unsafeBitCast(sendPtr, to: MRSendCommand.self),- register: regPtr.map { unsafeBitCast($0, to: MRRegister.self) },- getInfo: unsafeBitCast(infoPtr, to: MRGetInfo.self)- )-}--func emit(_ message: String, exitCode: Int32) -> Never {- print(message)- exit(exitCode)-}+let usage = "Usage: macos-media-remote --media-key-toggle"let args = CommandLine.argumentslet command = args.count > 1 ? args[1] : ""-switch command {-case "--play", "--is-playing", "--pause":- break-default:- emit(usage, exitCode: 1)-}--// macOS 15.4 closed the now-playing daemon to unprivileged Mach-O processes;-// both reads and sends silently no-op. Emit UNKNOWN so the consumer falls-// back to its media-key path.-let v = ProcessInfo.processInfo.operatingSystemVersion-if v.majorVersion > 15 || (v.majorVersion == 15 && v.minorVersion >= 4) {- emit("UNKNOWN", exitCode: 1)-}--guard let mr = loadMediaRemote() else {- emit("ERROR", exitCode: 1)-}--// macOS 13+ requires this before any subsequent get-callback fires.-mr.register?(DispatchQueue.main)--if command == "--play" {- let ok = mr.send(kMRPlay, nil)- emit(ok ? "OK" : "FAIL", exitCode: ok ? 0 : 1)-}--DispatchQueue.main.asyncAfter(deadline: .now() + 2) {- emit("NOT_PLAYING", exitCode: 1)+guard command == "--media-key-toggle" else {+ print(usage)+ exit(1)+}++let NSEventSubtypeMediaKey: Int16 = 8+let NX_KEYTYPE_PLAY: Int32 = 16++func postMediaKey(keyDown: Bool) -> Bool {+ let flags: UInt = keyDown ? 0xA00 : 0xB00+ let state: Int32 = keyDown ? 0xA : 0xB+ let data1 = (NX_KEYTYPE_PLAY << 16) | (state << 8)++ guard let event = NSEvent.otherEvent(+ with: .systemDefined,+ location: .zero,+ modifierFlags: NSEvent.ModifierFlags(rawValue: flags),+ timestamp: 0,+ windowNumber: 0,+ context: nil,+ subtype: NSEventSubtypeMediaKey,+ data1: Int(data1),+ data2: -1+ ) else {+ return false+ }+ guard let cgEvent = event.cgEvent else { return false }+ cgEvent.post(tap: .cghidEventTap)+ return true}-DispatchQueue.main.asyncAfter(deadline: .now() + 0.1) {- mr.getInfo(DispatchQueue.main) { info in- guard let info = info, !info.isEmpty else {- emit("NOT_PLAYING", exitCode: 1)- }- let rate = (info[playbackRateKey] as? NSNumber)?.doubleValue ?? 0- let playing = rate > 0- switch command {- case "--is-playing":- emit(playing ? "PLAYING" : "NOT_PLAYING", exitCode: playing ? 0 : 1)- case "--pause":- if !playing { emit("NOT_PLAYING", exitCode: 1) }- let ok = mr.send(kMRPause, nil)- emit(ok ? "OK" : "FAIL", exitCode: ok ? 0 : 1)- default:- emit(usage, exitCode: 1)- }- }+guard postMediaKey(keyDown: true), postMediaKey(keyDown: false) else {+ print("FAIL")+ exit(1)}-CFRunLoopRun()+print("OK")+exit(0)diff --git a/resources/mediaremote-adapter/LICENSE b/resources/mediaremote-adapter/LICENSEnew file mode 100644index 000000000..e70a4bdf3--- /dev/null+++ b/resources/mediaremote-adapter/LICENSE@@ -0,0 +1,28 @@+BSD 3-Clause License++Copyright (c) 2025, Jonas van den Berg and contributors++Redistribution and use in source and binary forms, with or without+modification, are permitted provided that the following conditions are met:++1. Redistributions of source code must retain the above copyright notice, this+ list of conditions and the following disclaimer.++2. Redistributions in binary form must reproduce the above copyright notice,+ this list of conditions and the following disclaimer in the documentation+ and/or other materials provided with the distribution.++3. Neither the name of the copyright holder nor the names of its+ contributors may be used to endorse or promote products derived from+ this software without specific prior written permission.++THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"+AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE+IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE+DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE+FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL+DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR+SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER+CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,+OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE+OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\ No newline at end of filediff --git a/resources/mediaremote-adapter/VERSION b/resources/mediaremote-adapter/VERSIONnew file mode 100644index 000000000..378c127dd--- /dev/null+++ b/resources/mediaremote-adapter/VERSION@@ -0,0 +1 @@+v0.7.6diff --git a/resources/mediaremote-adapter/bin/mediaremote-adapter.pl b/resources/mediaremote-adapter/bin/mediaremote-adapter.plnew file mode 100755index 000000000..f4c794b16--- /dev/null+++ b/resources/mediaremote-adapter/bin/mediaremote-adapter.pl@@ -0,0 +1,280 @@+#!/usr/bin/perl+# Copyright (c) 2025 Jonas van den Berg+# This file is licensed under the BSD 3-Clause License.++# For usage information read below or run the script without arguments.++use strict;+use warnings;+use DynaLoader;+use File::Spec;+use File::Basename;++sub print_help() {+ print <<'HELP';+Usage:+ mediaremote-adapter.pl FRAMEWORK_PATH [TEST_CLIENT_PATH]+ [FUNCTION [PARAMS|OPTIONS...]]++FRAMEWORK_PATH:+ Absolute path to the MediaRemoteAdapter.framework directory++TEST_CLIENT_PATH: (optional)+ Absolute path to the MediaRemoteAdapterTestClient executable. Only for "test"++FUNCTION:+ stream Streams now playing information (as diff by default)+ get Prints now playing information once with all available metadata+ send Sends a command to the now playing application+ seek Seeks to a specific timeline position+ shuffle Sets the shuffle mode+ repeat Sets the repeat mode+ speed Sets the playback speed+ test Tests if the adapter is entitled to use the MediaRemote framework.+ An exit code other than 0 indicates the adapter is non-functional++PARAMS:+ send(command)+ command: The MRCommand ID as a number (e.g. kMRPlay = 0)+ seek(position)+ position: The timeline position in microseconds+ shuffle(mode)+ mode: The shuffle mode+ repeat(mode)+ mode: The repeat mode+ speed(speed)+ speed: The playback speed++OPTIONS:+ get+ --now: Adds an "elapsedTimeNow" key with an estimation of the current+ elapsed playback time. This estimation may be off by up to a second.+ To determine a more accurate time without polling "get" continuously,+ calculate it using the "elapsedTime" and "timestamp" keys. "elapsedTime"+ contains the elapsed time at the time that is stored in "timestamp".+ stream+ --no-diff: Disable diffing and always dump all metadata+ --debounce=N: Delay in milliseconds to prevent spam (0 by default)+ get, stream+ --micros: Replaces the following time keys with microsecond equivalents:+ "duration" -> "durationMicros"+ "elapsedTime" -> "elapsedTimeMicros"+ "elapsedTimeNow" -> "elapsedTimeNowMicros"+ "timestamp" -> "timestampEpochMicros" (converted to epoch time)+ --no-artwork: Omits "artworkData" and "artworkMimeType" from the payload.+ Useful for consumers that do not render artwork, since this avoids+ emitting several hundred kilobytes of base64 data per update.+ --human-readable, -h: Makes values human-readable. Use only for debugging.+ The JSON output is pretty-printed and the following keys are adapted:+ "artworkData" -> Binary data is truncated to a shorter representation++Examples (script name and framework path omitted):+ stream --no-diff --debounce=100+ send 2 # Toggles play/pause in the media player (kMRATogglePlayPause)+ repeat 3 # Sets the repeat mode to "playlist" (kMRARepeatModePlaylist)++HELP+ exit 0;+}++if (!defined $ARGV[1]) {+ print_help();+}++sub fail {+ my ($error) = @_;+ print STDERR "$error\n";+ exit 1;+}++fail "Framework path not provided" unless @ARGV >= 1;++my $framework_path = shift @ARGV;++# Optionally accept MEDIAREMOTEADAPTER_TEST_CLIENT_PATH path as second argument+my $maybe_helper_path = $ARGV[0] // '';+if ($maybe_helper_path =~ m{/}){+ my $helper_path = shift @ARGV;+ $ENV{MEDIAREMOTEADAPTER_TEST_CLIENT_PATH} = $helper_path;+}++if (!defined $ARGV[0]) {+ print_help();+}++my $framework_basename = File::Basename::basename($framework_path);+fail "Provided path is not a framework: $framework_path"+ unless $framework_basename =~ s/\.framework$//;++my $framework = File::Spec->catfile($framework_path, $framework_basename);+fail "Framework not found at $framework" unless -e $framework;++my $handle = DynaLoader::dl_load_file($framework, 0)+ or fail "Failed to load framework: $framework";+my $function_name = shift @ARGV or fail "Missing function name";+fail "Invalid function name: '$function_name'"+ unless $function_name eq "stream"+ || $function_name eq "get"+ || $function_name eq "send"+ || $function_name eq "seek"+ || $function_name eq "shuffle"+ || $function_name eq "repeat"+ || $function_name eq "speed"+ || $function_name eq "test";++sub parse_options {+ my ($start_index) = @_;+ my %arg_map;+ my $i = $start_index;+ while ($i <= $#ARGV) {+ my $arg = $ARGV[$i];+ if ($arg =~ /^--([a-z:\.\\-]+)(?:=(.*))?$/) {+ my $key = $1;+ my $value = defined $2 ? $2 : undef;+ $arg_map{$key} = $value;+ splice @ARGV, $i, 1;+ }+ elsif ($arg =~ /^-([a-zA-Z]+)$/) {+ my @flags = split //, $1;+ $arg_map{$_} = undef for @flags;+ splice @ARGV, $i, 1;+ }+ else {+ $i++;+ }+ }+ return \%arg_map;+}++sub env_func {+ my $symbol_name = shift;+ return "${symbol_name}_env";+}++sub set_env_param {+ my ($func, $index, $name, $value) = @_;+ $ENV{"MEDIAREMOTEADAPTER_PARAM_${func}_${index}_${name}"} = "$value";+}++sub set_env_option_unsafe {+ my ($name, $value) = @_;+ $name =~ s/-/_/g;+ $ENV{"MEDIAREMOTEADAPTER_OPTION_${name}"} = defined $value ? "$value" : "";+}++sub set_env_option {+ my ($options, $key) = @_;+ my $value = $options->{$key};+ if (defined $value) {+ fail "Unexpected value for option '$key'";+ }+ set_env_option_unsafe($key, $value);+}++sub set_env_option_value {+ my ($options, $key) = @_;+ my $value = $options->{$key};+ if (!defined $value) {+ fail "Missing value for option '$key'";+ }+ set_env_option_unsafe($key, $value);+}++my $symbol_name = "adapter_$function_name";+if ($function_name eq "send") {+ my $id = shift @ARGV;+ fail "Missing ID for '$function_name' command" unless defined $id;+ set_env_param($symbol_name, 0, "command", "$id");+ $symbol_name = env_func($symbol_name);+}+elsif ($function_name eq "stream") {+ my $options = parse_options(0);+ foreach my $key (keys %{$options}) {+ if ($key eq "no-diff") {+ set_env_option($options, $key);+ }+ elsif ($key eq "debounce") {+ set_env_option_value($options, $key);+ }+ elsif ($key eq "micros") {+ set_env_option($options, $key);+ }+ elsif ($key eq "no-artwork") {+ set_env_option($options, $key);+ }+ elsif ($key eq "human-readable" || $key eq "h") {+ set_env_option($options, "human-readable");+ }+ elsif ($key eq "experimental-peculiar-debounce:com.tidal.desktop") {+ set_env_option_value($options, $key);+ }+ else {+ fail "Unrecognized option '$key'";+ }+ }+ $symbol_name = env_func($symbol_name);+}+elsif ($function_name eq "get") {+ my $options = parse_options(0);+ foreach my $key (keys %{$options}) {+ if ($key eq "micros") {+ set_env_option($options, $key);+ }+ elsif ($key eq "no-artwork") {+ set_env_option($options, $key);+ }+ elsif ($key eq "human-readable" || $key eq "h") {+ set_env_option($options, "human-readable");+ }+ elsif ($key eq "now") {+ set_env_option($options, $key);+ }+ else {+ fail "Unrecognized option '$key'";+ }+ }+ $symbol_name = env_func($symbol_name);+}+elsif ($function_name eq "seek") {+ my $position = shift @ARGV;+ fail "Missing position for '$function_name' command" unless defined $position;+ set_env_param($symbol_name, 0, "position", "$position");+ $symbol_name = env_func($symbol_name);+}+elsif ($function_name eq "shuffle") {+ my $mode = shift @ARGV;+ fail "Missing mode for '$function_name' command" unless defined $mode;+ set_env_param($symbol_name, 0, "mode", "$mode");+ $symbol_name = env_func($symbol_name);+}+elsif ($function_name eq "repeat") {+ my $mode = shift @ARGV;+ fail "Missing mode for '$function_name' command" unless defined $mode;+ set_env_param($symbol_name, 0, "mode", "$mode");+ $symbol_name = env_func($symbol_name);+}+elsif ($function_name eq "speed") {+ my $speed = shift @ARGV;+ fail "Missing speed for '$function_name' command" unless defined $speed;+ set_env_param($symbol_name, 0, "speed", "$speed");+ $symbol_name = env_func($symbol_name);+}+elsif ($function_name eq "test") {+ $symbol_name = "adapter_test";+}++if (defined shift @ARGV) {+ fail "Too many arguments";+}++my $symbol = DynaLoader::dl_find_symbol($handle, "$symbol_name")+ or fail "Symbol '$symbol_name' not found in $framework";+DynaLoader::dl_install_xsub("main::$function_name", $symbol);++eval {+ no strict "refs";+ &{"main::$function_name"}();+};+if ($@) {+ fail "Error executing $function_name: $@";+}diff --git a/resources/mediaremote-adapter/include/MediaRemoteAdapter.h b/resources/mediaremote-adapter/include/MediaRemoteAdapter.hnew file mode 100644index 000000000..c90321c85--- /dev/null+++ b/resources/mediaremote-adapter/include/MediaRemoteAdapter.h@@ -0,0 +1,126 @@+// Copyright (c) 2025 Jonas van den Berg+// This file is licensed under the BSD 3-Clause License.++#ifndef MEDIAREMOTEADAPTER_ADAPTER_H+#define MEDIAREMOTEADAPTER_ADAPTER_H++#import <Foundation/Foundation.h>++// Methods suffixed with "_env" read its parameters from the environment.+// Parameters must have the format:+// MEDIAREMOTEADAPTER_<FUNC_NAME>_<PARAM_INDEX>_<PARAM_NAME>+// Example: MEDIAREMOTEADAPTER_adapter_send_0_command++extern NSString *kMRAProcessIdentifier;+extern NSString *kMRABundleIdentifier;+extern NSString *kMRAParentApplicationBundleIdentifier;+extern NSString *kMRAPlaying;++extern NSString *kMRADurationMicros;+extern NSString *kMRAElapsedTimeMicros;+extern NSString *kMRATimestampEpochMicros;++extern NSString *kMRAElapsedTimeNow;+extern NSString *kMRAElapsedTimeNowMicros;++extern NSString *kMRATitle;+extern NSString *kMRAArtist;+extern NSString *kMRAAlbum;+extern NSString *kMRADuration;+extern NSString *kMRAElapsedTime;+extern NSString *kMRATimestamp;+extern NSString *kMRAArtworkMimeType;+extern NSString *kMRAArtworkData;++extern NSString *kMRAChapterNumber;+extern NSString *kMRAComposer;+extern NSString *kMRAGenre;+extern NSString *kMRAIsAdvertisement;+extern NSString *kMRAIsBanned;+extern NSString *kMRAIsInWishList;+extern NSString *kMRAIsLiked;+extern NSString *kMRAIsMusicApp;+extern NSString *kMRAPlaybackRate;+extern NSString *kMRAProhibitsSkip;+extern NSString *kMRAQueueIndex;+extern NSString *kMRARadioStationIdentifier;+extern NSString *kMRARepeatMode;+extern NSString *kMRAShuffleMode;+extern NSString *kMRAStartTime;+extern NSString *kMRASupportsFastForward15Seconds;+extern NSString *kMRASupportsIsBanned;+extern NSString *kMRASupportsIsLiked;+extern NSString *kMRASupportsRewind15Seconds;+extern NSString *kMRATotalChapterCount;+extern NSString *kMRATotalDiscCount;+extern NSString *kMRATotalQueueCount;+extern NSString *kMRATotalTrackCount;+extern NSString *kMRATrackNumber;+extern NSString *kMRAUniqueIdentifier;+extern NSString *kMRAContentItemIdentifier;+extern NSString *kMRARadioStationHash;+extern NSString *kMRAMediaType;++// Prints the current MediaRemote now playing information to stdout.+// Data is encoded as a JSON dictionary or "null" when there is no information.+extern void adapter_get();+extern void adapter_get_env();++// Streams MediaRemote now playing updates to stdout.+// Each update is printed on a separate lined, encoded as a JSON dictionary.+// Exits when the process receives a SIGTERM signal.+extern void adapter_stream();+extern void adapter_stream_env();++typedef enum {+ kMRAPlay = 0,+ kMRAPause = 1,+ kMRATogglePlayPause = 2,+ kMRAStop = 3,+ kMRANextTrack = 4,+ kMRAPreviousTrack = 5,+ kMRAToggleShuffle = 6,+ kMRAToggleRepeat = 7,+ kMRAStartForwardSeek = 8,+ kMRAEndForwardSeek = 9,+ kMRAStartBackwardSeek = 10,+ kMRAEndBackwardSeek = 11,+ kMRAGoBackFifteenSeconds = 12,+ kMRASkipFifteenSeconds = 13,+} MRACommand;++// Sends the given MediaRemote command to the current now playing application.+extern void adapter_send(MRACommand command);+extern void adapter_send_env();++// Seeks the timeline of the nowplaying application to the given position.+// The position must be given in microseconds.+extern void adapter_seek(long position);+extern void adapter_seek_env();++typedef enum {+ kMRAShuffleDisabled = 1,+ kMRAShuffleAlbums = 2,+ kMRAShuffleTracks = 3,+} MRAShuffleMode;++extern void adapter_shuffle(MRAShuffleMode mode);+extern void adapter_shuffle_env();++typedef enum {+ kMRARepeatDisabled = 1,+ kMRARepeatTrack = 2,+ kMRARepeatPlaylist = 3,+} MRARepeatMode;++extern void adapter_repeat(MRARepeatMode mode);+extern void adapter_repeat_env();++extern void adapter_speed(int speed);+extern void adapter_speed_env();++// Tests whether the process is entitled to use the MediaRemote framework.+// Exits with exit code 0, if it is. Any other exit code means it is not.+extern void adapter_test();++#endif // MEDIAREMOTEADAPTER_ADAPTER_Hdiff --git a/resources/mediaremote-adapter/src/adapter/env.h b/resources/mediaremote-adapter/src/adapter/env.hnew file mode 100644index 000000000..721e8f8f9--- /dev/null+++ b/resources/mediaremote-adapter/src/adapter/env.h@@ -0,0 +1,25 @@+// Copyright (c) 2025 Jonas van den Berg+// This file is licensed under the BSD 3-Clause License.++#ifndef MEDIAREMOTEADAPTER_ADAPTER_ENV_H+#define MEDIAREMOTEADAPTER_ADAPTER_ENV_H++#import <Foundation/Foundation.h>++NSString *getEnvValue(NSString *name);++NSString *getEnvFuncParam(NSString *func_name, int param_pos,+ NSString *param_name);+NSString *getEnvFuncParamSafe(NSString *func_name, int param_pos,+ NSString *param_name);+NSNumber *getEnvFuncParamInt(NSString *func_name, int param_pos,+ NSString *param_name);+long getEnvFuncParamLongSafe(NSString *func_name, int param_pos,+ NSString *param_name);+int getEnvFuncParamIntSafe(NSString *func_name, int param_pos,+ NSString *param_name);++NSString *getEnvOption(NSString *option_name);+NSNumber *getEnvOptionInt(NSString *option_name);++#endif // MEDIAREMOTEADAPTER_ADAPTER_ENV_Hdiff --git a/resources/mediaremote-adapter/src/adapter/env.m b/resources/mediaremote-adapter/src/adapter/env.mnew file mode 100644index 000000000..581538151--- /dev/null+++ b/resources/mediaremote-adapter/src/adapter/env.m@@ -0,0 +1,105 @@+// Copyright (c) 2025 Jonas van den Berg+// This file is licensed under the BSD 3-Clause License.++#import "env.h"++#include <limits.h>++#import <Foundation/Foundation.h>++#import "utility/helpers.h"++static NSNumber *parseIntegerOrNil(NSString *str) {+ if (str == nil)+ return nil;+ NSScanner *scanner = [NSScanner scannerWithString:str];+ NSInteger value;+ if ([scanner scanInteger:&value] && [scanner isAtEnd]) {+ return @(value);+ } else {+ return nil;+ }+}++NSString *getEnvValue(NSString *name) {+ NSDictionary *env = [[NSProcessInfo processInfo] environment];+ return env[[name stringByReplacingOccurrencesOfString:@"-"+ withString:@"_"]];+}++NSString *getEnvFuncParam(NSString *func_name, int param_pos,+ NSString *param_name) {+ NSString *envVarName =+ [NSString stringWithFormat:@"MEDIAREMOTEADAPTER_PARAM_%@_%d_%@",+ func_name, param_pos, param_name];+ return getEnvValue(envVarName);+}++NSString *getEnvFuncParamSafe(NSString *func_name, int param_pos,+ NSString *param_name) {+ NSString *result = getEnvFuncParam(func_name, param_pos, param_name);+ if (result == nil) {+ failf(@"Missing parameter '%@' for "+ @"function '%@' at position %d",+ param_name, func_name, param_pos);+ }+ return result;+}++NSNumber *getEnvFuncParamInt(NSString *func_name, int param_pos,+ NSString *param_name) {+ return parseIntegerOrNil(getEnvFuncParam(func_name, param_pos, param_name));+}++long getEnvFuncParamLongSafe(NSString *func_name, int param_pos,+ NSString *param_name) {++ NSString *raw = getEnvFuncParam(func_name, param_pos, param_name);+ if (raw == nil) {+ failf(@"Missing parameter '%@' for "+ @"function '%@' at position %d",+ param_name, func_name, param_pos);+ }+ NSNumber *result = parseIntegerOrNil(raw);+ if (result == nil) {+ failf(@"Parameter '%@' for "+ @"function '%@' at position %d is not an integer: '%@'",+ param_name, func_name, param_pos, raw);+ }+ if ([result longLongValue] > [result longValue]) {+ failf(@"Parameter '%@' for "+ @"function '%@' at position %d is too large to fit into a "+ @"long integer: %@",+ param_name, func_name, param_pos, raw);+ }+ return [result longValue];+}++int getEnvFuncParamIntSafe(NSString *func_name, int param_pos,+ NSString *param_name) {++ long value = getEnvFuncParamLongSafe(func_name, param_pos, param_name);+ if (value > INT_MAX) {+ failf(@"Parameter '%@' for "+ @"function '%@' at position %d is too large to fit into an "+ @"integer: %ld",+ param_name, func_name, param_pos, value);+ }+ if (value < INT_MIN) {+ failf(@"Parameter '%@' for "+ @"function '%@' at position %d is too small to fit into an "+ @"integer: %ld",+ param_name, func_name, param_pos, value);+ }+ return (int)value;+}++NSString *getEnvOption(NSString *option_name) {+ NSString *envVarName = [NSString+ stringWithFormat:@"MEDIAREMOTEADAPTER_OPTION_%@", option_name];+ return getEnvValue(envVarName);+}++NSNumber *getEnvOptionInt(NSString *option_name) {+ return parseIntegerOrNil(getEnvOption(option_name));+}diff --git a/resources/mediaremote-adapter/src/adapter/get.h b/resources/mediaremote-adapter/src/adapter/get.hnew file mode 100644index 000000000..a23886caa--- /dev/null+++ b/resources/mediaremote-adapter/src/adapter/get.h@@ -0,0 +1,11 @@+// Copyright (c) 2025 Jonas van den Berg+// This file is licensed under the BSD 3-Clause License.++#ifndef MEDIAREMOTEADAPTER_ADAPTER_GET_H+#define MEDIAREMOTEADAPTER_ADAPTER_GET_H++#import <Foundation/Foundation.h>++NSDictionary *internal_get(BOOL isTestMode);++#endif // MEDIAREMOTEADAPTER_ADAPTER_GET_Hdiff --git a/resources/mediaremote-adapter/src/adapter/get.m b/resources/mediaremote-adapter/src/adapter/get.mnew file mode 100644index 000000000..9ec059a6d--- /dev/null+++ b/resources/mediaremote-adapter/src/adapter/get.m@@ -0,0 +1,146 @@+// Copyright (c) 2025 Jonas van den Berg+// This file is licensed under the BSD 3-Clause License.++#include <Foundation/Foundation.h>+#import <dispatch/dispatch.h>++#import "MediaRemoteAdapter.h"+#import "adapter/env.h"+#import "adapter/get.h"+#import "adapter/globals.h"+#import "adapter/keys.h"+#import "adapter/now_playing.h"+#import "utility/helpers.h"++#define GET_TIMEOUT_MILLIS 2000+#define JSON_NULL @"null"++NSDictionary *internal_get(BOOL isTestMode) {+ NSString *micros_option = getEnvOption(@"micros");+ __block const bool convert_micros = micros_option != nil;++ NSString *human_readable_option = getEnvOption(@"human-readable");+ __block const bool human_readable = human_readable_option != nil;++ NSString *now_option = getEnvOption(@"now");+ __block const bool calculate_now = now_option != nil;++ NSString *no_artwork_option = getEnvOption(@"no-artwork");+ const bool no_artwork = no_artwork_option != nil;++ __block NSMutableDictionary *liveData = [NSMutableDictionary dictionary];+ __block BOOL isFromTestClient = NO;++ dispatch_group_t group = dispatch_group_create();++ // PID and Bundle Identifier+ dispatch_group_enter(group);+ g_mediaRemote.getNowPlayingApplicationPID(+ g_serialdispatchQueue, ^(int pid) {+ if (pid != 0) {+ liveData[kMRAProcessIdentifier] = @(pid);+ bool ok = appForPID(pid, ^(NSRunningApplication *process) {+ if (process.bundleIdentifier != nil) {+ liveData[kMRABundleIdentifier] = process.bundleIdentifier;+ }+ dispatch_group_leave(group);+ });+ if (!ok) {+ dispatch_group_leave(group);+ }+ } else {+ dispatch_group_leave(group);+ }+ });++ // Now Playing Client+ dispatch_group_enter(group);+ g_mediaRemote.getNowPlayingClient(g_serialdispatchQueue, ^(id client) {+ NSString *parentAppBundleID = nil;+ if (client && [client respondsToSelector:@selector+ (parentApplicationBundleIdentifier)]) {+ parentAppBundleID = [client+ performSelector:@selector(parentApplicationBundleIdentifier)];+ }+ if (parentAppBundleID) {+ liveData[kMRAParentApplicationBundleIdentifier] = parentAppBundleID;+ }+ dispatch_group_leave(group);+ });++ // Is Playing+ dispatch_group_enter(group);+ g_mediaRemote.getNowPlayingApplicationIsPlaying(+ g_serialdispatchQueue, ^(bool isPlaying) {+ liveData[kMRAPlaying] = @(isPlaying);+ dispatch_group_leave(group);+ });++ dispatch_group_enter(group);+ g_mediaRemote.getNowPlayingInfo(g_serialdispatchQueue, ^(+ NSDictionary *information) {+ NSString *serviceIdentifier =+ information[kMRMediaRemoteNowPlayingInfoServiceIdentifier];+ if (!isTestMode &&+ [serviceIdentifier+ isEqualToString:@"com.vandenbe.MediaRemoteAdapter.TestClient"]) {+ isFromTestClient = YES;+ dispatch_group_leave(group);+ return;+ }+ NSDictionary *converted = convertNowPlayingInformation(+ information, convert_micros, calculate_now, no_artwork);+ [liveData addEntriesFromDictionary:converted];+ dispatch_group_leave(group);+ });++ // Wait for all async callbacks or timeout+ dispatch_time_t timeout =+ dispatch_time(DISPATCH_TIME_NOW, GET_TIMEOUT_MILLIS * NSEC_PER_MSEC);+ long result = dispatch_group_wait(group, timeout);++ if (result != 0) {+ printErrf(+ @"Reading now playing information timed out after %d milliseconds",+ GET_TIMEOUT_MILLIS);+ return nil;+ }++ if (isFromTestClient) {+ return nil;+ }++ if (human_readable) {+ makePayloadHumanReadable(liveData);+ }++ if (!allMandatoryPayloadKeysSet(liveData)) {+ return nil;+ }++ return liveData;+}++void adapter_get() {+ NSDictionary *liveData = internal_get(NO);++ NSString *micros_option = getEnvOption(@"micros");+ const bool convert_micros = micros_option != nil;++ NSString *human_readable_option = getEnvOption(@"human-readable");+ const bool human_readable = human_readable_option != nil;++ NSString *resultStr = nil;+ if (!liveData) {+ resultStr = JSON_NULL;+ } else {+ resultStr = serializeJsonDictionarySafe(liveData, human_readable);+ if (!resultStr) {+ fail(@"Failed to serialize now playing information");+ }+ }++ printOut(resultStr);+}++extern void adapter_get_env() { adapter_get(); }diff --git a/resources/mediaremote-adapter/src/adapter/globals.h b/resources/mediaremote-adapter/src/adapter/globals.hnew file mode 100644index 000000000..27e340885--- /dev/null+++ b/resources/mediaremote-adapter/src/adapter/globals.h@@ -0,0 +1,15 @@+// Copyright (c) 2025 Jonas van den Berg+// This file is licensed under the BSD 3-Clause License.++#ifndef MEDIAREMOTEADAPTER_ADAPTER_GLOBALS_H+#define MEDIAREMOTEADAPTER_ADAPTER_GLOBALS_H++#import <CoreFoundation/CoreFoundation.h>+#import <dispatch/dispatch.h>++#import "private/MediaRemote.h"++extern MediaRemote* g_mediaRemote;+extern dispatch_queue_t g_serialdispatchQueue;++#endif // MEDIAREMOTEADAPTER_ADAPTER_GLOBALS_Hdiff --git a/resources/mediaremote-adapter/src/adapter/globals.m b/resources/mediaremote-adapter/src/adapter/globals.mnew file mode 100644index 000000000..7f3b26261--- /dev/null+++ b/resources/mediaremote-adapter/src/adapter/globals.m@@ -0,0 +1,19 @@+// Copyright (c) 2025 Jonas van den Berg+// This file is licensed under the BSD 3-Clause License.++#import "globals.h"++#import "utility/helpers.h"++MediaRemote *g_mediaRemote = NULL;+dispatch_queue_t g_serialdispatchQueue;++__attribute__((constructor)) static void initGlobals() {+ g_mediaRemote = [[MediaRemote alloc] init];+ if (!g_mediaRemote) {+ fail(@"Failed to initialize MediaRemote Framework");+ return;+ }+ g_serialdispatchQueue = dispatch_queue_create(+ "mediaremote-adapter.serial-dispatch-queue", DISPATCH_QUEUE_SERIAL);+}diff --git a/resources/mediaremote-adapter/src/adapter/keys.h b/resources/mediaremote-adapter/src/adapter/keys.hnew file mode 100644index 000000000..a3a5f03d2--- /dev/null+++ b/resources/mediaremote-adapter/src/adapter/keys.h@@ -0,0 +1,19 @@+// Copyright (c) 2025 Jonas van den Berg+// This file is licensed under the BSD 3-Clause License.++#ifndef MEDIAREMOTEADAPTER_ADAPTER_KEYS_H+#define MEDIAREMOTEADAPTER_ADAPTER_KEYS_H++#import <Foundation/Foundation.h>++// These keys are mandatory and must never be null, empty or missing.+NSArray<NSString *> *mandatoryPayloadKeys(void);++// Checks whether all mandatory payload keys returned by mandatoryPayloadKeys()+// are present in the given payload dictionary and have a non-null value.+bool allMandatoryPayloadKeysSet(NSDictionary *data);++// These keys identify a now playing item uniquely.+NSArray<NSString *> *identifyingPayloadKeys(void);++#endif // MEDIAREMOTEADAPTER_ADAPTER_KEYS_Hdiff --git a/resources/mediaremote-adapter/src/adapter/keys.m b/resources/mediaremote-adapter/src/adapter/keys.mnew file mode 100644index 000000000..7bb84cc9c--- /dev/null+++ b/resources/mediaremote-adapter/src/adapter/keys.m@@ -0,0 +1,83 @@+// Copyright (c) 2025 Jonas van den Berg+// This file is licensed under the BSD 3-Clause License.++#import "keys.h"++#import "MediaRemoteAdapter.h"++NSString *kMRAProcessIdentifier = @"processIdentifier";+NSString *kMRABundleIdentifier = @"bundleIdentifier";+NSString *kMRAParentApplicationBundleIdentifier =+ @"parentApplicationBundleIdentifier";+NSString *kMRAPlaying = @"playing";++NSString *kMRADurationMicros = @"durationMicros";+NSString *kMRAElapsedTimeMicros = @"elapsedTimeMicros";+NSString *kMRATimestampEpochMicros = @"timestampEpochMicros";++NSString *kMRAElapsedTimeNow = @"elapsedTimeNow";+NSString *kMRAElapsedTimeNowMicros = @"elapsedTimeNowMicros";++NSString *kMRATitle = @"title";+NSString *kMRAArtist = @"artist";+NSString *kMRAAlbum = @"album";+NSString *kMRADuration = @"duration";+NSString *kMRAElapsedTime = @"elapsedTime";+NSString *kMRATimestamp = @"timestamp";+NSString *kMRAArtworkMimeType = @"artworkMimeType";+NSString *kMRAArtworkData = @"artworkData";++NSString *kMRAChapterNumber = @"chapterNumber";+NSString *kMRAComposer = @"composer";+NSString *kMRAGenre = @"genre";+NSString *kMRAIsAdvertisement = @"isAdvertisement";+NSString *kMRAIsBanned = @"isBanned";+NSString *kMRAIsInWishList = @"isInWishList";+NSString *kMRAIsLiked = @"isLiked";+NSString *kMRAIsMusicApp = @"isMusicApp";+NSString *kMRAPlaybackRate = @"playbackRate";+NSString *kMRAProhibitsSkip = @"prohibitsSkip";+NSString *kMRAQueueIndex = @"queueIndex";+NSString *kMRARadioStationIdentifier = @"radioStationIdentifier";+NSString *kMRARepeatMode = @"repeatMode";+NSString *kMRAShuffleMode = @"shuffleMode";+NSString *kMRAStartTime = @"startTime";+NSString *kMRASupportsFastForward15Seconds = @"supportsFastForward15Seconds";+NSString *kMRASupportsIsBanned = @"supportsIsBanned";+NSString *kMRASupportsIsLiked = @"supportsIsLiked";+NSString *kMRASupportsRewind15Seconds = @"supportsRewind15Seconds";+NSString *kMRATotalChapterCount = @"totalChapterCount";+NSString *kMRATotalDiscCount = @"totalDiscCount";+NSString *kMRATotalQueueCount = @"totalQueueCount";+NSString *kMRATotalTrackCount = @"totalTrackCount";+NSString *kMRATrackNumber = @"trackNumber";+NSString *kMRAUniqueIdentifier = @"uniqueIdentifier";+NSString *kMRAContentItemIdentifier = @"contentItemIdentifier";+NSString *kMRARadioStationHash = @"radioStationHash";+NSString *kMRAMediaType = @"mediaType";++NSArray<NSString *> *mandatoryPayloadKeys(void) {+ return @[ kMRAProcessIdentifier, kMRATitle, kMRAPlaying ];+}++bool allMandatoryPayloadKeysSet(NSDictionary *data) {+ NSArray<NSString *> *keys = mandatoryPayloadKeys();+ for (NSString *key in keys) {+ if (data[key] == nil || data[key] == [NSNull null]) {+ return false;+ }+ id value = data[key];+ if ([value isKindOfClass:[NSString class]] &&+ [(NSString *)value length] == 0) {+ return false;+ }+ }+ return true;+}++NSArray<NSString *> *identifyingPayloadKeys(void) {+ return @[+ kMRAProcessIdentifier, kMRABundleIdentifier,+ kMRAParentApplicationBundleIdentifier, kMRATitle, kMRAArtist, kMRAAlbum+ ];+}diff --git a/resources/mediaremote-adapter/src/adapter/now_playing.h b/resources/mediaremote-adapter/src/adapter/now_playing.hnew file mode 100644index 000000000..5f93d4774--- /dev/null+++ b/resources/mediaremote-adapter/src/adapter/now_playing.h@@ -0,0 +1,20 @@+// Copyright (c) 2025 Jonas van den Berg+// This file is licensed under the BSD 3-Clause License.++#ifndef MEDIAREMOTEADAPTER_UTILITY_NOW_PLAYING_H+#define MEDIAREMOTEADAPTER_UTILITY_NOW_PLAYING_H++#import <Foundation/Foundation.h>++// Requests information once so that the process runs long enough for the+// MediaRemote command to actually be sent to the now playing application.+void waitForCommandCompletion();++// Converts raw MediaRemote now playing information to adapter keys.+// Optionally replaces keys with time values with microseconds equivalents.+NSMutableDictionary *convertNowPlayingInformation(NSDictionary *information,+ bool convertMicros,+ bool calculateNow,+ bool withoutArtwork);++#endif // MEDIAREMOTEADAPTER_UTILITY_NOW_PLAYING_Hdiff --git a/resources/mediaremote-adapter/src/adapter/now_playing.m b/resources/mediaremote-adapter/src/adapter/now_playing.mnew file mode 100644index 000000000..39e68c617--- /dev/null+++ b/resources/mediaremote-adapter/src/adapter/now_playing.m@@ -0,0 +1,201 @@+// Copyright (c) 2025 Jonas van den Berg+// This file is licensed under the BSD 3-Clause License.++#import "now_playing.h"++#import "MediaRemoteAdapter.h"+#import "adapter/globals.h"+#import "adapter/keys.h"+#import "private/MediaRemote.h"++#define WAIT_TIMEOUT_MILLIS 2000++void waitForCommandCompletion() {+ id semaphore = dispatch_semaphore_create(0);++ g_mediaRemote.getNowPlayingApplicationPID(+ g_serialdispatchQueue, ^(int pid) {+ dispatch_semaphore_signal(semaphore);+ });++ dispatch_time_t timeout =+ dispatch_time(DISPATCH_TIME_NOW, WAIT_TIMEOUT_MILLIS * NSEC_PER_MSEC);+ dispatch_semaphore_wait(semaphore, timeout);+}++NSNumber *getElapsedTimeNow(NSDictionary *information) {+ id elapsed = information[kMRMediaRemoteNowPlayingInfoElapsedTime];+ if (![elapsed isKindOfClass:[NSNumber class]]) {+ return nil;+ }++ id timestamp = information[kMRMediaRemoteNowPlayingInfoTimestamp];+ if (![timestamp isKindOfClass:[NSDate class]]) {+ return elapsed;+ }++ NSTimeInterval timestampEpoch = [(NSDate *)timestamp timeIntervalSince1970];+ NSTimeInterval currentEpoch = [[NSDate date] timeIntervalSince1970];+ NSTimeInterval timeDiff = currentEpoch - timestampEpoch;++ double playbackRate = 0;+ id playbackRateVal = information[kMRMediaRemoteNowPlayingInfoPlaybackRate];+ if ([playbackRateVal isKindOfClass:[NSNumber class]]) {+ playbackRate = [(NSNumber *)playbackRateVal doubleValue];+ }++ double realElapsed = [(NSNumber *)elapsed doubleValue];+ if (playbackRate >= 0) {+ realElapsed += timeDiff * playbackRate;+ }++ return @(realElapsed);+}++NSMutableDictionary *convertNowPlayingInformation(NSDictionary *information,+ bool convertMicros,+ bool calculateNow,+ bool withoutArtwork) {+ NSMutableDictionary *data = [NSMutableDictionary dictionary];++ void (^setKey)(id, id) = ^(id key, id fromKey) {+ id value = nil;+ if (information != nil) {+ id result = information[fromKey];+ if (result != nil) {+ value = result;+ }+ }+ if (value != nil) {+ [data setObject:value forKey:key];+ }+ };++ void (^setValue)(id key, id (^)(void)) = ^(id key, id (^evaluate)(void)) {+ id value = nil;+ if (information != nil) {+ value = evaluate();+ }+ if (value != nil) {+ [data setObject:value forKey:key];+ }+ };++ setKey(kMRATitle, kMRMediaRemoteNowPlayingInfoTitle);+ setKey(kMRAArtist, kMRMediaRemoteNowPlayingInfoArtist);+ setKey(kMRAAlbum, kMRMediaRemoteNowPlayingInfoAlbum);+ if (!withoutArtwork) {+ setKey(kMRAArtworkMimeType,+ kMRMediaRemoteNowPlayingInfoArtworkMIMEType);+ setKey(kMRAArtworkData, kMRMediaRemoteNowPlayingInfoArtworkData);+ }++ if (!convertMicros) {+ setKey(kMRADuration, kMRMediaRemoteNowPlayingInfoDuration);+ setKey(kMRAElapsedTime, kMRMediaRemoteNowPlayingInfoElapsedTime);+ setKey(kMRATimestamp, kMRMediaRemoteNowPlayingInfoTimestamp);+ if (calculateNow) {+ // This key is added and does not replace the original because it+ // is just a rough estimation, meant to be used for convenience.+ setValue(kMRAElapsedTimeNow, ^id {+ id elapsedTime =+ information[kMRMediaRemoteNowPlayingInfoElapsedTime];+ id nowValue = getElapsedTimeNow(information);+ if (nowValue != nil) {+ elapsedTime = nowValue;+ }+ return elapsedTime;+ });+ }+ } else {+ // These keys replace their original counterparts because semantics+ // don't change and no accuracy is lost, merely the time unit changes.+ setValue(kMRADurationMicros, ^id {+ id duration = information[kMRMediaRemoteNowPlayingInfoDuration];+ if (duration != nil && [duration isKindOfClass:[NSNumber class]]) {+ NSTimeInterval durationMicros =+ [duration doubleValue] * 1000 * 1000;+ return @(floor(durationMicros));+ }+ return nil;+ });+ setValue(kMRAElapsedTimeMicros, ^id {+ id elapsedTime = information[kMRMediaRemoteNowPlayingInfoElapsedTime];+ if (elapsedTime != nil &&+ [elapsedTime isKindOfClass:[NSNumber class]]) {+ NSTimeInterval elapsedTimeMicros =+ [elapsedTime doubleValue] * 1000 * 1000;+ return @(floor(elapsedTimeMicros));+ }+ return nil;+ });+ if (calculateNow) {+ // This key is added and does not replace the original because it+ // is just a rough estimation, meant to be used for convenience.+ setValue(kMRAElapsedTimeNowMicros, ^id {+ id elapsedTime =+ information[kMRMediaRemoteNowPlayingInfoElapsedTime];+ if (calculateNow) {+ elapsedTime = getElapsedTimeNow(information);+ }+ if (elapsedTime != nil &&+ [elapsedTime isKindOfClass:[NSNumber class]]) {+ NSTimeInterval elapsedTimeMicros =+ [elapsedTime doubleValue] * 1000 * 1000;+ return @(floor(elapsedTimeMicros));+ }+ return nil;+ });+ }+ setValue(kMRATimestampEpochMicros, ^id {+ id timestamp = information[kMRMediaRemoteNowPlayingInfoTimestamp];+ if (timestamp != nil && [timestamp isKindOfClass:[NSDate class]]) {+ NSTimeInterval timestampEpoch = [timestamp timeIntervalSince1970];+ NSTimeInterval timestampEpochMicro = timestampEpoch * 1000 * 1000;+ return @(floor(timestampEpochMicro));+ }+ return nil;+ });+ }++ // Some of the following keys might fail due to not being convertible+ // to JSON automatically. This is difficult to test because most media+ // players do not even set these keys and the data types are not documented+ // anywhere. Still, JSON serialization of the resulting dictionary deletes+ // any invalid keys, converts or deletes invalid values and prints error+ // messages whenever any dictionary entry has been removed. Users should+ // report whenever they encounter such an error with these keys.++ // clang-format off+ setKey(kMRAChapterNumber, kMRMediaRemoteNowPlayingInfoChapterNumber);+ setKey(kMRAComposer, kMRMediaRemoteNowPlayingInfoComposer);+ setKey(kMRAGenre, kMRMediaRemoteNowPlayingInfoGenre);+ setKey(kMRAIsAdvertisement, kMRMediaRemoteNowPlayingInfoIsAdvertisement);+ setKey(kMRAIsBanned, kMRMediaRemoteNowPlayingInfoIsBanned);+ setKey(kMRAIsInWishList, kMRMediaRemoteNowPlayingInfoIsInWishList);+ setKey(kMRAIsLiked, kMRMediaRemoteNowPlayingInfoIsLiked);+ setKey(kMRAIsMusicApp, kMRMediaRemoteNowPlayingInfoIsMusicApp);+ setKey(kMRAPlaybackRate, kMRMediaRemoteNowPlayingInfoPlaybackRate);+ setKey(kMRAProhibitsSkip, kMRMediaRemoteNowPlayingInfoProhibitsSkip);+ setKey(kMRAQueueIndex, kMRMediaRemoteNowPlayingInfoQueueIndex);+ setKey(kMRARadioStationIdentifier, kMRMediaRemoteNowPlayingInfoRadioStationIdentifier);+ setKey(kMRARepeatMode, kMRMediaRemoteNowPlayingInfoRepeatMode);+ setKey(kMRAShuffleMode, kMRMediaRemoteNowPlayingInfoShuffleMode);+ setKey(kMRAStartTime, kMRMediaRemoteNowPlayingInfoStartTime);+ setKey(kMRASupportsFastForward15Seconds, kMRMediaRemoteNowPlayingInfoSupportsFastForward15Seconds);+ setKey(kMRASupportsIsBanned, kMRMediaRemoteNowPlayingInfoSupportsIsBanned);+ setKey(kMRASupportsIsLiked, kMRMediaRemoteNowPlayingInfoSupportsIsLiked);+ setKey(kMRASupportsRewind15Seconds, kMRMediaRemoteNowPlayingInfoSupportsRewind15Seconds);+ setKey(kMRATotalChapterCount, kMRMediaRemoteNowPlayingInfoTotalChapterCount);+ setKey(kMRATotalDiscCount, kMRMediaRemoteNowPlayingInfoTotalDiscCount);+ setKey(kMRATotalQueueCount, kMRMediaRemoteNowPlayingInfoTotalQueueCount);+ setKey(kMRATotalTrackCount, kMRMediaRemoteNowPlayingInfoTotalTrackCount);+ setKey(kMRATrackNumber, kMRMediaRemoteNowPlayingInfoTrackNumber);+ setKey(kMRAUniqueIdentifier, kMRMediaRemoteNowPlayingInfoUniqueIdentifier);+ setKey(kMRAContentItemIdentifier, kMRMediaRemoteNowPlayingInfoContentItemIdentifier);+ setKey(kMRARadioStationHash, kMRMediaRemoteNowPlayingInfoRadioStationHash);+ setKey(kMRAMediaType, kMRMediaRemoteNowPlayingInfoMediaType);+ // clang-format on++ return data;+}diff --git a/resources/mediaremote-adapter/src/adapter/repeat.m b/resources/mediaremote-adapter/src/adapter/repeat.mnew file mode 100644index 000000000..d225656a2--- /dev/null+++ b/resources/mediaremote-adapter/src/adapter/repeat.m@@ -0,0 +1,44 @@+// Copyright (c) 2025 Jonas van den Berg+// This file is licensed under the BSD 3-Clause License.++#include "private/MediaRemote.h"+#include <limits.h>++#import <Foundation/Foundation.h>++#import "MediaRemoteAdapter.h"+#import "adapter/env.h"+#import "adapter/globals.h"+#import "adapter/now_playing.h"+#import "utility/helpers.h"++static NSArray<NSNumber *> *acceptedModes;++__attribute__((constructor)) static void init() {+ acceptedModes = @[+ @(kMRARepeatDisabled),+ @(kMRARepeatTrack),+ @(kMRARepeatPlaylist),+ ];+}++static bool isModeAccepted(int mode) {+ return [acceptedModes containsObject:@(mode)];+}++void adapter_repeat(MRARepeatMode mode) {++ if (!isModeAccepted((int)mode)) {+ failf(@"Invalid repeat mode: %d", (int)mode);+ }++ g_mediaRemote.setRepeatMode((int)mode);++ waitForCommandCompletion();+}++static inline int repeat_0_mode() {+ return getEnvFuncParamIntSafe(@"adapter_repeat", 0, @"mode");+}++void adapter_repeat_env() { adapter_repeat((MRARepeatMode)repeat_0_mode()); }diff --git a/resources/mediaremote-adapter/src/adapter/seek.m b/resources/mediaremote-adapter/src/adapter/seek.mnew file mode 100644index 000000000..6161e5c18--- /dev/null+++ b/resources/mediaremote-adapter/src/adapter/seek.m@@ -0,0 +1,30 @@+// Copyright (c) 2025 Jonas van den Berg+// This file is licensed under the BSD 3-Clause License.++#include "private/MediaRemote.h"+#include <limits.h>++#import <Foundation/Foundation.h>++#import "MediaRemoteAdapter.h"+#import "adapter/env.h"+#import "adapter/globals.h"+#import "adapter/now_playing.h"+#import "utility/helpers.h"++void adapter_seek(long position) {++ if (position < 0) {+ failf(@"Negative values are not allowed: %d", position);+ }++ g_mediaRemote.setElapsedTime(position / 1000000.0);++ waitForCommandCompletion();+}++static inline long seek_0_position() {+ return getEnvFuncParamLongSafe(@"adapter_seek", 0, @"position");+}++void adapter_seek_env() { adapter_seek(seek_0_position()); }diff --git a/resources/mediaremote-adapter/src/adapter/send.m b/resources/mediaremote-adapter/src/adapter/send.mnew file mode 100644index 000000000..2534dc021--- /dev/null+++ b/resources/mediaremote-adapter/src/adapter/send.m@@ -0,0 +1,69 @@+// Copyright (c) 2025 Jonas van den Berg+// This file is licensed under the BSD 3-Clause License.++#include "private/MediaRemote.h"+#include <limits.h>++#import <Foundation/Foundation.h>++#import "MediaRemoteAdapter.h"+#import "adapter/env.h"+#import "adapter/globals.h"+#import "adapter/now_playing.h"+#import "utility/helpers.h"++static NSArray<NSNumber *> *acceptedCommands;++__attribute__((constructor)) static void init() {+ acceptedCommands = @[+ @(kMRAPlay),+ @(kMRAPause),+ @(kMRATogglePlayPause),+ @(kMRAStop),+ @(kMRANextTrack),+ @(kMRAPreviousTrack),+ @(kMRAToggleShuffle),+ @(kMRAToggleRepeat),+ @(kMRAStartForwardSeek),+ @(kMRAEndForwardSeek),+ @(kMRAStartBackwardSeek),+ @(kMRAEndBackwardSeek),+ @(kMRAGoBackFifteenSeconds),+ @(kMRASkipFifteenSeconds),+ ];+ // TODO like/unlike tracks by reading now playing information first,+ // getting the track ID, station ID and station hash+ // and then sending the respective MRCommand.+ // does "ban" mean "remove like" here?+}++static MRCommand findCommand(int command, bool *found) {+ if ([acceptedCommands containsObject:@(command)]) {+ *found = true;+ return (MRCommand)command;+ }+ *found = false;+ return (MRCommand)0;+}++void adapter_send(MRACommand command) {++ bool ok = false;+ MRCommand commandValue = findCommand((int)command, &ok);+ if (!ok) {+ failf(@"Invalid command: %d", command);+ }++ bool result = g_mediaRemote.sendCommand(commandValue, nil);+ if (!result) {+ failf(@"Failed to send command %d", command);+ }++ waitForCommandCompletion();+}++static inline int send_0_command() {+ return getEnvFuncParamIntSafe(@"adapter_send", 0, @"command");+}++void adapter_send_env() { adapter_send((MRACommand)send_0_command()); }diff --git a/resources/mediaremote-adapter/src/adapter/shuffle.m b/resources/mediaremote-adapter/src/adapter/shuffle.mnew file mode 100644index 000000000..2afe8587d--- /dev/null+++ b/resources/mediaremote-adapter/src/adapter/shuffle.m@@ -0,0 +1,46 @@+// Copyright (c) 2025 Jonas van den Berg+// This file is licensed under the BSD 3-Clause License.++#include "private/MediaRemote.h"+#include <limits.h>++#import <Foundation/Foundation.h>++#import "MediaRemoteAdapter.h"+#import "adapter/env.h"+#import "adapter/globals.h"+#import "adapter/now_playing.h"+#import "utility/helpers.h"++static NSArray<NSNumber *> *acceptedModes;++__attribute__((constructor)) static void init() {+ acceptedModes = @[+ @(kMRAShuffleDisabled),+ @(kMRAShuffleAlbums),+ @(kMRAShuffleTracks),+ ];+}++static bool isModeAccepted(int mode) {+ return [acceptedModes containsObject:@(mode)];+}++void adapter_shuffle(MRAShuffleMode mode) {++ if (!isModeAccepted((int)mode)) {+ failf(@"Invalid shuffle mode: %d", (int)mode);+ }++ g_mediaRemote.setShuffleMode((int)mode);++ waitForCommandCompletion();+}++static inline int shuffle_0_mode() {+ return getEnvFuncParamIntSafe(@"adapter_shuffle", 0, @"mode");+}++void adapter_shuffle_env() {+ adapter_shuffle((MRAShuffleMode)shuffle_0_mode());+}diff --git a/resources/mediaremote-adapter/src/adapter/speed.m b/resources/mediaremote-adapter/src/adapter/speed.mnew file mode 100644index 000000000..d9e44dad1--- /dev/null+++ b/resources/mediaremote-adapter/src/adapter/speed.m@@ -0,0 +1,30 @@+// Copyright (c) 2025 Jonas van den Berg+// This file is licensed under the BSD 3-Clause License.++#include "private/MediaRemote.h"+#include <limits.h>++#import <Foundation/Foundation.h>++#import "MediaRemoteAdapter.h"+#import "adapter/env.h"+#import "adapter/globals.h"+#import "adapter/now_playing.h"+#import "utility/helpers.h"++void adapter_speed(int speed) {++ if (speed < 0) {+ failf(@"Negative values are not allowed: %d", speed);+ }++ g_mediaRemote.setPlaybackSpeed(speed);++ waitForCommandCompletion();+}++static inline int speed_0_speed() {+ return getEnvFuncParamIntSafe(@"adapter_speed", 0, @"speed");+}++void adapter_speed_env() { adapter_speed(speed_0_speed()); }diff --git a/resources/mediaremote-adapter/src/adapter/stream.m b/resources/mediaremote-adapter/src/adapter/stream.mnew file mode 100644index 000000000..ff27dc8b1--- /dev/null+++ b/resources/mediaremote-adapter/src/adapter/stream.m@@ -0,0 +1,523 @@+// Copyright (c) 2025 Jonas van den Berg+// This file is licensed under the BSD 3-Clause License.++#import <AppKit/AppKit.h>+#import <CoreFoundation/CoreFoundation.h>+#import <Foundation/Foundation.h>++#import "MediaRemoteAdapter.h"+#import "adapter/env.h"+#import "adapter/globals.h"+#import "adapter/keys.h"+#import "adapter/now_playing.h"+#import "private/MediaRemote.h"+#import "utility/Debounce.h"+#import "utility/helpers.h"++#ifndef DEBOUNCE_DELAY_MILLIS+#define DEBOUNCE_DELAY_MILLIS 0+#endif++static CFRunLoopRef g_runLoop = NULL;++static NSString *serializeData(NSDictionary *data, BOOL diff, BOOL pretty) {+ return serializeJsonDictionarySafe(+ @{+ @"type" : @"data",+ @"diff" : @(diff),+ @"payload" : data ?: @{},+ },+ pretty);+}++static NSDictionary *createDiff(NSDictionary *a, NSDictionary *b) {+ NSMutableDictionary *diff = [NSMutableDictionary dictionary];+ NSMutableSet *allKeys = [NSMutableSet setWithArray:a.allKeys];+ [allKeys addObjectsFromArray:b.allKeys];+ for (id key in allKeys) {+ id oldValue = a[key];+ id newValue = b[key];+ BOOL valuesDiffer = NO;+ if (oldValue == nil && newValue != nil) {+ valuesDiffer = YES;+ } else if (oldValue != nil && newValue == nil) {+ valuesDiffer = YES;+ } else if (![oldValue isEqual:newValue]) {+ valuesDiffer = YES;+ }+ if (valuesDiffer) {+ diff[key] = newValue ?: [NSNull null];+ }+ }+ return [diff copy];+}++static BOOL isSameItemIdentity(NSDictionary *a, NSDictionary *b) {+ NSArray<NSString *> *keys = identifyingPayloadKeys();+ for (NSString *key in keys) {+ id aValue = a[key];+ id bValue = b[key];+ if (aValue == nil && bValue == nil) {+ continue;+ }+ if (aValue == nil || bValue == nil) {+ return NO;+ }+ if (![aValue isEqual:bValue]) {+ return NO;+ }+ }+ return YES;+}++static NSDictionary *previousData = nil;++static void printData(NSDictionary *data, BOOL diff, BOOL pretty) {+ NSString *serialized = nil;+ if (diff && previousData != nil && isSameItemIdentity(previousData, data)) {+ NSDictionary *result = createDiff(previousData, data);+ if ([result count] == 0) {+ return;+ }+ serialized = serializeData(result, YES, pretty);+ } else {+ serialized = serializeData(data, NO, pretty);+ }+ if (serialized != nil) {+ if (diff) {+ previousData = [data copy];+ }+ // Print the serialized data without duplicates. Note that while this+ // can fail when the key order in the serialized JSON output changes,+ // it practically won't because if it did, there would also be a change+ // in values that needs to be reported.+ printOutUnique(serialized);+ }+ if (!diff) {+ previousData = nil;+ }+}++static void appForNotification(NSNotification *notification,+ void (^block)(NSRunningApplication *)) {+ NSDictionary *userInfo = notification.userInfo;+ id pidValue = userInfo[kMRMediaRemoteNowPlayingApplicationPIDUserInfoKey];+ if (pidValue != nil) {+ int pid = [pidValue intValue];+ appForPID(pid, block);+ } else {+ block(nil);+ }+};++typedef struct MetadataStats {+ BOOL trackTitleChanged;+ int identifyingTrackKeysIdentical;+ int identifyingTrackKeysChanged;+} MetadataStats;++static MetadataStats createMetadataStats() {+ MetadataStats stats = {+ .trackTitleChanged = NO,+ .identifyingTrackKeysIdentical = 0,+ .identifyingTrackKeysChanged = 0,+ };+ return stats;+}++static MetadataStats compareIdentifyingTrackKeys(NSDictionary *prev,+ NSDictionary *next) {+ MetadataStats stats = createMetadataStats();+ for (NSString *key in @[ kMRATitle, kMRAArtist, kMRAAlbum ]) {+ id a = prev[key], b = next[key];+ if (a == nil || b == nil)+ continue;+ if ([a isEqual:b]) {+ stats.identifyingTrackKeysIdentical++;+ } else {+ stats.identifyingTrackKeysChanged++;+ if ([key isEqualToString:kMRATitle]) {+ stats.trackTitleChanged = YES;+ }+ }+ }+ return stats;+}++extern void adapter_stream() {++ // Get ADAPTER_TEST_MODE as a boolean and set BOOL isTestMode+ BOOL isTestMode = NO;+ char *testModeEnv = getenv("ADAPTER_TEST_MODE");+ if (testModeEnv && strcmp(testModeEnv, "0") != 0 &&+ strlen(testModeEnv) > 0) {+ isTestMode = YES;+ }++ int debounce_delay_millis = 0;+ NSNumber *debounce_option = getEnvOptionInt(@"debounce");+ if (debounce_option != nil) {+ debounce_delay_millis = [debounce_option intValue];+ }++ NSString *no_diff_option = getEnvOption(@"no_diff");+ NSString *no_artwork_option = getEnvOption(@"no-artwork");+ NSString *micros_option = getEnvOption(@"micros");+ NSString *human_readable_option = getEnvOption(@"human-readable");++ // This option is needed for media players which, when changing tracks,+ // update the artist and/or other fields later than e.g. the title, the+ // invalid in-between metadata therefore representing "peculiar" media. The+ // only known player that does this is the TIDAL desktop player with the+ // bundle ID "com.tidal.desktop". This is easy to reproduce when playing+ // media from a playlist with tracks from different artists.+ // FIXME Implement this for any bundle ID, should other players need it.+ // In that case parse any "experimental-peculiar-debounce:*" option.+ NSNumber *peculiar_debounce_option =+ getEnvOptionInt(@"experimental-peculiar-debounce:com.tidal.desktop");+ __block NSString *peculiar_bundle_id = nil;+ __block Debounce *peculiar_debounce = nil;+ __block BOOL did_peculiar_debounce = NO;+ if (peculiar_debounce_option != nil) {+ peculiar_bundle_id = @"com.tidal.desktop";+ int debounce_millis = [peculiar_debounce_option intValue];+ peculiar_debounce =+ [[Debounce alloc] initWithDelay:(debounce_millis / 1000.0)+ queue:g_serialdispatchQueue];+ }++ __block NSMutableDictionary *liveData = [NSMutableDictionary dictionary];+ __block MetadataStats liveDataStats = createMetadataStats();+ __block const Debounce *const debounce =+ [[Debounce alloc] initWithDelay:(debounce_delay_millis / 1000.0)+ queue:g_serialdispatchQueue];+ __block const BOOL no_diff = (no_diff_option != nil);+ __block const BOOL no_artwork = (no_artwork_option != nil);+ __block const BOOL convert_micros = (micros_option != nil);+ __block const bool human_readable = (human_readable_option != nil);++ void (^localPrintData)(NSDictionary *) = ^(NSDictionary *data) {+ printData(data, !no_diff, human_readable);+ };++ void (^directHandle)() = ^() {+ if (allMandatoryPayloadKeysSet(liveData)) {+ if (human_readable) {+ NSMutableDictionary *shallowClone =+ [NSMutableDictionary dictionaryWithDictionary:liveData];+ makePayloadHumanReadable(shallowClone);+ localPrintData(shallowClone);+ } else {+ localPrintData(liveData);+ }+ } else {+ localPrintData(nil);+ }+ };++ void (^internalHandle)(bool) = ^(bool updatedStats) {+ if (peculiar_debounce == nil ||+ ![peculiar_bundle_id isEqual:liveData[kMRABundleIdentifier]]) {+ directHandle();+ return;+ }+ if (updatedStats && liveDataStats.trackTitleChanged &&+ liveDataStats.identifyingTrackKeysIdentical > 0) {+ did_peculiar_debounce = true;+ [peculiar_debounce call:^{+ did_peculiar_debounce = false;+ directHandle();+ }];+ } else if (did_peculiar_debounce &&+ (!updatedStats ||+ liveDataStats.identifyingTrackKeysChanged == 0)) {+ // Ignore this handle call, since there is an active debounce call.+ } else {+ [peculiar_debounce cancel];+ did_peculiar_debounce = false;+ directHandle();+ }+ };++ void (^handle)() = ^() {+ internalHandle(false);+ };++ void (^handleWithUpdatedStats)() = ^() {+ internalHandle(true);+ };++ void (^requestNowPlayingApplicationPID)() = ^{+ g_mediaRemote.getNowPlayingApplicationPID(+ g_serialdispatchQueue, ^(int pid) {+ if (pid == 0) {+ liveData[kMRAProcessIdentifier] = nil;+ handle();+ return;+ }+ liveData[kMRAProcessIdentifier] = @(pid);+ bool ok = appForPID(pid, ^(NSRunningApplication *process) {+ if (process.bundleIdentifier != nil) {+ liveData[kMRABundleIdentifier] = process.bundleIdentifier;+ }+ handle();+ });+ if (!ok) {+ handle();+ }+ });+ };++ void (^requestNowPlayingParentApplicationBundleIdentifier)() = ^{+ g_mediaRemote.getNowPlayingClient(g_serialdispatchQueue, ^(id client) {+ NSString *parentAppBundleID = nil;+ if (client && [client respondsToSelector:@selector+ (parentApplicationBundleIdentifier)]) {+ id result = [client+ performSelector:@selector(parentApplicationBundleIdentifier)];+ if ([result isKindOfClass:[NSString class]]) {+ parentAppBundleID = result;+ }+ }+ if (parentAppBundleID) {+ liveData[kMRAParentApplicationBundleIdentifier] = parentAppBundleID;+ } else {+ [liveData removeObjectForKey:kMRAParentApplicationBundleIdentifier];+ }+ handle();+ });+ };++ void (^requestNowPlayingApplicationIsPlaying)() = ^{+ g_mediaRemote.getNowPlayingApplicationIsPlaying(+ g_serialdispatchQueue, ^(bool isPlaying) {+ liveData[kMRAPlaying] = @(isPlaying);+ handle();+ });+ };++ void (^requestNowPlayingInfo)() = ^{+ g_mediaRemote.getNowPlayingInfo(g_serialdispatchQueue, ^(+ NSDictionary *information) {+ NSString *serviceIdentifier =+ information[kMRMediaRemoteNowPlayingInfoServiceIdentifier];+ if (!isTestMode &&+ [serviceIdentifier+ isEqualToString:+ @"com.vandenbe.MediaRemoteAdapter.TestClient"]) {+ return;+ }+ NSMutableDictionary *converted = convertNowPlayingInformation(+ information, convert_micros, false, no_artwork);+ // Transfer anything over from the existing live data.+ if (liveData[kMRAProcessIdentifier] != nil) {+ converted[kMRAProcessIdentifier] = liveData[kMRAProcessIdentifier];+ }+ if (liveData[kMRABundleIdentifier] != nil) {+ converted[kMRABundleIdentifier] = liveData[kMRABundleIdentifier];+ }+ if (liveData[kMRAParentApplicationBundleIdentifier] != nil) {+ converted[kMRAParentApplicationBundleIdentifier] =+ liveData[kMRAParentApplicationBundleIdentifier];+ }+ if (liveData[kMRAPlaying] != nil) {+ converted[kMRAPlaying] = liveData[kMRAPlaying];+ }+ // Use the old artwork data, since often the MediaRemote framework+ // unloads the artwork and then loads it again shortly after.+ // Only do this when the items have the same identity.+ if (isSameItemIdentity(liveData, converted) &&+ liveData[kMRAArtworkData] != nil &&+ liveData[kMRAArtworkData] != [NSNull null] &&+ converted[kMRAArtworkData] == nil) {+ converted[kMRAArtworkData] = liveData[kMRAArtworkData];+ if (liveData[kMRAArtworkMimeType] != nil &&+ liveData[kMRAArtworkMimeType] != [NSNull null] &&+ converted[kMRAArtworkMimeType] == nil) {+ converted[kMRAArtworkMimeType] = liveData[kMRAArtworkMimeType];+ }+ }++ liveDataStats = compareIdentifyingTrackKeys(liveData, converted);+ [liveData setDictionary:converted];+ handleWithUpdatedStats();+ });+ };++ void (^requestAll)() = ^{+ requestNowPlayingApplicationPID();+ requestNowPlayingParentApplicationBundleIdentifier();+ requestNowPlayingApplicationIsPlaying();+ requestNowPlayingInfo();+ };++ void (^resetAll)() = ^{+ [liveData removeAllObjects];+ };++ void (^refreshAll)() = ^{+ resetAll();+ requestAll();+ };++ // FIXME Is this foolproof? This continues and registers observers+ // which might intervene with the initial requests.+ requestAll();++ NSNotificationCenter *default_center = [NSNotificationCenter defaultCenter];+ NSNotificationCenter *shared_workscape_notification_center =+ [[NSWorkspace sharedWorkspace] notificationCenter];++ // TODO Refactor the below two callbacks. They share a lot of code.++ id is_playing_change_observer = [default_center+ addObserverForName:+ kMRMediaRemoteNowPlayingApplicationIsPlayingDidChangeNotification+ object:nil+ queue:nil+ usingBlock:^(NSNotification *notification) {+ dispatch_async(g_serialdispatchQueue, ^() {+ appForNotification(notification, ^(+ NSRunningApplication *process) {+ if (process == nil) {+ // The process for this notification could not be+ // determined. Assume that there is no now playing+ // application anymore.+ resetAll();+ handle();+ return;+ }+ id isPlayingValue =+ notification.userInfo+ [kMRMediaRemoteNowPlayingApplicationIsPlayingUserInfoKey];+ if (isPlayingValue == nil) {+ return;+ }+ if (liveData[kMRABundleIdentifier] != nil &&+ process.bundleIdentifier != nil &&+ ![liveData[kMRABundleIdentifier]+ isEqual:process.bundleIdentifier]) {+ // This is a different process, reset all data.+ resetAll();+ }+ if (liveData[kMRAProcessIdentifier] != nil &&+ ![liveData[kMRAProcessIdentifier]+ isEqual:@(process.processIdentifier)]) {+ // This is a different process, reset all data.+ resetAll();+ }+ liveData[kMRABundleIdentifier] = process.bundleIdentifier;+ requestNowPlayingParentApplicationBundleIdentifier();+ liveData[kMRAPlaying] = @([isPlayingValue boolValue]);+ if (liveData[kMRATitle] == nil) {+ requestNowPlayingInfo();+ } else {+ handle();+ }+ });+ });+ }];++ id info_change_observer = [default_center+ addObserverForName:kMRMediaRemoteNowPlayingInfoDidChangeNotification+ object:nil+ queue:nil+ usingBlock:^(NSNotification *notification) {+ [debounce call:^{+ appForNotification(notification, ^(+ NSRunningApplication *process) {+ if (process == nil) {+ // The process for this notification could not be+ // determined. Assume that there is no now playing+ // application anymore.+ resetAll();+ handle();+ return;+ }+ if (liveData[kMRABundleIdentifier] != nil &&+ process.bundleIdentifier != nil &&+ ![liveData[kMRABundleIdentifier]+ isEqual:process.bundleIdentifier]) {+ // This is a different process, reset all data.+ resetAll();+ }+ if (liveData[kMRAProcessIdentifier] != nil &&+ ![liveData[kMRAProcessIdentifier]+ isEqual:@(process.processIdentifier)]) {+ // This is a different process, reset all data.+ resetAll();+ }+ if (liveData[kMRAProcessIdentifier] == nil) {+ requestNowPlayingApplicationPID();+ }+ if (liveData[kMRAParentApplicationBundleIdentifier] ==+ nil) {+ requestNowPlayingParentApplicationBundleIdentifier();+ }+ if (liveData[kMRAPlaying] == nil) {+ requestNowPlayingApplicationIsPlaying();+ }+ requestNowPlayingInfo();+ });+ }];+ }];++ // Register notifications for when applications are closed.+ id app_termination_observer = [shared_workscape_notification_center+ addObserverForName:NSWorkspaceDidTerminateApplicationNotification+ object:nil+ queue:nil+ usingBlock:^(NSNotification *notification) {+ dispatch_async(g_serialdispatchQueue, ^() {+ NSDictionary *userInfo = [notification userInfo];+ id bundleIdentifier =+ userInfo[@"NSApplicationBundleIdentifier"];+ if (bundleIdentifier != nil &&+ [bundleIdentifier+ isEqual:liveData[kMRABundleIdentifier]]) {+ // Refresh all data, since the application terminated.+ refreshAll();+ }+ });+ }];++ g_mediaRemote.registerForNowPlayingNotifications(g_serialdispatchQueue);++ CFRunLoopRun();++ g_mediaRemote.unregisterForNowPlayingNotifications();++ [default_center removeObserver:is_playing_change_observer];+ [default_center removeObserver:info_change_observer];+ [shared_workscape_notification_center+ removeObserver:app_termination_observer];+}++extern void adapter_stream_env() { adapter_stream(); }++extern void _adapter_stream_cancel() {+ if (g_runLoop) {+ CFRunLoopStop(g_runLoop);+ }+}++static void handleSignal(int signal) {+ if (signal == SIGINT || signal == SIGTERM) {+ _adapter_stream_cancel();+ }+}++__attribute__((constructor)) static void init() {+ g_runLoop = CFRunLoopGetCurrent();+ signal(SIGINT, handleSignal);+ signal(SIGTERM, handleSignal);+}+__attribute__((destructor)) static void teardown() { _adapter_stream_cancel(); }++// FIXME Fix "peculiar media" (artist is updated later than title). Example:+/*+35.558 Thirteen by Big Star on Camping Songs+36.091 Good Vibrations (Remastered 2001) by Big Star on Camping Songs+36.204 Good Vibrations (Remastered 2001) by Big Star on Camping Songs (+image)+36.624 Good Vibrations (Remastered 2001) by The Beach Boys on Camping Songs+*/diff --git a/resources/mediaremote-adapter/src/private/MediaRemote.h b/resources/mediaremote-adapter/src/private/MediaRemote.hnew file mode 100644index 000000000..e23de3ad5--- /dev/null+++ b/resources/mediaremote-adapter/src/private/MediaRemote.h@@ -0,0 +1,163 @@+// clang-format off++#ifndef MEDIAREMOTE_PRIVATE_H_+#define MEDIAREMOTE_PRIVATE_H_++#include <Foundation/Foundation.h>++#pragma mark Notifications++extern NSString *kMRMediaRemoteNowPlayingInfoDidChangeNotification;+extern NSString *kMRMediaRemoteNowPlayingPlaybackQueueDidChangeNotification;+extern NSString *kMRMediaRemotePickableRoutesDidChangeNotification;+extern NSString *kMRMediaRemoteNowPlayingApplicationDidChangeNotification;+extern NSString *kMRMediaRemoteNowPlayingApplicationIsPlayingDidChangeNotification;+extern NSString *kMRMediaRemoteRouteStatusDidChangeNotification;++#pragma mark Keys++extern NSString *kMRMediaRemoteNowPlayingApplicationPIDUserInfoKey;+extern NSString *kMRMediaRemoteNowPlayingApplicationIsPlayingUserInfoKey;+extern NSString *kMRMediaRemoteNowPlayingInfoAlbum;+extern NSString *kMRMediaRemoteNowPlayingInfoArtist;+extern NSString *kMRMediaRemoteNowPlayingInfoArtworkData;+extern NSString *kMRMediaRemoteNowPlayingInfoArtworkMIMEType;+extern NSString *kMRMediaRemoteNowPlayingInfoChapterNumber;+extern NSString *kMRMediaRemoteNowPlayingInfoComposer;+extern NSString *kMRMediaRemoteNowPlayingInfoDuration;+extern NSString *kMRMediaRemoteNowPlayingInfoElapsedTime;+extern NSString *kMRMediaRemoteNowPlayingInfoGenre;+extern NSString *kMRMediaRemoteNowPlayingInfoIsAdvertisement;+extern NSString *kMRMediaRemoteNowPlayingInfoIsBanned;+extern NSString *kMRMediaRemoteNowPlayingInfoIsInWishList;+extern NSString *kMRMediaRemoteNowPlayingInfoIsLiked;+extern NSString *kMRMediaRemoteNowPlayingInfoIsMusicApp;+extern NSString *kMRMediaRemoteNowPlayingInfoPlaybackRate;+extern NSString *kMRMediaRemoteNowPlayingInfoProhibitsSkip;+extern NSString *kMRMediaRemoteNowPlayingInfoQueueIndex;+extern NSString *kMRMediaRemoteNowPlayingInfoRadioStationIdentifier;+extern NSString *kMRMediaRemoteNowPlayingInfoRepeatMode;+extern NSString *kMRMediaRemoteNowPlayingInfoShuffleMode;+extern NSString *kMRMediaRemoteNowPlayingInfoStartTime;+extern NSString *kMRMediaRemoteNowPlayingInfoSupportsFastForward15Seconds;+extern NSString *kMRMediaRemoteNowPlayingInfoSupportsIsBanned;+extern NSString *kMRMediaRemoteNowPlayingInfoSupportsIsLiked;+extern NSString *kMRMediaRemoteNowPlayingInfoSupportsRewind15Seconds;+extern NSString *kMRMediaRemoteNowPlayingInfoTimestamp;+extern NSString *kMRMediaRemoteNowPlayingInfoTitle;+extern NSString *kMRMediaRemoteNowPlayingInfoTotalChapterCount;+extern NSString *kMRMediaRemoteNowPlayingInfoTotalDiscCount;+extern NSString *kMRMediaRemoteNowPlayingInfoTotalQueueCount;+extern NSString *kMRMediaRemoteNowPlayingInfoTotalTrackCount;+extern NSString *kMRMediaRemoteNowPlayingInfoTrackNumber;+extern NSString *kMRMediaRemoteNowPlayingInfoUniqueIdentifier;+extern NSString *kMRMediaRemoteNowPlayingInfoContentItemIdentifier;+extern NSString *kMRMediaRemoteNowPlayingInfoRadioStationHash;+extern NSString *kMRMediaRemoteNowPlayingInfoMediaType;+extern NSString *kMRMediaRemoteNowPlayingInfoServiceIdentifier;+extern NSString *kMRMediaRemoteOptionMediaType;+extern NSString *kMRMediaRemoteOptionSourceID;+extern NSString *kMRMediaRemoteOptionTrackID;+extern NSString *kMRMediaRemoteOptionStationID;+extern NSString *kMRMediaRemoteOptionStationHash;+extern NSString *kMRMediaRemoteRouteDescriptionUserInfoKey;+extern NSString *kMRMediaRemoteRouteStatusUserInfoKey;++#pragma mark API++typedef enum {+ /*+ * Use nil for userInfo.+ */+ kMRPlay = 0,+ kMRPause = 1,+ kMRTogglePlayPause = 2,+ kMRStop = 3,+ kMRNextTrack = 4,+ kMRPreviousTrack = 5,+ kMRToggleShuffle = 6,+ kMRToggleRepeat = 7,+ kMRStartForwardSeek = 8,+ kMREndForwardSeek = 9,+ kMRStartBackwardSeek = 10,+ kMREndBackwardSeek = 11,+ kMRGoBackFifteenSeconds = 12,+ kMRSkipFifteenSeconds = 13,++ /*+ * Use a NSDictionary for userInfo, which contains three keys:+ * kMRMediaRemoteOptionTrackID+ * kMRMediaRemoteOptionStationID+ * kMRMediaRemoteOptionStationHash+ */+ kMRLikeTrack = 0x6A,+ kMRBanTrack = 0x6B,+ kMRAddTrackToWishList = 0x6C,+ kMRRemoveTrackFromWishList = 0x6D+} MRCommand;++extern CFStringRef MRMediaRemoteSendCommand;+typedef bool (*MRMediaRemoteSendCommand_t)(MRCommand command, id userInfo);++extern CFStringRef MRMediaRemoteSetPlaybackSpeed;+extern CFStringRef MRMediaRemoteSetElapsedTime;+extern CFStringRef MRMediaRemoteSetShuffleMode;+extern CFStringRef MRMediaRemoteSetRepeatMode;+typedef void (*MRMediaRemoteSetPlaybackSpeed_t)(int speed);+typedef void (*MRMediaRemoteSetElapsedTime_t)(double elapsedTime);+typedef void (*MRMediaRemoteSetShuffleMode_t)(int mode);+typedef void (*MRMediaRemoteSetRepeatMode_t)(int mode);++extern CFStringRef MRMediaRemoteRegisterForNowPlayingNotifications;+extern CFStringRef MRMediaRemoteUnregisterForNowPlayingNotifications;+extern CFStringRef MRMediaRemoteGetNowPlayingApplicationPID;+extern CFStringRef MRMediaRemoteGetNowPlayingClient;+extern CFStringRef MRMediaRemoteGetNowPlayingInfo;+extern CFStringRef MRMediaRemoteGetNowPlayingApplicationIsPlaying;++typedef void (*MRMediaRemoteRegisterForNowPlayingNotifications_t)(dispatch_queue_t queue);+typedef void (*MRMediaRemoteUnregisterForNowPlayingNotifications_t)();++typedef void (^MRMediaRemoteGetNowPlayingInfoCompletion_t)(NSDictionary *information);+typedef void (^MRMediaRemoteGetNowPlayingApplicationPIDCompletion_t)(int PID);+typedef void (^MRMediaRemoteGetNowPlayingClientCompletion_t)(id clientObj);+typedef void (^MRMediaRemoteGetNowPlayingApplicationIsPlayingCompletion_t)(bool isPlaying);++typedef void (*MRMediaRemoteGetNowPlayingApplicationPID_t)(dispatch_queue_t queue, MRMediaRemoteGetNowPlayingApplicationPIDCompletion_t completion);+typedef void (*MRMediaRemoteGetNowPlayingClient_t)(dispatch_queue_t queue, MRMediaRemoteGetNowPlayingClientCompletion_t completion);+typedef void (*MRMediaRemoteGetNowPlayingInfo_t)(dispatch_queue_t queue, MRMediaRemoteGetNowPlayingInfoCompletion_t completion);+typedef void (*MRMediaRemoteGetNowPlayingApplicationIsPlaying_t)(dispatch_queue_t queue, MRMediaRemoteGetNowPlayingApplicationIsPlayingCompletion_t completion);++#pragma mark Miscellaneous++extern NSString *kMRNowPlayingClientUserInfoKey;++// Accessed with the kMRNowPlayingClientUserInfoKey+// on the userInfo dictionary of an NSNotification.+@interface MRClient : NSObject {}+-(NSString *)parentApplicationBundleIdentifier;+-(NSString *)bundleIdentifier;+-(NSString *)displayName;+@end++@interface MediaRemote : NSObject+// Commands+@property(readonly) MRMediaRemoteSendCommand_t sendCommand;+// Other controls+@property(readonly) MRMediaRemoteSetPlaybackSpeed_t setPlaybackSpeed;+@property(readonly) MRMediaRemoteSetElapsedTime_t setElapsedTime;+@property(readonly) MRMediaRemoteSetShuffleMode_t setShuffleMode;+@property(readonly) MRMediaRemoteSetRepeatMode_t setRepeatMode;+// Observers+@property(readonly) MRMediaRemoteRegisterForNowPlayingNotifications_t registerForNowPlayingNotifications;+@property(readonly) MRMediaRemoteUnregisterForNowPlayingNotifications_t unregisterForNowPlayingNotifications;+// Metadata+@property(readonly) MRMediaRemoteGetNowPlayingApplicationPID_t getNowPlayingApplicationPID;+@property(readonly) MRMediaRemoteGetNowPlayingClient_t getNowPlayingClient;+@property(readonly) MRMediaRemoteGetNowPlayingInfo_t getNowPlayingInfo;+@property(readonly) MRMediaRemoteGetNowPlayingApplicationIsPlaying_t getNowPlayingApplicationIsPlaying;+// Constructor+-(id)init;+@end++#endif /* MEDIAREMOTE_PRIVATE_H_ */diff --git a/resources/mediaremote-adapter/src/private/MediaRemote.m b/resources/mediaremote-adapter/src/private/MediaRemote.mnew file mode 100644index 000000000..0c6690899--- /dev/null+++ b/resources/mediaremote-adapter/src/private/MediaRemote.m@@ -0,0 +1,114 @@+// clang-format off++#include <Foundation/Foundation.h>++#include "MediaRemote.h"++NSString *kMRMediaRemoteNowPlayingInfoDidChangeNotification = @"kMRMediaRemoteNowPlayingInfoDidChangeNotification";+NSString *kMRMediaRemoteNowPlayingPlaybackQueueDidChangeNotification = @"kMRMediaRemoteNowPlayingPlaybackQueueDidChangeNotification";+NSString *kMRMediaRemotePickableRoutesDidChangeNotification = @"kMRMediaRemotePickableRoutesDidChangeNotification";+NSString *kMRMediaRemoteNowPlayingApplicationDidChangeNotification = @"kMRMediaRemoteNowPlayingApplicationDidChangeNotification";+NSString *kMRMediaRemoteNowPlayingApplicationIsPlayingDidChangeNotification = @"kMRMediaRemoteNowPlayingApplicationIsPlayingDidChangeNotification";++NSString *kMRMediaRemoteRouteStatusDidChangeNotification = @"kMRMediaRemoteRouteStatusDidChangeNotification";+NSString *kMRMediaRemoteNowPlayingApplicationPIDUserInfoKey = @"kMRMediaRemoteNowPlayingApplicationPIDUserInfoKey";+NSString *kMRMediaRemoteNowPlayingApplicationIsPlayingUserInfoKey = @"kMRMediaRemoteNowPlayingApplicationIsPlayingUserInfoKey";+NSString *kMRMediaRemoteNowPlayingInfoAlbum = @"kMRMediaRemoteNowPlayingInfoAlbum";+NSString *kMRMediaRemoteNowPlayingInfoArtist = @"kMRMediaRemoteNowPlayingInfoArtist";+NSString *kMRMediaRemoteNowPlayingInfoArtworkData = @"kMRMediaRemoteNowPlayingInfoArtworkData";+NSString *kMRMediaRemoteNowPlayingInfoArtworkMIMEType = @"kMRMediaRemoteNowPlayingInfoArtworkMIMEType";+NSString *kMRMediaRemoteNowPlayingInfoChapterNumber = @"kMRMediaRemoteNowPlayingInfoChapterNumber";+NSString *kMRMediaRemoteNowPlayingInfoComposer = @"kMRMediaRemoteNowPlayingInfoComposer";+NSString *kMRMediaRemoteNowPlayingInfoDuration = @"kMRMediaRemoteNowPlayingInfoDuration";+NSString *kMRMediaRemoteNowPlayingInfoElapsedTime = @"kMRMediaRemoteNowPlayingInfoElapsedTime";+NSString *kMRMediaRemoteNowPlayingInfoGenre = @"kMRMediaRemoteNowPlayingInfoGenre";+NSString *kMRMediaRemoteNowPlayingInfoIsAdvertisement = @"kMRMediaRemoteNowPlayingInfoIsAdvertisement";+NSString *kMRMediaRemoteNowPlayingInfoIsBanned = @"kMRMediaRemoteNowPlayingInfoIsBanned";+NSString *kMRMediaRemoteNowPlayingInfoIsInWishList = @"kMRMediaRemoteNowPlayingInfoIsInWishList";+NSString *kMRMediaRemoteNowPlayingInfoIsLiked = @"kMRMediaRemoteNowPlayingInfoIsLiked";+NSString *kMRMediaRemoteNowPlayingInfoIsMusicApp = @"kMRMediaRemoteNowPlayingInfoIsMusicApp";+NSString *kMRMediaRemoteNowPlayingInfoPlaybackRate = @"kMRMediaRemoteNowPlayingInfoPlaybackRate";+NSString *kMRMediaRemoteNowPlayingInfoProhibitsSkip = @"kMRMediaRemoteNowPlayingInfoProhibitsSkip";+NSString *kMRMediaRemoteNowPlayingInfoQueueIndex = @"kMRMediaRemoteNowPlayingInfoQueueIndex";+NSString *kMRMediaRemoteNowPlayingInfoRadioStationIdentifier = @"kMRMediaRemoteNowPlayingInfoRadioStationIdentifier";+NSString *kMRMediaRemoteNowPlayingInfoRepeatMode = @"kMRMediaRemoteNowPlayingInfoRepeatMode";+NSString *kMRMediaRemoteNowPlayingInfoShuffleMode = @"kMRMediaRemoteNowPlayingInfoShuffleMode";+NSString *kMRMediaRemoteNowPlayingInfoStartTime = @"kMRMediaRemoteNowPlayingInfoStartTime";+NSString *kMRMediaRemoteNowPlayingInfoSupportsFastForward15Seconds = @"kMRMediaRemoteNowPlayingInfoSupportsFastForward15Seconds";+NSString *kMRMediaRemoteNowPlayingInfoSupportsIsBanned = @"kMRMediaRemoteNowPlayingInfoSupportsIsBanned";+NSString *kMRMediaRemoteNowPlayingInfoSupportsIsLiked = @"kMRMediaRemoteNowPlayingInfoSupportsIsLiked";+NSString *kMRMediaRemoteNowPlayingInfoSupportsRewind15Seconds = @"kMRMediaRemoteNowPlayingInfoSupportsRewind15Seconds";+NSString *kMRMediaRemoteNowPlayingInfoTimestamp = @"kMRMediaRemoteNowPlayingInfoTimestamp";+NSString *kMRMediaRemoteNowPlayingInfoTitle = @"kMRMediaRemoteNowPlayingInfoTitle";+NSString *kMRMediaRemoteNowPlayingInfoTotalChapterCount = @"kMRMediaRemoteNowPlayingInfoTotalChapterCount";+NSString *kMRMediaRemoteNowPlayingInfoTotalDiscCount = @"kMRMediaRemoteNowPlayingInfoTotalDiscCount";+NSString *kMRMediaRemoteNowPlayingInfoTotalQueueCount = @"kMRMediaRemoteNowPlayingInfoTotalQueueCount";+NSString *kMRMediaRemoteNowPlayingInfoTotalTrackCount = @"kMRMediaRemoteNowPlayingInfoTotalTrackCount";+NSString *kMRMediaRemoteNowPlayingInfoTrackNumber = @"kMRMediaRemoteNowPlayingInfoTrackNumber";+NSString *kMRMediaRemoteNowPlayingInfoUniqueIdentifier = @"kMRMediaRemoteNowPlayingInfoUniqueIdentifier";+NSString *kMRMediaRemoteNowPlayingInfoContentItemIdentifier = @"kMRMediaRemoteNowPlayingInfoContentItemIdentifier";+NSString *kMRMediaRemoteNowPlayingInfoRadioStationHash = @"kMRMediaRemoteNowPlayingInfoRadioStationHash";+NSString *kMRMediaRemoteNowPlayingInfoMediaType = @"kMRMediaRemoteNowPlayingInfoMediaType";+NSString *kMRMediaRemoteNowPlayingInfoServiceIdentifier = @"kMRMediaRemoteNowPlayingInfoServiceIdentifier";+NSString *kMRMediaRemoteOptionMediaType = @"kMRMediaRemoteOptionMediaType";+NSString *kMRMediaRemoteOptionSourceID = @"kMRMediaRemoteOptionSourceID";+NSString *kMRMediaRemoteOptionTrackID = @"kMRMediaRemoteOptionTrackID";+NSString *kMRMediaRemoteOptionStationID = @"kMRMediaRemoteOptionStationID";+NSString *kMRMediaRemoteOptionStationHash = @"kMRMediaRemoteOptionStationHash";+NSString *kMRMediaRemoteRouteDescriptionUserInfoKey = @"kMRMediaRemoteRouteDescriptionUserInfoKey";+NSString *kMRMediaRemoteRouteStatusUserInfoKey = @"kMRMediaRemoteRouteStatusUserInfoKey";++CFStringRef MRMediaRemoteSendCommand = CFSTR("MRMediaRemoteSendCommand");++CFStringRef MRMediaRemoteSetPlaybackSpeed = CFSTR("MRMediaRemoteSetPlaybackSpeed");+CFStringRef MRMediaRemoteSetElapsedTime = CFSTR("MRMediaRemoteSetElapsedTime");+CFStringRef MRMediaRemoteSetShuffleMode = CFSTR("MRMediaRemoteSetShuffleMode");+CFStringRef MRMediaRemoteSetRepeatMode = CFSTR("MRMediaRemoteSetRepeatMode");++CFStringRef MRMediaRemoteRegisterForNowPlayingNotifications = CFSTR("MRMediaRemoteRegisterForNowPlayingNotifications");+CFStringRef MRMediaRemoteUnregisterForNowPlayingNotifications = CFSTR("MRMediaRemoteUnregisterForNowPlayingNotifications");+CFStringRef MRMediaRemoteGetNowPlayingApplicationPID = CFSTR("MRMediaRemoteGetNowPlayingApplicationPID");+CFStringRef MRMediaRemoteGetNowPlayingClient = CFSTR("MRMediaRemoteGetNowPlayingClient");+CFStringRef MRMediaRemoteGetNowPlayingInfo = CFSTR("MRMediaRemoteGetNowPlayingInfo");+CFStringRef MRMediaRemoteGetNowPlayingApplicationIsPlaying = CFSTR("MRMediaRemoteGetNowPlayingApplicationIsPlaying");++NSString *kMRNowPlayingClientUserInfoKey = @"kMRNowPlayingClientUserInfoKey";++static NSString *MediaRemoteFrameworkBundleURL = @"/System/Library/PrivateFrameworks/MediaRemote.framework";++@implementation MediaRemote+@synthesize sendCommand;+@synthesize setPlaybackSpeed;+@synthesize setElapsedTime;+@synthesize setShuffleMode;+@synthesize setRepeatMode;+@synthesize registerForNowPlayingNotifications;+@synthesize unregisterForNowPlayingNotifications;+@synthesize getNowPlayingApplicationPID;+@synthesize getNowPlayingClient;+@synthesize getNowPlayingInfo;+@synthesize getNowPlayingApplicationIsPlaying;+-(id)init+{+ if (!(self = [super init])) {+ return nil;+ }+ CFURLRef bundleURL = (__bridge CFURLRef)[NSURL fileURLWithPath:MediaRemoteFrameworkBundleURL];+ CFBundleRef bundle = CFBundleCreate(kCFAllocatorDefault, bundleURL);+ if (!bundle) {+ return nil;+ }+ sendCommand = (MRMediaRemoteSendCommand_t)CFBundleGetFunctionPointerForName(bundle, MRMediaRemoteSendCommand);+ setPlaybackSpeed = (MRMediaRemoteSetPlaybackSpeed_t)CFBundleGetFunctionPointerForName(bundle, MRMediaRemoteSetPlaybackSpeed);+ setElapsedTime = (MRMediaRemoteSetElapsedTime_t)CFBundleGetFunctionPointerForName(bundle, MRMediaRemoteSetElapsedTime);+ setShuffleMode = (MRMediaRemoteSetShuffleMode_t)CFBundleGetFunctionPointerForName(bundle, MRMediaRemoteSetShuffleMode);+ setRepeatMode = (MRMediaRemoteSetRepeatMode_t)CFBundleGetFunctionPointerForName(bundle, MRMediaRemoteSetRepeatMode);+ registerForNowPlayingNotifications = (MRMediaRemoteRegisterForNowPlayingNotifications_t)CFBundleGetFunctionPointerForName(bundle, MRMediaRemoteRegisterForNowPlayingNotifications);+ unregisterForNowPlayingNotifications = (MRMediaRemoteUnregisterForNowPlayingNotifications_t)CFBundleGetFunctionPointerForName(bundle, MRMediaRemoteUnregisterForNowPlayingNotifications);+ getNowPlayingApplicationPID = (MRMediaRemoteGetNowPlayingApplicationPID_t)CFBundleGetFunctionPointerForName(bundle, MRMediaRemoteGetNowPlayingApplicationPID);+ getNowPlayingClient = (MRMediaRemoteGetNowPlayingClient_t)CFBundleGetFunctionPointerForName(bundle, MRMediaRemoteGetNowPlayingClient);+ getNowPlayingInfo = (MRMediaRemoteGetNowPlayingInfo_t)CFBundleGetFunctionPointerForName(bundle, MRMediaRemoteGetNowPlayingInfo);+ getNowPlayingApplicationIsPlaying = (MRMediaRemoteGetNowPlayingApplicationIsPlaying_t)CFBundleGetFunctionPointerForName(bundle, MRMediaRemoteGetNowPlayingApplicationIsPlaying);+ return self;+}+@enddiff --git a/resources/mediaremote-adapter/src/utility/Debounce.h b/resources/mediaremote-adapter/src/utility/Debounce.hnew file mode 100644index 000000000..79795c8bc--- /dev/null+++ b/resources/mediaremote-adapter/src/utility/Debounce.h@@ -0,0 +1,24 @@+// Copyright (c) 2025 Jonas van den Berg+// This file is licensed under the BSD 3-Clause License.++#ifndef MEDIAREMOTEADAPTER_UTILITY_DEBOUNCE_H+#define MEDIAREMOTEADAPTER_UTILITY_DEBOUNCE_H++#import <CoreFoundation/CoreFoundation.h>+#import <Foundation/Foundation.h>++NS_ASSUME_NONNULL_BEGIN++@interface Debounce : NSObject++@property(nonatomic, assign, readonly) NSTimeInterval delay;+- (instancetype)initWithDelay:(NSTimeInterval)delay+ queue:(nullable dispatch_queue_t)queue;+- (void)call:(dispatch_block_t)block;+- (void)cancel;++@end++NS_ASSUME_NONNULL_END++#endif // MEDIAREMOTEADAPTER_UTILITY_DEBOUNCE_Hdiff --git a/resources/mediaremote-adapter/src/utility/Debounce.m b/resources/mediaremote-adapter/src/utility/Debounce.mnew file mode 100644index 000000000..31c41f9fa--- /dev/null+++ b/resources/mediaremote-adapter/src/utility/Debounce.m@@ -0,0 +1,41 @@+// Copyright (c) 2025 Jonas van den Berg+// This file is licensed under the BSD 3-Clause License.++#import "Debounce.h"++@interface Debounce ()++@property(nonatomic, strong) dispatch_queue_t queue;+@property(nonatomic, strong, nullable) dispatch_block_t pendingBlock;+@property(nonatomic, assign, readwrite) NSTimeInterval delay;++@end++@implementation Debounce++- (instancetype)initWithDelay:(NSTimeInterval)delay+ queue:(dispatch_queue_t)queue {+ self = [super init];+ if (self) {+ _delay = MAX(0.0, delay);+ _queue = queue ?: dispatch_get_main_queue();+ }+ return self;+}++- (void)call:(dispatch_block_t)block {+ [self cancel];+ self.pendingBlock = dispatch_block_create(DISPATCH_BLOCK_BARRIER, block);+ dispatch_after(+ dispatch_time(DISPATCH_TIME_NOW, (int64_t)(self.delay * NSEC_PER_SEC)),+ self.queue, self.pendingBlock);+}++- (void)cancel {+ if (self.pendingBlock) {+ dispatch_block_cancel(self.pendingBlock);+ self.pendingBlock = nil;+ }+}++@enddiff --git a/resources/mediaremote-adapter/src/utility/helpers.h b/resources/mediaremote-adapter/src/utility/helpers.hnew file mode 100644index 000000000..006a86714--- /dev/null+++ b/resources/mediaremote-adapter/src/utility/helpers.h@@ -0,0 +1,27 @@+// Copyright (c) 2025 Jonas van den Berg+// This file is licensed under the BSD 3-Clause License.++#ifndef MEDIAREMOTEADAPTER_UTILITY_HELPERS_H+#define MEDIAREMOTEADAPTER_UTILITY_HELPERS_H++#include <stdarg.h>++#import <AppKit/AppKit.h>+#import <Foundation/Foundation.h>++void printOut(NSString *message);+void printOutUnique(NSString *message);+void printErr(NSString *message);+void printErrf(NSString *format, ...);++void fail(NSString *message);+void failf(NSString *format, ...);++NSString *formatError(NSError *error);+NSString *serializeJsonDictionarySafe(NSDictionary *any, bool prettyPrint);++bool appForPID(int pid, void (^block)(NSRunningApplication *));++void makePayloadHumanReadable(NSMutableDictionary *dict);++#endif // MEDIAREMOTEADAPTER_UTILITY_HELPERS_Hdiff --git a/resources/mediaremote-adapter/src/utility/helpers.m b/resources/mediaremote-adapter/src/utility/helpers.mnew file mode 100644index 000000000..02ee0b050--- /dev/null+++ b/resources/mediaremote-adapter/src/utility/helpers.m@@ -0,0 +1,246 @@+// Copyright (c) 2025 Jonas van den Berg+// This file is licensed under the BSD 3-Clause License.++#import "helpers.h"++#include <math.h>+#include <stdio.h>+#include <stdlib.h>++#import <ImageIO/ImageIO.h>+#if __has_include(<UniformTypeIdentifiers/UniformTypeIdentifiers.h>)+#import <UniformTypeIdentifiers/UniformTypeIdentifiers.h>+#else+#import <CoreServices/CoreServices.h>+#endif++#define JSON_NULL @"null";++void printOut(NSString *message) {+ fprintf(stdout, "%s\n", [message UTF8String]);+ fflush(stdout);+}++void printOutUnique(NSString *message) {+ static NSString *previous = nil;+ if (![previous isEqualToString:message]) {+ printOut(message);+ previous = [message copy];+ }+}++void printErr(NSString *message) {+ fprintf(stderr, "%s\n", [message UTF8String]);+ fflush(stderr);+}++void printErrf(NSString *format, ...) {+ va_list args;+ va_start(args, format);+ NSString *formattedMessage = [[NSString alloc] initWithFormat:format+ arguments:args];+ va_end(args);+ fprintf(stderr, "%s\n", [formattedMessage UTF8String]);+ fflush(stderr);+}++void fail(NSString *message) {+ printErr(message);+ exit(1);+}++void failf(NSString *format, ...) {+ va_list args;+ va_start(args, format);+ NSString *formattedMessage = [[NSString alloc] initWithFormat:format+ arguments:args];+ va_end(args);+ fail(formattedMessage);+}++NSString *formatError(NSError *error) {+ return+ [NSString stringWithFormat:@"%@ (%@:%ld)", [error localizedDescription],+ [error domain], (long)[error code]];+}++static id sanitizeValueForJsonEncoding(id value, NSString *parentKey) {+ const id unsupported_type = nil; // remove silently at call site with log+ if ([value isKindOfClass:[NSDictionary class]]) {+ NSDictionary *dictionary = (NSDictionary *)value;+ NSMutableDictionary *result = [NSMutableDictionary dictionary];+ for (id key in dictionary) {+ if (![key isKindOfClass:[NSString class]]) {+ printErrf(@"Invalid JSON key in dictionary: %@ (%@)",+ [key description], [key class]);+ continue;+ }+ id raw = [dictionary objectForKey:key];+ id clean = sanitizeValueForJsonEncoding(raw, key);+ if (clean) {+ result[key] = clean;+ } else {+ printErrf(@"Invalid JSON value type in dictionary for key "+ @"'%@': %@ (%@)",+ key, raw, [raw class]);+ }+ }+ return result;+ } else if ([value isKindOfClass:[NSArray class]]) {+ NSArray *array = (NSArray *)value;+ NSMutableArray *result = [NSMutableArray array];+ for (NSUInteger i = 0; i < array.count; i++) {+ id elem = array[i];+ id clean = sanitizeValueForJsonEncoding(elem, parentKey);+ if (clean) {+ [result addObject:clean];+ } else if (parentKey != nil) {+ printErrf(@"Invalid JSON value type in array at index %d "+ @"under key '%@': %@ (%@)",+ i, parentKey, elem, [elem class]);+ } else {+ printErrf(+ @"Invalid JSON value type in array at index %d: %@ (%@)", i,+ elem, [elem class]);+ }+ }+ return result;+ } else if ([value isKindOfClass:[NSString class]] ||+ [value isKindOfClass:[NSNull class]]) {+ return value;+ } else if ([value isKindOfClass:[NSNumber class]]) {+ NSNumber *number = (NSNumber *)value;+ double unwrapped = [number doubleValue];+ if (isnan(unwrapped) || isinf(unwrapped)) {+ return unsupported_type;+ }+ return value;+ } else if ([value isKindOfClass:[NSDate class]]) {+ static NSDateFormatter *formatter = nil;+ static dispatch_once_t onceToken;+ dispatch_once(&onceToken, ^{+ formatter = [[NSDateFormatter alloc] init];+ formatter.locale =+ [NSLocale localeWithLocaleIdentifier:@"en_US_POSIX"];+ formatter.timeZone = [NSTimeZone timeZoneWithAbbreviation:@"UTC"];+ formatter.dateFormat = @"yyyy-MM-dd'T'HH:mm:ss'Z'";+ });+ return [formatter stringFromDate:(NSDate *)value];+ } else if ([value isKindOfClass:[NSURL class]]) {+ return [(NSURL *)value absoluteString];+ } else if ([value isKindOfClass:[NSData class]]) {+ return [(NSData *)value base64EncodedStringWithOptions:0];+ } else {+ return unsupported_type;+ }+}++static NSDictionary *sanitizeDictionaryForJsonEncoding(NSDictionary *data) {+ return sanitizeValueForJsonEncoding(data, nil);+}++NSString *serializeJsonDictionarySafe(NSDictionary *any, bool prettyPrint) {+ if (any == nil) {+ NSCAssert(false, @"Cannot serialize nil as JSON");+ return JSON_NULL;+ }+ any = sanitizeDictionaryForJsonEncoding(any);+ if (any == nil) {+ NSCAssert(false, @"Sanitized JSON dictionary is nil");+ return JSON_NULL;+ }+ NSCAssert([NSJSONSerialization isValidJSONObject:any],+ @"Sanitized JSON dictionary is not a valid JSON object");+ @try {+ NSError *error;+ NSJSONWritingOptions options =+ prettyPrint ? NSJSONWritingPrettyPrinted : 0;+ NSData *serialized = [NSJSONSerialization dataWithJSONObject:any+ options:options+ error:&error];+ if (!serialized) {+ printErrf(@"Failed to serialize JSON: %@", error);+ return nil;+ }+ return [[NSString alloc] initWithData:serialized+ encoding:NSUTF8StringEncoding];+ } @catch (NSException *exception) {+ if ([exception.name isEqualToString:NSInvalidArgumentException]) {+ printErrf(@"Exception during JSON serialization: %@: %@", exception,+ [any class]);+ } else {+ printErrf(@"Exception during JSON serialization: %@", exception);+ }+ return nil;+ }+}++/*+// Dictionary with invalid values to test sanitization before serialization.+any = @{+ @"validString" : @"Hello",+ @"validNumber" : @123,+ @"invalidDate" : [NSDate date],+ @"invalidURL" : [NSURL URLWithString:@"https://apple.com"],+ @"invalidSet" : [NSSet setWithObjects:@"a", @"b", nil],+ @"nestedDict" : @{@42 : @"badKey", @"validNestedKey" :+ @"nestedValue"},+ @123 : @"badKeyAtRoot",+ @"binaryData" :+ [@"Hello, base64!" dataUsingEncoding:NSUTF8StringEncoding],+ @"invalidArray" : @[+ @"okay", [@"Hello, base64!"+ dataUsingEncoding:NSUTF8StringEncoding]+ ],+};+*/++bool appForPID(int pid, void (^block)(NSRunningApplication *)) {+ if (pid <= 0) {+ return false;+ }+ NSRunningApplication *process =+ [NSRunningApplication runningApplicationWithProcessIdentifier:pid];+ if (process == nil) {+ return false;+ }+ block(process);+ return true;+}++static NSString *guessImageMimeTypeFromData(NSData *data) {+ if (!data)+ return nil;+ CGImageSourceRef src =+ CGImageSourceCreateWithData((__bridge CFDataRef)data, NULL);+ if (!src)+ return nil;+ CFStringRef uti = CGImageSourceGetType(src);+ CFRelease(src);+ if (!uti)+ return nil;+#if __has_include(<UniformTypeIdentifiers/UniformTypeIdentifiers.h>)+ UTType *type = [UTType typeWithIdentifier:(__bridge NSString *)uti];+ return type.preferredMIMEType;+#else+ CFStringRef mime =+ UTTypeCopyPreferredTagWithClass(uti, kUTTagClassMIMEType);+ if (!mime)+ return nil;+ NSString *mimeType = (__bridge_transfer NSString *)mime;+ return mimeType;+#endif+}++void makePayloadHumanReadable(NSMutableDictionary *dict) {+ for (NSString *key in [dict allKeys]) {+ id value = dict[key];+ if ([value isKindOfClass:[NSData class]]) {+ NSString *mimeType = guessImageMimeTypeFromData(value);+ dict[key] = [NSString+ stringWithFormat:@"<%@%@%lu bytes...>", mimeType ?: @"",+ mimeType ? @" " : @"",+ (unsigned long)[value length]];+ }+ }+}diff --git a/scripts/afterPack.js b/scripts/afterPack.jsindex 0840bf4c2..295ab9df5 100644--- a/scripts/afterPack.js+++ b/scripts/afterPack.js@@ -41,7 +41,7 @@ function resolveResourcesDir(context) {: path.join(context.appOutDir, "resources");}-function collectFiles(rootDir) {+function collectFiles(rootDir, skipDirs = new Set()) {if (!fs.existsSync(rootDir)) {return [];}@@ -57,6 +57,7 @@ function collectFiles(rootDir) {const fullPath = path.join(currentDir, entry.name);if (entry.isDirectory()) {+ if (skipDirs.has(fullPath)) continue;queue.push(fullPath);continue;}@@ -70,6 +71,31 @@ function collectFiles(rootDir) {return files;}+function collectFrameworks(rootDir) {+ if (!fs.existsSync(rootDir)) return [];++ const out = [];+ const queue = [rootDir];++ while (queue.length > 0) {+ const currentDir = queue.pop();+ const entries = fs.readdirSync(currentDir, { withFileTypes: true });++ for (const entry of entries) {+ if (!entry.isDirectory()) continue;+ const fullPath = path.join(currentDir, entry.name);+ if (entry.name.endsWith(".framework")) {+ out.push(fullPath);+ // Don't descend into a framework — the bundle is signed as a unit.+ continue;+ }+ queue.push(fullPath);+ }+ }++ return out;+}+function isMachOBinary(filePath) {try {const description = execFileSync("file", ["-b", filePath], {@@ -89,19 +115,22 @@ function registerMacResourceBinariesForSigning(context) {}const resourcesDir = resolveResourcesDir(context);- const machOFiles = collectFiles(resourcesDir).filter(isMachOBinary);+ const frameworks = collectFrameworks(resourcesDir);+ const skipDirs = new Set(frameworks);+ const machOFiles = collectFiles(resourcesDir, skipDirs).filter(isMachOBinary);+ const toRegister = [...frameworks, ...machOFiles];- if (machOFiles.length === 0) {+ if (toRegister.length === 0) {return;}const macConfig = context.packager.platformSpecificBuildOptions;const existingBinaries = Array.isArray(macConfig.binaries) ? macConfig.binaries : [];- macConfig.binaries = [...new Set([...existingBinaries, ...machOFiles])];+ macConfig.binaries = [...new Set([...existingBinaries, ...toRegister])];console.log(- ` afterPack: registered ${machOFiles.length} Mach-O files under Contents/Resources for signing`+ ` afterPack: registered ${frameworks.length} framework(s) and ${machOFiles.length} loose Mach-O file(s) under Contents/Resources for signing`);}diff --git a/scripts/build-mediaremote-adapter.js b/scripts/build-mediaremote-adapter.jsnew file mode 100644index 000000000..ce4ff594e--- /dev/null+++ b/scripts/build-mediaremote-adapter.js@@ -0,0 +1,272 @@+#!/usr/bin/env node++// Builds resources/bin/MediaRemoteAdapter.framework from the vendored+// ungive/mediaremote-adapter sources under resources/mediaremote-adapter/.+//+// The framework is loaded at runtime by /usr/bin/perl, which is the only path+// that can talk to MediaRemote on macOS 15.4+. See src/helpers/mediaPlayer.js+// for the consumer side.++const { spawnSync } = require("child_process");+const crypto = require("crypto");+const fs = require("fs");+const path = require("path");++const isMac = process.platform === "darwin";+if (!isMac) {+ process.exit(0);+}++const archIndex = process.argv.indexOf("--arch");+const targetArch =+ (archIndex !== -1 && process.argv[archIndex + 1]) || process.env.TARGET_ARCH || process.arch;++const ARCH_TO_TARGET = {+ arm64: "arm64-apple-macos11.0",+ x64: "x86_64-apple-macos10.15",+};+const clangTarget = ARCH_TO_TARGET[targetArch];+if (!clangTarget) {+ console.error(`[mra] Unsupported architecture: ${targetArch}`);+ process.exit(1);+}++const projectRoot = path.resolve(__dirname, "..");+const sourceRoot = path.join(projectRoot, "resources", "mediaremote-adapter");+const outputDir = path.join(projectRoot, "resources", "bin");+const frameworkRoot = path.join(outputDir, "MediaRemoteAdapter.framework");+const hashFile = path.join(outputDir, `.MediaRemoteAdapter.${targetArch}.hash`);++const FRAMEWORK_NAME = "MediaRemoteAdapter";+const FRAMEWORK_VERSION = "A";+const BUNDLE_IDENTIFIER = "com.openwhispr.MediaRemoteAdapter";+const SHORT_VERSION = "0.7.6";++const SOURCES = [+ "src/adapter/env.m",+ "src/adapter/get.m",+ "src/adapter/globals.m",+ "src/adapter/keys.m",+ "src/adapter/now_playing.m",+ "src/adapter/repeat.m",+ "src/adapter/seek.m",+ "src/adapter/send.m",+ "src/adapter/shuffle.m",+ "src/adapter/speed.m",+ "src/adapter/stream.m",+ "src/private/MediaRemote.m",+ "src/utility/Debounce.m",+ "src/utility/helpers.m",+];++const PUBLIC_HEADER = "include/MediaRemoteAdapter.h";++// Mach-O CPU type constants for architecture verification+const ARCH_CPU_TYPE = {+ arm64: 0x0100000c,+ x64: 0x01000007,+};++function log(message) {+ console.log(`[mra] ${message}`);+}++function ensureDir(dirPath) {+ if (!fs.existsSync(dirPath)) {+ fs.mkdirSync(dirPath, { recursive: true });+ }+}++function symlinkForce(target, linkPath) {+ try {+ fs.unlinkSync(linkPath);+ } catch {+ // ignored+ }+ fs.symlinkSync(target, linkPath);+}++function verifyDylibArch(dylibPath, expectedArch) {+ try {+ const fd = fs.openSync(dylibPath, "r");+ const header = Buffer.alloc(8);+ fs.readSync(fd, header, 0, 8, 0);+ fs.closeSync(fd);++ const magic = header.readUInt32LE(0);+ if (magic !== 0xfeedfacf) return false;+ return header.readInt32LE(4) === ARCH_CPU_TYPE[expectedArch];+ } catch {+ return false;+ }+}++function hashSources() {+ const hash = crypto.createHash("sha256");+ hash.update(targetArch);+ for (const rel of [...SOURCES, PUBLIC_HEADER].sort()) {+ const full = path.join(sourceRoot, rel);+ hash.update(rel);+ hash.update(fs.readFileSync(full));+ }+ // Also include any headers referenced via #import (cheap: include all .h)+ const headerExtra = walkHeaders(path.join(sourceRoot, "src")).sort();+ for (const h of headerExtra) {+ hash.update(path.relative(sourceRoot, h));+ hash.update(fs.readFileSync(h));+ }+ return hash.digest("hex");+}++function walkHeaders(dir) {+ const out = [];+ for (const entry of fs.readdirSync(dir, { withFileTypes: true })) {+ const p = path.join(dir, entry.name);+ if (entry.isDirectory()) {+ out.push(...walkHeaders(p));+ } else if (entry.isFile() && entry.name.endsWith(".h")) {+ out.push(p);+ }+ }+ return out;+}++// Source hash gate — skip rebuild when nothing changed.+const dylibPath = path.join(frameworkRoot, "Versions", FRAMEWORK_VERSION, FRAMEWORK_NAME);++const currentHash = hashSources();+if (+ fs.existsSync(dylibPath) &&+ verifyDylibArch(dylibPath, targetArch) &&+ fs.existsSync(hashFile) &&+ fs.readFileSync(hashFile, "utf8").trim() === currentHash+) {+ process.exit(0);+}++ensureDir(outputDir);++// Build the framework directory layout:+// MediaRemoteAdapter.framework/+// MediaRemoteAdapter -> Versions/Current/MediaRemoteAdapter+// Headers -> Versions/Current/Headers+// Resources -> Versions/Current/Resources+// Versions/Current -> A+// Versions/A/MediaRemoteAdapter (the dylib)+// Versions/A/Headers/MediaRemoteAdapter.h+// Versions/A/Resources/Info.plist+fs.rmSync(frameworkRoot, { recursive: true, force: true });+const versionRoot = path.join(frameworkRoot, "Versions", FRAMEWORK_VERSION);+ensureDir(path.join(versionRoot, "Headers"));+ensureDir(path.join(versionRoot, "Resources"));++symlinkForce(FRAMEWORK_VERSION, path.join(frameworkRoot, "Versions", "Current"));+symlinkForce(+ path.join("Versions", "Current", FRAMEWORK_NAME),+ path.join(frameworkRoot, FRAMEWORK_NAME)+);+symlinkForce(path.join("Versions", "Current", "Headers"), path.join(frameworkRoot, "Headers"));+symlinkForce(path.join("Versions", "Current", "Resources"), path.join(frameworkRoot, "Resources"));++fs.copyFileSync(+ path.join(sourceRoot, PUBLIC_HEADER),+ path.join(versionRoot, "Headers", `${FRAMEWORK_NAME}.h`)+);++const infoPlist = `<?xml version="1.0" encoding="UTF-8"?>+<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">+<plist version="1.0">+<dict>+\t<key>CFBundleDevelopmentRegion</key>+\t<string>en</string>+\t<key>CFBundleExecutable</key>+\t<string>${FRAMEWORK_NAME}</string>+\t<key>CFBundleIdentifier</key>+\t<string>${BUNDLE_IDENTIFIER}</string>+\t<key>CFBundleInfoDictionaryVersion</key>+\t<string>6.0</string>+\t<key>CFBundleName</key>+\t<string>${FRAMEWORK_NAME}</string>+\t<key>CFBundlePackageType</key>+\t<string>FMWK</string>+\t<key>CFBundleShortVersionString</key>+\t<string>${SHORT_VERSION}</string>+\t<key>CFBundleVersion</key>+\t<string>${SHORT_VERSION}</string>+\t<key>NSPrincipalClass</key>+\t<string></string>+</dict>+</plist>+`;+fs.writeFileSync(path.join(versionRoot, "Resources", "Info.plist"), infoPlist);++const includeFlags = ["-I", path.join(sourceRoot, "include"), "-I", path.join(sourceRoot, "src")];++const commonFlags = [+ "-fobjc-arc",+ "-fvisibility=default",+ "-O2",+ "-target",+ clangTarget,+ ...includeFlags,+];++const dylibOut = path.join(versionRoot, FRAMEWORK_NAME);++const linkFlags = [+ "-dynamiclib",+ "-Wl,-install_name,@rpath/MediaRemoteAdapter.framework/Versions/A/MediaRemoteAdapter",+ "-compatibility_version",+ "1.0.0",+ "-current_version",+ SHORT_VERSION,+ "-framework",+ "Foundation",+ "-framework",+ "AppKit",+ "-framework",+ "ImageIO",+ "-framework",+ "CoreServices",+ "-framework",+ "UniformTypeIdentifiers",+];++const sourceArgs = SOURCES.map((rel) => path.join(sourceRoot, rel));++log(`Building ${FRAMEWORK_NAME}.framework for ${targetArch}`);++const clangArgs = [...commonFlags, ...sourceArgs, ...linkFlags, "-o", dylibOut];++const compile = spawnSync("xcrun", ["clang", ...clangArgs], {+ stdio: "inherit",+});++if (compile.status !== 0) {+ const fallback = spawnSync("clang", clangArgs, { stdio: "inherit" });+ if (fallback.status !== 0) {+ console.error("[mra] Failed to compile MediaRemoteAdapter framework.");+ process.exit(fallback.status ?? 1);+ }+}++if (!verifyDylibArch(dylibOut, targetArch)) {+ console.error(`[mra] FATAL: Compiled dylib architecture does not match target (${targetArch}).`);+ process.exit(1);+}++// Ad-hoc codesign so /usr/bin/perl can dlopen the framework. electron-builder+// will resign this with the developer identity during packaging on signed+// builds; the ad-hoc signature is only relied on for dev runs and CSC_IDENTITY+// _AUTO_DISCOVERY=false packs.+const sign = spawnSync("codesign", ["--force", "--sign", "-", "--timestamp=none", frameworkRoot], {+ stdio: "inherit",+});+if (sign.status !== 0) {+ console.error("[mra] codesign --force --sign - failed");+ process.exit(sign.status ?? 1);+}++fs.writeFileSync(hashFile, currentHash);++log(`Built MediaRemoteAdapter.framework (${targetArch})`);diff --git a/src/helpers/mediaPlayer.js b/src/helpers/mediaPlayer.jsindex b3ccb716b..63b313614 100644--- a/src/helpers/mediaPlayer.js+++ b/src/helpers/mediaPlayer.js@@ -1,8 +1,53 @@-const { spawnSync } = require("child_process");+const { spawn, spawnSync } = require("child_process");const path = require("path");const fs = require("fs");const debugLogger = require("./debugLogger");+// Runs `cmd args` asynchronously and resolves with { status, stdout, stderr }.+// Times out after `timeout` ms; on timeout, kills the child and resolves with+// status: null. Never rejects — callers branch on status === 0.+function spawnAsync(cmd, args, { timeout = 3000 } = {}) {+ return new Promise((resolve) => {+ let child;+ try {+ child = spawn(cmd, args, { stdio: ["ignore", "pipe", "pipe"] });+ } catch (err) {+ resolve({ status: null, stdout: "", stderr: String(err?.message || err) });+ return;+ }++ const chunks = { stdout: [], stderr: [] };+ let settled = false;+ const settle = (status) => {+ if (settled) return;+ settled = true;+ clearTimeout(timer);+ resolve({+ status,+ stdout: Buffer.concat(chunks.stdout).toString("utf8"),+ stderr: Buffer.concat(chunks.stderr).toString("utf8"),+ });+ };++ const timer = setTimeout(() => {+ try {+ child.kill("SIGKILL");+ } catch {+ // ignored+ }+ settle(null);+ }, timeout);++ child.stdout.on("data", (d) => chunks.stdout.push(d));+ child.stderr.on("data", (d) => chunks.stderr.push(d));+ child.on("error", (err) => {+ chunks.stderr.push(Buffer.from(String(err?.message || err)));+ settle(null);+ });+ child.on("close", (code) => settle(code));+ });+}+class MediaPlayer {constructor() {this._linuxBinaryChecked = false;@@ -14,6 +59,9 @@ class MediaPlayer {this._pausedPlayers = []; // MPRIS players we paused (Linux)this._didPause = false; // Whether we sent a pause via toggle fallbackthis._pausedWinApps = []; // GSMTC app IDs we paused (Windows)+ this._adapterChecked = false;+ this._adapterPaths = null; // { perl, script, framework } once resolved+ this._pausedViaAdapter = false; // macOS: whether we paused via the adapter}_resolveLinuxFastPaste() {@@ -92,12 +140,56 @@ class MediaPlayer {return null;}- pauseMedia() {+ // Resolves the vendored mediaremote-adapter Perl entry point and framework.+ // MediaRemote.framework was closed to unprivileged Mach-O processes on+ // macOS 15.4+; the only working state-aware path is to load our adapter+ // framework via /usr/bin/perl, which is system-entitled to talk to it.+ _resolveMediaRemoteAdapter() {+ if (this._adapterChecked) return this._adapterPaths;+ this._adapterChecked = true;++ const perl = "/usr/bin/perl";+ if (!fs.existsSync(perl)) return null;++ const scriptCandidates = [];+ const frameworkCandidates = [];++ if (process.resourcesPath) {+ scriptCandidates.push(path.join(process.resourcesPath, "bin", "mediaremote-adapter.pl"));+ frameworkCandidates.push(+ path.join(process.resourcesPath, "bin", "MediaRemoteAdapter.framework")+ );+ }++ scriptCandidates.push(+ path.join(+ __dirname,+ "..",+ "..",+ "resources",+ "mediaremote-adapter",+ "bin",+ "mediaremote-adapter.pl"+ )+ );+ frameworkCandidates.push(+ path.join(__dirname, "..", "..", "resources", "bin", "MediaRemoteAdapter.framework")+ );++ const script = scriptCandidates.find((p) => fs.existsSync(p));+ const framework = frameworkCandidates.find((p) => fs.existsSync(p));+ if (!script || !framework) return null;++ this._adapterPaths = { perl, script, framework };+ return this._adapterPaths;+ }++ async pauseMedia() {try {if (process.platform === "linux") {return this._pauseLinux();} else if (process.platform === "darwin") {- return this._pauseMacOS();+ return await this._pauseMacOS();} else if (process.platform === "win32") {return this._pauseWindows();}@@ -107,12 +199,12 @@ class MediaPlayer {return false;}- resumeMedia() {+ async resumeMedia() {try {if (process.platform === "linux") {return this._resumeLinux();} else if (process.platform === "darwin") {- return this._resumeMacOS();+ return await this._resumeMacOS();} else if (process.platform === "win32") {return this._resumeWindows();}@@ -122,12 +214,12 @@ class MediaPlayer {return false;}- toggleMedia() {+ async toggleMedia() {try {if (process.platform === "linux") {return this._toggleLinux();} else if (process.platform === "darwin") {- return this._toggleMacOS();+ return await this._toggleMacOS();} else if (process.platform === "win32") {return this._toggleWindows();}@@ -332,89 +424,136 @@ class MediaPlayer {return toggled;}- // --- macOS: MediaRemote-aware pause/resume ---+ // --- macOS: MediaRemote-aware pause/resume (async) ---- _pauseMacOS() {+ async _runAdapter(args, timeout = 3000) {+ const paths = this._resolveMediaRemoteAdapter();+ if (!paths) return null;+ return spawnAsync(paths.perl, [paths.script, paths.framework, ...args], {+ timeout,+ });+ }++ async _pauseMacOS() {this._didPause = false;+ this._pausedViaAdapter = false;++ // Primary path: vendored mediaremote-adapter via /usr/bin/perl. Works on+ // macOS 15.4+ where the framework is closed to user processes.+ const probe = await this._runAdapter(["get", "--no-artwork"]);+ if (probe && probe.status === 0) {+ const output = (probe.stdout || "").trim();+ let playing = null;+ if (output && output !== "null") {+ try {+ playing = !!JSON.parse(output).playing;+ } catch {+ playing = null;+ }+ } else if (output === "null") {+ playing = false;+ }- // Try MediaRemote binary first (state-aware, no toggle)- const binary = this._resolveMacMediaRemote();- if (binary) {- const result = spawnSync(binary, ["--pause"], {- stdio: "pipe",- timeout: 3000,- });- if (result.status === 0) {- debugLogger.debug("Media paused via MediaRemote", {}, "media");- this._didPause = true;- return true;+ if (playing === false) {+ debugLogger.debug("Adapter reports no media playing", {}, "media");+ return false;}- // exit 1 = nothing was playing, don't fallback to toggle- const output = (result.stdout?.toString() || "").trim();- if (output === "NOT_PLAYING") return false;++ if (playing === true) {+ // 1 = kMRAPause+ const pause = await this._runAdapter(["send", "1"]);+ if (pause && pause.status === 0) {+ debugLogger.debug("Media paused via adapter", {}, "media");+ this._pausedViaAdapter = true;+ this._didPause = true;+ return true;+ }+ debugLogger.debug(+ "Adapter send pause failed",+ {+ status: pause?.status,+ stderr: (pause?.stderr || "").trim().slice(0, 200),+ },+ "media"+ );+ }+ } else if (probe) {+ debugLogger.debug(+ "Adapter get failed, falling back to media key",+ {+ status: probe.status,+ stderr: (probe.stderr || "").trim().slice(0, 200),+ },+ "media"+ );}- // Fallback to media key toggle- debugLogger.debug("MediaRemote unavailable, falling back to osascript", {}, "media");- if (this._sendMacMediaKey()) {+ // Fallback: post a real media-key CGEvent. We don't know whether anything+ // is playing, so this can spuriously start playback — same toggle risk+ // the binary-based path had pre-adapter.+ if (await this._sendMacMediaKey()) {this._didPause = true;return true;}return false;}- _resumeMacOS() {+ async _resumeMacOS() {if (!this._didPause) return false;+ const usedAdapter = this._pausedViaAdapter;this._didPause = false;+ this._pausedViaAdapter = false;- const binary = this._resolveMacMediaRemote();- if (binary) {- const result = spawnSync(binary, ["--play"], {- stdio: "pipe",- timeout: 3000,- });- if (result.status === 0) {- debugLogger.debug("Media resumed via MediaRemote", {}, "media");+ if (usedAdapter) {+ // 0 = kMRAPlay+ const play = await this._runAdapter(["send", "0"]);+ if (play && play.status === 0) {+ debugLogger.debug("Media resumed via adapter", {}, "media");return true;}+ debugLogger.debug(+ "Adapter send play failed, falling back to media key",+ {+ status: play?.status,+ stderr: (play?.stderr || "").trim().slice(0, 200),+ },+ "media"+ );}- // Fallback to media key togglereturn this._sendMacMediaKey();}- _sendMacMediaKey() {- const result = spawnSync(- "osascript",- ["-e", 'tell application "System Events" to key code 100'],- {- stdio: "pipe",- timeout: 3000,- }- );+ // Posts a real NX_KEYTYPE_PLAY system-defined NSEvent via the bundled+ // helper. Media apps only respond to that event class — synthetic F-key+ // codes (osascript "key code") are not media keys and land in the focused+ // app as plain keystrokes instead.+ async _sendMacMediaKey() {+ const binary = this._resolveMacMediaRemote();+ if (!binary) return false;++ const result = await spawnAsync(binary, ["--media-key-toggle"], {+ timeout: 3000,+ });if (result.status === 0) {- debugLogger.debug("Media key sent via osascript", {}, "media");+ debugLogger.debug("Media key sent via CGEvent helper", {}, "media");return true;}- return false;- }-- _toggleMacOS() {- const result = spawnSync(- "osascript",- ["-e", 'tell application "System Events" to key code 100'],+ debugLogger.debug(+ "CGEvent media-key helper failed",{- stdio: "pipe",- timeout: 3000,- }+ status: result.status,+ stderr: (result.stderr || "").trim().slice(0, 200),+ },+ "media");- if (result.status === 0) {- debugLogger.debug("Media toggled via osascript", {}, "media");- return true;- }return false;}+ async _toggleMacOS() {+ return this._sendMacMediaKey();+ }+// --- Windows: GSMTC-aware pause/resume ---// WinRT IAsyncOperation objects appear as opaque System.__ComObject in