Repository Public
1// =============================================================================2// SP BOUCHER | SOFTWARE & RESEARCH3// ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4// =============================================================================5//6// PROJECT METADATA7// -----------------------------------------------------------------------------8// Project : SP Music pour macOS9// File : Tests/CoreTests/FLACSeekTests.swift10// Description : Tests: byte-range FLAC seeking is sample-exact and reads a11// fraction of the file.12// Module : CoreTests13// 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 XCTest90import AVFoundation91@testable import SPMusicCore9293/// Counts what is read, to prove a seek does not walk the file.94final class CountingSource: ByteSource, @unchecked Sendable {95 let inner: LocalFileSource96 private let lock = NSLock()97 private var _bytes = 098 var pretendRemote = true99 init(_ u: URL) throws { inner = try LocalFileSource(url: u) }100 var bytes: Int { lock.withLock { _bytes } }101 func reset() { lock.withLock { _bytes = 0 } }102 var length: Int64 { inner.length }103 var isLocal: Bool { !pretendRemote }104 var bufferedFraction: Double { pretendRemote ? 0.1 : 1 }105 func read(at offset: Int64, into buffer: UnsafeMutableRawPointer, count: Int) throws -> Int { lock.withLock { _bytes += count }; return try inner.read(at: offset, into: buffer, count: count) }106 func interruptReads() {}107 func resumeReads() {}108 func cancel() {}109}110111final class FLACSeekTests: XCTestCase {112 func noise(_ name: String, seconds: Int) throws -> URL {113 guard let ffmpeg = Fixtures.ffmpeg else { throw XCTSkip("ffmpeg is not installed") }114 let url = Fixtures.dir.appendingPathComponent(name)115 if !FileManager.default.fileExists(atPath: url.path) {116 try Fixtures.run(ffmpeg, ["-v", "error", "-nostdin", "-y", "-f", "lavfi", "-i", "anoisesrc=d=\(seconds):c=pink:r=44100:a=0.4", "-ac", "2", "-c:a", "flac", url.path])117 }118 return url119 }120121 /// Decoding from the located frame boundary gives exactly the samples that decoding the whole file gives at the122 /// same place, for a fraction of the reads. Checked on every file given (with and without a seek table).123 func check(_ url: URL, expectSeekTable: Bool?) throws {124 let whole = try AudioDecoder(source: LocalFileSource(url: url), typeHint: 0)125 let counting = try CountingSource(url)126 let index = try XCTUnwrap(try FLACIndex.parse(counting))127 XCTAssertEqual(Double(index.sampleRate), whole.info.sampleRate); XCTAssertEqual(index.channels, whole.info.channels)128 XCTAssertEqual(index.totalSamples, whole.info.lengthFrames); XCTAssertEqual(index.bitsPerSample, whole.info.bitDepth)129 if let expectSeekTable { XCTAssertEqual(!index.seekPoints.isEmpty, expectSeekTable) }130 let a = AVAudioPCMBuffer(pcmFormat: whole.processingFormat, frameCapacity: 8192)!, b = AVAudioPCMBuffer(pcmFormat: whole.processingFormat, frameCapacity: 8192)!131 for fraction in [0.13, 0.5, 0.77, 0.985] {132 let target = Int64(Double(index.totalSamples) * fraction)133 counting.reset()134 let at = try index.locate(sample: target, in: counting)135 XCTAssertLessThanOrEqual(at.sample, target); XCTAssertGreaterThan(at.byteOffset, index.audioStart)136 XCTAssertLessThan(target - at.sample, Int64(index.sampleRate) * 12, "the boundary is close to the target")137 let slice = try AudioDecoder(source: FLACSliceSource(base: counting, headerLength: index.audioStart, sliceStart: at.byteOffset), typeHint: 0)138 try slice.seek(toFrame: target - at.sample)139 XCTAssertEqual(try slice.read(into: b), 8192)140 XCTAssertLessThan(counting.bytes, Int(counting.length) / 4, "seeking to \(fraction) read \(counting.bytes) of \(counting.length) bytes")141 try whole.seek(toFrame: target)142 XCTAssertEqual(try whole.read(into: a), 8192)143 XCTAssertEqual(Signal.samples(a), Signal.samples(b), "sample-exact at \(fraction)")144 XCTAssertEqual(Signal.samples(a, channel: 1), Signal.samples(b, channel: 1))145 }146 // The slice plays to the true end of the file and stops cleanly.147 let target = index.totalSamples - Int64(index.sampleRate) * 2148 let at = try index.locate(sample: target, in: counting)149 let tail = try AudioDecoder(source: FLACSliceSource(base: counting, headerLength: index.audioStart, sliceStart: at.byteOffset), typeHint: 0)150 try tail.seek(toFrame: target - at.sample)151 var total: Int64 = 0152 while true { let n = try tail.read(into: b); if n == 0 { break }; total += Int64(n) }153 XCTAssertEqual(total, index.totalSamples - target)154 }155156 func testSeekByFrameSyncInAFileWithoutSeekTable() throws { try check(noise("seek-noise.flac", seconds: 150), expectSeekTable: false) }157158 /// A real album file (store-encoded, with a SEEKTABLE and an embedded cover) when one is provided; never part of the repository.159 func testSeekInARealFileWithSeekTable() throws {160 guard let p = ProcessInfo.processInfo.environment["SPMUSIC_REAL_FLAC"] ?? (FileManager.default.fileExists(atPath: "/tmp/spm-probe/sample.flac") ? "/tmp/spm-probe/sample.flac" : nil) else { throw XCTSkip("no real file provided") }161 try check(URL(fileURLWithPath: p), expectSeekTable: nil)162 }163164 func testTheEngineSeeksAStreamWithoutReadingItsWay() throws {165 let url = try noise("seek-noise.flac", seconds: 150)166 let src = try CountingSource(url)167 let engine = OfflinePlayer.engine()168 engine.load(token: UUID(), source: src, typeHint: AudioDecoder.typeHint(pathExtension: "flac"), autoplay: true)169 _ = OfflinePlayer.render(engine, seconds: 0.5)170 src.reset()171 engine.seek(to: 120)172 let x = OfflinePlayer.render(engine, seconds: 1)173 XCTAssertGreaterThan(Signal.rms(x[22050...]), 0.01)174 XCTAssertEqual(engine.status().position, 121, accuracy: 0.3)175 XCTAssertEqual(engine.status().duration, 150, accuracy: 0.1, "the duration is still the whole track's")176 XCTAssertLessThan(src.bytes, Int(src.length) / 4, "read \(src.bytes) of \(src.length)")177 // Back to the start, then to the end: the track finishes normally.178 engine.seek(to: 2); _ = OfflinePlayer.render(engine, seconds: 0.5)179 XCTAssertEqual(engine.status().position, 2.5, accuracy: 0.3)180 engine.seek(to: 148.5)181 _ = OfflinePlayer.render(engine, seconds: 2.5)182 XCTAssertFalse(engine.status().isPlaying, "playback stopped at the end of the track")183 }184185 func testNotFLACIsLeftAlone() throws {186 let mp3 = try Fixtures.sine("mp3.mp3", hz: 440, seconds: 2, codecArgs: Fixtures.formats[5].args)187 XCTAssertNil(try FLACIndex.parse(LocalFileSource(url: mp3)))188 }189}190