fix: async MPV commands to prevent ANR

This commit is contained in:
edde746
2026-01-20 01:14:45 +01:00
parent e18a9457dd
commit 9721e6bf3f
12 changed files with 397 additions and 10 deletions
@@ -52,6 +52,11 @@ class MpvPlayerCore: NSObject {
private var hdrEnabled = true // User preference for HDR
private var lastSigPeak: Double = 0.0 // Last known sig-peak for re-evaluation
// Async command tracking to prevent UI blocking
private var pendingCommands: [UInt64: (Result<Void, Error>) -> Void] = [:]
private var pendingCommandsLock = NSLock()
private var nextRequestId: UInt64 = 1
// MARK: - Initialization
func initialize(in window: NSWindow) -> Bool {
@@ -204,6 +209,50 @@ class MpvPlayerCore: NSObject {
command(args[0], args: Array(args.dropFirst()))
}
/// Execute an MPV command asynchronously to prevent UI blocking.
/// Uses mpv_command_async which returns immediately; the completion is called
/// when MPV_EVENT_COMMAND_REPLY is received.
func commandAsync(_ args: [String], completion: @escaping (Result<Void, Error>) -> Void) {
guard let mpv = mpv, !args.isEmpty else {
completion(.success(()))
return
}
// Generate unique request ID
pendingCommandsLock.lock()
let requestId = nextRequestId
nextRequestId += 1
pendingCommands[requestId] = completion
pendingCommandsLock.unlock()
// Build array of C strings for mpv_command_async
var cargs: [UnsafeMutablePointer<CChar>?] = args.map { strdup($0) }
cargs.append(nil) // null-terminate
// mpv_command_async returns immediately
cargs.withUnsafeBufferPointer { buffer in
var constPtrs = buffer.map { UnsafePointer($0) }
let result = mpv_command_async(mpv, requestId, &constPtrs)
if result < 0 {
// Command submission failed, complete immediately with error
pendingCommandsLock.lock()
if let pending = pendingCommands.removeValue(forKey: requestId) {
pendingCommandsLock.unlock()
let error = NSError(domain: "mpv", code: Int(result),
userInfo: [NSLocalizedDescriptionKey: String(cString: mpv_error_string(result))])
DispatchQueue.main.async { pending(.failure(error)) }
} else {
pendingCommandsLock.unlock()
}
}
}
// Free the C strings
for ptr in cargs {
free(ptr)
}
}
// MARK: - Visibility
func setVisible(_ visible: Bool) {
@@ -288,6 +337,23 @@ class MpvPlayerCore: NSObject {
let name = String(cString: property.name)
handlePropertyChange(name: name, property: property)
case MPV_EVENT_COMMAND_REPLY:
// Handle async command completion
let requestId = event.reply_userdata
pendingCommandsLock.lock()
let completion = pendingCommands.removeValue(forKey: requestId)
pendingCommandsLock.unlock()
if let completion = completion {
if event.error < 0 {
let error = NSError(domain: "mpv", code: Int(event.error),
userInfo: [NSLocalizedDescriptionKey: String(cString: mpv_error_string(event.error))])
DispatchQueue.main.async { completion(.failure(error)) }
} else {
DispatchQueue.main.async { completion(.success(())) }
}
}
case MPV_EVENT_FILE_LOADED:
DispatchQueue.main.async {
self.delegate?.onEvent(name: "file-loaded", data: nil)
@@ -441,6 +507,19 @@ class MpvPlayerCore: NSObject {
// MARK: - Cleanup
func dispose() {
// Cancel any pending async commands
pendingCommandsLock.lock()
let pending = pendingCommands
pendingCommands.removeAll()
pendingCommandsLock.unlock()
// Complete pending commands with cancellation error
let cancelError = NSError(domain: "mpv", code: -1,
userInfo: [NSLocalizedDescriptionKey: "Player disposed"])
for (_, completion) in pending {
DispatchQueue.main.async { completion(.failure(cancelError)) }
}
// Capture handle before clearing to avoid weak captures during deinit
let mpvHandle = mpv
mpv = nil
+9 -2
View File
@@ -178,8 +178,15 @@ class MpvPlayerPlugin: NSObject, FlutterPlugin, FlutterStreamHandler, MpvPlayerD
return
}
playerCore?.command(commandArgs)
result(nil)
// Use async command to prevent UI blocking during network operations
playerCore?.commandAsync(commandArgs) { commandResult in
switch commandResult {
case .success:
result(nil)
case .failure(let error):
result(FlutterError(code: "COMMAND_FAILED", message: error.localizedDescription, details: nil))
}
} ?? result(nil)
}
private func handleSetVisible(call: FlutterMethodCall, result: @escaping FlutterResult) {