NCLivePhoto.swift 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473
  1. //
  2. // LivePhoto.swift
  3. // NCLivePhoto
  4. //
  5. // Created by Alexander Pagliaro on 7/25/18.
  6. // Copyright © 2018 Limit Point LLC. All rights reserved.
  7. //
  8. import UIKit
  9. import AVFoundation
  10. import MobileCoreServices
  11. import Photos
  12. class NCLivePhoto {
  13. // MARK: PUBLIC
  14. typealias LivePhotoResources = (pairedImage: URL, pairedVideo: URL)
  15. /// Returns the paired image and video for the given PHLivePhoto
  16. public class func extractResources(from livePhoto: PHLivePhoto, completion: @escaping (LivePhotoResources?) -> Void) {
  17. queue.async {
  18. shared.extractResources(from: livePhoto, completion: completion)
  19. }
  20. }
  21. /// Generates a PHLivePhoto from an image and video. Also returns the paired image and video.
  22. public class func generate(from imageURL: URL?, videoURL: URL, progress: @escaping (CGFloat) -> Void, completion: @escaping (PHLivePhoto?, LivePhotoResources?) -> Void) {
  23. queue.async {
  24. shared.generate(from: imageURL, videoURL: videoURL, progress: progress, completion: completion)
  25. }
  26. }
  27. /// Save a Live Photo to the Photo Library by passing the paired image and video.
  28. public class func saveToLibrary(_ resources: LivePhotoResources, completion: @escaping (Bool) -> Void) {
  29. PHPhotoLibrary.shared().performChanges({
  30. let creationRequest = PHAssetCreationRequest.forAsset()
  31. let options = PHAssetResourceCreationOptions()
  32. creationRequest.addResource(with: PHAssetResourceType.pairedVideo, fileURL: resources.pairedVideo, options: options)
  33. creationRequest.addResource(with: PHAssetResourceType.photo, fileURL: resources.pairedImage, options: options)
  34. }, completionHandler: { (success, error) in
  35. if error != nil {
  36. print(error as Any)
  37. }
  38. completion(success)
  39. })
  40. }
  41. // MARK: PRIVATE
  42. private static let shared = NCLivePhoto()
  43. private static let queue = DispatchQueue(label: "com.limit-point.LivePhotoQueue", attributes: .concurrent)
  44. lazy private var cacheDirectory: URL? = {
  45. if let cacheDirectoryURL = try? FileManager.default.url(for: .cachesDirectory, in: .userDomainMask, appropriateFor: nil, create: false) {
  46. let fullDirectory = cacheDirectoryURL.appendingPathComponent("com.limit-point.LivePhoto", isDirectory: true)
  47. if !FileManager.default.fileExists(atPath: fullDirectory.absoluteString) {
  48. try? FileManager.default.createDirectory(at: fullDirectory, withIntermediateDirectories: true, attributes: nil)
  49. }
  50. return fullDirectory
  51. }
  52. return nil
  53. }()
  54. deinit {
  55. clearCache()
  56. }
  57. private func generateKeyPhoto(from videoURL: URL) -> URL? {
  58. var percent:Float = 0.5
  59. let videoAsset = AVURLAsset(url: videoURL)
  60. if let stillImageTime = videoAsset.stillImageTime() {
  61. percent = Float(stillImageTime.value) / Float(videoAsset.duration.value)
  62. }
  63. guard let imageFrame = videoAsset.getAssetFrame(percent: percent) else { return nil }
  64. guard let jpegData = imageFrame.jpegData(compressionQuality: 1) else { return nil }
  65. guard let url = cacheDirectory?.appendingPathComponent(UUID().uuidString).appendingPathExtension("jpg") else { return nil }
  66. do {
  67. try? jpegData.write(to: url)
  68. return url
  69. }
  70. }
  71. private func clearCache() {
  72. if let cacheDirectory = cacheDirectory {
  73. try? FileManager.default.removeItem(at: cacheDirectory)
  74. }
  75. }
  76. private func generate(from imageURL: URL?, videoURL: URL, progress: @escaping (CGFloat) -> Void, completion: @escaping (PHLivePhoto?, LivePhotoResources?) -> Void) {
  77. guard let cacheDirectory = cacheDirectory else {
  78. DispatchQueue.main.async {
  79. completion(nil, nil)
  80. }
  81. return
  82. }
  83. let assetIdentifier = UUID().uuidString
  84. let _keyPhotoURL = imageURL ?? generateKeyPhoto(from: videoURL)
  85. guard let keyPhotoURL = _keyPhotoURL, let pairedImageURL = addAssetID(assetIdentifier, toImage: keyPhotoURL, saveTo: cacheDirectory.appendingPathComponent(assetIdentifier).appendingPathExtension("jpg")) else {
  86. DispatchQueue.main.async {
  87. completion(nil, nil)
  88. }
  89. return
  90. }
  91. addAssetID(assetIdentifier, toVideo: videoURL, saveTo: cacheDirectory.appendingPathComponent(assetIdentifier).appendingPathExtension("mov"), progress: progress) { (_videoURL) in
  92. if let pairedVideoURL = _videoURL {
  93. _ = PHLivePhoto.request(withResourceFileURLs: [pairedVideoURL, pairedImageURL], placeholderImage: nil, targetSize: CGSize.zero, contentMode: PHImageContentMode.aspectFit, resultHandler: { (livePhoto: PHLivePhoto?, info: [AnyHashable : Any]) -> Void in
  94. if let isDegraded = info[PHLivePhotoInfoIsDegradedKey] as? Bool, isDegraded {
  95. return
  96. }
  97. DispatchQueue.main.async {
  98. completion(livePhoto, (pairedImageURL, pairedVideoURL))
  99. }
  100. })
  101. } else {
  102. DispatchQueue.main.async {
  103. completion(nil, nil)
  104. }
  105. }
  106. }
  107. }
  108. private func extractResources(from livePhoto: PHLivePhoto, to directoryURL: URL, completion: @escaping (LivePhotoResources?) -> Void) {
  109. let assetResources = PHAssetResource.assetResources(for: livePhoto)
  110. let group = DispatchGroup()
  111. var keyPhotoURL: URL?
  112. var videoURL: URL?
  113. for resource in assetResources {
  114. let buffer = NSMutableData()
  115. let options = PHAssetResourceRequestOptions()
  116. options.isNetworkAccessAllowed = true
  117. group.enter()
  118. PHAssetResourceManager.default().requestData(for: resource, options: options, dataReceivedHandler: { (data) in
  119. buffer.append(data)
  120. }) { (error) in
  121. if error == nil {
  122. if resource.type == .pairedVideo {
  123. videoURL = self.saveAssetResource(resource, to: directoryURL, resourceData: buffer as Data)
  124. } else {
  125. keyPhotoURL = self.saveAssetResource(resource, to: directoryURL, resourceData: buffer as Data)
  126. }
  127. } else {
  128. print(error as Any)
  129. }
  130. group.leave()
  131. }
  132. }
  133. group.notify(queue: DispatchQueue.main) {
  134. guard let pairedPhotoURL = keyPhotoURL, let pairedVideoURL = videoURL else {
  135. completion(nil)
  136. return
  137. }
  138. completion((pairedPhotoURL, pairedVideoURL))
  139. }
  140. }
  141. private func extractResources(from livePhoto: PHLivePhoto, completion: @escaping (LivePhotoResources?) -> Void) {
  142. if let cacheDirectory = cacheDirectory {
  143. extractResources(from: livePhoto, to: cacheDirectory, completion: completion)
  144. }
  145. }
  146. private func saveAssetResource(_ resource: PHAssetResource, to directory: URL, resourceData: Data) -> URL? {
  147. let fileExtension = UTTypeCopyPreferredTagWithClass(resource.uniformTypeIdentifier as CFString,kUTTagClassFilenameExtension)?.takeRetainedValue()
  148. guard let ext = fileExtension else {
  149. return nil
  150. }
  151. var fileUrl = directory.appendingPathComponent(NSUUID().uuidString)
  152. fileUrl = fileUrl.appendingPathExtension(ext as String)
  153. do {
  154. try resourceData.write(to: fileUrl, options: [Data.WritingOptions.atomic])
  155. } catch {
  156. print("Could not save resource \(resource) to filepath \(String(describing: fileUrl))")
  157. return nil
  158. }
  159. return fileUrl
  160. }
  161. func addAssetID(_ assetIdentifier: String, toImage imageURL: URL, saveTo destinationURL: URL) -> URL? {
  162. guard let imageDestination = CGImageDestinationCreateWithURL(destinationURL as CFURL, kUTTypeJPEG, 1, nil),
  163. let imageSource = CGImageSourceCreateWithURL(imageURL as CFURL, nil),
  164. var imageProperties = CGImageSourceCopyPropertiesAtIndex(imageSource, 0, nil) as? [AnyHashable : Any] else { return nil }
  165. let assetIdentifierKey = "17"
  166. let assetIdentifierInfo = [assetIdentifierKey : assetIdentifier]
  167. imageProperties[kCGImagePropertyMakerAppleDictionary] = assetIdentifierInfo
  168. CGImageDestinationAddImageFromSource(imageDestination, imageSource, 0, imageProperties as CFDictionary)
  169. CGImageDestinationFinalize(imageDestination)
  170. return destinationURL
  171. }
  172. var audioReader: AVAssetReader?
  173. var videoReader: AVAssetReader?
  174. var assetWriter: AVAssetWriter?
  175. func addAssetID(_ assetIdentifier: String, toVideo videoURL: URL, saveTo destinationURL: URL, progress: @escaping (CGFloat) -> Void, completion: @escaping (URL?) -> Void) {
  176. var audioWriterInput: AVAssetWriterInput?
  177. var audioReaderOutput: AVAssetReaderOutput?
  178. let videoAsset = AVURLAsset(url: videoURL)
  179. let frameCount = videoAsset.countFrames(exact: false)
  180. guard let videoTrack = videoAsset.tracks(withMediaType: .video).first else {
  181. completion(nil)
  182. return
  183. }
  184. do {
  185. // Create the Asset Writer
  186. assetWriter = try AVAssetWriter(outputURL: destinationURL, fileType: .mov)
  187. // Create Video Reader Output
  188. videoReader = try AVAssetReader(asset: videoAsset)
  189. let videoReaderSettings = [kCVPixelBufferPixelFormatTypeKey as String: NSNumber(value: kCVPixelFormatType_32BGRA as UInt32)]
  190. let videoReaderOutput = AVAssetReaderTrackOutput(track: videoTrack, outputSettings: videoReaderSettings)
  191. videoReader?.add(videoReaderOutput)
  192. // Create Video Writer Input
  193. let videoWriterInput = AVAssetWriterInput(mediaType: .video, outputSettings: [AVVideoCodecKey : AVVideoCodecType.h264, AVVideoWidthKey : videoTrack.naturalSize.width, AVVideoHeightKey : videoTrack.naturalSize.height])
  194. videoWriterInput.transform = videoTrack.preferredTransform
  195. videoWriterInput.expectsMediaDataInRealTime = true
  196. assetWriter?.add(videoWriterInput)
  197. // Create Audio Reader Output & Writer Input
  198. if let audioTrack = videoAsset.tracks(withMediaType: .audio).first {
  199. do {
  200. let _audioReader = try AVAssetReader(asset: videoAsset)
  201. let _audioReaderOutput = AVAssetReaderTrackOutput(track: audioTrack, outputSettings: nil)
  202. _audioReader.add(_audioReaderOutput)
  203. audioReader = _audioReader
  204. audioReaderOutput = _audioReaderOutput
  205. let _audioWriterInput = AVAssetWriterInput(mediaType: .audio, outputSettings: nil)
  206. _audioWriterInput.expectsMediaDataInRealTime = false
  207. assetWriter?.add(_audioWriterInput)
  208. audioWriterInput = _audioWriterInput
  209. } catch {
  210. print(error)
  211. }
  212. }
  213. // Create necessary identifier metadata and still image time metadata
  214. let assetIdentifierMetadata = metadataForAssetID(assetIdentifier)
  215. let stillImageTimeMetadataAdapter = createMetadataAdaptorForStillImageTime()
  216. assetWriter?.metadata = [assetIdentifierMetadata]
  217. assetWriter?.add(stillImageTimeMetadataAdapter.assetWriterInput)
  218. // Start the Asset Writer
  219. assetWriter?.startWriting()
  220. assetWriter?.startSession(atSourceTime: CMTime.zero)
  221. // Add still image metadata
  222. let _stillImagePercent: Float = 0.5
  223. stillImageTimeMetadataAdapter.append(AVTimedMetadataGroup(items: [metadataItemForStillImageTime()],timeRange: videoAsset.makeStillImageTimeRange(percent: _stillImagePercent, inFrameCount: frameCount)))
  224. // For end of writing / progress
  225. var writingVideoFinished = false
  226. var writingAudioFinished = false
  227. var currentFrameCount = 0
  228. func didCompleteWriting() {
  229. guard writingAudioFinished && writingVideoFinished else { return }
  230. assetWriter?.finishWriting {
  231. if self.assetWriter?.status == .completed {
  232. completion(destinationURL)
  233. } else {
  234. completion(nil)
  235. }
  236. }
  237. }
  238. // Start writing video
  239. if videoReader?.startReading() ?? false {
  240. videoWriterInput.requestMediaDataWhenReady(on: DispatchQueue(label: "videoWriterInputQueue")) {
  241. while videoWriterInput.isReadyForMoreMediaData {
  242. if let sampleBuffer = videoReaderOutput.copyNextSampleBuffer() {
  243. currentFrameCount += 1
  244. let percent:CGFloat = CGFloat(currentFrameCount)/CGFloat(frameCount)
  245. progress(percent)
  246. if !videoWriterInput.append(sampleBuffer) {
  247. print("Cannot write: \(String(describing: self.assetWriter?.error?.localizedDescription))")
  248. self.videoReader?.cancelReading()
  249. }
  250. } else {
  251. videoWriterInput.markAsFinished()
  252. writingVideoFinished = true
  253. didCompleteWriting()
  254. }
  255. }
  256. }
  257. } else {
  258. writingVideoFinished = true
  259. didCompleteWriting()
  260. }
  261. // Start writing audio
  262. if audioReader?.startReading() ?? false {
  263. audioWriterInput?.requestMediaDataWhenReady(on: DispatchQueue(label: "audioWriterInputQueue")) {
  264. while audioWriterInput?.isReadyForMoreMediaData ?? false {
  265. guard let sampleBuffer = audioReaderOutput?.copyNextSampleBuffer() else {
  266. audioWriterInput?.markAsFinished()
  267. writingAudioFinished = true
  268. didCompleteWriting()
  269. return
  270. }
  271. audioWriterInput?.append(sampleBuffer)
  272. }
  273. }
  274. } else {
  275. writingAudioFinished = true
  276. didCompleteWriting()
  277. }
  278. } catch {
  279. print(error)
  280. completion(nil)
  281. }
  282. }
  283. private func metadataForAssetID(_ assetIdentifier: String) -> AVMetadataItem {
  284. let item = AVMutableMetadataItem()
  285. let keyContentIdentifier = "com.apple.quicktime.content.identifier"
  286. let keySpaceQuickTimeMetadata = "mdta"
  287. item.key = keyContentIdentifier as (NSCopying & NSObjectProtocol)?
  288. item.keySpace = AVMetadataKeySpace(rawValue: keySpaceQuickTimeMetadata)
  289. item.value = assetIdentifier as (NSCopying & NSObjectProtocol)?
  290. item.dataType = "com.apple.metadata.datatype.UTF-8"
  291. return item
  292. }
  293. private func createMetadataAdaptorForStillImageTime() -> AVAssetWriterInputMetadataAdaptor {
  294. let keyStillImageTime = "com.apple.quicktime.still-image-time"
  295. let keySpaceQuickTimeMetadata = "mdta"
  296. let spec : NSDictionary = [
  297. kCMMetadataFormatDescriptionMetadataSpecificationKey_Identifier as NSString:
  298. "\(keySpaceQuickTimeMetadata)/\(keyStillImageTime)",
  299. kCMMetadataFormatDescriptionMetadataSpecificationKey_DataType as NSString:
  300. "com.apple.metadata.datatype.int8" ]
  301. var desc : CMFormatDescription? = nil
  302. CMMetadataFormatDescriptionCreateWithMetadataSpecifications(allocator: kCFAllocatorDefault, metadataType: kCMMetadataFormatType_Boxed, metadataSpecifications: [spec] as CFArray, formatDescriptionOut: &desc)
  303. let input = AVAssetWriterInput(mediaType: .metadata,
  304. outputSettings: nil, sourceFormatHint: desc)
  305. return AVAssetWriterInputMetadataAdaptor(assetWriterInput: input)
  306. }
  307. private func metadataItemForStillImageTime() -> AVMetadataItem {
  308. let item = AVMutableMetadataItem()
  309. let keyStillImageTime = "com.apple.quicktime.still-image-time"
  310. let keySpaceQuickTimeMetadata = "mdta"
  311. item.key = keyStillImageTime as (NSCopying & NSObjectProtocol)?
  312. item.keySpace = AVMetadataKeySpace(rawValue: keySpaceQuickTimeMetadata)
  313. item.value = 0 as (NSCopying & NSObjectProtocol)?
  314. item.dataType = "com.apple.metadata.datatype.int8"
  315. return item
  316. }
  317. }
  318. fileprivate extension AVAsset {
  319. func countFrames(exact:Bool) -> Int {
  320. var frameCount = 0
  321. if let videoReader = try? AVAssetReader(asset: self) {
  322. if let videoTrack = self.tracks(withMediaType: .video).first {
  323. frameCount = Int(CMTimeGetSeconds(self.duration) * Float64(videoTrack.nominalFrameRate))
  324. if exact {
  325. frameCount = 0
  326. let videoReaderOutput = AVAssetReaderTrackOutput(track: videoTrack, outputSettings: nil)
  327. videoReader.add(videoReaderOutput)
  328. videoReader.startReading()
  329. // count frames
  330. while true {
  331. let sampleBuffer = videoReaderOutput.copyNextSampleBuffer()
  332. if sampleBuffer == nil {
  333. break
  334. }
  335. frameCount += 1
  336. }
  337. videoReader.cancelReading()
  338. }
  339. }
  340. }
  341. return frameCount
  342. }
  343. func stillImageTime() -> CMTime? {
  344. var stillTime:CMTime? = nil
  345. if let videoReader = try? AVAssetReader(asset: self) {
  346. if let metadataTrack = self.tracks(withMediaType: .metadata).first {
  347. let videoReaderOutput = AVAssetReaderTrackOutput(track: metadataTrack, outputSettings: nil)
  348. videoReader.add(videoReaderOutput)
  349. videoReader.startReading()
  350. let keyStillImageTime = "com.apple.quicktime.still-image-time"
  351. let keySpaceQuickTimeMetadata = "mdta"
  352. var found = false
  353. while found == false {
  354. if let sampleBuffer = videoReaderOutput.copyNextSampleBuffer() {
  355. if CMSampleBufferGetNumSamples(sampleBuffer) != 0 {
  356. let group = AVTimedMetadataGroup(sampleBuffer: sampleBuffer)
  357. for item in group?.items ?? [] {
  358. if item.key as? String == keyStillImageTime && item.keySpace!.rawValue == keySpaceQuickTimeMetadata {
  359. stillTime = group?.timeRange.start
  360. //print("stillImageTime = \(CMTimeGetSeconds(stillTime!))")
  361. found = true
  362. break
  363. }
  364. }
  365. }
  366. }
  367. else {
  368. break;
  369. }
  370. }
  371. videoReader.cancelReading()
  372. }
  373. }
  374. return stillTime
  375. }
  376. func makeStillImageTimeRange(percent:Float, inFrameCount:Int = 0) -> CMTimeRange {
  377. var time = self.duration
  378. var frameCount = inFrameCount
  379. if frameCount == 0 {
  380. frameCount = self.countFrames(exact: true)
  381. }
  382. let frameDuration = Int64(Float(time.value) / Float(frameCount))
  383. time.value = Int64(Float(time.value) * percent)
  384. //print("stillImageTime = \(CMTimeGetSeconds(time))")
  385. return CMTimeRangeMake(start: time, duration: CMTimeMake(value: frameDuration, timescale: time.timescale))
  386. }
  387. func getAssetFrame(percent:Float) -> UIImage?
  388. {
  389. let imageGenerator = AVAssetImageGenerator(asset: self)
  390. imageGenerator.appliesPreferredTrackTransform = true
  391. imageGenerator.requestedTimeToleranceAfter = CMTimeMake(value: 1, timescale: 100)
  392. imageGenerator.requestedTimeToleranceBefore = CMTimeMake(value: 1, timescale: 100)
  393. var time = self.duration
  394. time.value = Int64(Float(time.value) * percent)
  395. do {
  396. var actualTime = CMTime.zero
  397. let imageRef = try imageGenerator.copyCGImage(at: time, actualTime:&actualTime)
  398. let img = UIImage(cgImage: imageRef)
  399. return img
  400. }
  401. catch let error as NSError
  402. {
  403. print("Image generation failed with error \(error)")
  404. return nil
  405. }
  406. }
  407. }