Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
12 changes: 11 additions & 1 deletion CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,17 @@ the public-API contract.

## [Unreleased]

_Nothing yet._
### Fixed

- **A DVD-Video image without an ISO9660 bridge volume plays its film, not its menu.** DVD recognition
only looked for `VIDEO_TS` through ISO9660, so an image that is UDF only (sector 16 starts UDF's BEA01
directly) went down the Blu-ray branch, found no `BDMV`, and was opened raw: the session played the
first VOB, which is the menu. *The Little Chinese Seamstress* reported 7.9 s and played only its menu;
it now reports 6364 s, as its IFO declares, and plays the title set. Such an image now has `VIDEO_TS`
listed through UDF once no `BDMV` is found, and the title is built as from ISO9660. A file recorded as
runs that do not continue each other is left out of the title. The UDF anchor is still read once, so a
source that is no disc costs the same probe reads as before. `aetherctl disc-inspect` reports such an
image as `dvdVideo`.

## [7.33.2] - 2026-10-09

Expand Down
7 changes: 7 additions & 0 deletions Sources/AetherEngine/Disc/DiscInspector.swift
Original file line number Diff line number Diff line change
Expand Up @@ -119,6 +119,13 @@ enum DiscInspector {
} else {
kind = .udfNoTitle
}
} else if let videoTS = root.first(where: { $0.isDir && $0.name.uppercased() == "VIDEO_TS" }) {
// A DVD-Video image with no ISO9660 bridge, as `DiscReader.wrapUDFDVD` reads it.
let names = ((try? udf.list(path: [videoTS.name])) ?? []).filter { !$0.isDir }.map(\.name)
d.dvdVOBFiles = names
let groups = DVDTitleSelector.enumerateTitleVOBGroups(
names.map { DiscFile(name: $0, startSector: 0, length: 1) })
kind = groups.isEmpty ? .udfNoBDMV : .dvdVideo
} else {
kind = .udfNoBDMV
}
Expand Down
61 changes: 54 additions & 7 deletions Sources/AetherEngine/Disc/DiscReader.swift
Original file line number Diff line number Diff line change
Expand Up @@ -33,8 +33,10 @@ enum DiscReader {
/// Emits `.demux` diagnostics once the UDF anchor is confirmed so a disc image
/// that fails recognition is debuggable (it would otherwise fall back to a raw
/// FFmpeg open that reports a bare INVALIDDATA). Non-disc sources stay silent.
static func wrapBluRay(_ reader: IOReader, selectTitleID: Int? = nil, cacheKey: String? = nil) throws -> DiscInfo? {
guard looksLikeUDF(reader) else { return nil }
/// `udfAnchorChecked`: the caller has already found the UDF anchor, so it is not read again.
static func wrapBluRay(_ reader: IOReader, selectTitleID: Int? = nil, cacheKey: String? = nil,
udfAnchorChecked: Bool = false) throws -> DiscInfo? {
guard udfAnchorChecked || looksLikeUDF(reader) else { return nil }
EngineLog.emit("[disc] UDF anchor present; attempting Blu-ray BDMV", category: .demux)
let udf: UDFReader
do { udf = try UDFReader(reader: reader) }
Expand Down Expand Up @@ -243,7 +245,15 @@ enum DiscReader {
selectedTitleIndex: cached.selectedTitleIndex,
clipTimeline: cached.clipTimeline)
}
guard looksLikeISO9660(reader) else { return try wrapBluRay(reader, selectTitleID: selectTitleID, cacheKey: cacheKey) }
guard looksLikeISO9660(reader) else {
// The anchor is read once: a probe's input budget counts every read recognition makes.
guard looksLikeUDF(reader) else { return nil }
if let bluRay = try wrapBluRay(reader, selectTitleID: selectTitleID, cacheKey: cacheKey,
udfAnchorChecked: true) {
return bluRay
}
return wrapUDFDVD(reader, selectTitleID: selectTitleID, cacheKey: cacheKey)
}
let iso: ISO9660Reader
do {
iso = try ISO9660Reader(reader: reader)
Expand All @@ -256,15 +266,52 @@ enum DiscReader {
} catch DiscError.directoryNotFound {
return try wrapBluRay(reader, selectTitleID: selectTitleID, cacheKey: cacheKey) // ISO9660 but not a DVD-Video disc (Blu-ray / data disc)
}
if let dvd = wrapDVD(reader, files: files, sectorSize: iso.sectorSize, selectTitleID: selectTitleID,
cacheKey: cacheKey) {
return dvd
}
return try wrapBluRay(reader, selectTitleID: selectTitleID, cacheKey: cacheKey)
}

/// A DVD-Video image with no ISO9660 bridge volume: sector 16 starts UDF's BEA01 directly, so the image
/// used to go down the Blu-ray branch, find no BDMV, and play as a raw file, which is the first VOB's
/// menu (8 s of a 6364 s film). `VIDEO_TS` is listed through UDF instead, and the title is built the
/// same way as from ISO9660. DVD files are one contiguous run on disc; a file recorded as runs that do
/// not continue each other is left out. The caller has found the UDF anchor.
static func wrapUDFDVD(_ reader: IOReader, selectTitleID: Int?, cacheKey: String?) -> DiscInfo? {
guard let udf = try? UDFReader(reader: reader),
let root = try? udf.list(path: []),
let dir = root.first(where: { $0.isDir && $0.name.uppercased() == "VIDEO_TS" }),
let entries = try? udf.list(path: [dir.name]) else { return nil }
let sectorSize = 2048
let files: [DiscFile] = entries.compactMap { entry in
guard !entry.isDir, let extents = try? udf.extents(of: entry), let first = extents.first,
first.offset % Int64(sectorSize) == 0 else { return nil }
var end = first.offset
for extent in extents {
guard extent.offset == end else { return nil }
end += extent.length
}
return DiscFile(name: entry.name, startSector: Int(first.offset / Int64(sectorSize)),
length: Int(end - first.offset))
}
EngineLog.emit("[disc] UDF-only image with VIDEO_TS (\(files.count) files); attempting DVD-Video", category: .demux)
return wrapDVD(reader, files: files, sectorSize: sectorSize, selectTitleID: selectTitleID, cacheKey: cacheKey)
}

/// A DVD-Video title set from a `VIDEO_TS` listing, whichever filesystem it came from; nil when the
/// listing holds no title VOBs.
private static func wrapDVD(_ reader: IOReader, files: [DiscFile], sectorSize: Int, selectTitleID: Int?,
cacheKey: String?) -> DiscInfo? {
let groups = DVDTitleSelector.enumerateTitleVOBGroups(files)
guard !groups.isEmpty else { return try wrapBluRay(reader, selectTitleID: selectTitleID, cacheKey: cacheKey) }
guard !groups.isEmpty else { return nil }
// VIDEO_TS.IFO's TT_SRPT names which title sets are real titles; filter the VOB groups to those so
// incidental content VTS are excluded. Any parse failure (or a filter that would empty the list)
// falls back to the full VOB-grouped set, so a disc with an unreadable VMGI still plays multi-title.
var orderedGroups = groups
let filesByName = Dictionary(files.map { ($0.name.uppercased(), $0) }, uniquingKeysWith: { first, _ in first })
if let ifoFile = filesByName["VIDEO_TS.IFO"] {
let ifoBytes = readAll(reader, [(offset: Int64(ifoFile.startSector * iso.sectorSize),
let ifoBytes = readAll(reader, [(offset: Int64(ifoFile.startSector * sectorSize),
length: Int64(ifoFile.length))])
if let ifoTitles = DVDIFOParser.parseTitles(ifoBytes) {
let titleVTSNs = Set(ifoTitles.map(\.vtsn))
Expand All @@ -274,7 +321,7 @@ enum DiscReader {
}
let selectedIndex = selectTitleID.flatMap { orderedGroups.indices.contains($0) ? $0 : nil } ?? 0
let extents = orderedGroups[selectedIndex].vobs.map {
(offset: Int64($0.startSector * iso.sectorSize), length: Int64($0.length))
(offset: Int64($0.startSector * sectorSize), length: Int64($0.length))
}
// Whole-VTS titles. Each VTS_NN_0.IFO's main PGC gives the title duration and chapter starts; a disc
// with an unreadable VTS IFO keeps duration 0 / no chapters but still plays. dvdVTSN keeps the
Expand All @@ -288,7 +335,7 @@ enum DiscReader {
let nn = g.vtsn < 10 ? "0\(g.vtsn)" : "\(g.vtsn)"
let ifoName = "VTS_\(nn)_0.IFO"
if let vtsIFO = filesByName[ifoName] {
let bytes = readAll(reader, [(offset: Int64(vtsIFO.startSector * iso.sectorSize),
let bytes = readAll(reader, [(offset: Int64(vtsIFO.startSector * sectorSize),
length: Int64(vtsIFO.length))])
if let detail = DVDIFOParser.parseTitleDetail(bytes) {
durationTicks = detail.durationTicks
Expand Down
76 changes: 74 additions & 2 deletions Tests/AetherEngineTests/UDFFixture.swift
Original file line number Diff line number Diff line change
Expand Up @@ -166,6 +166,80 @@ enum UDFFixture {
fsd[400..<416] = ArraySlice(longAD(lenBytes: ss, block: 2, partRef: 1))
putV(fsd, vblock: 1)

writeVolume(into: &image, partStart: partStart)

return Data(image)
}

/// A DVD-Video image with no ISO9660 bridge: UDF only, `VIDEO_TS` holding `files` in order. Directories
/// live in the metadata partition as in `make`; each file's data is one run in the physical partition
/// from block 40, unless it is named in `fragmented`, whose two halves are recorded as runs that do not
/// continue each other.
/// metadata vblock layout: 1=FSD, 2=root EFE, 3=root data, 4=VIDEO_TS EFE, 5=VIDEO_TS data, 6+i=file EFE.
static func makeDVD(files: [(name: String, bytes: [UInt8])], fragmented: Set<String> = []) -> Data {
let partStart = 270
func phys(_ vblock: Int) -> Int { partStart + 2 + vblock }
var block = 40
var placed: [(name: String, ads: [UInt8], length: Int)] = []
var data: [(block: Int, bytes: [UInt8])] = []
for file in files {
let sectors = { (count: Int) in max(1, (count + ss - 1) / ss) }
if fragmented.contains(file.name) {
let half = (file.bytes.count / 2 / ss) * ss
let first = Array(file.bytes[0..<half]), second = Array(file.bytes[half...])
data.append((block, first))
let gap = block + sectors(first.count) + 1 // one block of nothing between the runs
data.append((gap, second))
placed.append((file.name, longAD(lenBytes: first.count, block: block, partRef: 0)
+ longAD(lenBytes: second.count, block: gap, partRef: 0), file.bytes.count))
block = gap + sectors(second.count)
} else {
data.append((block, file.bytes))
placed.append((file.name, longAD(lenBytes: file.bytes.count, block: block, partRef: 0), file.bytes.count))
block += sectors(file.bytes.count)
}
}
var image = [UInt8](repeating: 0, count: (partStart + max(64, block + 1)) * ss)
func put(_ bytes: [UInt8], atSector s: Int) {
for (i, v) in bytes.enumerated() where i < ss { image[s*ss + i] = v }
}
func putV(_ bytes: [UInt8], vblock: Int) { put(bytes, atSector: phys(vblock)) }
for run in data {
for (i, v) in run.bytes.enumerated() { image[(partStart + run.block) * ss + i] = v }
}

var dirData = fid(location: 5, name: "", isDir: true, childBlock: 2, childPartRef: 1)
for (i, file) in placed.enumerated() {
putV(efe(location: 6 + i, fileType: 5, partRefOfSelf: 1, adType: 1, infoLen: file.length, ads: file.ads),
vblock: 6 + i)
dirData += fid(location: 5, name: file.name, isDir: false, childBlock: 6 + i, childPartRef: 1)
}
precondition(dirData.count <= ss, "VIDEO_TS listing must fit one sector")
putV(padTo(dirData, ss), vblock: 5)
putV(efe(location: 4, fileType: 4, partRefOfSelf: 1, adType: 1, infoLen: dirData.count,
ads: longAD(lenBytes: ss, block: 5, partRef: 1)), vblock: 4)

let rootData = fid(location: 3, name: "", isDir: true, childBlock: 2, childPartRef: 1)
+ fid(location: 3, name: "VIDEO_TS", isDir: true, childBlock: 4, childPartRef: 1)
putV(padTo(rootData, ss), vblock: 3)
putV(efe(location: 2, fileType: 4, partRefOfSelf: 1, adType: 1, infoLen: rootData.count,
ads: longAD(lenBytes: ss, block: 3, partRef: 1)), vblock: 2)

var fsd = [UInt8](repeating: 0, count: ss)
tag(256, location: 1, into: &fsd)
fsd[400..<416] = ArraySlice(longAD(lenBytes: ss, block: 2, partRef: 1))
putV(fsd, vblock: 1)

writeVolume(into: &image, partStart: partStart)
return Data(image)
}

/// The volume around the metadata partition: its Metadata File, the LVD, the Partition Descriptor and
/// the AVDP. Shared by every image here; the metadata partition is physical blocks 2..33.
private static func writeVolume(into image: inout [UInt8], partStart: Int) {
func put(_ bytes: [UInt8], atSector s: Int) {
for (i, v) in bytes.enumerated() where i < ss { image[s*ss + i] = v }
}
// --- Metadata File (E)FE at physical block 0 of partition 0 (sector partStart) ---
// one extent: metadata partition = physical blocks 2.. (short_ad, partition-relative)
let metaExtentBlocks = 32
Expand Down Expand Up @@ -211,8 +285,6 @@ enum UDFFixture {
tag(2, location: 256, into: &avdp)
avdp[16..<24] = ArraySlice(extentAD(lenBytes: 2*ss, location: 257)) // MainVDS extent
put(avdp, atSector: 256)

return Data(image)
}

static func padTo(_ b: [UInt8], _ n: Int) -> [UInt8] {
Expand Down
97 changes: 97 additions & 0 deletions Tests/AetherEngineTests/UDFOnlyDVDImageTests.swift
Original file line number Diff line number Diff line change
@@ -0,0 +1,97 @@
import Foundation
import Testing
@testable import AetherEngine

/// A DVD-Video image with no ISO9660 bridge volume, only UDF: recognized through UDF instead of falling
/// through to a raw open of the whole image.
@Suite("UDF-only DVD-Video images")
struct UDFOnlyDVDImageTests {

static func bytes(_ seed: UInt8, _ count: Int) -> [UInt8] {
(0..<count).map { UInt8(truncatingIfNeeded: Int(seed) &* 37 &+ $0) }
}

/// Two title sets; the first one's content is two VOBs. The IFOs are unreadable on purpose: the
/// title sets then come from the VOB names alone, as on any disc whose VMGI does not parse.
static func files(contentA: Int = 5000, contentB: Int = 4100) -> [(name: String, bytes: [UInt8])] {
[("VIDEO_TS.IFO", bytes(1, 2048)),
("VIDEO_TS.VOB", bytes(2, 2048)),
("VTS_01_0.IFO", bytes(3, 2048)),
("VTS_01_0.VOB", bytes(4, 2048)),
("VTS_01_1.VOB", bytes(5, contentA)),
("VTS_01_2.VOB", bytes(6, contentB)),
("VTS_02_1.VOB", bytes(7, 3000))]
}

static func readToEnd(_ reader: IOReader) -> [UInt8] {
var out: [UInt8] = []
var buffer = [UInt8](repeating: 0, count: 1000)
while true {
let n = buffer.withUnsafeMutableBufferPointer { reader.read($0.baseAddress, size: 1000) }
if n <= 0 { break }
out += buffer[0..<Int(n)]
}
return out
}

@Test("the main title set's VOBs play back to back, not the image from its first byte")
func recognizesTheTitleSets() throws {
let image = UDFFixture.makeDVD(files: Self.files())
let reader = DataIOReader(data: image)
#expect(!DiscReader.looksLikeISO9660(reader))
let info = try #require(try DiscReader.wrap(reader))
#expect(info.formatHint == "mpeg")
#expect(info.titles.count == 2)
#expect(info.titles.map(\.dvdVTSN) == [1, 2])
#expect(Self.readToEnd(info.reader) == Self.bytes(5, 5000) + Self.bytes(6, 4100))

let second = try #require(try DiscReader.wrap(DataIOReader(data: image), selectTitleID: 1))
#expect(Self.readToEnd(second.reader) == Self.bytes(7, 3000))
}

@Test("a file recorded as runs that do not continue each other is left out of the title")
func fragmentedFileIsLeftOut() throws {
let image = UDFFixture.makeDVD(files: Self.files(), fragmented: ["VTS_01_2.VOB"])
let info = try #require(try DiscReader.wrap(DataIOReader(data: image)))
#expect(Self.readToEnd(info.reader) == Self.bytes(5, 5000))
}

@Test("a UDF-only VIDEO_TS with no title VOBs is not a disc")
func noTitleVOBs() throws {
let image = UDFFixture.makeDVD(files: [("VIDEO_TS.IFO", Self.bytes(1, 2048)), ("VIDEO_TS.VOB", Self.bytes(2, 2048))])
#expect(try DiscReader.wrap(DataIOReader(data: image)) == nil)
}

@Test("disc-inspect calls it DVD-Video, as playback does")
func inspectorAgrees() {
let inspection = DiscInspector.inspect(DataIOReader(data: UDFFixture.makeDVD(files: Self.files())))
#expect(inspection.kind == .dvdVideo)
#expect(!inspection.iso9660Signature)
#expect(inspection.udfAnchor)
#expect(inspection.dvdVOBFiles.contains("VTS_01_1.VOB"))
#expect(inspection.wrapRecognized)
#expect(inspection.wrapFormatHint == "mpeg")
}

/// Records where a reader was asked to seek.
final class SeekLog: IOReader, @unchecked Sendable {
private let base: DataIOReader
private let lock = NSLock()
private var offsets: [Int64] = []
init(_ data: Data) { base = DataIOReader(data: data) }
var seeks: [Int64] { lock.withLock { offsets } }
func read(_ buffer: UnsafeMutablePointer<UInt8>?, size: Int32) -> Int32 { base.read(buffer, size: size) }
func seek(offset: Int64, whence: Int32) -> Int64 {
if whence == SEEK_SET { lock.withLock { offsets.append(offset) } }
return base.seek(offset: offset, whence: whence)
}
func close() {}
}

@Test("a source that is no disc is still sniffed for the UDF anchor once")
func nonDiscReadsTheAnchorOnce() throws {
let reader = SeekLog(Data(repeating: 0, count: 600 * 1024))
#expect(try DiscReader.wrap(reader) == nil)
#expect(reader.seeks.filter { $0 == 256 * 2048 }.count == 1)
}
}
Loading
Loading