-
Notifications
You must be signed in to change notification settings - Fork 2.9k
Expand file tree
/
Copy pathDCTAnimationCacheImpl.swift
More file actions
1571 lines (1333 loc) · 62.1 KB
/
Copy pathDCTAnimationCacheImpl.swift
File metadata and controls
1571 lines (1333 loc) · 62.1 KB
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
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import Foundation
import UIKit
import SwiftSignalKit
import CryptoUtils
import ManagedFile
import Compression
import AnimationCache
private let algorithm: compression_algorithm = COMPRESSION_LZFSE
private func alignUp(size: Int, align: Int) -> Int {
precondition(((align - 1) & align) == 0, "Align must be a power of two")
let alignmentMask = align - 1
return (size + alignmentMask) & ~alignmentMask
}
private func fileSize(_ path: String, useTotalFileAllocatedSize: Bool = false) -> Int64? {
if useTotalFileAllocatedSize {
let url = URL(fileURLWithPath: path)
if let values = (try? url.resourceValues(forKeys: Set([.isRegularFileKey, .fileAllocatedSizeKey]))) {
if values.isRegularFile ?? false {
if let fileSize = values.fileAllocatedSize {
return Int64(fileSize)
}
}
}
}
var value = stat()
if stat(path, &value) == 0 {
return value.st_size
} else {
return nil
}
}
private func md5Hash(_ string: String) -> String {
let hashData = string.data(using: .utf8)!.withUnsafeBytes { bytes -> Data in
return CryptoMD5(bytes.baseAddress!, Int32(bytes.count))
}
return hashData.withUnsafeBytes { bytes -> String in
let uintBytes = bytes.baseAddress!.assumingMemoryBound(to: UInt8.self)
return String(format: "%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x", uintBytes[0], uintBytes[1], uintBytes[2], uintBytes[3], uintBytes[4], uintBytes[5], uintBytes[6], uintBytes[7], uintBytes[8], uintBytes[9], uintBytes[10], uintBytes[11], uintBytes[12], uintBytes[13], uintBytes[14], uintBytes[15])
}
}
private func itemSubpath(hashString: String, width: Int, height: Int) -> (directory: String, fileName: String) {
assert(hashString.count == 32)
var directory = ""
for i in 0 ..< 1 {
if !directory.isEmpty {
directory.append("/")
}
directory.append(String(hashString[hashString.index(hashString.startIndex, offsetBy: i * 2) ..< hashString.index(hashString.startIndex, offsetBy: (i + 1) * 2)]))
}
return (directory, "\(hashString)_\(width)x\(height)")
}
private func roundUp(_ numToRound: Int, multiple: Int) -> Int {
if multiple == 0 {
return numToRound
}
let remainder = numToRound % multiple
if remainder == 0 {
return numToRound;
}
return numToRound + multiple - remainder
}
private func compressData(data: Data, addSizeHeader: Bool = false) -> Data? {
let scratchData = malloc(compression_encode_scratch_buffer_size(algorithm))!
defer {
free(scratchData)
}
let headerSize = addSizeHeader ? 4 : 0
var compressedData = Data(count: headerSize + data.count + 16 * 1024)
let resultSize = compressedData.withUnsafeMutableBytes { buffer -> Int in
guard let bytes = buffer.baseAddress?.assumingMemoryBound(to: UInt8.self) else {
return 0
}
if addSizeHeader {
var decompressedSize: UInt32 = UInt32(data.count)
memcpy(bytes, &decompressedSize, 4)
}
return data.withUnsafeBytes { sourceBuffer -> Int in
return compression_encode_buffer(bytes.advanced(by: headerSize), buffer.count - headerSize, sourceBuffer.baseAddress!.assumingMemoryBound(to: UInt8.self), sourceBuffer.count, scratchData, algorithm)
}
}
if resultSize <= 0 {
return nil
}
compressedData.count = headerSize + resultSize
return compressedData
}
private func decompressData(data: Data, range: Range<Int>, decompressedSize: Int) -> Data? {
let scratchData = malloc(compression_decode_scratch_buffer_size(algorithm))!
defer {
free(scratchData)
}
var decompressedFrameData = Data(count: decompressedSize)
let resultSize = decompressedFrameData.withUnsafeMutableBytes { buffer -> Int in
guard let bytes = buffer.baseAddress?.assumingMemoryBound(to: UInt8.self) else {
return 0
}
return data.withUnsafeBytes { sourceBuffer -> Int in
return compression_decode_buffer(bytes, buffer.count, sourceBuffer.baseAddress!.assumingMemoryBound(to: UInt8.self).advanced(by: range.lowerBound), range.upperBound - range.lowerBound, scratchData, algorithm)
}
}
if resultSize <= 0 {
return nil
}
if decompressedFrameData.count != resultSize {
decompressedFrameData.count = resultSize
}
return decompressedFrameData
}
private final class AnimationCacheItemWriterImpl: AnimationCacheItemWriter {
enum WriteError: Error {
case generic
}
struct CompressedResult {
var animationPath: String
}
private struct FrameMetadata {
var duration: Double
}
var queue: Queue {
return self.innerQueue
}
let innerQueue: Queue
var isCancelled: Bool = false
private let compressedPath: String
private var file: ManagedFile?
private var compressedWriter: CompressedFileWriter?
private let completion: (CompressedResult?) -> Void
private var currentSurface: ImageARGB?
private var currentYUVASurface: ImageYUVA420?
private var currentFrameFloat: FloatCoefficientsYUVA420?
private var previousFrameCoefficients: DctCoefficientsYUVA420?
private var deltaFrameFloat: FloatCoefficientsYUVA420?
private var previousYUVASurface: ImageYUVA420?
private var currentDctData: DctData?
private var differenceCoefficients: DctCoefficientsYUVA420?
private var currentDctCoefficients: DctCoefficientsYUVA420?
private var contentLengthOffset: Int?
private var isFailed: Bool = false
private var isFinished: Bool = false
private var frames: [FrameMetadata] = []
private let dctQualityLuma: Int
private let dctQualityChroma: Int
private let dctQualityDelta: Int
private let lock = Lock()
init?(queue: Queue, allocateTempFile: @escaping () -> String, completion: @escaping (CompressedResult?) -> Void) {
self.dctQualityLuma = 70
self.dctQualityChroma = 88
self.dctQualityDelta = 22
self.innerQueue = queue
self.compressedPath = allocateTempFile()
guard let file = ManagedFile(queue: nil, path: self.compressedPath, mode: .readwrite) else {
return nil
}
self.file = file
self.compressedWriter = CompressedFileWriter(file: file)
self.completion = completion
}
func add(with drawingBlock: (AnimationCacheItemDrawingSurface) -> Double?, proposedWidth: Int, proposedHeight: Int, insertKeyframe: Bool) {
do {
try self.lock.throwingLocked {
let width = roundUp(proposedWidth, multiple: 16)
let height = roundUp(proposedHeight, multiple: 16)
let surface: ImageARGB
if let current = self.currentSurface {
if current.argbPlane.width == width && current.argbPlane.height == height {
surface = current
surface.argbPlane.data.withUnsafeMutableBytes { bytes -> Void in
memset(bytes.baseAddress!, 0, bytes.count)
}
} else {
self.isFailed = true
return
}
} else {
surface = ImageARGB(width: width, height: height, rowAlignment: 32)
self.currentSurface = surface
}
let duration = surface.argbPlane.data.withUnsafeMutableBytes { bytes -> Double? in
return drawingBlock(AnimationCacheItemDrawingSurface(
argb: bytes.baseAddress!.assumingMemoryBound(to: UInt8.self),
width: width,
height: height,
bytesPerRow: surface.argbPlane.bytesPerRow,
length: bytes.count
))
}
guard let duration = duration else {
return
}
try addInternal(with: { yuvaSurface in
surface.toYUVA420(target: yuvaSurface)
return duration
}, width: width, height: height, insertKeyframe: insertKeyframe)
}
} catch {
}
}
func addYUV(with drawingBlock: (ImageYUVA420) -> Double?, proposedWidth: Int, proposedHeight: Int, insertKeyframe: Bool) throws {
let width = roundUp(proposedWidth, multiple: 16)
let height = roundUp(proposedHeight, multiple: 16)
do {
try self.lock.throwingLocked {
try addInternal(with: { yuvaSurface in
return drawingBlock(yuvaSurface)
}, width: width, height: height, insertKeyframe: insertKeyframe)
}
} catch {
}
}
func addInternal(with drawingBlock: (ImageYUVA420) -> Double?, width: Int, height: Int, insertKeyframe: Bool) throws {
if width == 0 || height == 0 {
self.isFailed = true
throw WriteError.generic
}
if self.isFailed || self.isFinished {
throw WriteError.generic
}
guard !self.isFailed, !self.isFinished, let file = self.file, let compressedWriter = self.compressedWriter else {
throw WriteError.generic
}
var isFirstFrame = false
let yuvaSurface: ImageYUVA420
if let current = self.currentYUVASurface {
if current.yPlane.width == width && current.yPlane.height == height {
yuvaSurface = current
} else {
self.isFailed = true
throw WriteError.generic
}
} else {
isFirstFrame = true
yuvaSurface = ImageYUVA420(width: width, height: height, rowAlignment: nil)
self.currentYUVASurface = yuvaSurface
}
let currentFrameFloat: FloatCoefficientsYUVA420
if let current = self.currentFrameFloat {
if current.yPlane.width == width && current.yPlane.height == height {
currentFrameFloat = current
} else {
self.isFailed = true
throw WriteError.generic
}
} else {
currentFrameFloat = FloatCoefficientsYUVA420(width: width, height: height)
self.currentFrameFloat = currentFrameFloat
}
let previousFrameCoefficients: DctCoefficientsYUVA420
if let current = self.previousFrameCoefficients {
if current.yPlane.width == width && current.yPlane.height == height {
previousFrameCoefficients = current
} else {
self.isFailed = true
throw WriteError.generic
}
} else {
previousFrameCoefficients = DctCoefficientsYUVA420(width: width, height: height)
self.previousFrameCoefficients = previousFrameCoefficients
}
let deltaFrameFloat: FloatCoefficientsYUVA420
if let current = self.deltaFrameFloat {
if current.yPlane.width == width && current.yPlane.height == height {
deltaFrameFloat = current
} else {
self.isFailed = true
throw WriteError.generic
}
} else {
deltaFrameFloat = FloatCoefficientsYUVA420(width: width, height: height)
self.deltaFrameFloat = deltaFrameFloat
}
let dctData: DctData
if let current = self.currentDctData {
dctData = current
} else {
dctData = DctData(generatingTablesAtQualityLuma: self.dctQualityLuma, chroma: self.dctQualityChroma, delta: self.dctQualityDelta)
self.currentDctData = dctData
}
let duration = drawingBlock(yuvaSurface)
guard let duration = duration else {
return
}
let dctCoefficients: DctCoefficientsYUVA420
if let current = self.currentDctCoefficients {
if current.yPlane.width == width && current.yPlane.height == height {
dctCoefficients = current
} else {
self.isFailed = true
throw WriteError.generic
}
} else {
dctCoefficients = DctCoefficientsYUVA420(width: width, height: height)
self.currentDctCoefficients = dctCoefficients
}
let differenceCoefficients: DctCoefficientsYUVA420
if let current = self.differenceCoefficients {
if current.yPlane.width == width && current.yPlane.height == height {
differenceCoefficients = current
} else {
self.isFailed = true
throw WriteError.generic
}
} else {
differenceCoefficients = DctCoefficientsYUVA420(width: width, height: height)
self.differenceCoefficients = differenceCoefficients
}
#if !arch(arm64)
var insertKeyframe = insertKeyframe
insertKeyframe = true
#endif
let previousYUVASurface: ImageYUVA420
if let current = self.previousYUVASurface {
previousYUVASurface = current
} else {
previousYUVASurface = ImageYUVA420(width: dctCoefficients.yPlane.width, height: dctCoefficients.yPlane.height, rowAlignment: nil)
self.previousYUVASurface = previousYUVASurface
}
let isKeyframe: Bool
if !isFirstFrame && !insertKeyframe {
isKeyframe = false
//previous + delta = current
//delta = current - previous
yuvaSurface.toCoefficients(target: differenceCoefficients)
differenceCoefficients.subtract(other: previousFrameCoefficients)
differenceCoefficients.dct4x4(dctData: dctData, target: dctCoefficients)
//previous + delta = current
dctCoefficients.idct4x4Add(dctData: dctData, target: previousFrameCoefficients)
//previousFrameCoefficients.add(other: differenceCoefficients)
} else {
isKeyframe = true
yuvaSurface.dct8x8(dctData: dctData, target: dctCoefficients)
dctCoefficients.idct8x8(dctData: dctData, target: yuvaSurface)
yuvaSurface.toCoefficients(target: previousFrameCoefficients)
}
if isFirstFrame {
file.write(6 as UInt32)
file.write(UInt32(dctCoefficients.yPlane.width))
file.write(UInt32(dctCoefficients.yPlane.height))
let lumaDctTable = dctData.lumaTable.serializedData()
file.write(UInt32(lumaDctTable.count))
let _ = file.write(lumaDctTable)
let chromaDctTable = dctData.chromaTable.serializedData()
file.write(UInt32(chromaDctTable.count))
let _ = file.write(chromaDctTable)
let deltaDctTable = dctData.deltaTable.serializedData()
file.write(UInt32(deltaDctTable.count))
let _ = file.write(deltaDctTable)
self.contentLengthOffset = Int(file.position())
file.write(0 as UInt32)
}
do {
let frameLength = dctCoefficients.yPlane.data.count + dctCoefficients.uPlane.data.count + dctCoefficients.vPlane.data.count + dctCoefficients.aPlane.data.count
try compressedWriter.writeUInt32(UInt32(frameLength))
try compressedWriter.writeUInt32(isKeyframe ? 1 : 0)
for i in 0 ..< 4 {
let dctPlane: DctCoefficientPlane
switch i {
case 0:
dctPlane = dctCoefficients.yPlane
case 1:
dctPlane = dctCoefficients.uPlane
case 2:
dctPlane = dctCoefficients.vPlane
case 3:
dctPlane = dctCoefficients.aPlane
default:
preconditionFailure()
}
try compressedWriter.writeUInt32(UInt32(dctPlane.data.count))
try dctPlane.data.withUnsafeBytes { bytes in
try compressedWriter.write(bytes: bytes.baseAddress!.assumingMemoryBound(to: UInt8.self), count: bytes.count)
}
}
self.frames.append(FrameMetadata(duration: duration))
} catch {
self.isFailed = true
throw WriteError.generic
}
}
func finish() {
do {
let result = try self.finishInternal()
self.completion(result)
} catch {
}
}
func finishInternal() throws -> CompressedResult? {
var shouldComplete = false
self.lock.locked {
if !self.isFinished {
self.isFinished = true
shouldComplete = true
guard let contentLengthOffset = self.contentLengthOffset, let file = self.file, let compressedWriter = self.compressedWriter else {
self.isFailed = true
return
}
assert(contentLengthOffset >= 0)
do {
try compressedWriter.flush()
let metadataPosition = file.position()
let contentLength = Int(metadataPosition) - contentLengthOffset - 4
let _ = file.seek(position: Int64(contentLengthOffset))
file.write(UInt32(contentLength))
let _ = file.seek(position: metadataPosition)
file.write(UInt32(self.frames.count))
for frame in self.frames {
file.write(Float32(frame.duration))
}
if !self.isFailed {
self.compressedWriter = nil
self.file = nil
file._unsafeClose()
}
} catch {
self.isFailed = true
}
}
}
if shouldComplete {
if !self.isFailed {
return CompressedResult(animationPath: self.compressedPath)
} else {
let _ = try? FileManager.default.removeItem(atPath: self.compressedPath)
return nil
}
} else {
return nil
}
}
}
private final class AnimationCacheItemAccessor {
private enum ReadError: Error {
case generic
}
final class CurrentFrame {
let index: Int
var remainingDuration: Double
let duration: Double
let yuva: ImageYUVA420
init(index: Int, duration: Double, yuva: ImageYUVA420) {
self.index = index
self.duration = duration
self.remainingDuration = duration
self.yuva = yuva
}
}
struct FrameInfo {
let duration: Double
}
private let data: Data
private var compressedDataReader: DecompressedData?
private let range: Range<Int>
private let frameMapping: [Int: FrameInfo]
private let width: Int
private let height: Int
private let durationMapping: [Double]
private var currentFrame: CurrentFrame?
private var currentYUVASurface: ImageYUVA420?
private var currentCoefficients: DctCoefficientsYUVA420?
private let currentDctData: DctData
private var sharedDctCoefficients: DctCoefficientsYUVA420?
private var deltaCoefficients: DctCoefficientsYUVA420?
init(data: Data, range: Range<Int>, frameMapping: [FrameInfo], width: Int, height: Int, dctData: DctData) {
self.data = data
self.range = range
self.width = width
self.height = height
var resultFrameMapping: [Int: FrameInfo] = [:]
var durationMapping: [Double] = []
for i in 0 ..< frameMapping.count {
let frame = frameMapping[i]
resultFrameMapping[i] = frame
durationMapping.append(frame.duration)
}
self.frameMapping = resultFrameMapping
self.durationMapping = durationMapping
self.currentDctData = dctData
}
private func loadNextFrame() -> Bool {
var didLoop = false
let index: Int
if let currentFrame = self.currentFrame {
if currentFrame.index + 1 >= self.durationMapping.count {
index = 0
self.compressedDataReader = nil
didLoop = true
} else {
index = currentFrame.index + 1
}
} else {
index = 0
self.compressedDataReader = nil
}
if self.compressedDataReader == nil {
self.compressedDataReader = DecompressedData(compressedData: self.data, dataRange: self.range)
}
guard let compressedDataReader = self.compressedDataReader else {
self.currentFrame = nil
return didLoop
}
do {
let frameLength = Int(try compressedDataReader.readUInt32())
let frameType = Int(try compressedDataReader.readUInt32())
let dctCoefficients: DctCoefficientsYUVA420
if let sharedDctCoefficients = self.sharedDctCoefficients, sharedDctCoefficients.yPlane.width == self.width, sharedDctCoefficients.yPlane.height == self.height, !"".isEmpty {
dctCoefficients = sharedDctCoefficients
} else {
dctCoefficients = DctCoefficientsYUVA420(width: self.width, height: self.height)
self.sharedDctCoefficients = dctCoefficients
}
var frameOffset = 0
for i in 0 ..< 4 {
let planeLength = Int(try compressedDataReader.readUInt32())
if planeLength < 0 || planeLength > 20 * 1024 * 1024 {
throw ReadError.generic
}
let plane: DctCoefficientPlane
switch i {
case 0:
plane = dctCoefficients.yPlane
case 1:
plane = dctCoefficients.uPlane
case 2:
plane = dctCoefficients.vPlane
case 3:
plane = dctCoefficients.aPlane
default:
throw ReadError.generic
}
if planeLength != plane.data.count {
throw ReadError.generic
}
if frameOffset + plane.data.count > frameLength {
throw ReadError.generic
}
try plane.data.withUnsafeMutableBytes { bytes in
try compressedDataReader.read(bytes: bytes.baseAddress!.assumingMemoryBound(to: UInt8.self), count: bytes.count)
}
frameOffset += plane.data.count
}
let yuvaSurface: ImageYUVA420
if let currentYUVASurface = self.currentYUVASurface {
yuvaSurface = currentYUVASurface
} else {
yuvaSurface = ImageYUVA420(width: dctCoefficients.yPlane.width, height: dctCoefficients.yPlane.height, rowAlignment: nil)
}
let currentCoefficients: DctCoefficientsYUVA420
if let current = self.currentCoefficients {
currentCoefficients = current
} else {
currentCoefficients = DctCoefficientsYUVA420(width: yuvaSurface.yPlane.width, height: yuvaSurface.yPlane.height)
self.currentCoefficients = currentCoefficients
}
/*let deltaCoefficients: DctCoefficientsYUVA420
if let current = self.deltaCoefficients {
deltaCoefficients = current
} else {
deltaCoefficients = DctCoefficientsYUVA420(width: yuvaSurface.yPlane.width, height: yuvaSurface.yPlane.height)
self.deltaCoefficients = deltaCoefficients
}*/
switch frameType {
case 1:
dctCoefficients.idct8x8(dctData: self.currentDctData, target: yuvaSurface)
yuvaSurface.toCoefficients(target: currentCoefficients)
default:
dctCoefficients.idct4x4Add(dctData: self.currentDctData, target: currentCoefficients)
//currentCoefficients.add(other: deltaCoefficients)
currentCoefficients.toYUVA420(target: yuvaSurface)
}
self.currentFrame = CurrentFrame(index: index, duration: self.durationMapping[index], yuva: yuvaSurface)
} catch {
self.currentFrame = nil
self.compressedDataReader = nil
}
return didLoop
}
func reset() {
self.currentFrame = nil
}
func advance(advance: AnimationCacheItem.Advance, requestedFormat: AnimationCacheItemFrame.RequestedFormat) -> AnimationCacheItem.AdvanceResult? {
var didLoop = false
switch advance {
case let .frames(count):
for _ in 0 ..< count {
if self.loadNextFrame() {
didLoop = true
}
}
case let .duration(duration):
var durationOverflow = duration
while true {
if let currentFrame = self.currentFrame {
currentFrame.remainingDuration -= durationOverflow
if currentFrame.remainingDuration <= 0.0 {
durationOverflow = -currentFrame.remainingDuration
if self.loadNextFrame() {
didLoop = true
}
} else {
break
}
} else {
if self.loadNextFrame() {
didLoop = true
}
break
}
}
}
guard let currentFrame = self.currentFrame else {
return nil
}
switch requestedFormat {
case .rgba:
let currentSurface = ImageARGB(width: currentFrame.yuva.yPlane.width, height: currentFrame.yuva.yPlane.height, rowAlignment: 32)
currentFrame.yuva.toARGB(target: currentSurface)
return AnimationCacheItem.AdvanceResult(
frame: AnimationCacheItemFrame(format: .rgba(data: currentSurface.argbPlane.data, width: currentSurface.argbPlane.width, height: currentSurface.argbPlane.height, bytesPerRow: currentSurface.argbPlane.bytesPerRow), duration: currentFrame.duration),
didLoop: didLoop
)
case .yuva:
return AnimationCacheItem.AdvanceResult(
frame: AnimationCacheItemFrame(
format: .yuva(
y: AnimationCacheItemFrame.Plane(
data: currentFrame.yuva.yPlane.data,
width: currentFrame.yuva.yPlane.width,
height: currentFrame.yuva.yPlane.height,
bytesPerRow: currentFrame.yuva.yPlane.bytesPerRow
),
u: AnimationCacheItemFrame.Plane(
data: currentFrame.yuva.uPlane.data,
width: currentFrame.yuva.uPlane.width,
height: currentFrame.yuva.uPlane.height,
bytesPerRow: currentFrame.yuva.uPlane.bytesPerRow
),
v: AnimationCacheItemFrame.Plane(
data: currentFrame.yuva.vPlane.data,
width: currentFrame.yuva.vPlane.width,
height: currentFrame.yuva.vPlane.height,
bytesPerRow: currentFrame.yuva.vPlane.bytesPerRow
),
a: AnimationCacheItemFrame.Plane(
data: currentFrame.yuva.aPlane.data,
width: currentFrame.yuva.aPlane.width,
height: currentFrame.yuva.aPlane.height,
bytesPerRow: currentFrame.yuva.aPlane.bytesPerRow
)
),
duration: currentFrame.duration
),
didLoop: didLoop
)
}
}
}
private func readData(data: Data, offset: Int, count: Int) -> Data {
var result = Data(count: count)
result.withUnsafeMutableBytes { bytes -> Void in
data.withUnsafeBytes { dataBytes -> Void in
memcpy(bytes.baseAddress!, dataBytes.baseAddress!.advanced(by: offset), count)
}
}
return result
}
private func readUInt32(data: Data, offset: Int) -> UInt32 {
var value: UInt32 = 0
withUnsafeMutableBytes(of: &value, { bytes -> Void in
data.withUnsafeBytes { dataBytes -> Void in
memcpy(bytes.baseAddress!, dataBytes.baseAddress!.advanced(by: offset), 4)
}
})
return value
}
private func readFloat32(data: Data, offset: Int) -> Float32 {
var value: Float32 = 0
withUnsafeMutableBytes(of: &value, { bytes -> Void in
data.withUnsafeBytes { dataBytes -> Void in
memcpy(bytes.baseAddress!, dataBytes.baseAddress!.advanced(by: offset), 4)
}
})
return value
}
private func writeUInt32(data: inout Data, value: UInt32) {
var value: UInt32 = value
withUnsafeBytes(of: &value, { bytes -> Void in
data.count += 4
data.withUnsafeMutableBytes { dataBytes -> Void in
memcpy(dataBytes.baseAddress!.advanced(by: dataBytes.count - 4), bytes.baseAddress!, 4)
}
})
}
private func writeFloat32(data: inout Data, value: Float32) {
var value: Float32 = value
withUnsafeBytes(of: &value, { bytes -> Void in
data.count += 4
data.withUnsafeMutableBytes { dataBytes -> Void in
memcpy(dataBytes.baseAddress!.advanced(by: dataBytes.count - 4), bytes.baseAddress!, 4)
}
})
}
private final class CompressedFileWriter {
enum WriteError: Error {
case generic
}
private let file: ManagedFile
private let stream: UnsafeMutablePointer<compression_stream>
private let tempOutputBufferSize: Int = 64 * 1024
private let tempOutputBuffer: UnsafeMutablePointer<UInt8>
private let tempInputBufferCapacity: Int = 64 * 1024
private let tempInputBuffer: UnsafeMutablePointer<UInt8>
private var tempInputBufferSize: Int = 0
private var didFail: Bool = false
init?(file: ManagedFile) {
self.file = file
self.stream = UnsafeMutablePointer<compression_stream>.allocate(capacity: 1)
guard compression_stream_init(self.stream, COMPRESSION_STREAM_ENCODE, algorithm) != COMPRESSION_STATUS_ERROR else {
self.stream.deallocate()
return nil
}
self.tempOutputBuffer = UnsafeMutablePointer<UInt8>.allocate(capacity: self.tempOutputBufferSize)
self.tempInputBuffer = UnsafeMutablePointer<UInt8>.allocate(capacity: self.tempInputBufferCapacity)
}
deinit {
compression_stream_destroy(self.stream)
self.stream.deallocate()
self.tempOutputBuffer.deallocate()
self.tempInputBuffer.deallocate()
}
private func flushBuffer() throws {
if self.didFail {
throw WriteError.generic
}
if self.tempInputBufferSize <= 0 {
return
}
self.stream.pointee.src_ptr = UnsafePointer(self.tempInputBuffer)
self.stream.pointee.src_size = self.tempInputBufferSize
while true {
self.stream.pointee.dst_ptr = self.tempOutputBuffer
self.stream.pointee.dst_size = self.tempOutputBufferSize
let status = compression_stream_process(self.stream, 0)
if status == COMPRESSION_STATUS_ERROR {
self.didFail = true
throw WriteError.generic
}
let writtenBytes = self.tempOutputBufferSize - self.stream.pointee.dst_size
if writtenBytes > 0 {
let _ = self.file.write(self.tempOutputBuffer, count: writtenBytes)
}
if status == COMPRESSION_STATUS_END {
break
} else {
if self.stream.pointee.src_size == 0 {
break
}
}
}
self.tempInputBufferSize = 0
}
func write(bytes: UnsafePointer<UInt8>, count: Int) throws {
var writtenBytes = 0
while writtenBytes < count {
let availableBytes = self.tempInputBufferCapacity - self.tempInputBufferSize
if availableBytes == 0 {
try flushBuffer()
} else {
let writeCount = min(availableBytes, count - writtenBytes)
memcpy(self.tempInputBuffer.advanced(by: self.tempInputBufferSize), bytes.advanced(by: writtenBytes), writeCount)
self.tempInputBufferSize += writeCount
writtenBytes += writeCount
}
}
}
func flush() throws {
if self.didFail {
throw WriteError.generic
}
try self.flushBuffer()
while true {
self.stream.pointee.dst_ptr = self.tempOutputBuffer
self.stream.pointee.dst_size = self.tempOutputBufferSize
let status = compression_stream_process(self.stream, Int32(COMPRESSION_STREAM_FINALIZE.rawValue))
if status == COMPRESSION_STATUS_ERROR {
self.didFail = true
throw WriteError.generic
}
let writtenBytes = self.tempOutputBufferSize - self.stream.pointee.dst_size
if writtenBytes > 0 {
let _ = self.file.write(self.tempOutputBuffer, count: writtenBytes)
}
if status == COMPRESSION_STATUS_END {
break
}
}
}
func writeUInt32(_ value: UInt32) throws {
var value: UInt32 = value
try withUnsafeBytes(of: &value, { bytes -> Void in
try self.write(bytes: bytes.baseAddress!.assumingMemoryBound(to: UInt8.self), count: 4)
})
}
func writeFloat32(_ value: Float32) throws {
var value: Float32 = value
try withUnsafeBytes(of: &value, { bytes -> Void in
try self.write(bytes: bytes.baseAddress!.assumingMemoryBound(to: UInt8.self), count: 4)
})
}
}
private final class DecompressedData {
enum ReadError: Error {
case didReadToEnd
}
private let compressedData: Data
private let dataRange: Range<Int>
private let stream: UnsafeMutablePointer<compression_stream>
private var isComplete = false
// Bytes of dataRange already consumed by compression_stream_process. src_ptr
// cannot be cached across calls: it must be re-derived from a live
// withUnsafeBytes pointer every time (see read(bytes:count:) below).
private var consumedSrcBytes = 0
init?(compressedData: Data, dataRange: Range<Int>) {
self.compressedData = compressedData
self.dataRange = dataRange
self.stream = UnsafeMutablePointer<compression_stream>.allocate(capacity: 1)
guard compression_stream_init(self.stream, COMPRESSION_STREAM_DECODE, algorithm) != COMPRESSION_STATUS_ERROR else {
self.stream.deallocate()
return nil
}
}
deinit {
compression_stream_destroy(self.stream)
self.stream.deallocate()
}
func read(bytes: UnsafeMutablePointer<UInt8>, count: Int) throws {
if self.isComplete {
throw ReadError.didReadToEnd
}
// The pointer handed to a withUnsafeBytes closure is only valid for the
// duration of that closure (Data's storage can move/deallocate once it
// returns). The previous code stashed it into stream.pointee.src_ptr in
// init and kept using it across later read() calls — a dangling-pointer
// read that corrupted the heap and surfaced later as a malloc abort
// (SIGABRT inside libsystem_malloc, DCTMultiAnimationRenderer-FirstFrame
// queue, build 33196). Re-derive a live pointer here on every call