-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathTimecodeEngine.swift
More file actions
637 lines (554 loc) · 26.4 KB
/
Copy pathTimecodeEngine.swift
File metadata and controls
637 lines (554 loc) · 26.4 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
import Foundation
import AVFoundation
// MARK: - Timecode Info
struct TCInfo {
let url: URL
let name: String
let startSec: Double // seconds since midnight
let endSec: Double // startSec + duration
let durationSec: Double
let fps: Double
let tcString: String // "HH:MM:SS:FF"
}
private func formatTCString(from startSec: Double, fps: Double) -> String {
let safeFPS = fps > 0 ? fps : 25.0
let totalFrames = Int(startSec * safeFPS)
let wholeFPS = max(1, Int(safeFPS.rounded()))
let ff = totalFrames % wholeFPS
let ss = (totalFrames / wholeFPS) % 60
let mm = (totalFrames / wholeFPS / 60) % 60
let hh = totalFrames / wholeFPS / 3600
return String(format: "%02d:%02d:%02d:%02d", hh, mm, ss, ff)
}
private func adjustedTCForTimelineSegment(_ tc: TCInfo, asset: MediaAsset) -> TCInfo {
guard asset.isTimelineSegment else { return tc }
let trimOffset = max(0, asset.start)
guard trimOffset > 0 else { return tc }
let adjustedStart = tc.startSec + trimOffset
return TCInfo(
url: tc.url,
name: tc.name,
startSec: adjustedStart,
endSec: adjustedStart + asset.duration,
durationSec: asset.duration,
fps: tc.fps,
tcString: formatTCString(from: adjustedStart, fps: tc.fps)
)
}
// MARK: - ffprobe Path
enum FFprobeInstaller {
static let downloadURL = URL(string: "https://evermeet.cx/ffmpeg/getrelease/ffprobe/zip")!
static var installDirectory: URL {
let appSupport = FileManager.default.urls(for: .applicationSupportDirectory, in: .userDomainMask).first!
return appSupport
.appendingPathComponent("WaveformMatcher", isDirectory: true)
.appendingPathComponent("bin", isDirectory: true)
}
static var installURL: URL {
installDirectory.appendingPathComponent("ffprobe", isDirectory: false)
}
static func install() async throws {
let fm = FileManager.default
try fm.createDirectory(at: installDirectory, withIntermediateDirectories: true)
let (archiveURL, _) = try await URLSession.shared.download(from: downloadURL)
let tempDir = fm.temporaryDirectory.appendingPathComponent(UUID().uuidString, isDirectory: true)
try fm.createDirectory(at: tempDir, withIntermediateDirectories: true)
defer { try? fm.removeItem(at: tempDir) }
let unzip = Process()
unzip.executableURL = URL(fileURLWithPath: "/usr/bin/ditto")
unzip.arguments = ["-x", "-k", archiveURL.path, tempDir.path]
try unzip.run()
unzip.waitUntilExit()
guard unzip.terminationStatus == 0 else {
throw NSError(domain: "WaveformMatcher.ffprobe", code: 1, userInfo: [
NSLocalizedDescriptionKey: "Could not extract FFprobe."
])
}
let extractedURL = tempDir.appendingPathComponent("ffprobe", isDirectory: false)
guard fm.isExecutableFile(atPath: extractedURL.path) || fm.fileExists(atPath: extractedURL.path) else {
throw NSError(domain: "WaveformMatcher.ffprobe", code: 2, userInfo: [
NSLocalizedDescriptionKey: "Downloaded archive did not contain ffprobe."
])
}
if fm.fileExists(atPath: installURL.path) {
try fm.removeItem(at: installURL)
}
try fm.moveItem(at: extractedURL, to: installURL)
let chmod = Process()
chmod.executableURL = URL(fileURLWithPath: "/bin/chmod")
chmod.arguments = ["755", installURL.path]
try chmod.run()
chmod.waitUntilExit()
guard chmod.terminationStatus == 0 else {
throw NSError(domain: "WaveformMatcher.ffprobe", code: 3, userInfo: [
NSLocalizedDescriptionKey: "Installed FFprobe but could not mark it executable."
])
}
}
}
private func ffprobePath() -> String? {
var candidates: [String] = []
// FCPXML-first policy: ffprobe is not bundled anymore.
// If a raw-file fallback is needed, prefer an app-managed install first,
// then look for an existing system/homebrew installation.
candidates.append(FFprobeInstaller.installURL.path)
if let pathEnv = ProcessInfo.processInfo.environment["PATH"] {
candidates += pathEnv
.split(separator: ":")
.map { String($0) + "/ffprobe" }
}
candidates += [
"/opt/homebrew/bin/ffprobe", // Apple Silicon Homebrew
"/usr/local/bin/ffprobe", // Intel Homebrew
"/usr/bin/ffprobe",
]
return candidates.first { FileManager.default.isExecutableFile(atPath: $0) }
}
// MARK: - Parse TC String → Seconds
func tcStringToSeconds(_ tc: String, fps: Double) -> Double? {
// Support both "HH:MM:SS:FF" and "HH:MM:SS;FF" (drop-frame)
let parts = tc.replacingOccurrences(of: ";", with: ":").split(separator: ":").compactMap { Int($0) }
guard parts.count == 4 else { return nil }
let h = parts[0], m = parts[1], s = parts[2], f = parts[3]
let safeFPS = fps > 0 ? fps : 25.0
return Double(h * 3600 + m * 60 + s) + Double(f) / safeFPS
}
// MARK: - Read TC via ffprobe
func readTCViaFFprobe(from asset: MediaAsset) async -> TCInfo? {
guard let ffprobe = ffprobePath() else { return nil }
let url = URL(fileURLWithPath: asset.path)
return await withCheckedContinuation { cont in
let proc = Process()
proc.executableURL = URL(fileURLWithPath: ffprobe)
proc.arguments = [
"-v", "quiet",
"-print_format", "json",
"-show_streams",
"-show_format",
asset.path,
]
let pipe = Pipe()
proc.standardOutput = pipe
proc.standardError = Pipe()
do {
try proc.run()
} catch {
cont.resume(returning: nil)
return
}
proc.waitUntilExit()
let data = pipe.fileHandleForReading.readDataToEndOfFile()
guard let json = try? JSONSerialization.jsonObject(with: data) as? [String: Any] else {
cont.resume(returning: nil)
return
}
// Debug: dump ALL tags so we can see exactly what ffprobe finds
print("[TC] \(asset.name) — ffprobe tags dump:")
if let streams = json["streams"] as? [[String: Any]] {
for (i, stream) in streams.enumerated() {
let codec = stream["codec_type"] as? String ?? "?"
print("[TC] stream[\(i)] codec_type=\(codec)")
if let tags = stream["tags"] as? [String: Any] {
for (k, v) in tags.sorted(by: { $0.key < $1.key }) {
print("[TC] \(k) = \(v)")
}
}
}
}
if let format = json["format"] as? [String: Any],
let tags = format["tags"] as? [String: Any] {
print("[TC] format tags:")
for (k, v) in tags.sorted(by: { $0.key < $1.key }) {
print("[TC] \(k) = \(v)")
}
}
// Try streams first (timecode track)
var tc: String?
var fpsFromStream: Double = 0
// Tag keys to check — Sound Devices / Zaxcom BWF use various spellings
let tcKeys = ["timecode", "TIMECODE", "time_code", "TIME_CODE", "com.apple.quicktime.information"]
if let streams = json["streams"] as? [[String: Any]] {
for stream in streams {
if let tags = stream["tags"] as? [String: Any] {
for key in tcKeys {
if let t = tags[key] as? String, tc == nil {
tc = t
}
}
// BWF BEXT time_reference: sample count from midnight → convert to TC string
// Key may be spelled multiple ways; value may be String or NSNumber (Int)
if tc == nil {
let bextKeys = ["time_reference", "TIME_REFERENCE",
"Time Reference", "bwf_time_reference",
"BWF_TIME_REFERENCE"]
for bKey in bextKeys {
if let v = tags[bKey] {
var refSamples: Int64?
if let s = v as? String { refSamples = Int64(s) }
else if let n = v as? NSNumber { refSamples = n.int64Value }
if let ref = refSamples, ref >= 0 {
tc = "BEXT:\(ref)"; break
}
}
}
}
}
// Extract FPS from video stream
if let codecType = stream["codec_type"] as? String, codecType == "video" {
if let rFrameRate = stream["r_frame_rate"] as? String {
let parts = rFrameRate.split(separator: "/")
if parts.count == 2, let num = Double(parts[0]), let den = Double(parts[1]), den > 0 {
fpsFromStream = num / den
}
}
if let fps = stream["avg_frame_rate"] as? String, fpsFromStream == 0 {
let parts = fps.split(separator: "/")
if parts.count == 2, let num = Double(parts[0]), let den = Double(parts[1]), den > 0 {
fpsFromStream = num / den
}
}
}
}
}
// Also check format tags (often where Sound Devices puts the TC)
if let format = json["format"] as? [String: Any],
let tags = format["tags"] as? [String: Any] {
for key in tcKeys {
if let t = tags[key] as? String, tc == nil { tc = t }
}
if tc == nil {
let bextKeys = ["time_reference", "TIME_REFERENCE",
"Time Reference", "bwf_time_reference",
"BWF_TIME_REFERENCE"]
for bKey in bextKeys {
if let v = tags[bKey] {
var refSamples: Int64?
if let s = v as? String { refSamples = Int64(s) }
else if let n = v as? NSNumber { refSamples = n.int64Value }
if let ref = refSamples, ref >= 0 {
tc = "BEXT:\(ref)"; break
}
}
}
}
}
// Resolve BEXT sample-count TC → HH:MM:SS:FF
// e.g. "BEXT:86400000" at 48000 Hz = 1800 seconds from midnight
if let tcStr = tc, tcStr.hasPrefix("BEXT:"),
let refSamples = Int64(tcStr.dropFirst(5)) {
// Get audio sample rate from first audio stream
var audioSR: Double = 48000
if let streams = json["streams"] as? [[String: Any]] {
for stream in streams {
if (stream["codec_type"] as? String) == "audio",
let srStr = stream["sample_rate"] as? String,
let sr = Double(srStr), sr > 0 {
audioSR = sr; break
}
}
}
let totalSec = Double(refSamples) / audioSR
let safeFPS = fpsFromStream > 0 ? fpsFromStream : 25.0
let totalFrames = Int(totalSec * safeFPS)
let fps2 = max(1, Int(safeFPS.rounded()))
let ff = totalFrames % fps2
let ss = (totalFrames / fps2) % 60
let mm = (totalFrames / fps2 / 60) % 60
let hh = totalFrames / fps2 / 3600
tc = String(format: "%02d:%02d:%02d:%02d", hh, mm, ss, ff)
print("[TC] \(asset.name) BEXT time_reference=\(refSamples) @ \(audioSR) Hz → \(tc!)")
}
// Get duration from format
var duration: Double = 0
if let format = json["format"] as? [String: Any],
let durStr = format["duration"] as? String,
let d = Double(durStr) {
duration = d
}
// Fallback from asset model
if duration <= 0 { duration = asset.duration }
guard let tcStr = tc else {
cont.resume(returning: nil)
return
}
let fps = fpsFromStream > 0 ? fpsFromStream : 25.0
guard let startSec = tcStringToSeconds(tcStr, fps: fps) else {
cont.resume(returning: nil)
return
}
cont.resume(returning: TCInfo(
url: url,
name: asset.name,
startSec: startSec,
endSec: startSec + duration,
durationSec: duration,
fps: fps,
tcString: tcStr
))
}
}
// MARK: - Read TC via AVFoundation (QuickTime timecode track)
func readTCViaAVFoundation(from asset: MediaAsset) async -> TCInfo? {
let url = URL(fileURLWithPath: asset.path)
let avAsset = AVURLAsset(url: url)
// 1. Try timecode track
guard let tracks = try? await avAsset.loadTracks(withMediaType: .timecode),
let tcTrack = tracks.first
else { return nil }
let fps = (try? await tcTrack.load(.nominalFrameRate)).map { Double($0) } ?? 25.0
let dur = (try? await avAsset.load(.duration))?.seconds ?? asset.duration
// Read sample (frame count from midnight)
// ใช้ AVAssetReaderAudioMixOutput สำหรับ timecode track ด้วย
// เพราะ AVAssetReaderTrackOutput อาจ throw ObjC exception
guard let reader = try? AVAssetReader(asset: avAsset) else { return nil }
let tcOutput = AVAssetReaderTrackOutput(track: tcTrack, outputSettings: nil)
tcOutput.alwaysCopiesSampleData = false
guard reader.canAdd(tcOutput) else { return nil }
reader.add(tcOutput)
guard reader.startReading() else { return nil }
guard let sb = tcOutput.copyNextSampleBuffer() else {
reader.cancelReading()
return nil
}
var frameCount: Int32 = 0
if let bb = CMSampleBufferGetDataBuffer(sb), CMBlockBufferGetDataLength(bb) >= 4 {
var raw: UInt32 = 0
CMBlockBufferCopyDataBytes(bb, atOffset: 0, dataLength: 4, destination: &raw)
frameCount = Int32(bitPattern: UInt32(bigEndian: raw))
}
reader.cancelReading()
let startSec = Double(frameCount) / fps
// Format as HH:MM:SS:FF
let totalFrames = Int(frameCount)
let safeFPS = max(1, Int(fps.rounded())) // never 0
let ff = totalFrames % safeFPS
let ss = (totalFrames / safeFPS) % 60
let mm = (totalFrames / safeFPS / 60) % 60
let hh = totalFrames / safeFPS / 3600
let tcStr = String(format: "%02d:%02d:%02d:%02d", hh, mm, ss, ff)
return TCInfo(
url: url,
name: asset.name,
startSec: startSec,
endSec: startSec + dur,
durationSec: dur,
fps: fps,
tcString: tcStr
)
}
// MARK: - Read TC from FCPXML metadata (fastest, no file access needed)
/// Builds TCInfo directly from the `start` and `duration` values that FCPXMLParser
/// already extracted from the <asset> element in the FCPXML.
///
/// When FCP creates FCPXML it reads the clip's embedded timecode and writes it as
/// `start=` on the <asset> resource (e.g. `start="53810s"` = 14:56:50:00).
/// This works for both video (QuickTime tmcd track) and audio (BWF BEXT chunk)
/// without opening the media file at all — no ffprobe, no AVFoundation, no sandbox issues.
///
/// Returns nil when `asset.start == 0` (TC at midnight or missing — fall through to
/// file-based methods) so midnight-TC clips are still attempted via ffprobe/AVFoundation.
func readTCFromFCPXML(from asset: MediaAsset) -> TCInfo? {
let baseStart = asset.isTimelineSegment
? (asset.sourceAssetStart ?? 0)
: asset.start
guard baseStart > 0 else { return nil } // 0 = midnight or no TC; try file methods
let trimOffset = asset.isTimelineSegment ? max(0, asset.start) : 0
let startSec = baseStart + trimOffset
let fps = asset.frameRate > 0 ? asset.frameRate : 25.0
let url = URL(fileURLWithPath: asset.path)
return TCInfo(url: url, name: asset.name,
startSec: startSec, endSec: startSec + asset.duration,
durationSec: asset.duration, fps: fps,
tcString: formatTCString(from: startSec, fps: fps))
}
// MARK: - Read TC (best method)
func readTC(from asset: MediaAsset) async -> TCInfo? {
// FCPXML-first policy:
// 1) Use start/duration already parsed from FCPXML whenever they are usable.
// 2) For video, prefer native AVFoundation before ffprobe.
// 3) Use ffprobe only as a raw-file fallback when FCPXML/native paths are insufficient.
// ── Priority 0: FCPXML start= attribute ──────────────────────
// FCP encodes the clip's embedded TC in <asset start="…"> when it creates the FCPXML.
// Reading from the parsed model avoids ffprobe and AVFoundation quirks entirely.
if let tc = readTCFromFCPXML(from: asset) {
print("[TC] \(asset.name) FCPXML✓ \(tc.tcString) (\(Int(tc.startSec))s)")
return tc
}
// ── Audio files (WAV etc.): no QuickTime timecode track ──────
// If FCPXML did not provide a usable start value, the only remaining path is
// a raw-file fallback via ffprobe (BWF/BEXT and related tags).
if asset.isAudio {
guard MatchingEngine.isFFprobeAvailable else {
print("[TC] \(asset.name) audio→no ffprobe fallback available")
return nil
}
let tc = await readTCViaFFprobe(from: asset).map { adjustedTCForTimelineSegment($0, asset: asset) }
print("[TC] \(asset.name) audio→ffprobe: \(tc?.tcString ?? "nil")")
return tc
}
// ── Video files: try AVFoundation before ffprobe ──────────────
let avResult = await readTCViaAVFoundation(from: asset).map { adjustedTCForTimelineSegment($0, asset: asset) }
// Trust AVFoundation only when it gives a clearly non-midnight TC (>= 10 min = 600 s).
// Cameras in "preset" TC mode (Sony etc.) start every clip at 00:00:00:00,
// so frameCount==0 → startSec==0 which is indistinguishable from a mis-read.
if let tc = avResult, tc.startSec >= 600.0 {
print("[TC] \(asset.name) AVFoundation✓ \(tc.tcString) (\(Int(tc.startSec))s)")
return tc
}
// AVFoundation returned near-midnight TC (or nil) → try ffprobe only if available.
if MatchingEngine.isFFprobeAvailable {
if let tc = await readTCViaFFprobe(from: asset).map({ adjustedTCForTimelineSegment($0, asset: asset) }) {
print("[TC] \(asset.name) ffprobe✓ \(tc.tcString) (\(Int(tc.startSec))s)")
return tc
}
} else {
print("[TC] \(asset.name) ffprobe unavailable; skipping raw-file fallback")
}
// Last resort: return whatever AVFoundation gave (even "00:00:00:00") or nil
print("[TC] \(asset.name) fallback AVFoundation: \(avResult?.tcString ?? "nil")")
return avResult
}
// MARK: - MatchingEngine Timecode Extension
extension MatchingEngine {
// Check if ffprobe is available on this machine
static var isFFprobeAvailable: Bool { ffprobePath() != nil }
/// Show ffprobe installation UI only when FCPXML/native timing is likely
/// insufficient. Audio clips are the key signal here because they have no
/// native QuickTime timecode fallback once FCPXML start values are unusable.
static func likelyNeedsFFprobeFallback(videos: [MediaAsset], audios: [MediaAsset]) -> Bool {
audios.contains { readTCFromFCPXML(from: $0) == nil }
}
/// Run timecode-based sync
/// Reads TC from each file, matches pairs by overlapping TC range.
/// `tcFrameOffset` shifts every audio TC by N frames (positive = audio TC moves forward)
/// to compensate for a known camera ↔ recorder TC discrepancy.
func runTimecode(videos: [MediaAsset], audios: [MediaAsset], tcFrameOffset: Int = 0) {
guard !isRunning else { return }
isRunning = true; isDone = false; results = []
progressStartedAt = Date()
wavAssets = audios
Task.detached(priority: .userInitiated) { [weak self] in
guard let self else { return }
await MainActor.run {
self.progress = 0.02
self.progressLabel = "🕐 Reading timecodes..."
}
let total = videos.count + audios.count
let concurrency = min(4, max(1, ProcessInfo.processInfo.activeProcessorCount / 2))
// ── Read TC from all files (limited concurrency) ──────────
typealias TCResult = (isVideo: Bool, asset: MediaAsset, tc: TCInfo?)
var videoTCs: [(MediaAsset, TCInfo?)] = []
var audioTCs: [(MediaAsset, TCInfo?)] = []
var done = 0
// Combine videos + audios into one list for the group
let allAssets: [(Bool, MediaAsset)] =
videos.map { (true, $0) } + audios.map { (false, $0) }
await withTaskGroup(of: TCResult.self) { g in
var inFlight = 0
var iter = allAssets.makeIterator()
while inFlight < concurrency, let (isVid, asset) = iter.next() {
g.addTask { (isVid, asset, await readTC(from: asset)) }
inFlight += 1
}
for await (isVid, asset, tc) in g {
if isVid { videoTCs.append((asset, tc)) }
else { audioTCs.append((asset, tc)) }
done += 1
inFlight -= 1
let progressDone = done
let assetName = asset.name
let p = 0.8 * Double(progressDone) / Double(max(1, total))
await MainActor.run {
self.progress = p
self.progressLabel = "🕐 TC [\(progressDone)/\(total)] \(assetName)"
}
if let (isVid2, asset2) = iter.next() {
g.addTask { (isVid2, asset2, await readTC(from: asset2)) }
inFlight += 1
}
}
}
// ── Match by TC overlap ────────────────────────────────────
await MainActor.run {
self.progress = 0.85
self.progressLabel = "⚡️ Matching by timecode..."
}
// Sort by original video order
videoTCs.sort { a, b in
let ia = videos.firstIndex(where: { $0.id == a.0.id }) ?? 0
let ib = videos.firstIndex(where: { $0.id == b.0.id }) ?? 0
return ia < ib
}
var out: [ClipResult] = []
for (vid, vidTC) in videoTCs {
guard let vtc = vidTC else {
// No TC in this video
out.append(ClipResult(
video: vid,
wav: nil,
score: 0,
syncOffset: 0,
status: .noAudio,
camBuffer: nil,
tcString: nil
))
continue
}
// Frame-offset correction: shift every audio TC forward by N frames
// (positive tcFrameOffset = audio TC moves later in the day)
let frameOffsetSec = Double(tcFrameOffset) / (vtc.fps > 0 ? vtc.fps : 25.0)
// Find best-matching audio by TC overlap
// Primary criterion: must overlap; secondary: closest start time to video
var bestAudio: MediaAsset? = nil
var bestOffset: Double = 0
var bestTC: TCInfo? = nil
for (aud, audTC) in audioTCs {
guard let atc = audTC else { continue }
// Apply frame offset to audio's effective TC position
let adjStart = atc.startSec + frameOffsetSec
let adjEnd = atc.endSec + frameOffsetSec
// Check overlap: ranges must intersect
let overlapStart = max(vtc.startSec, adjStart)
let overlapEnd = min(vtc.endSec, adjEnd)
guard overlapStart < overlapEnd else { continue }
// Among overlapping files, prefer the one whose start is
// closest to the video start (most likely same take/roll)
let curDiff = abs(adjStart - vtc.startSec)
let bestDiff = bestTC == nil ? Double.infinity : abs(bestOffset)
if curDiff < bestDiff {
// syncOffset = adjStart − videoStart
// positive → WAV TC > video TC → WAV started AFTER video → video leads
// negative → WAV TC < video TC → WAV started BEFORE video → audio leads
// FCPXMLGenerator uses this same convention (positive = video leads).
bestOffset = adjStart - vtc.startSec
bestAudio = aud
bestTC = atc
}
}
let status: MatchStatus = bestAudio != nil ? .matched : .none
out.append(ClipResult(
video: vid,
wav: bestAudio,
score: bestAudio != nil ? 1.0 : 0.0,
syncOffset: bestOffset,
status: status,
camBuffer: nil,
tcString: vtc.tcString
))
}
let matched = out.filter { $0.status == .matched }.count
let noTC = out.filter { $0.tcString == nil && $0.status != .matched }.count
let finalResults = out
let finalLabel = noTC > 0
? "✅ \(matched)/\(finalResults.count) matched · ⚠️ \(noTC) ไม่มี TC"
: "✅ \(matched)/\(finalResults.count) matched by timecode"
await MainActor.run {
self.results = finalResults
self.progress = 1.0
self.progressLabel = finalLabel
self.isRunning = false
self.isDone = true
}
}
}
}