SPB Git

Repository Public

Fixtures.swift 10.9 KB 196 lines swift

1// SP Lecture Studio — LectureTesting2// File: Packages/LectureTesting/Sources/Fixtures.swift3// Description: Test fixtures: generated PDFs, synthetic audio segments (tones, clicks, silences), synthetic event timelines and pixel probes.4//5// Author: Simon-Pierre Boucher6// Contact: contact@spboucher.ai7import Foundation8import CoreGraphics9import CoreText10import AVFoundation11import LectureCore12import LectureStorage13import LecturePDF1415public enum Fixtures {16    public static func tempDirectory(_ name: String = "slecture") -> URL {17        let u = FileManager.default.temporaryDirectory.appendingPathComponent("\(name)-\(UUID().uuidString)")18        try? FileManager.default.createDirectory(at: u, withIntermediateDirectories: true)19        return u20    }2122    /// Writes a PDF of `pages` pages. Each page has a pale background, a title "Page N — <title>" and a body line.23    /// `rotations` optionally sets /Rotate for given page indexes (to test rotated pages).24    @discardableResult25    public static func makePDF(at url: URL, pages: Int, size: CGSize = CGSize(width: 960, height: 540), title: String = "Cours") -> URL {26        var box = CGRect(origin: .zero, size: size)27        let ctx = CGContext(url as CFURL, mediaBox: &box, nil)!28        for i in 0..<pages {29            ctx.beginPDFPage(nil)30            ctx.setFillColor(CGColor(red: 0.97, green: 0.97, blue: 0.99, alpha: 1)); ctx.fill(box)31            // Deterministic coloured band: lets tests identify the page from pixels.32            ctx.setFillColor(bandColor(i)); ctx.fill(CGRect(x: 0, y: size.height - 30, width: size.width, height: 30))33            draw(text: "Page \(i + 1) — \(title)", at: CGPoint(x: 40, y: size.height - 100), size: 34, in: ctx)34            draw(text: "Contenu de la diapositive numéro \(i + 1) : évaluation immobilière", at: CGPoint(x: 40, y: size.height - 150), size: 18, in: ctx)35            ctx.endPDFPage()36        }37        ctx.closePDF()38        return url39    }4041    public static func bandColor(_ page: Int) -> CGColor {42        let hues: [(CGFloat, CGFloat, CGFloat)] = [(0.85, 0.1, 0.1), (0.1, 0.6, 0.15), (0.1, 0.2, 0.85), (0.8, 0.6, 0.0), (0.5, 0.1, 0.7), (0.0, 0.6, 0.65)]43        let c = hues[page % hues.count]44        return CGColor(red: c.0, green: c.1, blue: c.2, alpha: 1)45    }4647    static func draw(text: String, at point: CGPoint, size: CGFloat, in ctx: CGContext) {48        let font = CTFontCreateWithName("Helvetica" as CFString, size, nil)49        let attr = NSAttributedString(string: text, attributes: [NSAttributedString.Key(kCTFontAttributeName as String): font,50                                                                 NSAttributedString.Key(kCTForegroundColorAttributeName as String): CGColor(gray: 0.1, alpha: 1)])51        ctx.textPosition = point52        CTLineDraw(CTLineCreateWithAttributedString(attr), ctx)53    }5455    // MARK: Audio5657    public struct AudioPlan {58        public var sampleRate: Double = 48_00059        public var duration: Double60        /// Continuous tone amplitude (0 = silence) by time range.61        public var tones: [(range: ClosedRange<Double>, hz: Double, amplitude: Float)] = []62        /// One-millisecond full-scale clicks at these times.63        public var clicks: [Double] = []64        public var noiseAmplitude: Float = 065        public init(duration: Double) { self.duration = duration }66    }6768    /// Writes a 16-bit mono CAF following the plan; returns the number of frames.69    @discardableResult70    public static func writeAudio(_ plan: AudioPlan, to url: URL, startOffset: Double = 0, length: Double? = nil) throws -> Int64 {71        let rate = plan.sampleRate72        let settings: [String: Any] = [AVFormatIDKey: kAudioFormatLinearPCM, AVSampleRateKey: rate, AVNumberOfChannelsKey: 1,73                                       AVLinearPCMBitDepthKey: 16, AVLinearPCMIsFloatKey: false, AVLinearPCMIsBigEndianKey: false]74        let file = try AVAudioFile(forWriting: url, settings: settings, commonFormat: .pcmFormatFloat32, interleaved: false)75        let total = Int64(((length ?? (plan.duration - startOffset)) * rate).rounded())76        let first = Int64((startOffset * rate).rounded())77        let block: AVAudioFrameCount = 48_00078        let buffer = AVAudioPCMBuffer(pcmFormat: file.processingFormat, frameCapacity: block)!79        var seed: UInt64 = 0x9E3779B97F4A7C15 &+ UInt64(first)80        var written: Int64 = 081        let clickFrames = plan.clicks.map { Int64(($0 * rate).rounded()) }82        while written < total {83            let n = AVAudioFrameCount(min(Int64(block), total - written))84            buffer.frameLength = n85            let p = buffer.floatChannelData![0]86            for i in 0..<Int(n) {87                let frame = first + written + Int64(i)88                let t = Double(frame) / rate89                var v: Float = 090                for tone in plan.tones where tone.range.contains(t) { v += tone.amplitude * Float(sin(2 * .pi * tone.hz * t)) }91                if plan.noiseAmplitude > 0 {92                    seed = seed &* 6364136223846793005 &+ 144269504088896340793                    v += plan.noiseAmplitude * (Float(seed >> 40) / Float(1 << 24) * 2 - 1)94                }95                p[i] = v96            }97            for c in clickFrames where c >= first + written && c < first + written + Int64(n) {98                let at = Int(c - first - written)99                for k in 0..<min(48, Int(n) - at) { p[at + k] = k % 2 == 0 ? 0.95 : -0.95 }100            }101            try file.write(from: buffer)102            written += Int64(n)103        }104        return written105    }106107    // MARK: Synthetic project108109    public struct SyntheticProject {110        public var package: ProjectPackage111        public var manifest: ProjectManifest112        public var events: [TimelineEvent]113        public var document: SlideDocument114    }115116    /// Builds a complete project on disk: PDF, segmented audio following `plan`, and the given events.117    /// `events` receives a builder that stamps sequence numbers.118    public static func makeProject(in directory: URL, title: String = "Synthétique", pages: Int = 6, pageSize: CGSize = CGSize(width: 960, height: 540),119                                   audio plan: AudioPlan, segmentSeconds: Double = 30,120                                   events build: (inout EventBuilder) -> Void) throws -> SyntheticProject {121        let pdf = makePDF(at: directory.appendingPathComponent("source-\(UUID().uuidString.prefix(6)).pdf"), pages: pages, size: pageSize, title: title)122        var manifest = ProjectManifest(title: title, courseCode: "TEST", sessionNumber: 1)123        let pkg = try ProjectPackage.create(in: directory, manifest: manifest, pdf: pdf, pdfPageCount: pages)124        manifest = try pkg.loadManifest()125        var session = RecordingSession(timelineStart: .zero)126        var offset = 0.0, index = 1127        while offset < plan.duration - 1e-9 {128            let len = min(segmentSeconds, plan.duration - offset)129            let name = ProjectLayout.segmentFileName(kind: .audio, session: session, index: index)130            let rel = ProjectLayout.mediaDirectory + "/" + name131            let frames = try writeAudio(plan, to: pkg.url(rel), startOffset: offset, length: len)132            session.segments.append(MediaSegment(kind: .audio, path: rel, index: index, start: MediaTime(seconds: offset),133                                                 duration: MediaTime(frames: frames, sampleRate: plan.sampleRate), sampleRate: plan.sampleRate, channels: 1,134                                                 frames: frames, sha256: try Hashing.sha256(of: pkg.url(rel)), finalized: true))135            offset += len; index += 1136        }137        session.duration = MediaTime(seconds: plan.duration); session.endedAt = Date()138        manifest.sessions = [session]; manifest.recomputeDuration()139        var builder = EventBuilder()140        builder.add(0, .sessionStart(id: session.id)); builder.add(0, .page(index: 0))141        build(&builder)142        builder.add(plan.duration, .sessionEnd(id: session.id))143        let writer = try EventLogWriter(url: pkg.eventsURL)144        for e in builder.events { writer.append(e.e, at: e.t, wall: e.wall) }145        writer.flush()146        try pkg.saveManifest(manifest)147        return SyntheticProject(package: pkg, manifest: try pkg.loadManifest(), events: pkg.loadEvents().events, document: try SlideDocument(url: pkg.pdfURL))148    }149150    public struct EventBuilder {151        public private(set) var events: [TimelineEvent] = []152        public init() {}153        public mutating func add(_ seconds: Double, _ payload: EventPayload) {154            events.append(TimelineEvent(seq: Int64(events.count + 1), t: MediaTime(seconds: seconds), wall: Date(timeIntervalSince1970: 1_800_000_000 + seconds), e: payload))155        }156        /// A horizontal pen line drawn from `x0` to `x1` at height `y`, lasting `seconds`.157        @discardableResult158        public mutating func line(page: Int, at begin: Double, seconds: Double, y: Double, x0: Double = 0.2, x1: Double = 0.8,159                                  color: RGBAColor = .red, width: Double = 0.012, tool: InkTool = .pen) -> Stroke {160            let n = max(2, Int(seconds * 60))161            let pts = (0..<n).map { i -> StrokePoint in162                let f = Double(i) / Double(n - 1)163                return StrokePoint(x: x0 + (x1 - x0) * f, y: y, dt: Int64(seconds * f * 1e9), w: 1)164            }165            let s = Stroke(page: page, tool: tool, color: color, width: width, begin: MediaTime(seconds: begin), points: pts)166            add(begin + seconds, .strokeAdded(s))167            return s168        }169    }170}171172/// Reads pixels of a CGImage for assertions.173public struct PixelProbe {174    public let width: Int, height: Int175    private let data: [UInt8]176    public init?(_ image: CGImage) {177        width = image.width; height = image.height178        var bytes = [UInt8](repeating: 0, count: width * height * 4)179        let ok = bytes.withUnsafeMutableBytes { raw -> Bool in180            guard let ctx = Bitmap.context(width: image.width, height: image.height, data: raw.baseAddress, bytesPerRow: image.width * 4) else { return false }181            ctx.draw(image, in: CGRect(x: 0, y: 0, width: image.width, height: image.height)); return true182        }183        guard ok else { return nil }184        data = bytes185    }186    /// Colour at a position given as fractions of the image, origin top-left.187    public func rgb(x: Double, y: Double) -> (r: Double, g: Double, b: Double) {188        let px = min(width - 1, max(0, Int(x * Double(width)))), py = min(height - 1, max(0, Int(y * Double(height))))189        let o = (py * width + px) * 4190        return (Double(data[o + 2]) / 255, Double(data[o + 1]) / 255, Double(data[o]) / 255)191    }192    public func isReddish(x: Double, y: Double) -> Bool { let c = rgb(x: x, y: y); return c.r > 0.6 && c.g < 0.4 && c.b < 0.4 }193    public func isNearWhite(x: Double, y: Double) -> Bool { let c = rgb(x: x, y: y); return c.r > 0.9 && c.g > 0.9 && c.b > 0.9 }194    public func isNearBlack(x: Double, y: Double) -> Bool { let c = rgb(x: x, y: y); return c.r < 0.08 && c.g < 0.08 && c.b < 0.08 }195}196
Files main
Menu

Theme