-
Notifications
You must be signed in to change notification settings - Fork 8
/
Copy pathVideoTests.swift
1917 lines (1719 loc) · 76.4 KB
/
VideoTests.swift
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
// swiftlint:disable force_try force_cast
#if canImport(MediaToolSwift) // && !os(visionOS)
@testable import MediaToolSwift
import XCTest
import Foundation
import AVFoundation
import VideoToolbox
import CoreVideo
import Vision
import Accelerate.vImage
import UniformTypeIdentifiers
import QuartzCore
#if os(macOS)
import ImageIO
import AppKit
#else
import UIKit
#endif
struct ConfigList {
let filename: String
let url: String? // [nil] for local file
let input: Parameters
let configs: [Config]
}
struct Config {
let videoSettings: CompressionVideoSettings
let output: Parameters
}
struct Parameters {
let filename: String
let filesize: Int?
let resolution: CGSize?
let videoCodec: AVVideoCodecType
let fileType: VideoFileType
let bitrate: Int? // in bits (!), approximate, [nil] to skip, [-1] to check if output is less than input
let frameRate: Int? // [nil] to skip, [-1] to check if output is less than input
let duration: Double? // in seconds
let hasAlpha: Bool?
}
struct AudioData {
let format: AudioFormatID
let bitrate: Int?
let sampleRate: Int?
let channels: Int?
}
// Configurations used by tests
var configurations: [ConfigList] {
var videos = [
// Big Buck Bunny H.264 - https://test-videos.co.uk/bigbuckbunny/mp4-h264
ConfigList(
filename: "bigbuckbunny_h264_640x360.mp4",
url: "https://test-videos.co.uk/vids/bigbuckbunny/mp4/h264/360/Big_Buck_Bunny_360_10s_1MB.mp4",
input: Parameters(
filename: "bigbuckbunny_h264_640x360.mp4",
filesize: 991_017,
resolution: CGSize(width: 640.0, height: 360.0),
videoCodec: .h264,
fileType: .mp4,
bitrate: 789_000,
frameRate: 30,
duration: 10.0,
hasAlpha: false
),
configs: [
Config(
videoSettings: CompressionVideoSettings(
codec: .hevc
),
output: Parameters(
filename: "exported_bigbuckbunny_h264_640x360.mp4",
filesize: -1,
resolution: CGSize(width: 640.0, height: 360.0),
videoCodec: .hevc,
fileType: .mp4,
bitrate: -1,
frameRate: 30,
duration: 10.0,
hasAlpha: false
)
)
]
),
ConfigList(
filename: "bigbuckbunny_h264_1280x720.mp4",
url: "https://test-videos.co.uk/vids/bigbuckbunny/mp4/h264/720/Big_Buck_Bunny_720_10s_2MB.mp4",
input: Parameters(
filename: "bigbuckbunny_h264_1280x720.mp4",
filesize: 1_978_137,
resolution: CGSize(width: 1280.0, height: 720.0),
videoCodec: .h264,
fileType: .mp4,
bitrate: 1_579_000,
frameRate: 30,
duration: 10.0,
hasAlpha: false
),
configs: [
Config(
videoSettings: CompressionVideoSettings(
codec: .hevc,
size: .fit(CGSize(width: 720.0, height: 720.0))
),
output: Parameters(
filename: "exported_bigbuckbunny_h264_1280x720.mp4",
filesize: -1,
resolution: CGSize(width: 720.0, height: 404.0), // 404 rounded from 405
videoCodec: .hevc,
fileType: .mp4,
bitrate: -1,
frameRate: 30,
duration: 10.0,
hasAlpha: false
)
)
]
),
ConfigList(
filename: "chromecast.mp4",
url: nil,
input: Parameters(
filename: "chromecast.mp4",
filesize: 2_498_125,
resolution: CGSize(width: 1280.0, height: 720.0),
videoCodec: .h264,
fileType: .mp4,
bitrate: 1_135_000,
frameRate: 24, // 23.98
duration: 15.02,
hasAlpha: false
),
configs: [
Config(
videoSettings: CompressionVideoSettings(
codec: .hevc
),
output: Parameters(
filename: "exported_chromecast.mp4",
filesize: 2_100_000,
resolution: CGSize(width: 1280.0, height: 720.0),
videoCodec: .hevc,
fileType: .mp4,
bitrate: 950_000,
frameRate: 24, // 23.98
duration: 15.02,
hasAlpha: false
)
)
]
),
// Portrait Video H.264
ConfigList(
filename: "sunset_h264_portrait_480_848.mp4",
url: nil,
input: Parameters(
filename: "sunset_h264_portrait_480_848.mp4",
filesize: 1_066_855,
resolution: CGSize(width: 480.0, height: 848.0),
videoCodec: .h264,
fileType: .mp4,
bitrate: 1_639_000,
frameRate: 30,
duration: 5.2,
hasAlpha: false
),
configs: [
Config(
videoSettings: CompressionVideoSettings(
codec: .hevcWithAlpha, // should be replaced with hevc by compressor
preserveAlphaChannel: false
),
output: Parameters(
filename: "exported_sunset_h264_portrait_480_848.mp4",
filesize: nil,
resolution: CGSize(width: 480.0, height: 848.0),
videoCodec: .hevc,
fileType: .mp4,
bitrate: nil,
frameRate: 30,
duration: 5.2,
hasAlpha: false
)
)
]
),
// Alpha channel
ConfigList(
filename: "transparent_ball_hevc.mov",
url: nil,
input: Parameters(
filename: "transparent_ball_hevc.mov",
filesize: 236_047,
resolution: CGSize(width: 1280.0, height: 720.0),
videoCodec: .hevcWithAlpha,
fileType: .mov,
bitrate: 462_000,
frameRate: 60,
duration: 4.0,
hasAlpha: true
),
configs: [
// Preserve alpha channel
Config(
videoSettings: CompressionVideoSettings(
codec: .hevcWithAlpha,
bitrate: .value(450_000),
preserveAlphaChannel: true
),
output: Parameters(
filename: "exported_transparent_ball_hevc.mov",
filesize: nil,
resolution: CGSize(width: 1280.0, height: 720.0),
videoCodec: .hevcWithAlpha,
fileType: .mov,
bitrate: nil,
frameRate: 60,
duration: 4.0,
hasAlpha: true
)
),
// Remove alpha channel
Config(
videoSettings: CompressionVideoSettings(
codec: .hevc,
preserveAlphaChannel: false
),
output: Parameters(
filename: "exported_transparent_ball_hevc_2.mov",
filesize: nil,
resolution: CGSize(width: 1280.0, height: 720.0),
videoCodec: .hevc,
fileType: .mov,
bitrate: nil,
frameRate: 60,
duration: 4.0,
hasAlpha: false
)
)
]
),
// HDR, portrait (Google Pixel 7)
ConfigList(
filename: "google_pixel_hdr.mp4",
url: nil,
input: Parameters(
filename: "google_pixel_hdr.mp4",
filesize: 43_376_890,
resolution: CGSize(width: 2160.0, height: 3840.0),
videoCodec: .hevc,
fileType: .mp4,
bitrate: 43_299_000,
frameRate: 30, // 29.99
duration: 7.97,
hasAlpha: false
),
configs: [
Config(
videoSettings: CompressionVideoSettings(bitrate: .value(4_000_000)),
output: Parameters(
filename: "exported_google_pixel_hdr.mov",
filesize: nil, // ~= 17_000_000
resolution: CGSize(width: 2160.0, height: 3840.0),
videoCodec: .hevcWithAlpha,
fileType: .mov,
bitrate: nil, // ~- 15_715_000
frameRate: 30,
duration: 7.97,
hasAlpha: false
)
)
]
),
// Slo-mo, 120/240fps, all video codecs supported, lowering frame rate (240->120), custom bitrate and video operations works
// On iOS any videos above ~120 fps handled as slo-mo
ConfigList(
filename: "slomo_120_fps.mov",
url: nil,
input: Parameters(
filename: "slomo_120_fps.mov",
filesize: 13_354_827,
resolution: CGSize(width: 1080.0, height: 1920.0),
videoCodec: .hevc,
fileType: .mov,
bitrate: 21_273_000,
frameRate: 108, // originally 120, but was cropped so at average is lower
duration: 4.33,
hasAlpha: false
),
configs: [
Config(
videoSettings: CompressionVideoSettings(bitrate: .value(21_000_000)),
output: Parameters(
filename: "exported_slomo_120_fps.mov",
filesize: nil, // ~= 13_303_814
resolution: CGSize(width: 1080.0, height: 1920.0),
videoCodec: .hevc,
fileType: .mov,
bitrate: 21_000_000, // nil
frameRate: 120,
duration: 4.33,
hasAlpha: false
)
)
]
),
ConfigList(
filename: "slomo_240_fps.mov",
url: nil,
input: Parameters(
filename: "slomo_240_fps.mov",
filesize: 31_071_646,
resolution: CGSize(width: 1080.0, height: 1920.0),
videoCodec: .hevc,
fileType: .mov,
bitrate: 53_915_000,
frameRate: 240,
duration: 4.60,
hasAlpha: false
),
configs: [
Config(
videoSettings: CompressionVideoSettings(bitrate: .value(10_000_000)),
output: Parameters(
filename: "exported_slomo_240_fps.mov",
filesize: nil, // ~= 31_030_000
resolution: CGSize(width: 1080.0, height: 1920.0),
videoCodec: .hevc,
fileType: .mov,
bitrate: nil, // ~- 53_915_000
frameRate: 240,
duration: 4.60,
hasAlpha: false
)
),
Config(
videoSettings: CompressionVideoSettings(
codec: .h264,
bitrate: .value(10_000_000),
frameRate: 120
),
output: Parameters(
filename: "exported_slomo_240_fps_2.mov",
filesize: nil, // ~= 5_908_000
resolution: CGSize(width: 1080.0, height: 1920.0),
videoCodec: .h264,
fileType: .mov,
bitrate: 10_000_000, // nil
frameRate: 120,
duration: 4.60,
hasAlpha: false
)
)
]
),
// Time-lapse, normally stored at 30 fps as any other video
ConfigList(
filename: "time_lapse.MOV",
url: nil,
input: Parameters(
filename: "time_lapse.MOV",
filesize: 3_340_362,
resolution: CGSize(width: 1080.0, height: 1920.0),
videoCodec: .hevc,
fileType: .mov,
bitrate: 14_565_000,
frameRate: 30,
duration: 1.83,
hasAlpha: false
),
configs: [
Config(
videoSettings: CompressionVideoSettings(codec: .h264),
output: Parameters(
filename: "exported_time_lapse.mov",
filesize: nil, // ~= 1_560_000
resolution: CGSize(width: 1080.0, height: 1920.0),
videoCodec: .h264,
fileType: .mov,
bitrate: nil, // 6_800_000
frameRate: 30,
duration: 1.83,
hasAlpha: false
)
)
]
)
]
// Prores
#if !os(visionOS)
videos.append(contentsOf: [
ConfigList(
filename: "transparent_ball_prores.mov",
url: nil,
input: Parameters(
filename: "transparent_ball_prores.mov",
filesize: 236_047,
resolution: CGSize(width: 1280.0, height: 720.0),
videoCodec: .proRes4444,
fileType: .mov,
bitrate: 20_723_000,
frameRate: 60,
duration: 4.0,
hasAlpha: true
),
configs: [
// Prores output
Config(
videoSettings: CompressionVideoSettings(
codec: .proRes4444,
size: .fit(CGSize(width: 720.0, height: 405.0)),
preserveAlphaChannel: true
),
output: Parameters(
filename: "exported_transparent_ball_prores.mov",
filesize: nil,
resolution: CGSize(width: 720.0, height: 405),
videoCodec: .proRes4444,
fileType: .mov,
bitrate: nil,
frameRate: 60,
duration: 4.0,
hasAlpha: true
)
),
// HEVC output
Config(
videoSettings: CompressionVideoSettings(
codec: .hevcWithAlpha,
preserveAlphaChannel: true
),
output: Parameters(
filename: "exported_transparent_ball_prores_2.mov",
filesize: nil,
resolution: CGSize(width: 1280.0, height: 720.0),
videoCodec: .hevcWithAlpha,
fileType: .mov,
bitrate: nil,
frameRate: 60,
duration: 4.0,
hasAlpha: true
)
)
]
),
// HDR, Portrait
ConfigList(
filename: "oludeniz.MOV",
url: nil,
input: Parameters(
filename: "oludeniz.MOV",
filesize: 8_429_475,
resolution: CGSize(width: 1080.0, height: 1920.0),
videoCodec: .hevc,
fileType: .mov,
bitrate: 8_688_000,
frameRate: 30,
duration: 7.6,
hasAlpha: false
),
configs: [
Config(
videoSettings: CompressionVideoSettings(bitrate: .value(4_000_000)),
output: Parameters(
filename: "exported_oludeniz_default.mov",
filesize: nil, // ~= 3_875_000
resolution: CGSize(width: 1080.0, height: 1920.0),
videoCodec: .hevc,
fileType: .mov,
bitrate: nil, // ~- 4_000_000
frameRate: 30,
duration: 7.6,
hasAlpha: false
)
),
Config(
videoSettings: CompressionVideoSettings(
codec: .proRes4444,
bitrate: .encoder,
size: .fit(CGSize(width: 3000.0, height: 4000.0)),
frameRate: 60
),
output: Parameters(
filename: "exported_oludeniz_prores.mov",
filesize: nil,
resolution: CGSize(width: 1080.0, height: 1920.0),
videoCodec: .proRes4444,
fileType: .mov,
bitrate: nil,
frameRate: 30,
duration: 7.6,
hasAlpha: false
)
),
Config(
videoSettings: CompressionVideoSettings(
size: .fit(CGSize(width: 1280.0, height: 1280.0))
),
output: Parameters(
filename: "exported_oludeniz.mov",
filesize: -1, // ~= 1.8 MB
resolution: CGSize(width: 720.0, height: 1280.0),
videoCodec: .hevc,
fileType: .mov,
bitrate: -1, // ~= 1.75-2.0 MBps
frameRate: 30,
duration: 7.6,
hasAlpha: false
)
),
Config(
videoSettings: CompressionVideoSettings(
codec: .h264,
bitrate: .value(2_000_000),
size: .fit(CGSize(width: 720.0, height: 720.0)),
frameRate: 24
),
output: Parameters(
filename: "exported_oludeniz.mp4",
filesize: 2_050_000,
resolution: CGSize(width: 404.0, height: 720.0), // floor applied to value of 405 by encoder
videoCodec: .h264,
fileType: .mp4,
bitrate: 2_000_000,
frameRate: 24,
duration: 7.6,
hasAlpha: false
)
)
]
)
])
#endif
// INFO: VP9 and AV1 are not supported yet
// Big Buck Bunny VP9 - https://test-videos.co.uk/bigbuckbunny/webm-vp9
// Big Buck Bunny AV1 - https://test-videos.co.uk/bigbuckbunny/webm-av1
// Jellyfish - https://test-videos.co.uk/jellyfish/mp4-h265
// Chromium test videos - https://github.com/chromium/chromium/tree/master/media/test/data
// WebM test videos - https://github.com/webmproject/libwebm/tree/main/testing/testdata
return []
}
// Download file from url and save to local directory
func downloadFile(url: String, path: String) async throws {
let url: URL = URL(string: url)!
let (data, _) = try await URLSession.shared.data(from: url)
try data.write(to: URL(fileURLWithPath: path))
}
class MediaToolSwiftTests: XCTestCase {
static let testsDirectory = URL(fileURLWithPath: #file).deletingLastPathComponent()
static let mediaDirectory = testsDirectory.appendingPathComponent("media")
static let tempDirectory = mediaDirectory.appendingPathComponent("temp")
static var setUpCalled = false
override func setUp() {
guard !Self.setUpCalled else { return }
// Used to stop execution of fulfillment expectations whenever at least one of them fails
// XCTestObservationCenter.shared.addTestObserver(TestObserver())
super.setUp()
Task {
// Fetch all video files
for config in configurations {
if let url = config.url {
let path: String = Self.mediaDirectory.appendingPathComponent(config.filename).path
if !FileManager.default.fileExists(atPath: path) {
try! await downloadFile(url: url, path: path)
}
}
}
}
var isDirectory: ObjCBool = true
if !FileManager.default.fileExists(atPath: Self.tempDirectory.path, isDirectory: &isDirectory) {
try! FileManager.default.createDirectory(atPath: Self.tempDirectory.path, withIntermediateDirectories: false)
}
Self.setUpCalled = true
}
override func tearDown() {
// Delete system AVAssetWriter temp files
do {
let files = try! FileManager.default.contentsOfDirectory(at: Self.tempDirectory, includingPropertiesForKeys: nil, options: .skipsHiddenFiles)
for file in files where !(
file.pathExtension.lowercased() == "mov" ||
file.pathExtension.lowercased() == "mp4" ||
file.pathExtension.lowercased() == "m4v" ||
file.pathExtension.lowercased() == "jpg" ||
file.pathExtension.lowercased() == "jpeg" ||
file.pathExtension.lowercased() == "png" ||
file.pathExtension.lowercased() == "bmp" ||
file.pathExtension.lowercased() == "tiff" ||
file.pathExtension.lowercased() == "ico" ||
file.pathExtension.lowercased() == "gif" ||
file.pathExtension.lowercased() == "heic" ||
file.pathExtension.lowercased() == "heif" ||
file.pathExtension.lowercased() == "heics" ||
file.pathExtension.lowercased() == "webp" ||
file.pathExtension.lowercased() == "m4a" ||
file.pathExtension.lowercased() == "mp3" ||
file.pathExtension.lowercased() == "wav" ||
file.pathExtension.lowercased() == "caf" ||
file.pathExtension.lowercased() == "aiff" ||
file.pathExtension.lowercased() == "aifc" ||
file.hasDirectoryPath
) {
try FileManager.default.removeItem(at: file)
}
} catch { }
super.tearDown()
}
static func fulfill(_ expectation: XCTestExpectation) {
// Allow compressor to complete
DispatchQueue.main.asyncAfter(deadline: .now() + 0.25) {
// Let the app to finish
expectation.fulfill()
}
}
#if targetEnvironment(simulator)
// Apple TV and iOS simulator compression is really slow
let osAdditionalTimeout: TimeInterval = 300 // 5 min
#else
let osAdditionalTimeout: TimeInterval = 0
#endif
#if os(macOS)
func testImageThumbnails() async {
let expectation = XCTestExpectation(description: "Test Video Image Thumbnails")
let source = Self.mediaDirectory.appendingPathComponent("chromecast.mp4")
let asset = AVAsset(url: source)
var thumbnails: [VideoThumbnail] = []
try! VideoTool.thumbnailImages(for: asset, at: [4.1], size: CGSize(width: 256, height: 256)) { items in
thumbnails.append(contentsOf: items)
Self.fulfill(expectation)
}
await fulfillment(of: [expectation], timeout: 10 + osAdditionalTimeout)
XCTAssertTrue(!thumbnails.isEmpty, "Empty thumbnails array")
}
#endif
#if os(macOS)
func testFileThumbnails() async {
let expectation = XCTestExpectation(description: "Test Video File Thumbnails")
let thumbnailsDirectory = Self.tempDirectory.appendingPathComponent("thumbnails")
// Create directory if non exists
var isDirectory: ObjCBool = true
if !FileManager.default.fileExists(atPath: thumbnailsDirectory.path, isDirectory: &isDirectory) {
try! FileManager.default.createDirectory(atPath: thumbnailsDirectory.path, withIntermediateDirectories: false)
}
let source = Self.mediaDirectory.appendingPathComponent("chromecast.mp4")
let destination = thumbnailsDirectory.appendingPathComponent("chromecast_thumb.jpg")
let asset = AVAsset(url: source)
var error: Error?
VideoTool.thumbnailFiles(of: asset, at: [VideoThumbnailRequest(time: 1.0, url: destination), VideoThumbnailRequest(time: 4.1, url: destination), VideoThumbnailRequest(time: 7.5, url: destination)], settings: ImageSettings(format: .jpeg), completion: { result in
switch result {
case .failure(let err):
error = err
case .success(_):
break
}
Self.fulfill(expectation)
})
await fulfillment(of: [expectation], timeout: 10 + osAdditionalTimeout)
XCTAssertNil(error, error!.localizedDescription)
if !FileManager.default.fileExists(atPath: destination.path) {
try? FileManager.default.removeItem(at: destination)
}
}
#endif
#if os(macOS)
func testThumbnail() async {
let expectation = XCTestExpectation(description: "Test Video Thumbnails")
let thumbnailsDirectory = Self.tempDirectory.appendingPathComponent("thumbnails")
// Create directory if non exists
var isDirectory: ObjCBool = true
if !FileManager.default.fileExists(atPath: thumbnailsDirectory.path, isDirectory: &isDirectory) {
try! FileManager.default.createDirectory(atPath: thumbnailsDirectory.path, withIntermediateDirectories: false)
}
let source = Self.mediaDirectory.appendingPathComponent("oludeniz.MOV") // chromecast.mp4 transparent_ball_hevc.mov oludeniz.MOV
let asset = AVAsset(url: source)
let formats: [ImageFormat: String] = [
.heif: ".heic",
.heic: ".c.heic",
.heif10: ".10.heic",
.png: ".png",
.jpeg: ".jpg",
.jpeg2000: ".jpeg",
.gif: ".gif",
.tiff: ".tiff",
.bmp: ".bmp",
.ico: ".ico"
]
for (format, ext) in formats {
let imageUrl = thumbnailsDirectory.appendingPathComponent("thumb\(ext)")
if FileManager.default.fileExists(atPath: imageUrl.path) {
try! FileManager.default.removeItem(atPath: imageUrl.path)
}
let settings = ImageSettings(
format: format,
//size: .fit(.hd),
//size: .crop(fit: .hd, options: .init(size: CGSize(width: 512, height: 512), aligment: .center)),
size: .crop(options: .init(size: CGSize(width: 256, height: 256), aligment: .center)),
edit: [
//.rotate(.angle(.pi/4))
//.rotate(.angle(.pi/4), fill: .color(alpha: 255, red: 255, green: 255, blue: 255)),
//.rotate(.clockwise)
/*.imageProcessing { image in
// This will extend the image frame by a little (!)
image.applyingFilter("CIGaussianBlur", parameters: [
"inputRadius": 7.5
])
}*/
]
)
VideoTool.thumbnailFiles(of: asset, at: [.init(time: 4.1, url: imageUrl)], settings: settings, timeToleranceBefore: .zero, timeToleranceAfter: .zero, completion: { result in
switch result {
case .success(_):
break
case .failure(let error):
print(error)
}
Self.fulfill(expectation)
})
}
await fulfillment(of: [expectation], timeout: 30 + osAdditionalTimeout)
// Check files exists
for (_, ext) in formats {
let imageUrl = thumbnailsDirectory.appendingPathComponent("thumb\(ext)")
XCTAssertTrue(FileManager.default.fileExists(atPath: imageUrl.path))
}
// Check the HDR data persist
let heic10URL = thumbnailsDirectory.appendingPathComponent("thumb.10.heic")
let heicImageSource = CGImageSourceCreateWithURL(heic10URL as CFURL, nil)!
let heicCGImage = CGImageSourceCreateImageAtIndex(heicImageSource, 0, nil)!
XCTAssertTrue(heicCGImage.bitsPerComponent > 8, "No HDR data found")
let heicProperties = CGImageSourceCopyPropertiesAtIndex(heicImageSource, 0, nil) as? [CFString: Any]
XCTAssertTrue(heicProperties?[kCGImagePropertyDepth] as? Int ?? 8 > 8, "No HDR data found (depth)")
// Delete thumbnails
/*do {
let files = try! FileManager.default.contentsOfDirectory(at: thumbnailsDirectory, includingPropertiesForKeys: nil, options: .skipsHiddenFiles)
for file in files {
try FileManager.default.removeItem(at: file)
}
} catch { }*/
}
#endif
#if !os(visionOS)
/// Video overlay, apply CIFilters, and many more using custom CIImage processor
func testImageProcessing() async {
#if os(macOS)
typealias Font = NSFont
typealias Color = NSColor
#else
typealias Font = UIFont
typealias Color = UIColor
#endif
let expectation = XCTestExpectation(description: "Image Processing Example")
let source = Self.mediaDirectory.appendingPathComponent("oludeniz.MOV")
let destination = Self.tempDirectory.appendingPathComponent("image_processor_oludeniz.MOV")
let duration = AVAsset(url: source).duration.seconds // source video duration, be carefull with cutting
let white = CGColor(red: 244/255, green: 244/255, blue: 244/255, alpha: 1.0)
//let dark = CGColor(red: 43/255, green: 43/255, blue: 43/255, alpha: 1.0)
//let black = CGColor(red: 35/255, green: 34/255, blue: 35/255, alpha: 1.0)
let darkGreen = CGColor(red: 7/255, green: 94/255, blue: 84/255, alpha: 1.0)
//let orange = CGColor(red: 252/255, green: 176/255, blue: 69/255, alpha: 0.9)
let yellow = CGColor(red: 250/255, green: 197/255, blue: 22/255, alpha: 1.0)
//let red = CGColor(red: 250/255, green: 75/255, blue: 22/255, alpha: 1.0)
let imageProcessor = { (_ image: CIImage, _ context: CIContext, _ time: Double) -> CIImage in
/* Parameters:
- Image: An CIImage to modify
- Context: CIContext for reuse
- Time: Frame time in seconds, use this to show/hide overlays or filter based on video time
*/
var image = image
let size = image.extent.size
// Warning: This method called once for each frame, the code in this block must be optimized
// For example initialize filter once and reuse, render text to image once, then composite based on time
// Warning: When .mirror, .flip or other tranformation (except rotation) is applied to video, it's also applied overlays
// To prevent apply oposite tranformation
let mirrored = CGAffineTransform(scaleX: -1.0, y: 1.0).translatedBy(x: -size.width, y: 0)
// let flipped = CGAffineTransform(scaleX: 1.0, y: -1.0).translatedBy(x: 0, y: -size.height)
let transform: CGAffineTransform = mirrored // .identity, mirrored, flipped
// Apply Blur after 2.8 sec
if time >= 2.8 {
//https://developer.apple.com/documentation/coreimage/processing_an_image_using_built-in_filters
//https://developer.apple.com/library/archive/documentation/GraphicsImaging/Reference/CoreImageFilterReference/index.html#//apple_ref/doc/filter/ci
image = image.clampedToExtent().applyingFilter("CIGaussianBlur", parameters: [
"inputRadius": 7.5
]).cropped(to: CGRect(origin: .zero, size: size))
}
// Progress
let timeFactor = time/duration
let timeFactorBefore = { (end: Double) in time / end }
let timeFactorAfter = { (start: Double) in max(0, (time - start) / (duration - start)) }
let timeFactorRange = { (start: Double, end: Double) in
let progress = (time - start) / (end - start)
return max(0, min(progress, 1))
}
// Overlay text, all the duration
let shadow = NSShadow()
shadow.shadowColor = Color.white
shadow.shadowBlurRadius = Easing.default(from: -5, to: 15, with: timeFactor)
// Text attributes
let attributes: [NSAttributedString.Key: Any] = [
.font: Font.systemFont(ofSize: Easing.default(from: 92, to: 200, with: timeFactor)),
.foregroundColor: time <= 6 ?
Easing.linear.interpolate(from: white, to: yellow, with: timeFactorBefore(6)) :
Easing.sineIn.interpolate(from: yellow, to: darkGreen, with: timeFactorAfter(6)),
.backgroundColor: CGColor(red: 40/255, green: 40/255, blue: 40/255, alpha: Easing.default(from: 0.5, to: 0.0, with: timeFactorBefore(2.8))),
.strokeWidth: time >= 2.8 ? Easing.default(from: 3, to: 2, with: timeFactor) : 0.0,
.shadow: shadow
]
let attributedString = NSAttributedString(string: " Ölüdeniz 🏖️ ", attributes: attributes)
let textFilter = CIFilter(name: "CIAttributedTextImageGenerator", parameters: [
"inputText": attributedString
])!
var textImage = textFilter.outputImage!
// Center text
textImage = textImage.transformed(by: .init(
translationX: Easing.bounceOut.interpolate(
from: (size.width - textImage.extent.width) / 2.0 + 200,
to: (size.width - textImage.extent.width) / 2.0,
with: timeFactor
),
y: Easing.bounceOut.interpolate(
from: (size.height - textImage.extent.height) / 2.0 + 640,
to: (size.height - textImage.extent.height) / 2.0,
with: timeFactor
)
))
// Transform
textImage = textImage.transformed(by: transform)
// Place text over source image
image = textImage
.cropped(to: image.extent)
.composited(over: image)
// Advanced String/Letters Animation by rendering each letter separately and then animate position/opacity/atd.
if timeFactor < 0.99 {
#if os(macOS)
let fontSize: CGFloat = 36
#else
let fontSize: CGFloat = 24
#endif
let orange = Color(red: 252/255, green: 176/255, blue: 69/255, alpha: 0.9)
let green = Color(red: 7/255, green: 94/255, blue: 84/255, alpha: 1.0)
// String to animate with base character attributes
let storage = NSTextStorage(string: "Animated String ✨", attributes: [
.foregroundColor: Color.white,
.font: Font.boldSystemFont(ofSize: fontSize),
//.kern: 18.0,
])
// Separate attributed strings for each character using .byComposedCharacterSequences
// Or animate by words, sentences, lines, paragraphs, atd. using .byWords, .byLines, ...
var attributedCharacters: [NSAttributedString] = []
storage.string.enumerateSubstrings(in: storage.string.startIndex..<storage.string.endIndex, options: .byComposedCharacterSequences, { (substring, substringRange, _, _) in
let range = NSRange(substringRange, in: storage.string)
let char = storage.attributedSubstring(from: range)
let customized: NSMutableAttributedString = char.mutableCopy() as! NSMutableAttributedString
if range.length == 1 {
customized.addAttribute(.foregroundColor, value: attributedCharacters.count % 2 == 0 ? orange : green, range: NSMakeRange(0, 1))
}
attributedCharacters.append(customized)
})
// Text size
let textSize = storage.boundingRect(with: CGRect.infinite.size, options: [.usesLineFragmentOrigin, .usesFontLeading], context: nil).size
// Position on image
#if os(macOS)
let spacing: CGFloat = 24 // space between characters
#else
let spacing: CGFloat = 32
#endif
let allSpacing = max(0, (CGFloat(attributedCharacters.count) - 2)) * spacing
let centerX = (size.width - (textSize.width + allSpacing)) / 2.0
// let centerY = (size.height - textSize.height) / 2.0
let point = CGPoint(x: centerX, y: 256) // starting point
var offsetX: CGFloat = 0 // used to draw letters one by one while increasing offset
let stepsY: CGFloat = 10 // animation height - fullSize.height * stepsY
let startPoint = CGPoint(x: point.x, y: point.y + textSize.height * stepsY)
let endPoint = CGPoint(x: point.x, y: point.y )
let delay = 0.3 // delay in animation between chars, from left to right, in sec
for idx in 0...attributedCharacters.count-1 {
let char = attributedCharacters[idx]
let size = char.size()
let progress = timeFactorRange(Double(idx) * delay, 0.99 * duration)
// Create an character image
#if os(macOS)
let characterImage = NSImage(size: size)
characterImage.lockFocus()
char.draw(at: .zero)
characterImage.unlockFocus()
// Construct CIImage
var ciImage = CIImage(data: characterImage.tiffRepresentation!)!
// var ciImage = CIImage(cgImage: characterImage.cgImage(forProposedRect: nil, context: nil, hints: nil)!)
#else
let renderer = UIGraphicsImageRenderer(size: size)
let characterImage = renderer.image { context in
char.draw(at: .zero)
}
var ciImage = CIImage(image: characterImage)!
#endif
// Position
let start = CGPoint(x: startPoint.x + offsetX, y: startPoint.y)
let end = CGPoint(x: endPoint.x + offsetX, y: endPoint.y)
ciImage = ciImage.transformed(by: .init(
translationX: Easing.bounceInOut.interpolate(from: start.x, to: end.x, with: progress),
y: Easing.bounceInOut.interpolate(from: start.y, to: end.y, with: progress)
))
// Opacity
let alpha = Easing.default(from: 0.0, to: 1.0, with: progress)
ciImage = ciImage.applyingFilter("CIColorMatrix", parameters: [
"inputAVector": CIVector(values: [0.0, 0.0, 0.0, CGFloat(alpha)], count: 4),
])
offsetX += size.width + spacing
// Transform & Insert
ciImage = ciImage.transformed(by: transform)
image = ciImage
.cropped(to: image.extent)
.composited(over: image)
}
}
// Image overlay
if time >= 2.8 {
let imageUrl = Self.mediaDirectory.appendingPathComponent("starkdev.png")
var ciImageOverlay = CIImage(contentsOf: imageUrl)! // 512x512
// Resize
ciImageOverlay = ciImageOverlay.transformed(by: .init(scaleX: 0.25, y: 0.25))
// Adjust position
ciImageOverlay = ciImageOverlay.transformed(by: .init(translationX: size.width - ciImageOverlay.extent.size.width - 44, y: 44))
// Tint PNG
ciImageOverlay = CIImage(color: CIColor(red: 244/255, green: 244/255, blue: 244/255, alpha: 1.0))
.cropped(to: ciImageOverlay.extent)
.applyingFilter("CIBlendWithAlphaMask", parameters: [
"inputBackgroundImage": ciImageOverlay,