AVAssetImageDataProvider.swift 5.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151
  1. //
  2. // AVAssetImageDataProvider.swift
  3. // Kingfisher
  4. //
  5. // Created by onevcat on 2020/08/09.
  6. //
  7. // Copyright (c) 2020 Wei Wang <onevcat@gmail.com>
  8. //
  9. // Permission is hereby granted, free of charge, to any person obtaining a copy
  10. // of this software and associated documentation files (the "Software"), to deal
  11. // in the Software without restriction, including without limitation the rights
  12. // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  13. // copies of the Software, and to permit persons to whom the Software is
  14. // furnished to do so, subject to the following conditions:
  15. //
  16. // The above copyright notice and this permission notice shall be included in
  17. // all copies or substantial portions of the Software.
  18. //
  19. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  20. // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  21. // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  22. // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  23. // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  24. // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  25. // THE SOFTWARE.
  26. #if !os(watchOS)
  27. import Foundation
  28. import AVKit
  29. #if canImport(MobileCoreServices)
  30. import MobileCoreServices
  31. #else
  32. import CoreServices
  33. #endif
  34. /// A data provider to provide thumbnail data from a given AVKit asset.
  35. public struct AVAssetImageDataProvider: ImageDataProvider {
  36. /// The possible error might be caused by the `AVAssetImageDataProvider`.
  37. /// - userCancelled: The data provider process is cancelled.
  38. /// - invalidImage: The retrieved image is invalid.
  39. public enum AVAssetImageDataProviderError: Error {
  40. case userCancelled
  41. case invalidImage(_ image: CGImage?)
  42. }
  43. /// The asset image generator bound to `self`.
  44. public let assetImageGenerator: AVAssetImageGenerator
  45. /// The time at which the image should be generate in the asset.
  46. public let time: CMTime
  47. private var internalKey: String {
  48. guard let url = (assetImageGenerator.asset as? AVURLAsset)?.url else {
  49. return UUID().uuidString
  50. }
  51. return url.cacheKey
  52. }
  53. /// The cache key used by `self`.
  54. public var cacheKey: String {
  55. return "\(internalKey)_\(time.seconds)"
  56. }
  57. /// Creates an asset image data provider.
  58. /// - Parameters:
  59. /// - assetImageGenerator: The asset image generator controls data providing behaviors.
  60. /// - time: At which time in the asset the image should be generated.
  61. public init(assetImageGenerator: AVAssetImageGenerator, time: CMTime) {
  62. self.assetImageGenerator = assetImageGenerator
  63. self.time = time
  64. }
  65. /// Creates an asset image data provider.
  66. /// - Parameters:
  67. /// - assetURL: The URL of asset for providing image data.
  68. /// - time: At which time in the asset the image should be generated.
  69. ///
  70. /// This method uses `assetURL` to create an `AVAssetImageGenerator` object and calls
  71. /// the `init(assetImageGenerator:time:)` initializer.
  72. ///
  73. public init(assetURL: URL, time: CMTime) {
  74. let asset = AVAsset(url: assetURL)
  75. let generator = AVAssetImageGenerator(asset: asset)
  76. generator.appliesPreferredTrackTransform = true
  77. self.init(assetImageGenerator: generator, time: time)
  78. }
  79. /// Creates an asset image data provider.
  80. ///
  81. /// - Parameters:
  82. /// - assetURL: The URL of asset for providing image data.
  83. /// - seconds: At which time in seconds in the asset the image should be generated.
  84. ///
  85. /// This method uses `assetURL` to create an `AVAssetImageGenerator` object, uses `seconds` to create a `CMTime`,
  86. /// and calls the `init(assetImageGenerator:time:)` initializer.
  87. ///
  88. public init(assetURL: URL, seconds: TimeInterval) {
  89. let time = CMTime(seconds: seconds, preferredTimescale: 600)
  90. self.init(assetURL: assetURL, time: time)
  91. }
  92. public func data(handler: @escaping (Result<Data, Error>) -> Void) {
  93. assetImageGenerator.generateCGImagesAsynchronously(forTimes: [NSValue(time: time)]) {
  94. (requestedTime, image, imageTime, result, error) in
  95. if let error = error {
  96. handler(.failure(error))
  97. return
  98. }
  99. if result == .cancelled {
  100. handler(.failure(AVAssetImageDataProviderError.userCancelled))
  101. return
  102. }
  103. guard let cgImage = image, let data = cgImage.jpegData else {
  104. handler(.failure(AVAssetImageDataProviderError.invalidImage(image)))
  105. return
  106. }
  107. handler(.success(data))
  108. }
  109. }
  110. }
  111. extension CGImage {
  112. var jpegData: Data? {
  113. guard let mutableData = CFDataCreateMutable(nil, 0) else {
  114. return nil
  115. }
  116. #if os(visionOS)
  117. guard let destination = CGImageDestinationCreateWithData(
  118. mutableData, UTType.jpeg.identifier as CFString , 1, nil
  119. ) else {
  120. return nil
  121. }
  122. #else
  123. guard let destination = CGImageDestinationCreateWithData(mutableData, kUTTypeJPEG, 1, nil) else {
  124. return nil
  125. }
  126. #endif
  127. CGImageDestinationAddImage(destination, self, nil)
  128. guard CGImageDestinationFinalize(destination) else { return nil }
  129. return mutableData as Data
  130. }
  131. }
  132. #endif