-
-
Notifications
You must be signed in to change notification settings - Fork 289
/
Utilities.swift
4104 lines (3368 loc) Β· 100 KB
/
Utilities.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
import Cocoa
import AVFoundation
import class Quartz.QLPreviewPanel
import StoreKit.SKStoreReviewController
import Accelerate.vImage
import Defaults
/**
Convenience function for initializing an object and modifying its properties
```
let label = with(NSTextField()) {
$0.stringValue = "Foo"
$0.textColor = .systemBlue
view.addSubview($0)
}
```
*/
@discardableResult
func with<T>(_ item: T, update: (inout T) throws -> Void) rethrows -> T {
var this = item
try update(&this)
return this
}
func delay(seconds: TimeInterval, closure: @escaping () -> Void) {
DispatchQueue.main.asyncAfter(deadline: .now() + seconds, execute: closure)
}
extension NSView {
func shake(duration: TimeInterval = 0.3, direction: NSUserInterfaceLayoutOrientation) {
let translation = direction == .horizontal ? "x" : "y"
let animation = CAKeyframeAnimation(keyPath: "transform.translation.\(translation)")
animation.timingFunction = .linear
animation.duration = duration
animation.values = [-5, 5, -2.5, 2.5, 0]
layer?.add(animation, forKey: nil)
}
}
/// This is useful as `awakeFromNib` is not called for programatically created views.
class SSView: NSView { // swiftlint:disable:this final_class
var didAppearWasCalled = false
/// Meant to be overridden in subclasses
func didAppear() {}
override func viewDidMoveToSuperview() {
super.viewDidMoveToSuperview()
if !didAppearWasCalled {
didAppearWasCalled = true
didAppear()
}
}
}
extension NSWindow {
// Helper.
private static func centeredOnScreen(rect: CGRect) -> CGRect {
guard let screen = NSScreen.main else {
return rect
}
// Looks better than perfectly centered.
let yOffset = 0.12
return rect.centered(in: screen.visibleFrame, xOffsetPercent: 0, yOffsetPercent: yOffset)
}
static let defaultContentSize = CGSize(width: 480, height: 300)
static var defaultContentRect: CGRect {
centeredOnScreen(rect: defaultContentSize.cgRect)
}
static let defaultStyleMask: NSWindow.StyleMask = [.titled, .closable, .miniaturizable, .resizable]
static func centeredWindow(size: CGSize = defaultContentSize) -> Self {
let window = self.init(
contentRect: NSWindow.defaultContentRect,
styleMask: NSWindow.defaultStyleMask,
backing: .buffered,
defer: true
)
window.setContentSize(size)
window.centerNatural()
return window
}
convenience init(contentRect: CGRect) {
self.init(contentRect: contentRect, styleMask: NSWindow.defaultStyleMask, backing: .buffered, defer: true)
}
/// Moves the window to the center of the screen, slightly more in the center than `window#center()`.
func centerNatural() {
setFrame(NSWindow.centeredOnScreen(rect: frame), display: true)
}
}
extension NSWindowController {
/// Expose the `view` like in NSViewController.
var view: NSView? { window?.contentView }
}
extension NSView {
@discardableResult
func insertVibrancyView(
material: NSVisualEffectView.Material,
blendingMode: NSVisualEffectView.BlendingMode = .behindWindow,
appearanceName: NSAppearance.Name? = nil
) -> NSVisualEffectView {
let view = NSVisualEffectView(frame: bounds)
view.autoresizingMask = [.width, .height]
view.material = material
view.blendingMode = blendingMode
if let appearanceName = appearanceName {
view.appearance = NSAppearance(named: appearanceName)
}
addSubview(view, positioned: .below, relativeTo: nil)
return view
}
}
extension NSWindow {
private enum AssociatedKeys {
static let observationToken = ObjectAssociation<NSKeyValueObservation?>()
}
func makeVibrant() {
// So there seems to be a visual effect view already created by NSWindow.
// If we can attach ourselves to it and make it a vibrant one - awesome.
// If not, let's just add our view as a first one so it is vibrant anyways.
if let visualEffectView = contentView?.superview?.subviews.lazy.compactMap({ $0 as? NSVisualEffectView }).first {
visualEffectView.blendingMode = .behindWindow
visualEffectView.material = .underWindowBackground
AssociatedKeys.observationToken[self] = visualEffectView.observe(\.effectiveAppearance) { _, _ in
visualEffectView.blendingMode = .behindWindow
visualEffectView.material = .underWindowBackground
}
} else {
contentView?.superview?.insertVibrancyView(material: .underWindowBackground)
}
}
}
extension NSWindow {
var toolbarView: NSView? { standardWindowButton(.closeButton)?.superview }
var titlebarView: NSView? { toolbarView?.superview }
var titlebarHeight: Double { Double(titlebarView?.bounds.height ?? 0) }
}
// TODO: Remove these when targeting macOS 11.
private func __windowSheetPosition(_ window: NSWindow, willPositionSheet sheet: NSWindow, using rect: CGRect) -> CGRect {
if #available(macOS 11, *) {
return rect
}
// Adjust sheet position so it goes below the traffic lights.
if window.styleMask.contains(.fullSizeContentView) {
return rect.offsetBy(dx: 0, dy: CGFloat(-window.titlebarHeight))
}
return rect
}
/// - Note: Ensure you set `window.delegate = self` in the NSWindowController subclass.
extension NSWindowController: NSWindowDelegate {
public func window(_ window: NSWindow, willPositionSheet sheet: NSWindow, using rect: CGRect) -> CGRect {
__windowSheetPosition(window, willPositionSheet: sheet, using: rect)
}
}
extension NSView {
private final class AddedToSuperviewObserverView: NSView {
var onAdded: (() -> Void)?
override var acceptsFirstResponder: Bool { false }
convenience init() {
self.init(frame: .zero)
}
override func viewDidMoveToWindow() {
guard window != nil else {
return
}
onAdded?()
removeFromSuperview()
}
}
func onAddedToSuperview(_ closure: @escaping () -> Void) {
let view = AddedToSuperviewObserverView()
view.onAdded = closure
addSubview(view)
}
}
extension NSAlert {
/// Show an alert as a window-modal sheet, or as an app-modal (window-indepedendent) alert if the window is `nil` or not given.
@discardableResult
static func showModal(
for window: NSWindow? = nil,
title: String,
message: String? = nil,
detailText: String? = nil,
style: Style = .warning,
buttonTitles: [String] = [],
defaultButtonIndex: Int? = nil
) -> NSApplication.ModalResponse {
NSAlert(
title: title,
message: message,
detailText: detailText,
style: style,
buttonTitles: buttonTitles,
defaultButtonIndex: defaultButtonIndex
).runModal(for: window)
}
/// The index in the `buttonTitles` array for the button to use as default.
/// Set `-1` to not have any default. Useful for really destructive actions.
var defaultButtonIndex: Int {
get {
buttons.firstIndex { $0.keyEquivalent == "\r" } ?? -1
}
set {
// Clear the default button indicator from other buttons.
for button in buttons where button.keyEquivalent == "\r" {
button.keyEquivalent = ""
}
if newValue != -1 {
buttons[newValue].keyEquivalent = "\r"
}
}
}
convenience init(
title: String,
message: String? = nil,
detailText: String? = nil,
style: Style = .warning,
buttonTitles: [String] = [],
defaultButtonIndex: Int? = nil
) {
self.init()
self.messageText = title
self.alertStyle = style
if let message = message {
self.informativeText = message
}
if let detailText = detailText {
let scrollView = NSTextView.scrollableTextView()
// We're setting the frame manually here as it's impossible to use auto-layout,
// since it has nothing to constrain to. This will eventually be rewritten in SwiftUI anyway.
scrollView.frame = CGRect(width: 300, height: 120)
scrollView.onAddedToSuperview {
if let messageTextField = (scrollView.superview?.superview?.subviews.first { $0 is NSTextField }) {
scrollView.frame.width = messageTextField.frame.width
} else {
assertionFailure("Couldn't detect the message textfield view of the NSAlert panel")
}
}
let textView = scrollView.documentView as! NSTextView
textView.drawsBackground = false
textView.isEditable = false
textView.font = .systemFont(ofSize: NSFont.systemFontSize(for: .small))
textView.textColor = .secondaryLabelColor
textView.string = detailText
self.accessoryView = scrollView
}
addButtons(withTitles: buttonTitles)
if let defaultButtonIndex = defaultButtonIndex {
self.defaultButtonIndex = defaultButtonIndex
}
}
/// Runs the alert as a window-modal sheet, or as an app-modal (window-indepedendent) alert if the window is `nil` or not given.
@discardableResult
func runModal(for window: NSWindow? = nil) -> NSApplication.ModalResponse {
guard let window = window else {
return runModal()
}
beginSheetModal(for: window) { returnCode in
NSApp.stopModal(withCode: returnCode)
}
return NSApp.runModal(for: window)
}
/// Adds buttons with the given titles to the alert.
func addButtons(withTitles buttonTitles: [String]) {
for buttonTitle in buttonTitles {
addButton(withTitle: buttonTitle)
}
}
}
extension AVAssetImageGenerator {
struct CompletionHandlerResult {
let image: CGImage
let requestedTime: CMTime
let actualTime: CMTime
let completedCount: Int
let totalCount: Int
let isFinished: Bool
let isFinishedIgnoreImage: Bool
}
/// - Note: If you use `result.completedCount`, don't forget to update its usage in each `completionHandler` call as it can change if frames are skipped, for example, blank frames.
func generateCGImagesAsynchronously(
forTimePoints timePoints: [CMTime],
completionHandler: @escaping (Swift.Result<CompletionHandlerResult, Error>) -> Void
) {
let times = timePoints.map { NSValue(time: $0) }
var totalCount = times.count
var completedCount = 0
var decodeFailureFrameCount = 0
generateCGImagesAsynchronously(forTimes: times) { requestedTime, image, actualTime, result, error in
switch result {
case .succeeded:
completedCount += 1
completionHandler(
.success(
CompletionHandlerResult(
image: image!,
requestedTime: requestedTime,
actualTime: actualTime,
completedCount: completedCount,
totalCount: totalCount,
isFinished: completedCount == totalCount,
isFinishedIgnoreImage: false
)
)
)
case .failed:
// TODO: Ideally, we should trim blank frames when initially reading the video in `VideoValidator.swift`, but I don't know a way to detect blank frames. We should still keep this fix even if we find a way to trim as this handles blank frames in the middle of the video.
// TODO: Report the `xcrun` bug to Apple if it's still an issue in macOS 11.
if let error = error as? AVError {
// Ugly workaround for when the last frame is a failure.
func finishWithoutImageIfNeeded() {
guard completedCount == totalCount else {
return
}
completionHandler(
.success(
CompletionHandlerResult(
image: .empty,
requestedTime: requestedTime,
actualTime: actualTime,
completedCount: completedCount,
totalCount: totalCount,
isFinished: true,
isFinishedIgnoreImage: true
)
)
)
}
// We ignore blank frames. A video can sometimes contain blank frames at the start when you record an iOS simulator using `xcrun simctl io booted recordVideo simulator.mp4`.
if error.code == .noImageAtTime {
totalCount -= 1
print("No image at time. Completed: \(completedCount) Total: \(totalCount)")
finishWithoutImageIfNeeded()
break
}
// macOS 11 (still an issue in macOS 11.2) started throwing βdecode failedβ error for some frames in screen recordings. As a workaround, we ignore these as the GIF seems fine still.
if error.code == .decodeFailed {
decodeFailureFrameCount += 1
totalCount -= 1
print("Decode failure. Completed: \(completedCount) Total: \(totalCount)")
Crashlytics.recordNonFatalError(error: error, userInfo: ["requestedTime": requestedTime.seconds])
finishWithoutImageIfNeeded()
break
}
}
completionHandler(.failure(error!))
case .cancelled:
completionHandler(.failure(CancellationError()))
@unknown default:
assertionFailure("AVAssetImageGenerator.generateCGImagesAsynchronously() received a new enum case. Please handle it.")
}
}
}
}
extension CMTimeScale {
/**
Apple-recommended scale for video.
```
CMTime(seconds: (1 / fps), preferredTimescale: .video)
```
*/
static let video: Self = 600
}
extension Comparable {
/// Note: It's not possible to implement `Range` or `PartialRangeUpTo` here as we can't know what `1.1..<1.53` would be. They only work with Stridable in our case.
/// Example: 20.5.clamped(from: 10.3, to: 15)
func clamped(from lowerBound: Self, to upperBound: Self) -> Self {
min(max(self, lowerBound), upperBound)
}
/// Example: 20.5.clamped(to: 10.3...15)
func clamped(to range: ClosedRange<Self>) -> Self {
clamped(from: range.lowerBound, to: range.upperBound)
}
/// Example: 20.5.clamped(to: ...10.3)
/// => 10.3
func clamped(to range: PartialRangeThrough<Self>) -> Self {
min(self, range.upperBound)
}
/// Example: 5.5.clamped(to: 10.3...)
/// => 10.3
func clamped(to range: PartialRangeFrom<Self>) -> Self {
max(self, range.lowerBound)
}
}
extension Strideable where Stride: SignedInteger {
/// Example: 20.clamped(to: 5..<10)
/// => 9
func clamped(to range: CountableRange<Self>) -> Self {
clamped(from: range.lowerBound, to: range.upperBound.advanced(by: -1))
}
/// Example: 20.clamped(to: 5...10)
/// => 10
func clamped(to range: CountableClosedRange<Self>) -> Self {
clamped(from: range.lowerBound, to: range.upperBound)
}
/// Example: 20.clamped(to: ..<10)
/// => 9
func clamped(to range: PartialRangeUpTo<Self>) -> Self {
min(self, range.upperBound.advanced(by: -1))
}
}
extension FixedWidthInteger {
/// Returns the integer formatted as a human readble file size.
/// Example: `2.3 GB`
var bytesFormattedAsFileSize: String {
ByteCountFormatter.string(fromByteCount: Int64(self), countStyle: .file)
}
}
extension String.StringInterpolation {
/**
Interpolate the value by unwrapping it, and if `nil`, use the given default string.
```
// This doesn't work as you can only use nil coalescing in interpolation with the same type as the optional
"foo \(optionalDouble ?? "none")
// Now you can do this
"foo \(optionalDouble, default: "none")
```
*/
public mutating func appendInterpolation(_ value: Any?, default defaultValue: String) {
if let value = value {
appendInterpolation(value)
} else {
appendLiteral(defaultValue)
}
}
/**
Interpolate the value by unwrapping it, and if `nil`, use `"nil"`.
```
// This doesn't work as you can only use nil coalescing in interpolation with the same type as the optional
"foo \(optionalDouble ?? "nil")
// Now you can do this
"foo \(describing: optionalDouble)
```
*/
public mutating func appendInterpolation(describing value: Any?) {
if let value = value {
appendInterpolation(value)
} else {
appendLiteral("nil")
}
}
}
extension Double {
/**
Converts the number to a string and strips fractional trailing zeros.
```
let x = 1.0
print(1.0)
//=> "1.0"
print(1.0.formatted)
//=> "1"
print(0.0100.formatted)
//=> "0.01"
```
*/
var formatted: String {
truncatingRemainder(dividingBy: 1) == 0 ? String(format: "%.0f", self) : String(self)
}
}
extension CGFloat {
var formatted: String { Double(self).formatted }
}
extension CGSize {
/// Example: `140Γ100`
var formatted: String { "\(width.formatted)Γ\(height.formatted)" }
}
extension NSImage {
/// `UIImage` polyfill.
convenience init(cgImage: CGImage) {
let size = CGSize(width: cgImage.width, height: cgImage.height)
self.init(cgImage: cgImage, size: size)
}
}
extension CGImage {
var nsImage: NSImage { NSImage(cgImage: self) }
}
extension AVAssetImageGenerator {
func image(at time: CMTime) -> NSImage? {
(try? copyCGImage(at: time, actualTime: nil))?.nsImage
}
}
extension AVAsset {
func image(at time: CMTime) -> NSImage? {
let imageGenerator = AVAssetImageGenerator(asset: self)
imageGenerator.appliesPreferredTrackTransform = true
imageGenerator.requestedTimeToleranceAfter = .zero
imageGenerator.requestedTimeToleranceBefore = .zero
return imageGenerator.image(at: time)
}
}
extension AVAssetTrack {
/// Returns the dimensions of the track if it's a video.
var dimensions: CGSize? {
guard naturalSize != .zero else {
return nil
}
let size = naturalSize.applying(preferredTransform)
let preferredSize = CGSize(width: abs(size.width), height: abs(size.height))
// Workaround for https://github.com/sindresorhus/Gifski/issues/76
guard preferredSize != .zero else {
return asset?.image(at: CMTime(seconds: 0, preferredTimescale: .video))?.size
}
return preferredSize
}
/// Returns the frame rate of the track if it's a video.
var frameRate: Double? { Double(nominalFrameRate) }
/// Returns the aspect ratio of the track if it's a video.
var aspectRatio: Double? {
guard let dimensions = dimensions else {
return nil
}
return Double(dimensions.height / dimensions.width)
}
/// Example:
/// `avc1` (video)
/// `aac` (audio)
var codecIdentifier: String? {
guard
let rawDescription = formatDescriptions.first
else {
return nil
}
// This is the only way to do it. It's guaranteed to be this type.
// swiftlint:disable:next force_cast
let formatDescription = rawDescription as! CMFormatDescription
return CMFormatDescriptionGetMediaSubType(formatDescription).fourCharCodeToString()
}
var codec: AVFormat? {
guard let codecString = codecIdentifier else {
return nil
}
return AVFormat(fourCC: codecString)
}
/// Use this for presenting the codec to the user. This is either the codec name, if known, or the codec identifier. You can just default to `"Unknown"` if this is `nil`.
var codecTitle: String? { codec?.description ?? codecIdentifier }
/// Returns a debug string with the media format.
/// Example: `vide/avc1`
var mediaFormat: String {
// This is the only way to do it. It's guaranteed to be this type.
// swiftlint:disable:next force_cast
let descriptions = formatDescriptions as! [CMFormatDescription]
var format = [String]()
for description in descriptions {
// Get string representation of media type (vide, soun, sbtl, etc.)
let type = CMFormatDescriptionGetMediaType(description).fourCharCodeToString()
// Get string representation media subtype (avc1, aac, tx3g, etc.)
let subType = CMFormatDescriptionGetMediaSubType(description).fourCharCodeToString()
format.append("\(type)/\(subType)")
}
return format.joined(separator: ",")
}
/// Estimated file size of the track in bytes.
var estimatedFileSize: Int {
let dataRateInBytes = Double(estimatedDataRate / 8)
return Int(timeRange.duration.seconds * dataRateInBytes)
}
}
extension AVAssetTrack {
/// Whether the track's duration is the same as the total asset duration.
var isFullDuration: Bool { timeRange.duration == asset?.duration }
/**
Extract the track into a new AVAsset.
This can be useful if you only want the video or audio of an asset. For example, sometimes the video track duration is shorter than the total asset duration. Extracting the track into a new asset ensures the asset duration is only as long as the video track duration.
*/
func extractToNewAsset() -> AVAsset? {
let composition = AVMutableComposition()
guard
let track = composition.addMutableTrack(withMediaType: mediaType, preferredTrackID: kCMPersistentTrackID_Invalid),
(try? track.insertTimeRange(CMTimeRange(start: .zero, duration: timeRange.duration), of: self, at: .zero)) != nil
else {
return nil
}
track.preferredTransform = preferredTransform
return composition
}
}
/*
> FOURCC is short for "four character code" - an identifier for a video codec, compression format, color or pixel format used in media files.
*/
extension FourCharCode {
/// Create a String representation of a FourCC.
func fourCharCodeToString() -> String {
let a_ = self >> 24
let b_ = self >> 16
let c_ = self >> 8
let d_ = self
let bytes: [CChar] = [
CChar(a_ & 0xFF),
CChar(b_ & 0xFF),
CChar(c_ & 0xFF),
CChar(d_ & 0xFF),
0
]
// Swift type-checking is too slow for this...
// let bytes: [CChar] = [
// CChar((self >> 24) & 0xff),
// CChar((self >> 16) & 0xff),
// CChar((self >> 8) & 0xff),
// CChar(self & 0xff),
// 0
// ]
return String(cString: bytes).trimmingCharacters(in: .whitespaces)
}
}
// TODO: Support audio formats too.
enum AVFormat: String {
case hevc
case h264
case av1
case vp9
case appleProResRAWHQ
case appleProResRAW
case appleProRes4444XQ
case appleProRes4444
case appleProRes422HQ
case appleProRes422
case appleProRes422LT
case appleProRes422Proxy
case appleAnimation
// https://hap.video/using-hap.html
// https://github.com/Vidvox/hap/blob/master/documentation/HapVideoDRAFT.md#names-and-identifiers
case hap1
case hap5
case hapY
case hapM
case hapA
case hap7
case cineFormHD
// https://en.wikipedia.org/wiki/QuickTime_Graphics
case quickTimeGraphics
init?(fourCC: String) {
switch fourCC.trimmingCharacters(in: .whitespaces) {
case "hvc1":
self = .hevc
case "avc1":
self = .h264
case "av01":
self = .av1
case "vp09":
self = .vp9
case "aprh": // From https://avpres.net/Glossar/ProResRAW.html
self = .appleProResRAWHQ
case "aprn":
self = .appleProResRAW
case "ap4x":
self = .appleProRes4444XQ
case "ap4h":
self = .appleProRes4444
case "apch":
self = .appleProRes422HQ
case "apcn":
self = .appleProRes422
case "apcs":
self = .appleProRes422LT
case "apco":
self = .appleProRes422Proxy
case "rle":
self = .appleAnimation
case "Hap1":
self = .hap1
case "Hap5":
self = .hap5
case "HapY":
self = .hapY
case "HapM":
self = .hapM
case "HapA":
self = .hapA
case "Hap7":
self = .hap7
case "CFHD":
self = .cineFormHD
case "smc":
self = .quickTimeGraphics
default:
return nil
}
}
init?(fourCC: FourCharCode) {
self.init(fourCC: fourCC.fourCharCodeToString())
}
var fourCC: String {
switch self {
case .hevc:
return "hvc1"
case .h264:
return "avc1"
case .av1:
return "av01"
case .vp9:
return "vp09"
case .appleProResRAWHQ:
return "aprh"
case .appleProResRAW:
return "aprn"
case .appleProRes4444XQ:
return "ap4x"
case .appleProRes4444:
return "ap4h"
case .appleProRes422HQ:
return "apcn"
case .appleProRes422:
return "apch"
case .appleProRes422LT:
return "apcs"
case .appleProRes422Proxy:
return "apco"
case .appleAnimation:
return "rle "
case .hap1:
return "Hap1"
case .hap5:
return "Hap5"
case .hapY:
return "HapY"
case .hapM:
return "HapM"
case .hapA:
return "HapA"
case .hap7:
return "Hap7"
case .cineFormHD:
return "CFHD"
case .quickTimeGraphics:
return "smc"
}
}
var isAppleProRes: Bool {
[
.appleProResRAWHQ,
.appleProResRAW,
.appleProRes4444XQ,
.appleProRes4444,
.appleProRes422HQ,
.appleProRes422,
.appleProRes422LT,
.appleProRes422Proxy
].contains(self)
}
/// - Important: This check only covers known (by us) compatible formats. It might be missing some. Don't use it for strict matching. Also keep in mind that even though a codec is supported, it might still not be decodable as the codec profile level might not be supported.
var isSupported: Bool {
self == .hevc || self == .h264 || isAppleProRes
}
}
extension AVFormat: CustomStringConvertible {
var description: String {
switch self {
case .hevc:
return "HEVC"
case .h264:
return "H264"
case .av1:
return "AV1"
case .vp9:
return "VP9"
case .appleProResRAWHQ:
return "Apple ProRes RAW HQ"
case .appleProResRAW:
return "Apple ProRes RAW"
case .appleProRes4444XQ:
return "Apple ProRes 4444 XQ"
case .appleProRes4444:
return "Apple ProRes 4444"
case .appleProRes422HQ:
return "Apple ProRes 422 HQ"
case .appleProRes422:
return "Apple ProRes 422"
case .appleProRes422LT:
return "Apple ProRes 422 LT"
case .appleProRes422Proxy:
return "Apple ProRes 422 Proxy"
case .appleAnimation:
return "Apple Animation"
case .hap1:
return "Vidvox Hap"
case .hap5:
return "Vidvox Hap Alpha"
case .hapY:
return "Vidvox Hap Q"
case .hapM:
return "Vidvox Hap Q Alpha"
case .hapA:
return "Vidvox Hap Alpha-Only"
case .hap7:
// No official name for this.
return "Vidvox Hap"
case .cineFormHD:
return "CineForm HD"
case .quickTimeGraphics:
return "QuickTime Graphics"
}
}
}
extension AVFormat: CustomDebugStringConvertible {
var debugDescription: String {
"\(description) (\(fourCC.trimmingCharacters(in: .whitespaces)))"
}
}
extension AVMediaType: CustomDebugStringConvertible {
public var debugDescription: String {
switch self {
case .audio:
return "Audio"
case .closedCaption:
return "Closed-caption content"
case .depthData:
return "Depth data"
case .metadata:
return "Metadata"
// iOS
// case .metadataObject:
// return "Metadata objects"
case .muxed:
return "Muxed media"
case .subtitle:
return "Subtitles"
case .text:
return "Text"
case .timecode:
return "Time code"
case .video:
return "Video"
default:
return "Unknown"
}
}
}
extension AVAsset {
/// Whether the first video track is decodable.
var isVideoDecodable: Bool {
guard
isReadable,
let firstVideoTrack = tracks(withMediaType: .video).first
else {
return false
}
return firstVideoTrack.isDecodable
}
/// Returns a boolean of whether there are any video tracks.
var hasVideo: Bool { !tracks(withMediaType: .video).isEmpty }
/// Returns a boolean of whether there are any audio tracks.
var hasAudio: Bool { !tracks(withMediaType: .audio).isEmpty }
/// Returns the first video track if any.
var firstVideoTrack: AVAssetTrack? { tracks(withMediaType: .video).first }
/// Returns the first audio track if any.