Branchwell

Inkspring / app · inkspring.ai / native-mac / Sources / Inkspring / WebMMetadata.swift

Raw 7.7 KB on 8f75dd7d901e2186ca9d9e1cf2f061105c02ae42
1import Foundation
2
3enum WebMMetadata {
4 private enum ID {
5 static let ebml: UInt64 = 0x1A45DFA3
6 static let docType: UInt64 = 0x4282
7 static let segment: UInt64 = 0x18538067
8 static let info: UInt64 = 0x1549A966
9 static let tracks: UInt64 = 0x1654AE6B
10 static let cluster: UInt64 = 0x1F43B675
11 static let timestampScale: UInt64 = 0x2AD7B1
12 static let duration: UInt64 = 0x4489
13 static let trackEntry: UInt64 = 0xAE
14 static let trackType: UInt64 = 0x83
15 static let enabled: UInt64 = 0xB9
16 static let codec: UInt64 = 0x86
17 static let video: UInt64 = 0xE0
18 static let pixelWidth: UInt64 = 0xB0
19 static let pixelHeight: UInt64 = 0xBA
20 static let defaultDuration: UInt64 = 0x23E383
21 }
22
23 static func inspect(_ url: URL) throws -> VideoMetadata {
24 let input = try FileHandle(forReadingFrom: url)
25 defer { try? input.close() }
26 let end = try input.seekToEnd()
27 let reader = Reader(input: input)
28 let header = try reader.element(at: 0, before: end)
29 guard header.id == ID.ebml,
30 let docType = try reader.children(of: header).first(where: { $0.id == ID.docType }),
31 try reader.string(docType) == "webm" else { throw invalid }
32
33 var offset = header.bytes.upperBound
34 var segment: Element?
35 for _ in 0..<10_000 where offset < end {
36 let element = try reader.element(at: offset, before: end)
37 if element.id == ID.segment { segment = element; break }
38 offset = element.bytes.upperBound
39 }
40 guard let segment else { throw invalid }
41
42 var info: Element?
43 var tracks: Element?
44 var hasMedia = false
45 offset = segment.bytes.lowerBound
46 for _ in 0..<10_000 where offset < segment.bytes.upperBound {
47 let element = try reader.element(at: offset, before: segment.bytes.upperBound)
48 switch element.id {
49 case ID.info: info = element
50 case ID.tracks: tracks = element
51 case ID.cluster: hasMedia = hasMedia || !element.bytes.isEmpty
52 default: break
53 }
54 if info != nil && tracks != nil && hasMedia { break }
55 offset = element.bytes.upperBound
56 }
57 guard let info, let tracks, hasMedia else { throw invalid }
58 let timeFields = try reader.children(of: info)
59 let scale = try timeFields.first(where: { $0.id == ID.timestampScale }).map(reader.integer) ?? 1_000_000
60 guard let durationField = timeFields.first(where: { $0.id == ID.duration }) else {
61 throw WorkspaceError("Choose a WebM export with a known duration.")
62 }
63 let seconds = try reader.floatingPoint(durationField) * Double(scale) / 1_000_000_000
64 guard seconds.isFinite, seconds > 0, seconds <= 600 else {
65 throw WorkspaceError("Choose a playable video of up to ten minutes.")
66 }
67
68 for entry in try reader.children(of: tracks) where entry.id == ID.trackEntry {
69 let fields = try reader.children(of: entry)
70 guard let type = fields.first(where: { $0.id == ID.trackType }), try reader.integer(type) == 1,
71 try fields.first(where: { $0.id == ID.enabled }).map(reader.integer) != 0,
72 let codec = fields.first(where: { $0.id == ID.codec }),
73 ["V_VP8", "V_VP9", "V_AV1"].contains(try reader.string(codec)),
74 let video = fields.first(where: { $0.id == ID.video }) else { continue }
75 let dimensions = try reader.children(of: video)
76 guard let width = try dimensions.first(where: { $0.id == ID.pixelWidth }).map(reader.integer),
77 let height = try dimensions.first(where: { $0.id == ID.pixelHeight }).map(reader.integer),
78 (360...4096).contains(width), (360...4096).contains(height) else {
79 throw WorkspaceError("Video width and height must each be between 360 and 4,096 pixels.")
80 }
81 let nanoseconds = try fields.first(where: { $0.id == ID.defaultDuration }).map(reader.integer) ?? 0
82 // Nanosecond precision can encode 60 fps as slightly above 60.
83 let rate = nanoseconds > 0 ? Float((1_000_000_000_000 / Double(nanoseconds)).rounded() / 1_000) : 0
84 return VideoMetadata(duration: seconds, width: Int(width), height: Int(height), frameRate: rate)
85 }
86 throw invalid
87 }
88
89 private static var invalid: WorkspaceError { WorkspaceError("This file couldn’t be read as a WebM video.") }
90
91 private struct Element {
92 let id: UInt64
93 let bytes: Range<UInt64>
94 }
95
96 private struct Reader {
97 let input: FileHandle
98
99 func element(at offset: UInt64, before end: UInt64) throws -> Element {
100 try input.seek(toOffset: offset)
101 let header = try input.read(upToCount: Int(min(12, end - offset))) ?? Data()
102 let (id, idLength, _) = try number(in: header, at: 0, maxLength: 4, stripMarker: false)
103 let (size, sizeLength, unknown) = try number(in: header, at: idLength, maxLength: 8, stripMarker: true)
104 let start = offset + UInt64(idLength + sizeLength)
105 guard start <= end, unknown ? [ID.segment, ID.cluster].contains(id) : size <= end - start else {
106 throw invalid
107 }
108 return Element(id: id, bytes: start..<(unknown ? end : start + size))
109 }
110
111 func children(of parent: Element) throws -> [Element] {
112 var result: [Element] = []
113 var offset = parent.bytes.lowerBound
114 while offset < parent.bytes.upperBound {
115 guard result.count < 10_000 else { throw invalid }
116 let child = try element(at: offset, before: parent.bytes.upperBound)
117 result.append(child)
118 offset = child.bytes.upperBound
119 }
120 return result
121 }
122
123 func integer(_ element: Element) throws -> UInt64 {
124 try bytes(element, maximum: 8).reduce(0) { ($0 << 8) | UInt64($1) }
125 }
126
127 func floatingPoint(_ element: Element) throws -> Double {
128 let value = try integer(element)
129 switch element.bytes.upperBound - element.bytes.lowerBound {
130 case 4: return Double(Float(bitPattern: UInt32(value)))
131 case 8: return Double(bitPattern: value)
132 default: throw invalid
133 }
134 }
135
136 func string(_ element: Element) throws -> String {
137 String(decoding: try bytes(element, maximum: 64), as: UTF8.self)
138 }
139
140 private func bytes(_ element: Element, maximum: UInt64) throws -> Data {
141 let length = element.bytes.upperBound - element.bytes.lowerBound
142 guard length <= maximum else { throw invalid }
143 if length == 0 { return Data() }
144 try input.seek(toOffset: element.bytes.lowerBound)
145 guard let data = try input.read(upToCount: Int(length)), data.count == Int(length) else { throw invalid }
146 return data
147 }
148
149 private func number(in data: Data, at start: Int, maxLength: Int,
150 stripMarker: Bool) throws -> (UInt64, Int, Bool) {
151 guard start < data.count, data[start] != 0 else { throw invalid }
152 let first = data[start]
153 let length = first.leadingZeroBitCount + 1
154 guard length <= maxLength, start + length <= data.count else { throw invalid }
155 let mask = UInt8(0x80) >> (length - 1)
156 var value = UInt64(stripMarker ? first & (mask - 1) : first)
157 for byte in data[(start + 1)..<(start + length)] { value = (value << 8) | UInt64(byte) }
158 let unknown = stripMarker && value == (1 << (length * 7)) - 1
159 return (value, length, unknown)
160 }
161 }
162}