Skip to content
This repository has been archived by the owner on Sep 16, 2023. It is now read-only.

Commit

Permalink
Fix deadlock in ViewLayer.draw methods, #11
Browse files Browse the repository at this point in the history
The commit changes the order of acquiring locks in both of the ViewLayer draw
methods to first lock the OpenGL context before locking uninitLock.
  • Loading branch information
low-batt authored and CarterLi committed Jan 21, 2022
1 parent 4d86523 commit d75e6a3
Showing 1 changed file with 16 additions and 11 deletions.
27 changes: 16 additions & 11 deletions iina/ViewLayer.swift
Original file line number Diff line number Diff line change
Expand Up @@ -101,15 +101,20 @@ class ViewLayer: CAOpenGLLayer {
let mpv = videoView.player.mpv!
needsMPVRender = false

// Previously uninitLock was locked first. This caused a deadlock when locking was added to the
// other draw method in that same order. Apple documentation is unclear but one example from
// Apple has a comment indicating the OpenGL context is set before calling this method. It may
// already be locked as well since switching the order of locking solved the deadlock.
// Continuing to lock and set the context just to be sure.
CGLLockContext(ctx)
CGLSetCurrentContext(ctx)
videoView.uninitLock.lock()

guard !videoView.isUninited else {
defer {
videoView.uninitLock.unlock()
return
CGLUnlockContext(ctx)
}

CGLLockContext(ctx)
CGLSetCurrentContext(ctx)
guard !videoView.isUninited else { return }

glClear(GLbitfield(GL_COLOR_BUFFER_BIT))

Expand Down Expand Up @@ -143,9 +148,6 @@ class ViewLayer: CAOpenGLLayer {
}
}
glFlush()

CGLUnlockContext(ctx)
videoView.uninitLock.unlock()
}

func suspend() {
Expand All @@ -168,10 +170,15 @@ class ViewLayer: CAOpenGLLayer {
return
}
if needsMPVRender {
// Order of locking must match the other draw method.
videoView.player.mpv?.lockAndSetOpenGLContext()
videoView.uninitLock.lock()
defer {
videoView.uninitLock.unlock()
videoView.player.mpv?.unlockOpenGLContext()
}
// draw(inCGLContext:) is not called, needs a skip render
if !videoView.isUninited, let renderContext = videoView.player.mpv?.mpvRenderContext {
videoView.player.mpv?.lockAndSetOpenGLContext()
var skip: CInt = 1
withUnsafeMutablePointer(to: &skip) { skip in
var params: [mpv_render_param] = [
Expand All @@ -180,9 +187,7 @@ class ViewLayer: CAOpenGLLayer {
]
mpv_render_context_render(renderContext, &params);
}
videoView.player.mpv?.unlockOpenGLContext()
}
videoView.uninitLock.unlock()
needsMPVRender = false
}
}
Expand Down

0 comments on commit d75e6a3

Please sign in to comment.