Roll.swift (6106B)
1 // SPDX-License-Identifier: GPL-2.0-only 2 // Each shot is written to disk (Documents/pellicule) then transferred to Photos right away: 3 // nothing depends on the end of the dive, and a shot left there after a crash goes at the next 4 // launch. For the gallery, the app only keeps a reduced image of each shot of the session 5 // (it is only allowed to add to the photo library, not to read it back). 6 // The folder names ("pellicule", "apercus") are French for compatibility with existing installs, 7 // which may still hold shots there: do not rename them. 8 import AVFoundation 9 import ImageIO 10 import Photos 11 import UIKit 12 13 struct RollItem: Identifiable, Equatable, Sendable { 14 let url: URL 15 var id: String { url.lastPathComponent } 16 var isVideo: Bool { url.pathExtension == "mov" } 17 /// ProRAW negative taken with the photo, if any. 18 var rawURL: URL? { 19 let raw = url.deletingPathExtension().appendingPathExtension("dng") 20 return FileManager.default.fileExists(atPath: raw.path) ? raw : nil 21 } 22 } 23 24 enum Roll { 25 static var directory: URL { 26 let url = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask)[0].appendingPathComponent("pellicule") 27 try? FileManager.default.createDirectory(at: url, withIntermediateDirectories: true) 28 return url 29 } 30 31 /// Timestamped name (alphabetical order is shooting order), without extension. 32 static func newBase() -> URL { 33 let format = DateFormatter() 34 format.dateFormat = "yyyyMMdd-HHmmss-SSS" 35 return directory.appendingPathComponent("merou-\(format.string(from: Date()))") 36 } 37 38 static func items() -> [RollItem] { 39 ((try? FileManager.default.contentsOfDirectory(at: directory, includingPropertiesForKeys: nil)) ?? []) 40 .filter { ["heic", "mov"].contains($0.pathExtension) } 41 .sorted { $0.lastPathComponent < $1.lastPathComponent } 42 .map(RollItem.init) 43 } 44 45 // MARK: Previews of the session (gallery) 46 47 static var previewDirectory: URL { 48 let url = FileManager.default.urls(for: .cachesDirectory, in: .userDomainMask)[0].appendingPathComponent("apercus") 49 try? FileManager.default.createDirectory(at: url, withIntermediateDirectories: true) 50 return url 51 } 52 53 /// Previews of the session, oldest first; a video has "-video" in its name. 54 static func previews() -> [URL] { 55 ((try? FileManager.default.contentsOfDirectory(at: previewDirectory, includingPropertiesForKeys: nil)) ?? []) 56 .filter { $0.pathExtension == "jpg" }.sorted { $0.lastPathComponent < $1.lastPathComponent } 57 } 58 59 static func clearPreviews() { 60 try? FileManager.default.removeItem(at: previewDirectory) 61 } 62 63 private static func previewURL(for item: RollItem) -> URL { 64 let base = item.url.deletingPathExtension().lastPathComponent + (item.isVideo ? "-video" : "") 65 return previewDirectory.appendingPathComponent(base).appendingPathExtension("jpg") 66 } 67 68 /// Makes the preview of a shot when it is missing (before the transfer, which moves the file). 69 static func makePreview(_ item: RollItem) async { 70 let target = previewURL(for: item) 71 guard !FileManager.default.fileExists(atPath: target.path), let image = await preview(item), 72 let data = image.jpegData(compressionQuality: 0.8) else { return } 73 try? data.write(to: target, options: .atomic) 74 } 75 76 static func delete(_ item: RollItem) { 77 if let raw = item.rawURL { try? FileManager.default.removeItem(at: raw) } 78 try? FileManager.default.removeItem(at: item.url) 79 } 80 81 /// Reduced image for the screen (a photo is up to 48 MP); first frame for a video. 82 static func preview(_ item: RollItem, maxPixel: Int = 1600) async -> UIImage? { 83 if item.isVideo { 84 let generator = AVAssetImageGenerator(asset: AVURLAsset(url: item.url)) 85 generator.appliesPreferredTrackTransform = true 86 generator.maximumSize = CGSize(width: maxPixel, height: maxPixel) 87 guard let frame = try? await generator.image(at: .zero).image else { return nil } 88 return UIImage(cgImage: frame) 89 } 90 let options: [CFString: Any] = [ 91 kCGImageSourceCreateThumbnailFromImageAlways: true, kCGImageSourceCreateThumbnailWithTransform: true, 92 kCGImageSourceThumbnailMaxPixelSize: maxPixel, 93 ] 94 guard let source = CGImageSourceCreateWithURL(item.url as CFURL, nil), 95 let image = CGImageSourceCreateThumbnailAtIndex(source, 0, options as CFDictionary) else { return nil } 96 return UIImage(cgImage: image) 97 } 98 99 /// Transfers the whole roll to Photos, one shot at a time; only deletes what has been transferred. 100 static func export(done: @escaping @Sendable (_ moved: Int, _ problem: String?) -> Void) { 101 let pending = items() 102 guard !pending.isEmpty else { done(0, nil); return } 103 PHPhotoLibrary.requestAuthorization(for: .addOnly) { status in 104 guard status == .authorized || status == .limited else { 105 done(0, String(localized: "photo library access denied (shots stay in Files → Open Mérou)")) 106 return 107 } 108 exportNext(pending[...], moved: 0, done: done) 109 } 110 } 111 112 private static func exportNext(_ rest: ArraySlice<RollItem>, moved: Int, done: @escaping @Sendable (Int, String?) -> Void) { 113 guard let item = rest.first else { done(moved, nil); return } 114 PHPhotoLibrary.shared().performChanges { 115 let request = PHAssetCreationRequest.forAsset() 116 request.addResource(with: item.isVideo ? .video : .photo, fileURL: item.url, options: nil) 117 if let raw = item.rawURL { request.addResource(with: .alternatePhoto, fileURL: raw, options: nil) } 118 } completionHandler: { ok, error in 119 guard ok else { done(moved, error?.localizedDescription ?? String(localized: "transfer failed")); return } 120 delete(item) 121 exportNext(rest.dropFirst(), moved: moved + 1, done: done) 122 } 123 } 124 }