diff --git a/Dreamio/NativePlayerViewController.swift b/Dreamio/NativePlayerViewController.swift index 1679f1f..d810e94 100644 --- a/Dreamio/NativePlayerViewController.swift +++ b/Dreamio/NativePlayerViewController.swift @@ -9,6 +9,10 @@ final class NativePlayerViewController: UIViewController { private var progressTimer: Timer? private var isScrubbing = false private var attachedSubtitleURLs: Set + private var parsedExternalSubtitleURLs: Set = [] + private var externalSubtitleTracks: [ExternalSubtitleTrack] = [] + private var selectedExternalSubtitleTrackID: Int? + private var nextExternalSubtitleTrackID = 1 private var audioMenuSignature: String? private var captionsMenuSignature: String? var onDismiss: (() -> Void)? @@ -99,6 +103,20 @@ final class NativePlayerViewController: UIViewController { return label }() + private let subtitleOverlayLabel: UILabel = { + let label = UILabel() + label.translatesAutoresizingMaskIntoConstraints = false + label.textColor = .white + label.textAlignment = .center + label.numberOfLines = 3 + label.font = .systemFont(ofSize: 20, weight: .semibold) + label.backgroundColor = UIColor.black.withAlphaComponent(0.48) + label.layer.cornerRadius = 6 + label.clipsToBounds = true + label.isHidden = true + return label + }() + init( request: NativePlaybackRequest, backend: NativePlaybackBackend = VLCNativePlaybackBackend(), @@ -165,6 +183,7 @@ final class NativePlayerViewController: UIViewController { #endif return } + self.ingestExternalSubtitleTracks(resolvedCandidates) let attachableCandidates = resolvedCandidates.filter { candidate in guard !self.attachedSubtitleURLs.contains(candidate.url) || pendingCandidates.contains(where: { $0.url == candidate.url }) else { return false @@ -254,6 +273,7 @@ final class NativePlayerViewController: UIViewController { view.addSubview(tapSurfaceView) view.addSubview(loadingView) view.addSubview(failureLabel) + view.addSubview(subtitleOverlayLabel) view.addSubview(controlsContainer) view.addSubview(closeButton) closeButton.addTarget(self, action: #selector(close), for: .touchUpInside) @@ -315,6 +335,11 @@ final class NativePlayerViewController: UIViewController { failureLabel.trailingAnchor.constraint(equalTo: view.safeAreaLayoutGuide.trailingAnchor, constant: -28), failureLabel.centerYAnchor.constraint(equalTo: view.centerYAnchor), + subtitleOverlayLabel.centerXAnchor.constraint(equalTo: view.safeAreaLayoutGuide.centerXAnchor), + subtitleOverlayLabel.leadingAnchor.constraint(greaterThanOrEqualTo: view.safeAreaLayoutGuide.leadingAnchor, constant: 18), + subtitleOverlayLabel.trailingAnchor.constraint(lessThanOrEqualTo: view.safeAreaLayoutGuide.trailingAnchor, constant: -18), + subtitleOverlayLabel.bottomAnchor.constraint(equalTo: view.safeAreaLayoutGuide.bottomAnchor, constant: -92), + closeButton.widthAnchor.constraint(equalToConstant: 36), closeButton.heightAnchor.constraint(equalToConstant: 36), closeButton.topAnchor.constraint(equalTo: view.safeAreaLayoutGuide.topAnchor, constant: 10), @@ -403,18 +428,33 @@ final class NativePlayerViewController: UIViewController { private func captionsMenu() -> UIMenu { let selectedTrackID = backend.selectedSubtitleTrackID let tracks = backend.subtitleTracks - let options = SubtitleOptionMapper.options(from: tracks) + let backendOptions = tracks.filter { $0.id >= 0 } #if DEBUG - print("[DreamioCaptions] build-menu tracks=\(SubtitleDebugFormatter.trackSummary(tracks)) options=\(SubtitleDebugFormatter.trackSummary(options)) selected=\(selectedTrackID)") + print("[DreamioCaptions] build-menu tracks=\(SubtitleDebugFormatter.trackSummary(tracks)) external=\(externalSubtitleTracks.map { "{id=\($0.id), name=\($0.name)}" }.joined(separator: ", ")) selected=\(selectedTrackID) externalSelected=\(selectedExternalSubtitleTrackID.map(String.init) ?? "none")") #endif - let trackActions = options.map { track in + let noneAction = UIAction( + title: SubtitleOptionMapper.noneTrack.name, + state: selectedTrackID < 0 && selectedExternalSubtitleTrackID == nil ? .on : .off + ) { [weak self] _ in + guard let self else { + return + } + self.selectedExternalSubtitleTrackID = nil + self.subtitleOverlayLabel.isHidden = true + self.backend.selectSubtitleTrack(id: SubtitleOptionMapper.noneTrack.id) + self.captionsMenuSignature = nil + self.refreshControls() + } + let backendActions = backendOptions.map { track in UIAction( title: track.name, - state: track.id == selectedTrackID ? .on : .off + state: selectedExternalSubtitleTrackID == nil && track.id == selectedTrackID ? .on : .off ) { [weak self] _ in guard let self else { return } + self.selectedExternalSubtitleTrackID = nil + self.subtitleOverlayLabel.isHidden = true #if DEBUG print("[DreamioCaptions] select-request id=\(track.id) name=\(track.name) before=\(self.backend.selectedSubtitleTrackID)") #endif @@ -426,6 +466,20 @@ final class NativePlayerViewController: UIViewController { self.refreshControls() } } + let externalActions = externalSubtitleTracks.map { track in + UIAction( + title: track.name, + state: track.id == selectedExternalSubtitleTrackID ? .on : .off + ) { [weak self] _ in + guard let self else { + return + } + self.selectedExternalSubtitleTrackID = track.id + self.backend.selectSubtitleTrack(id: SubtitleOptionMapper.noneTrack.id) + self.captionsMenuSignature = nil + self.refreshControls() + } + } let delayActions = UIMenu( title: "Delay", @@ -448,7 +502,7 @@ final class NativePlayerViewController: UIViewController { ] ) - return UIMenu(title: "Captions", children: trackActions + [delayActions]) + return UIMenu(title: "Captions", children: [noneAction] + backendActions + externalActions + [delayActions]) } private func audioMenu() -> UIMenu { @@ -497,6 +551,7 @@ final class NativePlayerViewController: UIViewController { jumpForwardButton.isEnabled = backend.isSeekable updateAudioMenuIfNeeded(audioTracks: audioTracks) updateCaptionsMenuIfNeeded(subtitleTracks: subtitleTracks) + updateExternalSubtitleOverlay() elapsedLabel.text = PlaybackTimeFormatter.label(for: backend.currentTime) remainingLabel.text = "-\(PlaybackTimeFormatter.label(for: backend.remainingTime))" if !isScrubbing { @@ -530,9 +585,10 @@ final class NativePlayerViewController: UIViewController { let signature = captionsMenuSignatureValue( tracks: subtitleTracks, selectedTrackID: selectedTrackID, + selectedExternalTrackID: selectedExternalSubtitleTrackID, delay: backend.subtitleDelay ) - let hasSelectableTrack = subtitleTracks.contains { $0.id >= 0 } + let hasSelectableTrack = subtitleTracks.contains { $0.id >= 0 } || !externalSubtitleTracks.isEmpty captionsButton.isEnabled = hasSelectableTrack guard signature != captionsMenuSignature else { return @@ -548,10 +604,14 @@ final class NativePlayerViewController: UIViewController { private func captionsMenuSignatureValue( tracks: [SubtitleTrack], selectedTrackID: Int32, + selectedExternalTrackID: Int?, delay: TimeInterval ) -> String { let trackSignature = trackMenuSignatureValue(tracks: tracks, selectedTrackID: selectedTrackID) - return "\(trackSignature)#delay=\(String(format: "%.1f", delay))" + let externalSignature = externalSubtitleTracks + .map { "\($0.id):\($0.name):\($0.cues.count)" } + .joined(separator: "|") + return "\(trackSignature)#external=\(externalSignature)#externalSelected=\(selectedExternalTrackID.map(String.init) ?? "none")#delay=\(String(format: "%.1f", delay))" } private func trackMenuSignatureValue( @@ -574,6 +634,53 @@ final class NativePlayerViewController: UIViewController { scheduleControlsHide() } + private func ingestExternalSubtitleTracks(_ candidates: [SubtitleCandidate]) { + candidates.forEach { candidate in + guard candidate.url.isFileURL, + !parsedExternalSubtitleURLs.contains(candidate.url), + let track = ExternalSubtitleTrackParser.track( + from: candidate, + id: nextExternalSubtitleTrackID + ) + else { + return + } + + parsedExternalSubtitleURLs.insert(candidate.url) + externalSubtitleTracks.append(track) + nextExternalSubtitleTrackID += 1 + if selectedExternalSubtitleTrackID == nil, + !backend.subtitleTracks.contains(where: { $0.id >= 0 }) { + selectedExternalSubtitleTrackID = track.id + } +#if DEBUG + print("[DreamioCaptions] parsed external subtitle id=\(track.id) name=\(track.name) cues=\(track.cues.count)") +#endif + } + if !candidates.isEmpty { + captionsMenuSignature = nil + } + } + + private func updateExternalSubtitleOverlay() { + guard let selectedExternalSubtitleTrackID, + backend.selectedSubtitleTrackID < 0, + let track = externalSubtitleTracks.first(where: { $0.id == selectedExternalSubtitleTrackID }) + else { + subtitleOverlayLabel.isHidden = true + return + } + + let adjustedTime = backend.currentTime - backend.subtitleDelay + guard let cue = track.cues.first(where: { adjustedTime >= $0.start && adjustedTime <= $0.end }) else { + subtitleOverlayLabel.isHidden = true + return + } + + subtitleOverlayLabel.text = " \(cue.text) " + subtitleOverlayLabel.isHidden = false + } + private func hideControls() { controlsContainer.isUserInteractionEnabled = false closeButton.isUserInteractionEnabled = false @@ -615,3 +722,99 @@ final class NativePlayerViewController: UIViewController { } } } + +private struct ExternalSubtitleTrack { + let id: Int + let name: String + let cues: [ExternalSubtitleCue] +} + +private struct ExternalSubtitleCue { + let start: TimeInterval + let end: TimeInterval + let text: String +} + +private enum ExternalSubtitleTrackParser { + static func track(from candidate: SubtitleCandidate, id: Int) -> ExternalSubtitleTrack? { + guard let text = try? String(contentsOf: candidate.url, encoding: .utf8) else { + return nil + } + + let cues = parseCues(from: text) + guard !cues.isEmpty else { + return nil + } + + return ExternalSubtitleTrack( + id: id, + name: SubtitleDisplayName.displayName(for: candidate), + cues: cues + ) + } + + private static func parseCues(from text: String) -> [ExternalSubtitleCue] { + let normalized = text + .replacingOccurrences(of: "\r\n", with: "\n") + .replacingOccurrences(of: "\r", with: "\n") + let blocks = normalized.components(separatedBy: "\n\n") + return blocks.compactMap(parseCueBlock) + } + + private static func parseCueBlock(_ block: String) -> ExternalSubtitleCue? { + let lines = block + .components(separatedBy: .newlines) + .map { $0.trimmingCharacters(in: .whitespacesAndNewlines) } + .filter { !$0.isEmpty && !$0.lowercased().hasPrefix("webvtt") } + guard !lines.isEmpty else { + return nil + } + + guard let timingIndex = lines.firstIndex(where: { $0.contains("-->") }) else { + return nil + } + let timingParts = lines[timingIndex].components(separatedBy: "-->") + guard timingParts.count == 2, + let start = parseTimestamp(timingParts[0]), + let end = parseTimestamp(timingParts[1]) + else { + return nil + } + + let cueText = lines + .dropFirst(timingIndex + 1) + .map(cleanCueText) + .filter { !$0.isEmpty } + .joined(separator: "\n") + guard !cueText.isEmpty else { + return nil + } + + return ExternalSubtitleCue(start: start, end: end, text: cueText) + } + + private static func parseTimestamp(_ value: String) -> TimeInterval? { + let timestamp = value + .trimmingCharacters(in: .whitespacesAndNewlines) + .replacingOccurrences(of: ",", with: ".") + .components(separatedBy: .whitespaces) + .first ?? "" + let pieces = timestamp.split(separator: ":").map(String.init) + guard let secondsPiece = pieces.last, + let seconds = Double(secondsPiece) + else { + return nil + } + + let minutes = pieces.count >= 2 ? Double(pieces[pieces.count - 2]) ?? 0 : 0 + let hours = pieces.count >= 3 ? Double(pieces[pieces.count - 3]) ?? 0 : 0 + return hours * 3600 + minutes * 60 + seconds + } + + private static func cleanCueText(_ value: String) -> String { + value + .replacingOccurrences(of: #"<[^>]+>"#, with: "", options: .regularExpression) + .replacingOccurrences(of: #"\{\\[^}]+\}"#, with: "", options: .regularExpression) + .trimmingCharacters(in: .whitespacesAndNewlines) + } +} diff --git a/docs/turns/2026-05-25-queue-vlc-subtitles-until-media-start.html b/docs/turns/2026-05-25-queue-vlc-subtitles-until-media-start.html index f3f3688..856ada2 100644 --- a/docs/turns/2026-05-25-queue-vlc-subtitles-until-media-start.html +++ b/docs/turns/2026-05-25-queue-vlc-subtitles-until-media-start.html @@ -591,9 +591,118 @@

Related Beads issue: dreamio-3aq.

+ +
+

New Changes as of May 25, 2026 at 7:10 PM EDT

+

Summary of changes

+

After confirming that MobileVLCKit still exposed no tracks from local subtitle files added before playback, Dreamio now has a native subtitle overlay fallback. Resolved local subtitle files are parsed into cue tracks, auto-selected when VLC has no subtitle tracks, and rendered over the player using the backend playback time.

+

Why this change was made

+

The logs proved the full handoff into VLC was correct: local .srt files existed, were queued before playback, and were passed as media slaves. Since MobileVLCKit continued reporting an empty subtitle track list, native rendering is the practical path that gives users captions without depending on VLC external track import.

+

Code diffs

+
Dreamio/NativePlayerViewController.swift
-7+210
8 unmodified lines
9
10
11
12
13
14
84 unmodified lines
99
100
101
102
103
104
60 unmodified lines
165
166
167
168
169
170
83 unmodified lines
254
255
256
257
258
259
55 unmodified lines
315
316
317
318
319
320
82 unmodified lines
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
5 unmodified lines
426
427
428
429
430
431
16 unmodified lines
448
449
450
451
452
453
454
42 unmodified lines
497
498
499
500
501
502
27 unmodified lines
530
531
532
533
534
535
536
537
538
9 unmodified lines
548
549
550
551
552
553
554
555
556
557
16 unmodified lines
574
575
576
577
578
579
35 unmodified lines
615
616
617
8 unmodified lines
private var progressTimer: Timer?
private var isScrubbing = false
private var attachedSubtitleURLs: Set<URL>
private var audioMenuSignature: String?
private var captionsMenuSignature: String?
var onDismiss: (() -> Void)?
84 unmodified lines
return label
}()
+
init(
request: NativePlaybackRequest,
backend: NativePlaybackBackend = VLCNativePlaybackBackend(),
60 unmodified lines
#endif
return
}
let attachableCandidates = resolvedCandidates.filter { candidate in
guard !self.attachedSubtitleURLs.contains(candidate.url) || pendingCandidates.contains(where: { $0.url == candidate.url }) else {
return false
83 unmodified lines
view.addSubview(tapSurfaceView)
view.addSubview(loadingView)
view.addSubview(failureLabel)
view.addSubview(controlsContainer)
view.addSubview(closeButton)
closeButton.addTarget(self, action: #selector(close), for: .touchUpInside)
55 unmodified lines
failureLabel.trailingAnchor.constraint(equalTo: view.safeAreaLayoutGuide.trailingAnchor, constant: -28),
failureLabel.centerYAnchor.constraint(equalTo: view.centerYAnchor),
+
closeButton.widthAnchor.constraint(equalToConstant: 36),
closeButton.heightAnchor.constraint(equalToConstant: 36),
closeButton.topAnchor.constraint(equalTo: view.safeAreaLayoutGuide.topAnchor, constant: 10),
82 unmodified lines
private func captionsMenu() -> UIMenu {
let selectedTrackID = backend.selectedSubtitleTrackID
let tracks = backend.subtitleTracks
let options = SubtitleOptionMapper.options(from: tracks)
#if DEBUG
print("[DreamioCaptions] build-menu tracks=\(SubtitleDebugFormatter.trackSummary(tracks)) options=\(SubtitleDebugFormatter.trackSummary(options)) selected=\(selectedTrackID)")
#endif
let trackActions = options.map { track in
UIAction(
title: track.name,
state: track.id == selectedTrackID ? .on : .off
) { [weak self] _ in
guard let self else {
return
}
#if DEBUG
print("[DreamioCaptions] select-request id=\(track.id) name=\(track.name) before=\(self.backend.selectedSubtitleTrackID)")
#endif
5 unmodified lines
self.refreshControls()
}
}
+
let delayActions = UIMenu(
title: "Delay",
16 unmodified lines
]
)
+
return UIMenu(title: "Captions", children: trackActions + [delayActions])
}
+
private func audioMenu() -> UIMenu {
42 unmodified lines
jumpForwardButton.isEnabled = backend.isSeekable
updateAudioMenuIfNeeded(audioTracks: audioTracks)
updateCaptionsMenuIfNeeded(subtitleTracks: subtitleTracks)
elapsedLabel.text = PlaybackTimeFormatter.label(for: backend.currentTime)
remainingLabel.text = "-\(PlaybackTimeFormatter.label(for: backend.remainingTime))"
if !isScrubbing {
27 unmodified lines
let signature = captionsMenuSignatureValue(
tracks: subtitleTracks,
selectedTrackID: selectedTrackID,
delay: backend.subtitleDelay
)
let hasSelectableTrack = subtitleTracks.contains { $0.id >= 0 }
captionsButton.isEnabled = hasSelectableTrack
guard signature != captionsMenuSignature else {
return
9 unmodified lines
private func captionsMenuSignatureValue(
tracks: [SubtitleTrack],
selectedTrackID: Int32,
delay: TimeInterval
) -> String {
let trackSignature = trackMenuSignatureValue(tracks: tracks, selectedTrackID: selectedTrackID)
return "\(trackSignature)#delay=\(String(format: "%.1f", delay))"
}
+
private func trackMenuSignatureValue(
16 unmodified lines
scheduleControlsHide()
}
+
private func hideControls() {
controlsContainer.isUserInteractionEnabled = false
closeButton.isUserInteractionEnabled = false
35 unmodified lines
}
}
}
8 unmodified lines
9
10
11
12
13
14
15
16
17
18
84 unmodified lines
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
60 unmodified lines
183
184
185
186
187
188
189
83 unmodified lines
273
274
275
276
277
278
279
55 unmodified lines
335
336
337
338
339
340
341
342
343
344
345
82 unmodified lines
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
5 unmodified lines
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
16 unmodified lines
502
503
504
505
506
507
508
42 unmodified lines
551
552
553
554
555
556
557
27 unmodified lines
585
586
587
588
589
590
591
592
593
594
9 unmodified lines
604
605
606
607
608
609
610
611
612
613
614
615
616
617
16 unmodified lines
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
35 unmodified lines
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
8 unmodified lines
private var progressTimer: Timer?
private var isScrubbing = false
private var attachedSubtitleURLs: Set<URL>
private var parsedExternalSubtitleURLs: Set<URL> = []
private var externalSubtitleTracks: [ExternalSubtitleTrack] = []
private var selectedExternalSubtitleTrackID: Int?
private var nextExternalSubtitleTrackID = 1
private var audioMenuSignature: String?
private var captionsMenuSignature: String?
var onDismiss: (() -> Void)?
84 unmodified lines
return label
}()
+
private let subtitleOverlayLabel: UILabel = {
let label = UILabel()
label.translatesAutoresizingMaskIntoConstraints = false
label.textColor = .white
label.textAlignment = .center
label.numberOfLines = 3
label.font = .systemFont(ofSize: 20, weight: .semibold)
label.backgroundColor = UIColor.black.withAlphaComponent(0.48)
label.layer.cornerRadius = 6
label.clipsToBounds = true
label.isHidden = true
return label
}()
+
init(
request: NativePlaybackRequest,
backend: NativePlaybackBackend = VLCNativePlaybackBackend(),
60 unmodified lines
#endif
return
}
self.ingestExternalSubtitleTracks(resolvedCandidates)
let attachableCandidates = resolvedCandidates.filter { candidate in
guard !self.attachedSubtitleURLs.contains(candidate.url) || pendingCandidates.contains(where: { $0.url == candidate.url }) else {
return false
83 unmodified lines
view.addSubview(tapSurfaceView)
view.addSubview(loadingView)
view.addSubview(failureLabel)
view.addSubview(subtitleOverlayLabel)
view.addSubview(controlsContainer)
view.addSubview(closeButton)
closeButton.addTarget(self, action: #selector(close), for: .touchUpInside)
55 unmodified lines
failureLabel.trailingAnchor.constraint(equalTo: view.safeAreaLayoutGuide.trailingAnchor, constant: -28),
failureLabel.centerYAnchor.constraint(equalTo: view.centerYAnchor),
+
subtitleOverlayLabel.centerXAnchor.constraint(equalTo: view.safeAreaLayoutGuide.centerXAnchor),
subtitleOverlayLabel.leadingAnchor.constraint(greaterThanOrEqualTo: view.safeAreaLayoutGuide.leadingAnchor, constant: 18),
subtitleOverlayLabel.trailingAnchor.constraint(lessThanOrEqualTo: view.safeAreaLayoutGuide.trailingAnchor, constant: -18),
subtitleOverlayLabel.bottomAnchor.constraint(equalTo: view.safeAreaLayoutGuide.bottomAnchor, constant: -92),
+
closeButton.widthAnchor.constraint(equalToConstant: 36),
closeButton.heightAnchor.constraint(equalToConstant: 36),
closeButton.topAnchor.constraint(equalTo: view.safeAreaLayoutGuide.topAnchor, constant: 10),
82 unmodified lines
private func captionsMenu() -> UIMenu {
let selectedTrackID = backend.selectedSubtitleTrackID
let tracks = backend.subtitleTracks
let backendOptions = tracks.filter { $0.id >= 0 }
#if DEBUG
print("[DreamioCaptions] build-menu tracks=\(SubtitleDebugFormatter.trackSummary(tracks)) external=\(externalSubtitleTracks.map { "{id=\($0.id), name=\($0.name)}" }.joined(separator: ", ")) selected=\(selectedTrackID) externalSelected=\(selectedExternalSubtitleTrackID.map(String.init) ?? "none")")
#endif
let noneAction = UIAction(
title: SubtitleOptionMapper.noneTrack.name,
state: selectedTrackID < 0 && selectedExternalSubtitleTrackID == nil ? .on : .off
) { [weak self] _ in
guard let self else {
return
}
self.selectedExternalSubtitleTrackID = nil
self.subtitleOverlayLabel.isHidden = true
self.backend.selectSubtitleTrack(id: SubtitleOptionMapper.noneTrack.id)
self.captionsMenuSignature = nil
self.refreshControls()
}
let backendActions = backendOptions.map { track in
UIAction(
title: track.name,
state: selectedExternalSubtitleTrackID == nil && track.id == selectedTrackID ? .on : .off
) { [weak self] _ in
guard let self else {
return
}
self.selectedExternalSubtitleTrackID = nil
self.subtitleOverlayLabel.isHidden = true
#if DEBUG
print("[DreamioCaptions] select-request id=\(track.id) name=\(track.name) before=\(self.backend.selectedSubtitleTrackID)")
#endif
5 unmodified lines
self.refreshControls()
}
}
let externalActions = externalSubtitleTracks.map { track in
UIAction(
title: track.name,
state: track.id == selectedExternalSubtitleTrackID ? .on : .off
) { [weak self] _ in
guard let self else {
return
}
self.selectedExternalSubtitleTrackID = track.id
self.backend.selectSubtitleTrack(id: SubtitleOptionMapper.noneTrack.id)
self.captionsMenuSignature = nil
self.refreshControls()
}
}
+
let delayActions = UIMenu(
title: "Delay",
16 unmodified lines
]
)
+
return UIMenu(title: "Captions", children: [noneAction] + backendActions + externalActions + [delayActions])
}
+
private func audioMenu() -> UIMenu {
42 unmodified lines
jumpForwardButton.isEnabled = backend.isSeekable
updateAudioMenuIfNeeded(audioTracks: audioTracks)
updateCaptionsMenuIfNeeded(subtitleTracks: subtitleTracks)
updateExternalSubtitleOverlay()
elapsedLabel.text = PlaybackTimeFormatter.label(for: backend.currentTime)
remainingLabel.text = "-\(PlaybackTimeFormatter.label(for: backend.remainingTime))"
if !isScrubbing {
27 unmodified lines
let signature = captionsMenuSignatureValue(
tracks: subtitleTracks,
selectedTrackID: selectedTrackID,
selectedExternalTrackID: selectedExternalSubtitleTrackID,
delay: backend.subtitleDelay
)
let hasSelectableTrack = subtitleTracks.contains { $0.id >= 0 } || !externalSubtitleTracks.isEmpty
captionsButton.isEnabled = hasSelectableTrack
guard signature != captionsMenuSignature else {
return
9 unmodified lines
private func captionsMenuSignatureValue(
tracks: [SubtitleTrack],
selectedTrackID: Int32,
selectedExternalTrackID: Int?,
delay: TimeInterval
) -> String {
let trackSignature = trackMenuSignatureValue(tracks: tracks, selectedTrackID: selectedTrackID)
let externalSignature = externalSubtitleTracks
.map { "\($0.id):\($0.name):\($0.cues.count)" }
.joined(separator: "|")
return "\(trackSignature)#external=\(externalSignature)#externalSelected=\(selectedExternalTrackID.map(String.init) ?? "none")#delay=\(String(format: "%.1f", delay))"
}
+
private func trackMenuSignatureValue(
16 unmodified lines
scheduleControlsHide()
}
+
private func ingestExternalSubtitleTracks(_ candidates: [SubtitleCandidate]) {
candidates.forEach { candidate in
guard candidate.url.isFileURL,
!parsedExternalSubtitleURLs.contains(candidate.url),
let track = ExternalSubtitleTrackParser.track(
from: candidate,
id: nextExternalSubtitleTrackID
)
else {
return
}
+
parsedExternalSubtitleURLs.insert(candidate.url)
externalSubtitleTracks.append(track)
nextExternalSubtitleTrackID += 1
if selectedExternalSubtitleTrackID == nil,
!backend.subtitleTracks.contains(where: { $0.id >= 0 }) {
selectedExternalSubtitleTrackID = track.id
}
#if DEBUG
print("[DreamioCaptions] parsed external subtitle id=\(track.id) name=\(track.name) cues=\(track.cues.count)")
#endif
}
if !candidates.isEmpty {
captionsMenuSignature = nil
}
}
+
private func updateExternalSubtitleOverlay() {
guard let selectedExternalSubtitleTrackID,
backend.selectedSubtitleTrackID < 0,
let track = externalSubtitleTracks.first(where: { $0.id == selectedExternalSubtitleTrackID })
else {
subtitleOverlayLabel.isHidden = true
return
}
+
let adjustedTime = backend.currentTime - backend.subtitleDelay
guard let cue = track.cues.first(where: { adjustedTime >= $0.start && adjustedTime <= $0.end }) else {
subtitleOverlayLabel.isHidden = true
return
}
+
subtitleOverlayLabel.text = " \(cue.text) "
subtitleOverlayLabel.isHidden = false
}
+
private func hideControls() {
controlsContainer.isUserInteractionEnabled = false
closeButton.isUserInteractionEnabled = false
35 unmodified lines
}
}
}
+
private struct ExternalSubtitleTrack {
let id: Int
let name: String
let cues: [ExternalSubtitleCue]
}
+
private struct ExternalSubtitleCue {
let start: TimeInterval
let end: TimeInterval
let text: String
}
+
private enum ExternalSubtitleTrackParser {
static func track(from candidate: SubtitleCandidate, id: Int) -> ExternalSubtitleTrack? {
guard let text = try? String(contentsOf: candidate.url, encoding: .utf8) else {
return nil
}
+
let cues = parseCues(from: text)
guard !cues.isEmpty else {
return nil
}
+
return ExternalSubtitleTrack(
id: id,
name: SubtitleDisplayName.displayName(for: candidate),
cues: cues
)
}
+
private static func parseCues(from text: String) -> [ExternalSubtitleCue] {
let normalized = text
.replacingOccurrences(of: "\r\n", with: "\n")
.replacingOccurrences(of: "\r", with: "\n")
let blocks = normalized.components(separatedBy: "\n\n")
return blocks.compactMap(parseCueBlock)
}
+
private static func parseCueBlock(_ block: String) -> ExternalSubtitleCue? {
let lines = block
.components(separatedBy: .newlines)
.map { $0.trimmingCharacters(in: .whitespacesAndNewlines) }
.filter { !$0.isEmpty && !$0.lowercased().hasPrefix("webvtt") }
guard !lines.isEmpty else {
return nil
}
+
guard let timingIndex = lines.firstIndex(where: { $0.contains("-->") }) else {
return nil
}
let timingParts = lines[timingIndex].components(separatedBy: "-->")
guard timingParts.count == 2,
let start = parseTimestamp(timingParts[0]),
let end = parseTimestamp(timingParts[1])
else {
return nil
}
+
let cueText = lines
.dropFirst(timingIndex + 1)
.map(cleanCueText)
.filter { !$0.isEmpty }
.joined(separator: "\n")
guard !cueText.isEmpty else {
return nil
}
+
return ExternalSubtitleCue(start: start, end: end, text: cueText)
}
+
private static func parseTimestamp(_ value: String) -> TimeInterval? {
let timestamp = value
.trimmingCharacters(in: .whitespacesAndNewlines)
.replacingOccurrences(of: ",", with: ".")
.components(separatedBy: .whitespaces)
.first ?? ""
let pieces = timestamp.split(separator: ":").map(String.init)
guard let secondsPiece = pieces.last,
let seconds = Double(secondsPiece)
else {
return nil
}
+
let minutes = pieces.count >= 2 ? Double(pieces[pieces.count - 2]) ?? 0 : 0
let hours = pieces.count >= 3 ? Double(pieces[pieces.count - 3]) ?? 0 : 0
return hours * 3600 + minutes * 60 + seconds
}
+
private static func cleanCueText(_ value: String) -> String {
value
.replacingOccurrences(of: #"<[^>]+>"#, with: "", options: .regularExpression)
.replacingOccurrences(of: #"\{\\[^}]+\}"#, with: "", options: .regularExpression)
.trimmingCharacters(in: .whitespacesAndNewlines)
}
}
+

Related issues or PRs

+

Related Beads issue: dreamio-7wi.

+
+

Expected Impact for End-Users

-

When an MKV stream opens through the real local range buffer, subtitles discovered before playback should still appear in the captions menu and be eligible for auto-selection once VLC exposes the track list. Stremio subtitle downloads should now reach VLC as local subtitle files rather than extensionless provider URLs, including plain cue-text payloads that do not match classic indexed SRT. Queued subtitles are now registered with VLC before playback starts.

+

When an MKV stream opens through the real local range buffer, subtitles discovered before playback should still appear in the captions menu and be eligible for auto-selection once VLC exposes the track list. Stremio subtitle downloads should now reach VLC as local subtitle files rather than extensionless provider URLs, including plain cue-text payloads that do not match classic indexed SRT. Queued subtitles are now registered with VLC before playback starts, and Dreamio can render parsed external subtitles natively when VLC still exposes no text tracks.

@@ -601,7 +710,7 @@
  • Ran git diff --check: passed.
  • Ran pod install to restore missing local CocoaPods support files in this worktree.
  • -
  • Ran xcodebuild -workspace Dreamio.xcworkspace -scheme Dreamio -destination 'generic/platform=iOS Simulator' -quiet build: passed after moving queued subtitles to pre-playback media options.
  • +
  • Ran xcodebuild -workspace Dreamio.xcworkspace -scheme Dreamio -destination 'generic/platform=iOS Simulator' -quiet build: passed after adding the native subtitle overlay fallback.
  • Ran swiftc -parse-as-library -D DEBUG Dreamio/StreamCandidate.swift Dreamio/StreamResolver.swift Dreamio/ProgressiveHTTPRangeCache.swift Tests/StreamResolverTests.swift -o /tmp/StreamResolverTests && /tmp/StreamResolverTests: passed, including the Stremio subtitle cache tests for strict SRT and plain cue text.
  • The build still reports existing MobileVLCKit warnings about simulator deployment target and a run-script phase, but compilation succeeded.
@@ -609,14 +718,14 @@

Issues, Limitations, and Mitigations

-

This addresses the pre-media attachment race shown in the logs and the follow-on issue where extensionless Stremio subtitle download URLs were accepted by VLC without visible tracks. If a provider returns a compressed archive, a non-UTF-8 payload, HTML/XML, JSON without a direct subtitle link, or a format VLC cannot parse after local caching, that would still need a separate resolver enhancement. If MobileVLCKit still refuses :input-slave subtitle files on iOS, the next mitigation would be a different subtitle rendering path outside VLC track import.

+

This addresses the pre-media attachment race shown in the logs and the follow-on issue where extensionless Stremio subtitle download URLs were accepted by VLC without visible tracks. If a provider returns a compressed archive, a non-UTF-8 payload, HTML/XML, JSON without a direct subtitle link, or a format VLC cannot parse after local caching, that would still need a separate resolver enhancement. Dreamio now includes a subtitle rendering path outside VLC track import. The fallback parser handles SRT/WebVTT-style cue blocks and simple HTML/ASS cleanup, but more advanced ASS styling is intentionally flattened to plain text.

Follow-up Work

  • Re-test on device with the South Park stream and confirm the log order changes to queued subtitles followed by flushing queued subtitles after opening mode=local-cache.
  • -
  • Re-test on device and look for [DreamioSubtitles] cached subtitle followed by VLC attachment logs with ext=srt, ext=vtt, or ext=ass. If rejection still occurs, inspect the new preview= field in the rejection log. Also verify the next VLC log shows queued subtitle slave before opening mode=local-cache.
  • +
  • Re-test on device and look for [DreamioSubtitles] cached subtitle followed by VLC attachment logs with ext=srt, ext=vtt, or ext=ass. If rejection still occurs, inspect the new preview= field in the rejection log. Also verify the next log shows [DreamioCaptions] parsed external subtitle entries and that the captions menu is enabled even while VLC track logs remain empty.
  • If tracks still do not appear after local caching, capture whether VLC receives file URLs and whether MobileVLCKit reports any subtitle import errors.