1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
import Foundation
import ImageIO
import UIKit
import UniformTypeIdentifiers
enum ImageDownloadError: Error, Equatable {
case httpStatus(Int)
case imageTooLarge
case gifTooLarge
}
enum GIFDownload {
static let byteLimit = 15 * 1024 * 1024
static let imageByteLimit = 64 * 1024 * 1024
static func load(
_ url: URL, configuration: URLSessionConfiguration = .default
) async throws -> (Data, URLResponse) {
let download = ChunkedImageDownload(configuration: configuration)
return try await withTaskCancellationHandler {
try await download.load(url)
} onCancel: {
download.cancel()
}
}
static func validate(_ data: Data) throws {
guard !RemoteImageDecoder.isGIF(data) || data.count <= byteLimit else {
throw ImageDownloadError.gifTooLarge
}
guard data.count <= imageByteLimit else {
throw ImageDownloadError.imageTooLarge
}
}
}
struct ImageDownloadBuffer {
private(set) var data = Data()
mutating func append(_ chunk: Data) throws {
let prefix = Data((data.prefix(6) + chunk.prefix(max(0, 6 - data.count))).prefix(6))
if RemoteImageDecoder.isGIF(prefix) && chunk.count > GIFDownload.byteLimit - data.count {
throw ImageDownloadError.gifTooLarge
}
guard chunk.count <= GIFDownload.imageByteLimit - data.count else {
throw ImageDownloadError.imageTooLarge
}
data.append(chunk)
}
}
final class ChunkedImageDownload: NSObject, URLSessionDataDelegate, @unchecked Sendable {
private let lock = NSLock()
private let configuration: URLSessionConfiguration
private var task: URLSessionDataTask?
private var session: URLSession?
private var continuation: CheckedContinuation<(Data, URLResponse), Error>?
private var cancelled = false
private var buffer = ImageDownloadBuffer()
private var response: URLResponse?
private var downloadError: ImageDownloadError?
init(configuration: URLSessionConfiguration) {
self.configuration = configuration
super.init()
}
func load(_ url: URL) async throws -> (Data, URLResponse) {
try await withCheckedThrowingContinuation { continuation in
lock.lock()
if cancelled {
lock.unlock()
continuation.resume(throwing: CancellationError())
return
}
self.continuation = continuation
let queue = OperationQueue()
queue.maxConcurrentOperationCount = 1
queue.qualityOfService = .utility
let session = URLSession(configuration: configuration, delegate: self, delegateQueue: queue)
self.session = session
let task = session.dataTask(with: url)
self.task = task
lock.unlock()
task.resume()
}
}
func cancel() {
lock.lock()
cancelled = true
let task = task
lock.unlock()
task?.cancel()
}
func urlSession(
_ session: URLSession, dataTask: URLSessionDataTask, didReceive response: URLResponse,
completionHandler: @escaping (URLSession.ResponseDisposition) -> Void
) {
guard let http = response as? HTTPURLResponse else {
completionHandler(.cancel)
return
}
guard (200..<300).contains(http.statusCode) else {
downloadError = .httpStatus(http.statusCode)
completionHandler(.cancel)
return
}
guard response.expectedContentLength <= Int64(GIFDownload.imageByteLimit) else {
downloadError = .imageTooLarge
completionHandler(.cancel)
return
}
self.response = response
completionHandler(.allow)
}
func urlSession(_ session: URLSession, dataTask: URLSessionDataTask, didReceive chunk: Data) {
do {
try buffer.append(chunk)
} catch let error as ImageDownloadError {
downloadError = error
dataTask.cancel()
} catch {
dataTask.cancel()
}
}
func urlSession(_ session: URLSession, task: URLSessionTask, didCompleteWithError error: Error?) {
lock.lock()
let continuation = continuation
self.continuation = nil
self.task = nil
self.session = nil
lock.unlock()
defer { session.finishTasksAndInvalidate() }
if let downloadError {
continuation?.resume(throwing: downloadError)
} else if let error {
continuation?.resume(throwing: error)
} else if let response {
continuation?.resume(returning: (buffer.data, response))
} else {
continuation?.resume(throwing: URLError(.badServerResponse))
}
}
}
actor ImageDecodeQueue {
struct InlineImage {
let image: UIImage
let borderColors: AvatarRingColors
}
static let shared = ImageDecodeQueue()
func decode(_ data: Data, resolution: RemoteImageDecoder.Resolution = .thumbnail) -> UIImage? {
guard !Task.isCancelled else { return nil }
return RemoteImageDecoder.decode(data, resolution: resolution)
}
func decodeInline(_ data: Data) -> InlineImage? {
guard let image = decode(data) else { return nil }
let frame = image.images?.first ?? image
let colors = frame.cgImage.map(AvatarRingColors.calculate) ?? .fallback
return InlineImage(image: image, borderColors: colors)
}
}
enum RemoteImageDecoder {
enum Resolution {
case thumbnail
case fullSize
}
static func isGIF(_ data: Data) -> Bool {
data.starts(with: Data("GIF87a".utf8)) || data.starts(with: Data("GIF89a".utf8))
}
static func decode(_ data: Data, resolution: Resolution = .thumbnail) -> UIImage? {
guard let source = CGImageSourceCreateWithData(data as CFData, nil),
CGImageSourceGetCount(source) > 0
else { return nil }
let sourceType = CGImageSourceGetType(source) as String?
if sourceType == UTType.gif.identifier {
return decodeGIF(source, resolution: resolution)
}
return decodeFrame(source, at: 0, resolution: resolution)
}
private static func decodeGIF(_ source: CGImageSource, resolution: Resolution) -> UIImage? {
let count = CGImageSourceGetCount(source)
let properties = CGImageSourceCopyPropertiesAtIndex(source, 0, nil) as? [CFString: Any]
guard let width = properties?[kCGImagePropertyPixelWidth] as? Int,
let height = properties?[kCGImagePropertyPixelHeight] as? Int,
(1...4096).contains(width), (1...4096).contains(height),
width * height <= 8_000_000, count <= 500
else { return nil }
guard count > 1 else { return decodeFrame(source, at: 0, resolution: resolution) }
let pixelsPerFrame = resolution == .thumbnail ? min(width, 720) * min(height, 720) : width * height
let frameLimit = max(2, min(30, 10_000_000 / max(1, pixelsPerFrame)))
let step = max(1, Int(ceil(Double(count) / Double(frameLimit))))
var frames: [UIImage] = []
var duration: TimeInterval = 0
for index in stride(from: 0, to: count, by: step) {
guard let frame = decodeFrame(source, at: index, resolution: resolution) else { continue }
frames.append(frame)
let frameProperties = CGImageSourceCopyPropertiesAtIndex(source, index, nil) as? [CFString: Any]
let gifProperties = frameProperties?[kCGImagePropertyGIFDictionary] as? [CFString: Any]
let delay =
(gifProperties?[kCGImagePropertyGIFUnclampedDelayTime] as? TimeInterval)
?? (gifProperties?[kCGImagePropertyGIFDelayTime] as? TimeInterval)
?? 0.1
duration += max(0.02, delay) * Double(min(step, count - index))
}
guard frames.count > 1 else { return frames.first }
return UIImage.animatedImage(with: frames, duration: max(duration, 0.1))
}
private static func decodeFrame(_ source: CGImageSource, at index: Int, resolution: Resolution) -> UIImage? {
let maximumPixelSize: Int
if resolution == .fullSize {
let properties = CGImageSourceCopyPropertiesAtIndex(source, index, nil) as? [CFString: Any]
guard let width = properties?[kCGImagePropertyPixelWidth] as? Int,
let height = properties?[kCGImagePropertyPixelHeight] as? Int,
width > 0, height > 0
else { return nil }
maximumPixelSize = max(width, height)
} else {
maximumPixelSize = 720
}
let options: [CFString: Any] = [
kCGImageSourceCreateThumbnailFromImageAlways: true,
kCGImageSourceThumbnailMaxPixelSize: maximumPixelSize,
kCGImageSourceCreateThumbnailWithTransform: true,
kCGImageSourceShouldCacheImmediately: true
]
guard let image = CGImageSourceCreateThumbnailAtIndex(source, index, options as CFDictionary) else {
return nil
}
return UIImage(cgImage: image)
}
}