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

geesawra.industries/hydraulophone

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

0
0
main
77 lines · 2.8 KB Raw History
import AVFoundation
import Foundation
import HydraulophoneCore

/// The actor transfers each completed buffer to the output engine exactly once.
/// Neither side mutates a buffer after it has been scheduled for playback.
struct NativeOpusPCMChunk: @unchecked Sendable {
  let buffer: AVAudioPCMBuffer
  let timestamp: TimeInterval
}

actor NativeOpusPCMSource {
  private let reader: WebMOpusReader
  private var decoder: NativeOpusDecoder?
  private var discardBefore: TimeInterval = 0

  init(source: NativeOpusByteSource) {
    reader = WebMOpusReader { offset, count in
      try await source.read(offset: offset, count: count)
    }
  }

  func prepare() async throws -> WebMOpusTrack {
    let track = try await reader.prepare()
    decoder = try NativeOpusDecoder(channels: track.channels, outputGainDB: track.outputGainDB)
    return track
  }

  func seek(to target: TimeInterval) async throws {
    try await reader.seek(to: target)
    try decoder?.reset()
    discardBefore = target
  }

  func nextChunk() async throws -> NativeOpusPCMChunk? {
    guard let decoder,
      let output = AVAudioPCMBuffer(pcmFormat: decoder.format, frameCapacity: 24_000),
      let channels = output.floatChannelData
    else { throw NativeOpusError.invalidFormat }
    var written = 0
    var timestamp: TimeInterval?
    while written < 12_000 {
      try Task.checkCancellation()
      guard let packet = try await reader.nextPacket() else { break }
      let decoded = try decoder.decode(packet.data)
      let frameCount = Int(decoded.frameLength)
      guard packet.timestamp.isFinite, packet.discardPadding.isFinite else {
        throw NativeOpusError.invalidPacket
      }
      let startTrim = Int(
        min(Double(frameCount), max(0, ((discardBefore - packet.timestamp) * 48_000).rounded())))
      let paddingStart =
        packet.discardPadding < 0
        ? Int(min(Double(frameCount), (-packet.discardPadding * 48_000).rounded())) : 0
      let first = min(frameCount, max(startTrim, paddingStart))
      let end =
        frameCount
        - Int(min(Double(frameCount), max(0, (packet.discardPadding * 48_000).rounded())))
      guard first < end else { continue }
      let count = end - first
      guard written + count <= Int(output.frameCapacity),
        let sourceChannels = decoded.floatChannelData
      else {
        throw NativeOpusError.invalidFormat
      }
      if timestamp == nil { timestamp = packet.timestamp + Double(first) / 48_000 }
      for channel in 0..<Int(decoder.format.channelCount) {
        channels[channel].advanced(by: written).update(
          from: sourceChannels[channel].advanced(by: first), count: count)
      }
      written += count
    }
    guard written > 0, let timestamp else { return nil }
    output.frameLength = AVAudioFrameCount(written)
    return NativeOpusPCMChunk(buffer: output, timestamp: max(0, timestamp))
  }
}