SPB Git

Repository Public

FLACSeeker.swift 13.9 KB 269 lines swift

1// =============================================================================2//                  SP BOUCHER | SOFTWARE & RESEARCH3//             ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4// =============================================================================5//6// PROJECT METADATA7// -----------------------------------------------------------------------------8// Project          : SP Music pour macOS9// File             : Core/Audio/FLACSeeker.swift10// Description      : Byte-accurate seeking inside a FLAC file that is still11//                    arriving from the cluster.12// Module           : Core13// Repository       : https://git.spboucher.ai/sp-music-macos14// Created          : 2026-11-1815// Last Modified    : 2026-11-1816//17// =============================================================================18// AUTHOR & PROFESSIONAL AFFILIATION19// =============================================================================20//21// Author           : Simon-Pierre Boucher22// Position         : Professor of Finance23// Institution      : Université du Québec en Outaouais (UQO)24// Department       : Département des sciences administratives25// Organization     : SP Boucher26//27// Website          : https://spboucher.ai28// Git              : https://git.spboucher.ai29//30// =============================================================================31// OFFICIAL CONTACT DIRECTORY32// =============================================================================33//34// General          : info@spboucher.ai35// Professional     : contact@spboucher.ai36// Direct           : simon@spboucher.ai37// Research         : research@spboucher.ai38// Development      : dev@spboucher.ai39// Support          : support@spboucher.ai40// Security/Admin   : admin@spboucher.ai41// Notifications    : notifications@spboucher.ai42//43// Preferred Contact: support@spboucher.ai44//45// =============================================================================46// COPYRIGHT & INTELLECTUAL PROPERTY47// =============================================================================48//49// Copyright (c) 202650// Simon-Pierre Boucher51//52// All rights reserved where applicable.53//54// This file is governed by the applicable project license,55// copyright notices, institutional agreements and relevant law.56//57// Unless expressly authorized by the applicable license or58// rights holder, copying, redistribution, sublicensing,59// publication and commercial exploitation are not permitted.60//61// Existing third-party rights and notices remain unaffected.62//63// =============================================================================64// CONFIDENTIALITY & SECURITY65// =============================================================================66//67// Classification   : Public68// Distribution     : Public repository; use is governed by the project license69// Security Contact : admin@spboucher.ai70//71// Access to this source does not independently grant permission72// to redistribute or disclose confidential materials.73//74// Do not embed credentials, private keys, access tokens,75// certificates or confidential personal information.76//77// =============================================================================78// LICENSE & MAINTENANCE79// =============================================================================80//81// License          : None specified (no license file in this repository)82// Maintainer       : Simon-Pierre Boucher83// Technical Contact: dev@spboucher.ai84//85// =============================================================================86// END OF SP BOUCHER SOURCE HEADER87// =============================================================================8889import Foundation9091/// Byte-accurate seeking inside a FLAC file that is still arriving from the cluster.92///93/// Core Audio seeks in FLAC by reading the file from its start up to the target (measured: it ignores the seek94/// table), which on a stream means waiting for everything before the target to download. This finds, with a few95/// kilobytes of reads, a frame boundary just before the target — from the file's SEEKTABLE when it has one, else by96/// locating a frame header near the estimated position and checking its CRC — so that decoding can restart there.97public struct FLACIndex: Sendable, Equatable {98    public var audioStart: Int64            // offset of the first audio frame99    public var sampleRate: Int100    public var channels: Int101    public var bitsPerSample: Int102    public var minBlock: Int, maxBlock: Int103    public var totalSamples: Int64104    public var seekPoints: [SeekPoint]105    public struct SeekPoint: Sendable, Equatable { public var sample: Int64; public var offset: Int64 }106107    public struct Location: Sendable, Equatable { public var byteOffset: Int64; public var sample: Int64 }108109    private static func bytes(_ source: ByteSource, at offset: Int64, count: Int) throws -> [UInt8] {110        var buf = [UInt8](repeating: 0, count: count)111        let n = try buf.withUnsafeMutableBytes { try source.read(at: offset, into: $0.baseAddress!, count: count) }112        return Array(buf.prefix(n))113    }114115    /// Reads the metadata blocks at the head of the file. Returns nil when the file is not FLAC.116    public static func parse(_ source: ByteSource) throws -> FLACIndex? {117        var pos: Int64 = 0118        var head = try bytes(source, at: 0, count: 10)119        // An ID3v2 tag may precede the stream.120        if head.count == 10, head[0] == 0x49, head[1] == 0x44, head[2] == 0x33 {121            pos = 10 + (Int64(head[6] & 0x7f) << 21 | Int64(head[7] & 0x7f) << 14 | Int64(head[8] & 0x7f) << 7 | Int64(head[9] & 0x7f))122            head = try bytes(source, at: pos, count: 4)123        }124        guard head.count >= 4, head[0] == 0x66, head[1] == 0x4c, head[2] == 0x61, head[3] == 0x43 else { return nil }      // "fLaC"125        pos += 4126        var index = FLACIndex(audioStart: 0, sampleRate: 0, channels: 0, bitsPerSample: 0, minBlock: 0, maxBlock: 0, totalSamples: 0, seekPoints: [])127        while true {128            let h = try bytes(source, at: pos, count: 4)129            guard h.count == 4 else { return nil }130            let last = h[0] & 0x80 != 0, type = h[0] & 0x7f131            let size = Int(h[1]) << 16 | Int(h[2]) << 8 | Int(h[3])132            pos += 4133            if type == 0, size >= 34 {134                let s = try bytes(source, at: pos, count: 34)135                guard s.count == 34 else { return nil }136                index.minBlock = Int(s[0]) << 8 | Int(s[1]); index.maxBlock = Int(s[2]) << 8 | Int(s[3])137                index.sampleRate = Int(s[10]) << 12 | Int(s[11]) << 4 | Int(s[12]) >> 4138                index.channels = Int(s[12] >> 1 & 0x07) + 1139                index.bitsPerSample = (Int(s[12] & 0x01) << 4 | Int(s[13] >> 4)) + 1140                index.totalSamples = Int64(s[13] & 0x0f) << 32 | Int64(s[14]) << 24 | Int64(s[15]) << 16 | Int64(s[16]) << 8 | Int64(s[17])141            } else if type == 3, size <= 1 << 20 {142                let t = try bytes(source, at: pos, count: size)143                for i in stride(from: 0, to: t.count - 17, by: 18) {144                    var sample: Int64 = 0, offset: Int64 = 0145                    for k in 0..<8 { sample = sample << 8 | Int64(t[i + k]); offset = offset << 8 | Int64(t[i + 8 + k]) }146                    if sample != -1 { index.seekPoints.append(SeekPoint(sample: sample, offset: offset)) }     // 0xFFFF… marks a placeholder147                }148            }149            pos += Int64(size)150            if last { break }151            if pos >= source.length { return nil }152        }153        guard index.sampleRate > 0 else { return nil }154        index.audioStart = pos155        index.seekPoints.sort { $0.sample < $1.sample }156        return index157    }158159    private static let crcTable: [UInt8] = (0..<256).map { i in160        var c = UInt8(i)161        for _ in 0..<8 { c = c & 0x80 != 0 ? (c << 1) ^ 0x07 : c << 1 }162        return c163    }164165    /// Parses a frame header at `b[i...]`. Returns the frame's first sample and block size when the header is valid (CRC-8 included).166    func frameHeader(_ b: [UInt8], at i: Int) -> (sample: Int64, blockSize: Int)? {167        guard i + 16 <= b.count, b[i] == 0xff, b[i + 1] & 0xfe == 0xf8 else { return nil }168        let variable = b[i + 1] & 0x01 != 0169        let blockCode = Int(b[i + 2] >> 4), rateCode = Int(b[i + 2] & 0x0f)170        let channelCode = Int(b[i + 3] >> 4), sizeCode = Int(b[i + 3] >> 1 & 0x07)171        guard blockCode != 0, rateCode != 15, channelCode <= 10, sizeCode != 3, sizeCode != 7, b[i + 3] & 0x01 == 0 else { return nil }172        if channelCode < 8, channelCode + 1 != channels { return nil }173        if channelCode >= 8, channels != 2 { return nil }174        // The frame or sample number, coded like UTF-8 (up to 36 bits).175        var p = i + 4176        let first = b[p]177        var extra = 0178        var value: Int64179        if first & 0x80 == 0 { value = Int64(first) }180        else if first & 0xe0 == 0xc0 { value = Int64(first & 0x1f); extra = 1 }181        else if first & 0xf0 == 0xe0 { value = Int64(first & 0x0f); extra = 2 }182        else if first & 0xf8 == 0xf0 { value = Int64(first & 0x07); extra = 3 }183        else if first & 0xfc == 0xf8 { value = Int64(first & 0x03); extra = 4 }184        else if first & 0xfe == 0xfc { value = Int64(first & 0x01); extra = 5 }185        else if first == 0xfe { value = 0; extra = 6 }186        else { return nil }187        p += 1188        for _ in 0..<extra { guard p < b.count, b[p] & 0xc0 == 0x80 else { return nil }; value = value << 6 | Int64(b[p] & 0x3f); p += 1 }189        var blockSize = 0190        switch blockCode {191        case 1: blockSize = 192192        case 2...5: blockSize = 576 << (blockCode - 2)193        case 6: guard p < b.count else { return nil }; blockSize = Int(b[p]) + 1; p += 1194        case 7: guard p + 1 < b.count else { return nil }; blockSize = (Int(b[p]) << 8 | Int(b[p + 1])) + 1; p += 2195        default: blockSize = 256 << (blockCode - 8)196        }197        if rateCode == 12 { p += 1 } else if rateCode == 13 || rateCode == 14 { p += 2 }198        guard p < b.count else { return nil }199        var crc: UInt8 = 0200        for k in i..<p { crc = Self.crcTable[Int(crc ^ b[k])] }201        guard crc == b[p] else { return nil }202        if maxBlock > 0, blockSize > maxBlock { return nil }203        // Fixed block size: the header carries a frame number; every frame but the last has the stream's block size.204        return (variable ? value : value * Int64(minBlock > 0 ? minBlock : blockSize), blockSize)205    }206207    /// A frame boundary at or shortly before `target`, found with as few reads as possible.208    public func locate(sample target: Int64, in source: ByteSource) throws -> Location {209        let start = Location(byteOffset: audioStart, sample: 0)210        guard target > 0, totalSamples > 0, source.length > audioStart else { return start }211        var floor = start212        if let p = seekPoints.last(where: { $0.sample <= target }) { floor = Location(byteOffset: audioStart + p.offset, sample: p.sample) }213        // Close enough (under five seconds of audio to skip): decode from the seek point.214        if target - floor.sample <= Int64(sampleRate) * 5 { return floor }215        let audioBytes = source.length - audioStart216        var guess = audioStart + Int64(Double(audioBytes) * Double(target) / Double(totalSamples)) - 96 * 1024217        for _ in 0..<6 {218            guess = max(floor.byteOffset, min(guess, source.length - 4096))219            if guess <= floor.byteOffset { return floor }220            let window = try Self.bytes(source, at: guess, count: Int(min(128 * 1024, source.length - guess)))221            var i = 0222            scan: while i + 16 <= window.count {223                if window[i] == 0xff, window[i + 1] & 0xfe == 0xf8, let h = frameHeader(window, at: i) {224                    if h.sample > target { break }225                    if h.sample > floor.sample {226                        // A header whose CRC matches by chance is ruled out: the next frame must follow with the expected sample number.227                        var j = i + 16228                        let limit = min(window.count - 16, i + 96 * 1024)229                        while j <= limit {230                            if window[j] == 0xff, window[j + 1] & 0xfe == 0xf8, let n = frameHeader(window, at: j), n.sample == h.sample + Int64(h.blockSize) {231                                return Location(byteOffset: guess + Int64(i), sample: h.sample)232                            }233                            j += 1234                        }235                    }236                }237                i += 1238            }239            guess -= 256 * 1024          // variable bit rate put the target earlier than estimated: look further back240        }241        return floor242    }243}244245/// Presents "the file's header, then its audio from a later frame boundary" as one contiguous file, which is a valid246/// FLAC stream that any decoder can read from its beginning.247public final class FLACSliceSource: ByteSource, @unchecked Sendable {248    private let base: ByteSource249    private let headerLength: Int64250    private let sliceStart: Int64251    public init(base: ByteSource, headerLength: Int64, sliceStart: Int64) { self.base = base; self.headerLength = headerLength; self.sliceStart = max(headerLength, sliceStart) }252    public var length: Int64 { headerLength + (base.length - sliceStart) }253    public var isLocal: Bool { base.isLocal }254    public var bufferedFraction: Double { base.bufferedFraction }255    public func read(at offset: Int64, into buffer: UnsafeMutableRawPointer, count: Int) throws -> Int {256        var done = 0257        if offset < headerLength {258            let n = Int(min(Int64(count), headerLength - offset))259            done = try base.read(at: offset, into: buffer, count: n)260            if done < n || done == count { return done }261        }262        let at = sliceStart + (offset + Int64(done) - headerLength)263        return done + (try base.read(at: at, into: buffer + done, count: count - done))264    }265    public func interruptReads() { base.interruptReads() }266    public func resumeReads() { base.resumeReads() }267    public func cancel() {}       // the engine cancels the underlying source itself268}269
Files main
Menu

Theme