AVAssetExportSession stalls at the first run

28 Views Asked by At

In my iOS application I am using AVAssetExportSession in order to compress the video file

if let exportSession = AVAssetExportSession(asset: singleVideoComposition, presetName: AVAssetExportPresetMediumQuality) {
                
   exportSession.outputFileType = .mp4
   exportSession.timeRange = videoTrack.timeRange
                
   await exportSession.export() // cause a main thread to stall when called for the very first time
                
   if exportSession.status == .completed {
      completion(outputURL)
   } else {
      completion(nil)
   }
}

This code is running inside Task. The issue is - on the very first compression it stalls the main thread for 1-2 seconds which causes unpleasant feeling in UI. After first use, it does not stall main thread at all, it works in the background and UI is nice and smooth.

Why is this happening and how to adress that issue? Thank you!

1

There are 1 best solutions below

2
Luca Angeletti On

Just my 2 cents.

This code is running inside Task

If you create that Task from the main actor, then you are running the code on the main actor itself.

To check that add this line

print("Task.isMainActor: \(Task.isMainActor)")

Once confirmed that you are on the main actor, let's focus on this

await exportSession.export()

We don't know where the export function runs the operation.

  • It might be on the inherited actor (in this case it explains the UI lag).
  • Or it might be a specific actor (in this case the next steps won't help probably).

But you can try!

When you create the Task you mentioned, make sure it's not on the main actor using this code.

Task(priority: .background) {
        
}