~ knotless Search/
↑↓ move↵ open⇧↵ all results

geesawra.industries/hydraulophone

An unofficial YouTube Music app for iPhone, iPad, and Mac.

0
0
main
902 lines · 33.0 KB Raw History
import Foundation

public struct WebMOpusTrack: Sendable, Equatable {
  public let channels: Int
  public let sampleRate: Double
  public let codecDelay: TimeInterval
  public let seekPreRoll: TimeInterval
  public let duration: TimeInterval?
  public let outputGainDB: Double

  public init(
    channels: Int, sampleRate: Double, codecDelay: TimeInterval, seekPreRoll: TimeInterval,
    duration: TimeInterval?, outputGainDB: Double
  ) {
    self.channels = channels
    self.sampleRate = sampleRate
    self.codecDelay = codecDelay
    self.seekPreRoll = seekPreRoll
    self.duration = duration
    self.outputGainDB = outputGainDB
  }
}

public struct WebMOpusPacket: Sendable, Equatable {
  public let data: Data
  public let timestamp: TimeInterval
  public let discardPadding: TimeInterval

  public init(data: Data, timestamp: TimeInterval, discardPadding: TimeInterval) {
    self.data = data
    self.timestamp = timestamp
    self.discardPadding = discardPadding
  }
}

public actor WebMOpusReader {
  public typealias Read = @Sendable (Int64, Int) async throws -> Data

  private let read: Read
  private var cursor: Int64 = 0
  private var segmentStart: Int64 = 0
  private var segmentEnd: Int64?
  private var timecodeScale: UInt64 = 1_000_000
  private var duration: TimeInterval?
  private var trackNumber: UInt64?
  private var trackInfo: WebMOpusTrack?
  private var codecDelayNS: UInt64 = 0
  private var cues: [(time: TimeInterval, position: Int64)] = []
  private var clusters: [(time: TimeInterval, position: Int64)] = []
  private var cuePosition: Int64?
  private var clusterIndexBuilt = false
  private var pending: [WebMOpusPacket] = []
  private var ended = false
  private var clusterTime: UInt64 = 0
  private var inCluster = false
  private var currentClusterEnd: Int64?

  private static let maxMetadata = 1_048_576
  private static let maxBlock = 1_048_576
  private static let maxElements = 200_000
  private static let maxClusters = 100_000
  private static let maxCuePoints = 100_000

  public init(read: @escaping Read) {
    self.read = read
  }

  public func prepare() async throws -> WebMOpusTrack {
    if let trackInfo { return trackInfo }
    try Task.checkCancellation()
    cursor = 0
    let header = try await elementHeader(at: cursor)
    guard header.id == 0x1A45_DFA3, !header.unknownSize else {
      throw Failure.invalid("Missing EBML header")
    }
    try await scanChildren(header)
    cursor = header.end
    let segment = try await elementHeader(at: cursor)
    guard segment.id == 0x1853_8067 else { throw Failure.invalid("Missing Segment") }
    segmentStart = segment.payload
    segmentEnd = segment.unknownSize ? nil : segment.end
    cursor = segment.payload

    var seekPositions: [UInt64: Int64] = [:]
    var foundInfo = false
    var foundTracks = false
    var elements = 0
    while segmentEnd.map({ cursor < $0 }) ?? true {
      try Task.checkCancellation()
      guard elements < Self.maxElements else { throw Failure.invalid("Too many Segment elements") }
      elements += 1
      guard let h = try await optionalElementHeader(at: cursor) else { break }
      if h.unknownSize && h.id != 0x1F43_B675 {
        throw Failure.invalid("Unknown size on non-Cluster element")
      }
      if h.id == 0x1F43_B675 {
        if !foundInfo || !foundTracks {
          if let seek = seekPositions[0x1549_A966], !foundInfo {
            try await parseInfo(at: try checkedAdd(segmentStart, seek))
            foundInfo = true
          }
          if let seek = seekPositions[0x1654_AE6B], !foundTracks {
            try await parseTracks(at: try checkedAdd(segmentStart, seek))
            foundTracks = true
          }
          guard foundInfo && foundTracks else {
            throw Failure.invalid("Info and Tracks must precede media or be indexed by SeekHead")
          }
        }
        if let cuePosition, cues.isEmpty {
          try await parseCues(at: try checkedAdd(segmentStart, cuePosition))
        }
        let clusterPosition = cursor
        if firstClusterPosition == nil { firstClusterPosition = clusterPosition }
        let clusterTicks =
          h.unknownSize ? try await scanUnknownClusterTimestamp(h) : try await scanClusterTicks(h)
        let clusterSeconds = Double(clusterTicks) * Double(timecodeScale) / 1_000_000_000
        if clusters.count < Self.maxClusters { clusters.append((clusterSeconds, clusterPosition)) }
        cursor = clusterPosition
        break
      }
      switch h.id {
      case 0x114D_9B74:
        seekPositions.merge(try await parseSeekHead(h), uniquingKeysWith: { _, new in new })
        cuePosition = seekPositions[0x1C53_BB6B]
      case 0x1549_A966:
        try await parseInfo(h)
        foundInfo = true
      case 0x1654_AE6B:
        try await parseTracks(h)
        foundTracks = true
      case 0x1C53_BB6B: try await parseCues(h)
      default: break
      }
      cursor = h.end
      if let end = segmentEnd, cursor > end {
        throw Failure.invalid("Segment child exceeds Segment bounds")
      }
    }
    guard foundInfo, foundTracks, let trackInfo else {
      throw Failure.invalid("No supported Opus audio track")
    }
    if !cues.isEmpty { cues.sort { $0.time < $1.time } }
    if !clusters.isEmpty { clusters.sort { $0.time < $1.time } }
    let preparedTrack = WebMOpusTrack(
      channels: trackInfo.channels, sampleRate: trackInfo.sampleRate,
      codecDelay: trackInfo.codecDelay, seekPreRoll: trackInfo.seekPreRoll, duration: duration,
      outputGainDB: trackInfo.outputGainDB)
    self.trackInfo = preparedTrack
    cursor = firstClusterPosition ?? segmentStart
    ended = false
    return preparedTrack
  }

  private var firstClusterPosition: Int64?

  public func seek(to seconds: TimeInterval) async throws {
    guard seconds.isFinite, seconds >= 0 else {
      throw Failure.invalid("Seek time must be finite and nonnegative")
    }
    if trackInfo == nil { _ = try await prepare() }
    try Task.checkCancellation()
    if cues.isEmpty && !clusterIndexBuilt { try await buildClusterIndex() }
    let target = max(0, seconds - (trackInfo?.seekPreRoll ?? 0))
    let points = cues.isEmpty ? clusters : cues
    guard let point = points.last(where: { $0.time <= target }) ?? points.first else {
      throw Failure.invalid("No cluster index is available for seeking")
    }
    cursor = point.position
    inCluster = false
    currentClusterEnd = nil
    pending.removeAll(keepingCapacity: true)
    ended = false
  }

  public func nextPacket() async throws -> WebMOpusPacket? {
    if trackInfo == nil { _ = try await prepare() }
    try Task.checkCancellation()
    if !pending.isEmpty { return pending.removeFirst() }
    guard !ended, let trackNumber else { return nil }
    while true {
      try Task.checkCancellation()
      if !inCluster {
        if let end = segmentEnd, cursor >= end {
          ended = true
          return nil
        }
        guard let top = try await optionalElementHeader(at: cursor) else {
          ended = true
          return nil
        }
        if top.id == 0x1F43_B675 {
          if top.unknownSize {
            clusterTime = try await scanUnknownClusterTimestamp(top)
            currentClusterEnd = nil
          } else {
            clusterTime = try await scanClusterTicks(top)
            currentClusterEnd = top.end
          }
          cursor = top.payload
          inCluster = true
          continue
        }
        guard !top.unknownSize else {
          throw Failure.invalid("Unknown-size Segment child cannot be skipped")
        }
        cursor = top.end
        continue
      }

      if let clusterEnd = currentClusterEnd, cursor >= clusterEnd {
        cursor = clusterEnd
        currentClusterEnd = nil
        inCluster = false
        continue
      }
      guard let child = try await optionalElementHeader(at: cursor) else {
        if currentClusterEnd != nil { throw Failure.truncated }
        ended = true
        inCluster = false
        return nil
      }
      if currentClusterEnd == nil && Self.isSegmentLevel(child.id) {
        inCluster = false
        continue
      }
      if let clusterEnd = currentClusterEnd, child.end > clusterEnd {
        throw Failure.invalid("Cluster child exceeds Cluster bounds")
      }
      switch child.id {
      case 0xE7:
        clusterTime = try await readUnsigned(child.payload, size: child.size)
        cursor = child.end
      case 0xA3:
        let raw = try await boundedPayload(child, maximum: Self.maxBlock)
        let frames = try parseBlock(raw, trackNumber: trackNumber)
        var frameOffset: TimeInterval = 0
        for (frame, relative) in frames {
          let absoluteTicks = try blockTicks(clusterTime, relative)
          let time =
            Double(absoluteTicks) * Double(timecodeScale) / 1_000_000_000
            - (trackInfo?.codecDelay ?? 0) + frameOffset
          pending.append(WebMOpusPacket(data: frame, timestamp: time, discardPadding: 0))
          frameOffset += opusPacketDuration(frame)
        }
        cursor = child.end
      case 0xA0:
        let parsed = try await parseBlockGroup(
          child, clusterEnd: currentClusterEnd, clusterTimestamp: clusterTime,
          trackNumber: trackNumber)
        pending.append(contentsOf: parsed)
        cursor = child.end
      default:
        cursor = child.end
      }
      if !pending.isEmpty { return pending.removeFirst() }
    }
  }

  private func scanChildren(_ parent: Header) async throws {
    var position = parent.payload
    var count = 0
    while position < parent.end {
      try Task.checkCancellation()
      guard count < Self.maxElements else { throw Failure.invalid("Too many EBML header elements") }
      count += 1
      let child = try await elementHeader(at: position)
      guard !child.unknownSize, child.end <= parent.end else {
        throw Failure.invalid("Invalid EBML header child")
      }
      position = child.end
    }
  }

  private struct Header {
    let id: UInt64
    let payload: Int64
    let size: Int64
    let end: Int64
    let unknownSize: Bool
  }
  private static func isSegmentLevel(_ id: UInt64) -> Bool {
    [
      0x114D_9B74, 0x1549_A966, 0x1654_AE6B, 0x1F43_B675, 0x1C53_BB6B, 0x1941_A469, 0x1043_A770,
      0x1254_C367,
    ].contains(id)
  }

  private func optionalElementHeader(at position: Int64) async throws -> Header? {
    let first = try await read(position, 1)
    try Task.checkCancellation()
    if first.isEmpty { return nil }
    guard first.count == 1 else {
      throw Failure.invalid("Read callback returned more bytes than requested")
    }
    return try await elementHeader(at: position)
  }

  private func elementHeader(at position: Int64) async throws -> Header {
    let (id, idLength) = try await readVInt(at: position, isID: true)
    let sizeAt = try checkedAdd(position, Int64(idLength))
    let (rawSize, sizeLength) = try await readVInt(at: sizeAt, isID: false)
    let unknown = rawSize == ((UInt64(1) << UInt64(7 * sizeLength)) - 1)
    let payload = try checkedAdd(sizeAt, Int64(sizeLength))
    guard unknown || rawSize <= UInt64(Int64.max) else {
      throw Failure.invalid("Element size exceeds supported file size")
    }
    let size = unknown ? 0 : Int64(rawSize)
    let end = unknown ? Int64.max : try checkedAdd(payload, size)
    if let segmentEnd, !unknown, end > segmentEnd {
      throw Failure.invalid("Element exceeds Segment bounds")
    }
    return Header(id: id, payload: payload, size: size, end: end, unknownSize: unknown)
  }

  private func readVInt(at position: Int64, isID: Bool) async throws -> (UInt64, Int) {
    let first = try await bytes(at: position, count: 1)[0]
    guard first != 0 else { throw Failure.invalid("Invalid EBML variable integer") }
    var mask: UInt8 = 0x80
    var length = 1
    while first & mask == 0 {
      mask >>= 1
      length += 1
    }
    guard length <= (isID ? 4 : 8) else {
      throw Failure.invalid("EBML variable integer is too long")
    }
    let data = try await bytes(at: position, count: length)
    var value = UInt64(isID ? first : first & (mask &- 1))
    for byte in data.dropFirst() { value = (value << 8) | UInt64(byte) }
    return (value, length)
  }

  private func bytes(at position: Int64, count: Int) async throws -> Data {
    guard position >= 0, count >= 0, count <= Self.maxMetadata else {
      throw Failure.invalid("Read exceeds safety limit")
    }
    var result = Data()
    result.reserveCapacity(count)
    var offset = position
    while result.count < count {
      try Task.checkCancellation()
      let amount = min(64 * 1024, count - result.count)
      let part = try await read(offset, amount)
      try Task.checkCancellation()
      guard !part.isEmpty, part.count <= amount else { throw Failure.truncated }
      result.append(part)
      offset = try checkedAdd(offset, Int64(part.count))
    }
    return result
  }

  private func boundedPayload(_ h: Header, maximum: Int) async throws -> Data {
    guard !h.unknownSize, h.size <= Int64(maximum) else {
      throw Failure.invalid("Element payload exceeds safety limit")
    }
    return try await bytes(at: h.payload, count: Int(h.size))
  }

  private func parseInfo(at position: Int64) async throws {
    let h = try await elementHeader(at: position)
    guard h.id == 0x1549_A966, !h.unknownSize else {
      throw Failure.invalid("Invalid Info location")
    }
    try await parseInfo(h)
  }

  private func parseInfo(_ h: Header) async throws {
    var p = h.payload
    var count = 0
    while p < h.end {
      guard count < Self.maxElements else { throw Failure.invalid("Too many Info elements") }
      count += 1
      let e = try await elementHeader(at: p)
      guard e.end <= h.end else { throw Failure.invalid("Info child exceeds bounds") }
      if e.id == 0x2AD7B1 { timecodeScale = try await readUnsigned(e.payload, size: e.size) }
      if e.id == 0x4489 {
        duration = try await readFloat(e.payload, size: e.size).map {
          $0 * Double(timecodeScale) / 1_000_000_000
        }
      }
      p = e.end
    }
    guard timecodeScale > 0 else { throw Failure.invalid("TimestampScale must be positive") }
  }

  private func parseTracks(at position: Int64) async throws {
    let h = try await elementHeader(at: position)
    guard h.id == 0x1654_AE6B, !h.unknownSize else {
      throw Failure.invalid("Invalid Tracks location")
    }
    try await parseTracks(h)
  }

  private func parseTracks(_ h: Header) async throws {
    var p = h.payload
    var count = 0
    while p < h.end {
      guard count < Self.maxElements else { throw Failure.invalid("Too many Tracks elements") }
      count += 1
      let e = try await elementHeader(at: p)
      guard e.end <= h.end else { throw Failure.invalid("Tracks child exceeds bounds") }
      if e.id == 0xAE { try await parseTrackEntry(e) }
      p = e.end
    }
  }

  private func parseTrackEntry(_ h: Header) async throws {
    var p = h.payload
    var count = 0
    var number: UInt64?
    var type: UInt64?
    var codec: String?
    var privateData: Data?
    var delay: UInt64?
    var preRoll: UInt64?
    var channelCount: UInt64 = 0
    var sampleRate = 48_000.0
    while p < h.end {
      guard count < Self.maxElements else { throw Failure.invalid("Too many TrackEntry elements") }
      count += 1
      let e = try await elementHeader(at: p)
      guard e.end <= h.end else { throw Failure.invalid("TrackEntry child exceeds bounds") }
      switch e.id {
      case 0xD7: number = try await readUnsigned(e.payload, size: e.size)
      case 0x83: type = try await readUnsigned(e.payload, size: e.size)
      case 0x86: codec = String(data: try await boundedPayload(e, maximum: 256), encoding: .utf8)
      case 0x63A2: privateData = try await boundedPayload(e, maximum: 256)
      case 0x56AA: delay = try await readUnsigned(e.payload, size: e.size)
      case 0x56BB: preRoll = try await readUnsigned(e.payload, size: e.size)
      case 0xE1:
        var a = e.payload
        var audioElements = 0
        while a < e.end {
          guard audioElements < Self.maxElements else {
            throw Failure.invalid("Too many Audio elements")
          }
          audioElements += 1
          let audio = try await elementHeader(at: a)
          guard !audio.unknownSize, audio.end <= e.end else {
            throw Failure.invalid("Audio child exceeds bounds")
          }
          if audio.id == 0x9F {
            channelCount = try await readUnsigned(audio.payload, size: audio.size)
          }
          if audio.id == 0xB5 {
            sampleRate = try await readFloat(audio.payload, size: audio.size) ?? 48_000
          }
          a = audio.end
        }
      default: break
      }
      p = e.end
    }
    guard type == 2, codec == "A_OPUS", let number, number > 0, let privateData,
      let opus = parseOpusHead(privateData)
    else { return }
    let channels = opus.channels
    guard channels == 1 || channels == 2 else {
      throw Failure.invalid("Only mono and stereo Opus tracks are supported")
    }
    if channelCount != 0, channelCount != UInt64(channels) {
      throw Failure.invalid("Track channel count disagrees with OpusHead")
    }
    guard sampleRate.isFinite, sampleRate > 0 else {
      throw Failure.invalid("Invalid Opus sample rate")
    }
    trackNumber = number
    codecDelayNS = delay ?? UInt64(opus.preSkip) * 1_000_000_000 / 48_000
    let delaySeconds = Double(codecDelayNS) / 1_000_000_000
    let preRollSeconds = Double(preRoll ?? 80_000_000) / 1_000_000_000
    trackInfo = WebMOpusTrack(
      channels: channels, sampleRate: 48_000, codecDelay: delaySeconds, seekPreRoll: preRollSeconds,
      duration: duration, outputGainDB: opus.gainDB)
  }

  private func parseOpusHead(_ data: Data) -> (channels: Int, gainDB: Double, preSkip: Int)? {
    guard data.count >= 19, data.prefix(8) == Data("OpusHead".utf8), data[8] < 16, data[18] == 0
    else {
      return nil
    }
    let channels = Int(data[9])
    let preSkip = Int(data[10]) | (Int(data[11]) << 8)
    let gainBits = UInt16(data[16]) | (UInt16(data[17]) << 8)
    let gain = Double(Int16(bitPattern: gainBits)) / 256.0
    return (channels, gain, preSkip)
  }

  private func parseSeekHead(_ h: Header) async throws -> [UInt64: Int64] {
    var result: [UInt64: Int64] = [:]
    var p = h.payload
    var count = 0
    while p < h.end {
      guard count < Self.maxElements else { throw Failure.invalid("Too many SeekHead elements") }
      count += 1
      let seek = try await elementHeader(at: p)
      guard seek.end <= h.end else { throw Failure.invalid("SeekHead child exceeds bounds") }
      if seek.id == 0x4DBB {
        var a = seek.payload
        var id: UInt64?
        var position: UInt64?
        while a < seek.end {
          let e = try await elementHeader(at: a)
          guard e.end <= seek.end else { throw Failure.invalid("Seek child exceeds bounds") }
          if e.id == 0x53AB {
            let raw = try await boundedPayload(e, maximum: 4)
            id = raw.reduce(UInt64(0)) { ($0 << 8) | UInt64($1) }
          } else if e.id == 0x53AC {
            position = try await readUnsigned(e.payload, size: e.size)
          }
          a = e.end
        }
        if let id, let position {
          guard position <= UInt64(Int64.max) else {
            throw Failure.invalid("Seek position exceeds supported file size")
          }
          _ = try checkedAdd(segmentStart, Int64(position))
          result[id] = Int64(position)
        }
      }
      p = seek.end
    }
    return result
  }

  private func parseCues(_ h: Header) async throws {
    var p = h.payload
    var pointCount = 0
    while p < h.end {
      guard pointCount < Self.maxCuePoints else {
        throw Failure.invalid("Cues index exceeds safety limit")
      }
      pointCount += 1
      let point = try await elementHeader(at: p)
      guard point.end <= h.end else { throw Failure.invalid("Cues child exceeds bounds") }
      if point.id == 0xBB {
        var a = point.payload
        var tick: UInt64?
        var cluster: UInt64?
        var cueTrack: UInt64?
        var cueFields = 0
        while a < point.end {
          guard cueFields < Self.maxElements else {
            throw Failure.invalid("Too many CuePoint fields")
          }
          cueFields += 1
          let e = try await elementHeader(at: a)
          guard !e.unknownSize, e.end <= point.end else {
            throw Failure.invalid("CuePoint child exceeds bounds")
          }
          if e.id == 0xB3 { tick = try await readUnsigned(e.payload, size: e.size) }
          if e.id == 0xB7 {
            var b = e.payload
            var positionFields = 0
            while b < e.end {
              guard positionFields < Self.maxElements else {
                throw Failure.invalid("Too many CueTrackPositions fields")
              }
              positionFields += 1
              let pos = try await elementHeader(at: b)
              guard !pos.unknownSize, pos.end <= e.end else {
                throw Failure.invalid("CueTrackPositions child exceeds bounds")
              }
              if pos.id == 0xF7 { cueTrack = try await readUnsigned(pos.payload, size: pos.size) }
              if pos.id == 0xF1 { cluster = try await readUnsigned(pos.payload, size: pos.size) }
              b = pos.end
            }
          }
          a = e.end
        }
        if let tick, let cluster, cueTrack == trackNumber {
          guard cluster <= UInt64(Int64.max) else {
            throw Failure.invalid("Cue position exceeds supported file size")
          }
          let absolute = try checkedAdd(segmentStart, Int64(cluster))
          cues.append((Double(tick) * Double(timecodeScale) / 1_000_000_000, absolute))
        }
      }
      p = point.end
    }
  }

  private func parseCues(at position: Int64) async throws {
    let h = try await elementHeader(at: position)
    guard h.id == 0x1C53_BB6B, !h.unknownSize else {
      throw Failure.invalid("Invalid Cues location")
    }
    try await parseCues(h)
    cues.sort { $0.time < $1.time }
  }

  private func buildClusterIndex() async throws {
    guard let firstClusterPosition else {
      throw Failure.invalid("No Cluster is available for seeking")
    }
    clusters.removeAll(keepingCapacity: true)
    var position = firstClusterPosition
    var count = 0
    while segmentEnd.map({ position < $0 }) ?? true {
      try Task.checkCancellation()
      guard count < Self.maxClusters else {
        throw Failure.invalid("Cluster index exceeds safety limit")
      }
      guard let h = try await optionalElementHeader(at: position) else { break }
      count += 1
      if h.id == 0x1F43_B675 {
        if h.unknownSize {
          let scanned = try await scanUnknownCluster(h)
          clusters.append((scanned.time, position))
          position = scanned.end
        } else {
          let ticks = try await scanClusterTicks(h)
          clusters.append((Double(ticks) * Double(timecodeScale) / 1_000_000_000, position))
          position = h.end
        }
      } else {
        guard !h.unknownSize else {
          throw Failure.invalid("Unknown-size Segment child cannot be indexed")
        }
        if h.id == 0x1C53_BB6B {
          try await parseCues(h)
          cues.sort { $0.time < $1.time }
          break
        }
        position = h.end
      }
    }
    clusters.sort { $0.time < $1.time }
    clusterIndexBuilt = true
  }

  private func scanClusterTicks(_ h: Header) async throws -> UInt64 {
    guard !h.unknownSize else { return 0 }
    var p = h.payload
    while p < h.end {
      let e = try await elementHeader(at: p)
      guard e.end <= h.end else { throw Failure.invalid("Cluster child exceeds bounds") }
      if e.id == 0xE7 {
        return try await readUnsigned(e.payload, size: e.size)
      }
      p = e.end
    }
    return 0
  }

  private func scanUnknownClusterTimestamp(_ h: Header) async throws -> UInt64 {
    var p = h.payload
    var count = 0
    while count < Self.maxElements {
      try Task.checkCancellation()
      guard let child = try await optionalElementHeader(at: p) else { return 0 }
      if Self.isSegmentLevel(child.id) { return 0 }
      if child.unknownSize { throw Failure.invalid("Unknown-sized child inside Cluster") }
      if child.id == 0xE7 { return try await readUnsigned(child.payload, size: child.size) }
      p = child.end
      count += 1
    }
    throw Failure.invalid("Too many Cluster elements before Timestamp")
  }

  private func scanUnknownCluster(_ h: Header) async throws -> (time: TimeInterval, end: Int64) {
    var p = h.payload
    var time: TimeInterval = 0
    var hasTimestamp = false
    var elements = 0
    while true {
      try Task.checkCancellation()
      guard elements < Self.maxElements else {
        throw Failure.invalid("Too many unknown-size Cluster elements")
      }
      elements += 1
      guard let child = try await optionalElementHeader(at: p) else { return (time, p) }
      if Self.isSegmentLevel(child.id) { return (time, p) }
      if child.unknownSize { throw Failure.invalid("Unknown-sized child inside Cluster") }
      if child.id == 0xE7, !hasTimestamp {
        let ticks = try await readUnsigned(child.payload, size: child.size)
        time = Double(ticks) * Double(timecodeScale) / 1_000_000_000
        hasTimestamp = true
      }
      p = child.end
    }
  }

  private func parseBlockGroup(
    _ h: Header, clusterEnd: Int64?, clusterTimestamp: UInt64, trackNumber: UInt64
  ) async throws -> [WebMOpusPacket] {
    var p = h.payload
    var count = 0
    var block: Data?
    var padding: Int64 = 0
    while p < h.end {
      guard count < Self.maxElements else { throw Failure.invalid("Too many BlockGroup elements") }
      count += 1
      let e = try await elementHeader(at: p)
      guard e.end <= h.end else { throw Failure.invalid("BlockGroup child exceeds bounds") }
      if let clusterEnd, e.end > clusterEnd {
        throw Failure.invalid("BlockGroup exceeds Cluster bounds")
      }
      if e.id == 0xA1 { block = try await boundedPayload(e, maximum: Self.maxBlock) }
      if e.id == 0x75A2 { padding = try await readSigned(e.payload, size: e.size) }
      p = e.end
    }
    guard let block else { return [] }
    let frames = try parseBlock(block, trackNumber: trackNumber)
    var frameOffset: TimeInterval = 0
    return try frames.enumerated().map { index, item in
      let (frame, relative) = item
      let tick = try blockTicks(clusterTimestamp, relative)
      let time =
        Double(tick) * Double(timecodeScale) / 1_000_000_000 - (trackInfo?.codecDelay ?? 0)
        + frameOffset
      frameOffset += opusPacketDuration(frame)
      let appliesPadding = padding < 0 ? index == 0 : index == frames.count - 1
      return WebMOpusPacket(
        data: frame, timestamp: time,
        discardPadding: appliesPadding ? Double(padding) / 1_000_000_000 : 0)
    }
  }

  private func blockTicks(_ clusterTimestamp: UInt64, _ relative: Int16) throws -> Int64 {
    guard clusterTimestamp <= UInt64(Int64.max) else {
      throw Failure.invalid("Cluster timestamp exceeds supported range")
    }
    let (result, overflow) = Int64(clusterTimestamp).addingReportingOverflow(Int64(relative))
    guard !overflow else { throw Failure.invalid("Block timestamp overflow") }
    return result
  }

  private func opusPacketDuration(_ packet: Data) -> TimeInterval {
    guard let toc = packet.first else { return 0 }
    let config = Int(toc >> 3)
    let frameDuration: Double
    if config >= 16 {
      frameDuration = [0.0025, 0.005, 0.01, 0.02][config & 0x03]
    } else if config >= 12 {
      frameDuration = (config & 0x01) == 0 ? 0.01 : 0.02
    } else {
      frameDuration = [0.01, 0.02, 0.04, 0.06][config & 0x03]
    }
    let code = Int(toc & 0x03)
    let frameCount: Int
    if code == 0 {
      frameCount = 1
    } else if code == 1 || code == 2 {
      frameCount = 2
    } else {
      frameCount = packet.count > 1 ? Int(packet[1] & 0x3F) : 0
    }
    return frameDuration * Double(frameCount)
  }

  private func parseBlock(_ data: Data, trackNumber expected: UInt64) throws -> [(Data, Int16)] {
    guard !data.isEmpty else { throw Failure.invalid("Empty Block") }
    let track = try parseVInt(data, offset: 0, isID: false)
    guard track.value == expected else { return [] }
    var index = track.length
    guard data.count - index >= 3 else { throw Failure.invalid("Truncated Block header") }
    let relative = Int16(bitPattern: UInt16(data[index]) << 8 | UInt16(data[index + 1]))
    index += 2
    let flags = data[index]
    index += 1
    let lace = (flags >> 1) & 0x03
    if lace == 0 { return [(Data(data[index...]), relative)] }
    guard index < data.count else { throw Failure.invalid("Missing lacing frame count") }
    let count = Int(data[index]) + 1
    index += 1
    guard count <= 256 else { throw Failure.invalid("Too many laced frames") }
    var sizes: [Int] = []
    if lace == 1 {  // Xiph
      var sum = 0
      for _ in 0..<(count - 1) {
        var size = 0
        while true {
          guard index < data.count else { throw Failure.invalid("Truncated Xiph lace") }
          let byte = Int(data[index])
          index += 1
          guard size <= Self.maxBlock - byte else {
            throw Failure.invalid("Xiph lace size overflow")
          }
          size += byte
          if byte < 255 { break }
        }
        sum += size
        sizes.append(size)
      }
      let last = data.count - index - sum
      guard last >= 0 else { throw Failure.invalid("Xiph lace exceeds Block") }
      sizes.append(last)
    } else if lace == 2 {  // Fixed-size
      let payload = data.count - index
      guard payload >= 0, payload % count == 0 else {
        throw Failure.invalid("Invalid fixed lacing")
      }
      sizes = Array(repeating: payload / count, count: count)
    } else {  // EBML
      let first = try parseVInt(data, offset: index, isID: false)
      index += first.length
      guard first.value <= UInt64(Self.maxBlock) else {
        throw Failure.invalid("EBML lace size exceeds safety limit")
      }
      sizes.append(Int(first.value))
      var sum = sizes[0]
      if count > 2 {
        for _ in 0..<(count - 2) {
          let encoded = try parseVInt(data, offset: index, isID: false)
          index += encoded.length
          let bias = (Int64(1) << Int64(7 * encoded.length - 1)) - 1
          let diff = Int64(encoded.value) - bias
          guard let previousSize = sizes.last else {
            throw Failure.invalid("Missing previous EBML lace size")
          }
          let next = Int64(previousSize) + diff
          guard next >= 0, next <= Int64(Self.maxBlock) else {
            throw Failure.invalid("Invalid EBML lace delta")
          }
          sizes.append(Int(next))
          sum += Int(next)
        }
      }
      let last = data.count - index - sum
      guard last >= 0 else { throw Failure.invalid("EBML lace exceeds Block") }
      sizes.append(last)
    }
    guard sizes.count == count, sizes.allSatisfy({ $0 >= 0 }),
      sizes.reduce(0, +) == data.count - index
    else { throw Failure.invalid("Invalid lacing sizes") }
    var result: [(Data, Int16)] = []
    var offset = index
    for size in sizes {
      result.append((Data(data[offset..<(offset + size)]), relative))
      offset += size
    }
    return result
  }

  private func parseVInt(_ data: Data, offset: Int, isID: Bool) throws -> (
    value: UInt64, length: Int
  ) {
    guard offset < data.count, data[offset] != 0 else {
      throw Failure.invalid("Invalid EBML integer")
    }
    let first = data[offset]
    var marker: UInt8 = 0x80
    var length = 1
    while first & marker == 0 {
      marker >>= 1
      length += 1
    }
    guard length <= (isID ? 4 : 8), offset + length <= data.count else {
      throw Failure.invalid("Truncated EBML integer")
    }
    var value = UInt64(isID ? first : first & (marker &- 1))
    for byte in data[(offset + 1)..<(offset + length)] { value = (value << 8) | UInt64(byte) }
    return (value, length)
  }

  private func readUnsigned(_ position: Int64, size: Int64) async throws -> UInt64 {
    guard size > 0, size <= 8 else { throw Failure.invalid("Invalid integer width") }
    return try await bytes(at: position, count: Int(size)).reduce(UInt64(0)) {
      ($0 << 8) | UInt64($1)
    }
  }

  private func readSigned(_ position: Int64, size: Int64) async throws -> Int64 {
    let raw = try await readUnsigned(position, size: size)
    let shift = 64 - Int(size * 8)
    return Int64(bitPattern: raw << shift) >> shift
  }

  private func readFloat(_ position: Int64, size: Int64) async throws -> Double? {
    let data = try await bytes(at: position, count: Int(size))
    if size == 4 {
      let bits = data.reduce(UInt32(0)) { ($0 << 8) | UInt32($1) }
      let value = Double(Float(bitPattern: bits))
      return value.isFinite ? value : nil
    }
    if size == 8 {
      let bits = data.reduce(UInt64(0)) { ($0 << 8) | UInt64($1) }
      let value = Double(bitPattern: bits)
      return value.isFinite ? value : nil
    }
    throw Failure.invalid("Invalid float width")
  }

  private func checkedAdd(_ lhs: Int64, _ rhs: Int64) throws -> Int64 {
    let (value, overflow) = lhs.addingReportingOverflow(rhs)
    guard !overflow, value >= 0 else { throw Failure.invalid("File offset overflow") }
    return value
  }

  public enum Failure: Error, LocalizedError, Sendable, Equatable {
    case invalid(String)
    case truncated

    public var errorDescription: String? {
      switch self {
      case .invalid(let message): return "Invalid WebM Opus stream: \(message)"
      case .truncated: return "The WebM Opus stream ended unexpectedly."
      }
    }
  }
}