Skip to content

Instantly share code, notes, and snippets.

@samsonjs
Created July 11, 2024 06:27
Show Gist options
  • Save samsonjs/b87ead39339d0152c4f25158897b21e3 to your computer and use it in GitHub Desktop.
Save samsonjs/b87ead39339d0152c4f25158897b21e3 to your computer and use it in GitHub Desktop.
Task cancellation in a dispatch queue world of AVAssetWriterInputs
actor SampleWriter {
// ...
var isCancelled = false
// ...
func cancel() async {
isCancelled = true
}
private func encodeAudioTracks() async {
// Don't do anything when we have no audio to encode.
guard audioInput != nil, audioOutput != nil else { return }
return await withTaskCancellationHandler {
await withCheckedContinuation { continuation in
self.audioInput!.requestMediaDataWhenReady(on: queue) {
self.assumeIsolated { _self in
guard !_self.isCancelled else {
log.debug("Cancelled while encoding audio")
_self.reader.cancelReading()
_self.writer.cancelWriting()
continuation.resume()
return
}
let hasMoreSamples = _self.writeReadySamples(
output: _self.audioOutput!,
input: _self.audioInput!
)
if !hasMoreSamples {
log.debug("Finished encoding audio")
continuation.resume()
}
}
}
}
} onCancel: {
log.debug("Task cancelled while encoding audio")
Task {
await self.cancel()
}
}
}
private func encodeVideoTracks() async {
return await withTaskCancellationHandler {
await withCheckedContinuation { continuation in
self.videoInput!.requestMediaDataWhenReady(on: queue) {
self.assumeIsolated { _self in
guard !_self.isCancelled else {
log.debug("Cancelled while encoding video")
_self.reader.cancelReading()
_self.writer.cancelWriting()
continuation.resume()
return
}
let hasMoreSamples = _self.writeReadySamples(
output: _self.videoOutput!,
input: _self.videoInput!
)
if !hasMoreSamples {
log.debug("Finished encoding video")
continuation.resume()
}
}
}
}
} onCancel: {
log.debug("Task cancelled while encoding video")
Task {
await self.cancel()
}
}
}
// ...
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment