Skip to content

Main thread isolation in VideoView #659

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 4 commits into from
Apr 4, 2025
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions .nanpa/swift-6-video-view-crash.kdl
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
patch type="fixed" "Swift 6: Fixed crash in VideoView with .v6 language mode"
2 changes: 1 addition & 1 deletion Sources/LiveKit/Support/StateSync.swift
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,7 @@ import Foundation
public final class StateSync<State>: @unchecked Sendable {
// MARK: - Types

public typealias OnDidMutate = (_ newState: State, _ oldState: State) -> Void
public typealias OnDidMutate = @Sendable (_ newState: State, _ oldState: State) -> Void

// MARK: - Public

Expand Down
16 changes: 14 additions & 2 deletions Sources/LiveKit/Views/VideoView.swift
Original file line number Diff line number Diff line change
Expand Up @@ -285,7 +285,7 @@ public class VideoView: NativeView, Loggable {

// Enter .main only if UI updates are required
if trackDidUpdate || shouldRenderDidUpdate || renderModeDidUpdate {
self.mainSyncOrAsync {
self.mainSyncOrAsync { @MainActor in
Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This MainActor is necessary only for <5.9 due to lack of assumeIsolate as you see below 🫳

var didReCreateNativeRenderer = false

if trackDidUpdate || shouldRenderDidUpdate {
Expand Down Expand Up @@ -862,7 +862,18 @@ extension LKRTCMTLVideoView: Mirrorable {
#endif

private extension VideoView {
func mainSyncOrAsync(operation: @escaping () -> Void) {
#if compiler(>=5.9)
nonisolated func mainSyncOrAsync(operation: @MainActor @escaping () -> Void) {
if Thread.current.isMainThread {
MainActor.assumeIsolated(operation)
} else {
Task { @MainActor in
operation()
}
}
}
#else
nonisolated func mainSyncOrAsync(operation: @escaping () -> Void) {
if Thread.current.isMainThread {
operation()
} else {
Expand All @@ -871,6 +882,7 @@ private extension VideoView {
}
}
}
#endif
}

#if os(iOS)
Expand Down
Loading