Cotton code
175 lines · 7.8 KB · SwiftRaw
import AVFoundationimport CottonValuesimport Foundationimport XCTest@testable import CottonUI/// The music player's own engine (`SongEngine`), played offline over silent/// songs written for the test: where a song stands, a gapless join, a song in/// another shape, a crossfade, a seek; and the knobs and the meters.@MainActorfinal class SongEngineTests: XCTestCase {    private var folder: URL!    override func setUp() async throws {        folder = FileManager.default.temporaryDirectory.appendingPathComponent("song-engine-\(UUID().uuidString)", isDirectory: true)        try FileManager.default.createDirectory(at: folder, withIntermediateDirectories: true)    }    override func tearDown() async throws {        try? FileManager.default.removeItem(at: folder)    }    /// A song of `seconds` silence (or a tone of `amplitude`) written as a WAV.    private func fixture(_ name: String, seconds: Double, rate: Double = 44_100, channels: AVAudioChannelCount = 2, amplitude: Float = 0) throws -> AVAudioFile {        let url = folder.appendingPathComponent("\(name).wav")        let format = AVAudioFormat(standardFormatWithSampleRate: rate, channels: channels)!        let settings: [String: Any] = [AVFormatIDKey: kAudioFormatLinearPCM, AVSampleRateKey: rate, AVNumberOfChannelsKey: channels,                                       AVLinearPCMBitDepthKey: 16, AVLinearPCMIsFloatKey: false, AVLinearPCMIsBigEndianKey: false]        let frames = AVAudioFrameCount(seconds * rate)        do {            let file = try AVAudioFile(forWriting: url, settings: settings, commonFormat: .pcmFormatFloat32, interleaved: false)            let buffer = AVAudioPCMBuffer(pcmFormat: format, frameCapacity: frames)!            buffer.frameLength = frames            for channel in 0..<Int(channels) {                let samples = buffer.floatChannelData![channel]                for frame in 0..<Int(frames) { samples[frame] = amplitude * sin(Float(frame) * 2 * .pi * 440 / Float(rate)) }            }            try file.write(from: buffer)        }        return try XCTUnwrap(SongEngine.open(url))    }    private func song(_ id: String, duration: Double? = nil) -> QueuedSong {        QueuedSong(id: id, file: "db/music/\(id).wav", title: id, duration: duration)    }    private func engine() -> SongEngine {        SongEngine(offline: AVAudioFormat(standardFormatWithSampleRate: 44_100, channels: 2)!)    }    /// Renders `seconds`, the clock ticking as the player's does, and lets    /// the decks' ends land on the main queue.    private func run(_ engine: SongEngine, _ seconds: Double) async throws {        var left = seconds        while left > 0 {            let step = min(0.05, left)            try engine.render(step)            engine.tick()            left -= step            await Task.yield()        }        try await Task.sleep(for: .milliseconds(30))    }    /// RULE: A song stands where its deck's clock says, and says it has finished, with nothing after it, at its end.    func testASongStandsAndFinishes() async throws {        let engine = engine()        var finished: [(String, Bool)] = []        engine.onFinished = { finished.append(($0, $1)) }        engine.load(song("a"), file: try fixture("a", seconds: 1))        engine.play()        XCTAssertTrue(engine.playing)        try await run(engine, 0.5)        XCTAssertEqual(engine.elapsed, 0.5, accuracy: 0.1)        XCTAssertEqual(engine.duration, 1, accuracy: 0.01)        try await run(engine, 0.8)        XCTAssertEqual(finished.map(\.0), ["a"])        XCTAssertEqual(finished.first?.1, false)    }    /// RULE: Gapless, the next song is joined behind the first on its deck and plays the moment the first ends.    func testAGaplessJoin() async throws {        let engine = engine()        var finished: [(String, Bool)] = []        engine.onFinished = { finished.append(($0, $1)) }        engine.load(song("a"), file: try fixture("a", seconds: 1))        engine.prepare(song("b"), file: try fixture("b", seconds: 1))        engine.play()        try await run(engine, 1.5)        XCTAssertEqual(finished.map(\.0), ["a"])        XCTAssertEqual(finished.first?.1, true, "b was already playing")        XCTAssertEqual(engine.current?.id, "b")        XCTAssertEqual(engine.elapsed, 0.5, accuracy: 0.1)    }    /// RULE: A song in another shape (another rate, mono) waits on the other deck and starts as the first ends.    func testASongInAnotherShapeFollowsOnTheOtherDeck() async throws {        let engine = engine()        var finished: [(String, Bool)] = []        engine.onFinished = { finished.append(($0, $1)) }        engine.load(song("a"), file: try fixture("a", seconds: 1))        engine.prepare(song("b"), file: try fixture("b", seconds: 1, rate: 48_000, channels: 1))        engine.play()        try await run(engine, 1.4)        XCTAssertEqual(finished.first?.0, "a")        XCTAssertEqual(finished.first?.1, true)        XCTAssertEqual(engine.current?.id, "b")        XCTAssertGreaterThan(engine.elapsed, 0.1)    }    /// RULE: With a crossfade, the next song starts that many seconds before the end, and the song held is the next one from then.    func testACrossfadeStartsBeforeTheEnd() async throws {        let engine = engine()        var knobs = PlayerKnobs()        knobs.crossfade = 0.5        engine.set(knobs)        var finished: [(String, Bool)] = []        engine.onFinished = { finished.append(($0, $1)) }        engine.load(song("a"), file: try fixture("a", seconds: 2))        engine.prepare(song("b"), file: try fixture("b", seconds: 2))        engine.play()        try await run(engine, 1.3)        XCTAssertTrue(finished.isEmpty)        try await run(engine, 0.4)        XCTAssertEqual(finished.map(\.0), ["a"], "it starts with half a second left")        XCTAssertEqual(engine.current?.id, "b")        try await run(engine, 1)        XCTAssertEqual(engine.current?.id, "b")        XCTAssertGreaterThan(engine.elapsed, 0.9)    }    /// RULE: A seek moves the song to where it was sent, and it plays on from there; the gapless join behind it stays.    func testASeek() async throws {        let engine = engine()        var finished: [(String, Bool)] = []        engine.onFinished = { finished.append(($0, $1)) }        engine.load(song("a"), file: try fixture("a", seconds: 2))        engine.prepare(song("b"), file: try fixture("b", seconds: 1))        engine.play()        try await run(engine, 0.2)        engine.seek(to: 1.5)        XCTAssertEqual(engine.elapsed, 1.5, accuracy: 0.06)        try await run(engine, 0.2)        XCTAssertEqual(engine.elapsed, 1.7, accuracy: 0.1)        try await run(engine, 0.5)        XCTAssertEqual(finished.first?.0, "a")        XCTAssertEqual(engine.current?.id, "b")    }    /// RULE: Paused, the song stands still and the meters read nothing.    func testPausedStandsStill() async throws {        let engine = engine()        engine.load(song("a"), file: try fixture("a", seconds: 2, amplitude: 0.5))        engine.play()        try await run(engine, 0.3)        XCTAssertGreaterThan(engine.level.left, 0.5, "a loud tone reads high")        engine.pause()        XCTAssertFalse(engine.playing)        let at = engine.elapsed        XCTAssertEqual(engine.level, TrackLevel(left: 0, right: 0))        engine.play()        XCTAssertEqual(engine.elapsed, at, accuracy: 0.05)    }    // MARK: The meters    /// RULE: The meters read as a VU meter: nought VU at −18 dBFS stands where the face paints 0, silence at the bottom, full scale at the top.    func testTheMeterScale() {        XCTAssertEqual(SongMeter.level(rms: 0), 0)        XCTAssertEqual(SongMeter.level(rms: pow(10, -18 / 20)), 40.0 / 43, accuracy: 0.001)        XCTAssertEqual(SongMeter.level(rms: 1), 1)        XCTAssertEqual(SongMeter.level(rms: pow(10, -70 / 20)), 0)    }}