Skip to content

Commit

Permalink
Decode on a background thread
Browse files Browse the repository at this point in the history
  • Loading branch information
kornelski committed Feb 1, 2018
1 parent df06e76 commit 97d3655
Showing 1 changed file with 11 additions and 23 deletions.
34 changes: 11 additions & 23 deletions Gifski/AppDelegate.swift
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,6 @@ extension AVAssetImageGenerator {
@NSApplicationMain
final class AppDelegate: NSObject, NSApplicationDelegate {
@IBOutlet private weak var window: NSWindow!
var g: OpaquePointer!

func applicationShouldTerminateAfterLastWindowClosed(_ sender: NSApplication) -> Bool {
return true
Expand All @@ -24,8 +23,13 @@ final class AppDelegate: NSObject, NSApplicationDelegate {
func gifski(inputFile: URL, outputFile: URL) {
var settings = GifskiSettings(width: 0, height: 0, quality: 100, once: false, fast: false)
let g = gifski_new(&settings)
self.g = g

gifski_set_progress_callback(g) { isDone in
print("isDone", isDone)
return 1
}

DispatchQueue.global(qos: .background).async {
let asset = AVURLAsset(url: inputFile, options: nil)
let generator = AVAssetImageGenerator(asset: asset)
generator.requestedTimeToleranceAfter = kCMTimeZero
Expand All @@ -35,27 +39,15 @@ final class AppDelegate: NSObject, NSApplicationDelegate {
let frameCount = Int(asset.duration.seconds) * FPS
var frameForTimes = [CMTime]()

// for i in 0..<frameCount {
// frameForTimes.append(CMTimeMake(Int64(i), Int32(FPS)))
// }

frameForTimes.append(CMTimeMake(1, Int32(FPS)))
frameForTimes.append(CMTimeMake(2, Int32(FPS)))
frameForTimes.append(CMTimeMake(3, Int32(FPS)))
frameForTimes.append(CMTimeMake(4, Int32(FPS)))

// FIXME: Hangs when this is enabled
// frameForTimes.append(CMTimeMake(5, Int32(FPS)))

gifski_set_progress_callback(g) { isDone in
print("isDone", isDone)

return 1
for i in 0..<frameCount {
frameForTimes.append(CMTimeMake(Int64(i), Int32(FPS)))
}

var i = 0

generator.generateCGImagesAsynchronouslyForTimePoints(frameForTimes) { _, image, _, _, error in
print("Frame:", i)

guard let image = image, error == nil else {
fatalError("Error with image \(i): \(error!)")
}
Expand All @@ -66,18 +58,14 @@ final class AppDelegate: NSObject, NSApplicationDelegate {
let result = gifski_add_frame_rgba(g, UInt32(i), UInt32(image.width), UInt32(image.height), buffer, UInt16(100 / FPS))
precondition(result == GIFSKI_OK, String(describing: result))

print("Frame:", i)

i += 1

if i == frameForTimes.count {
self.done(outputFile: outputFile)
gifski_end_adding_frames(g)
}
}
}

func done(outputFile: URL) {
gifski_end_adding_frames(g)
gifski_write(g, outputFile.path)
gifski_drop(g)
}
Expand Down

0 comments on commit 97d3655

Please sign in to comment.