Repository Public License
1// ORIX Convert — App/Sources/Features/Shared/BuiltInPresets.swift2// Description: The presets shipped with the app. Each one names a real path of a wired engine and real option values;3// all are validated at launch against the registry and the engine's option descriptors. A preset whose4// path, key or value does not exist in this build is not offered, and the reason is logged.5// Author: Simon-Pierre Boucher — contact@spboucher.ai6import ConvertCore7import Foundation8import os910nonisolated struct BuiltInPreset: Sendable, Identifiable {11 /// Stable key (also the seed of the preset's identifier, so a rule or a workflow can keep referring to it).12 let key: String13 let family: String14 let name: String15 let summary: String16 let scope: ConversionPreset.Scope17 /// A source format the preset is checked with (and converted from in the self-test).18 let sample: FormatID19 let destination: FormatID20 let operation: String?21 let options: [String: OptionValue]22 /// Planned from the `.folder` pseudo-source (archives of any files).23 var generic = false2425 var id: String { key }2627 var preset: ConversionPreset {28 ConversionPreset(id: BuiltInPresets.identifier(for: key), name: name, summary: summary, source: scope, destinationFormat: destination, operation: operation,29 options: ConversionOptions(options), isBuiltIn: true)30 }31}3233nonisolated enum BuiltInPresets {34 private static let log = Logger(subsystem: "ai.spboucher.orix.convert", category: "presets")3536 /// A deterministic UUID from the key (the same preset keeps the same identifier across launches).37 static func identifier(for key: String) -> UUID {38 var bytes = [UInt8](repeating: 0, count: 16)39 var hash: UInt64 = 0xcbf2_9ce4_8422_232540 for (index, byte) in Array(("orix-convert-preset:" + key).utf8).enumerated() {41 hash = (hash ^ UInt64(byte)) &* 0x0000_0100_0000_01B342 bytes[index % 16] ^= UInt8(truncatingIfNeeded: hash >> UInt64((index % 8) * 8))43 }44 bytes[6] = (bytes[6] & 0x0F) | 0x5045 bytes[8] = (bytes[8] & 0x3F) | 0x8046 return UUID(uuid: (bytes[0], bytes[1], bytes[2], bytes[3], bytes[4], bytes[5], bytes[6], bytes[7], bytes[8], bytes[9], bytes[10], bytes[11], bytes[12], bytes[13], bytes[14], bytes[15]))47 }4849 private static func p(_ key: String, _ family: String, _ name: String, _ summary: String, _ scope: ConversionPreset.Scope, _ sample: FormatID, _ destination: FormatID,50 _ operation: String? = nil, _ options: [String: OptionValue] = [:], generic: Bool = false) -> BuiltInPreset {51 BuiltInPreset(key: key, family: family, name: name, summary: summary, scope: scope, sample: sample, destination: destination, operation: operation, options: options, generic: generic)52 }5354 /// Everything the app would like to offer. `validated(in:)` keeps what this build can really do.55 static let all: [BuiltInPreset] = [56 // Images57 p("image.web-jpeg", "Images", "Web JPEG 2000 px", "JPEG, long edge 2000 px, quality 82, sRGB, location removed.", .category(.image), .png, .jpeg, nil,58 ["resize.mode": .string("long-edge"), "resize.long-edge": .int(2000), "quality": .int(82), "color.profile": .string("srgb"), "metadata": .string("strip-location")]),59 p("image.webp-web", "Images", "WebP for web", "WebP, long edge 2000 px, quality 80, metadata removed.", .category(.image), .png, .webp, nil,60 ["resize.mode": .string("long-edge"), "resize.long-edge": .int(2000), "quality": .int(80), "metadata": .string("strip")]),61 p("image.png-optimised", "Images", "PNG lossless optimised", "Recompresses a PNG with the strongest effort; pixels unchanged.", .format(.png), .png, .png, "image.optimize",62 ["png.effort": .int(2)]),63 p("image.strip-location", "Images", "Strip location data", "Same JPEG picture without GPS position.", .format(.jpeg), .jpeg, .jpeg, nil, ["metadata": .string("strip-location")]),64 // Video65 p("video.mp4-1080", "Video", "MP4 H.264 1080p", "H.264 in MP4, 1080p, balanced quality, AAC audio.", .category(.video), .mov, .mp4, nil,66 ["video.codec": .string("h264"), "resize.preset": .string("1080"), "quality.preset": .string("balanced")]),67 p("video.hevc-high", "Video", "HEVC high quality (hardware)", "HEVC in MP4 with the hardware encoder, high quality.", .category(.video), .mov, .mp4, nil,68 ["video.codec": .string("hevc"), "video.encoder": .string("hardware"), "quality.preset": .string("high")]),69 p("video.messaging", "Video", "Small for messaging", "H.264 in MP4, 720p, small files.", .category(.video), .mov, .mp4, nil,70 ["video.codec": .string("h264"), "resize.preset": .string("720"), "quality.preset": .string("small")]),71 p("video.prores", "Video", "ProRes 422 for editing", "ProRes 422 in a QuickTime movie.", .category(.video), .mp4, .mov, nil,72 ["video.codec": .string("prores"), "video.prores.profile": .string("standard")]),73 p("video.audio-only", "Video", "Audio only (M4A)", "Extracts the sound track as AAC in M4A.", .category(.video), .mp4, .m4a, "video.extract-audio", [:]),74 // Audio75 p("audio.mp3-320", "Audio", "MP3 320", "MP3 at 320 kbit/s.", .category(.audio), .wav, .mp3, nil, ["audio.mode": .string("bitrate"), "audio.bitrate": .int(320)]),76 p("audio.aac-256", "Audio", "AAC 256", "AAC in M4A at 256 kbit/s.", .category(.audio), .wav, .m4a, nil, ["audio.mode": .string("bitrate"), "audio.bitrate": .int(256)]),77 p("audio.flac", "Audio", "FLAC lossless", "FLAC, strongest compression, bit depth kept.", .category(.audio), .wav, .flac, nil, ["audio.flac.level": .int(8)]),78 p("audio.podcast", "Audio", "Podcast loudness −16 LUFS", "MP3 128 kbit/s normalised to −16 LUFS.", .category(.audio), .wav, .mp3, nil,79 ["loudness.normalize": .bool(true), "loudness.target": .double(-16), "audio.mode": .string("bitrate"), "audio.bitrate": .int(128)]),80 // PDF81 p("pdf.email", "PDF", "Compress for e-mail", "Pictures resampled to 110 dpi and recompressed for a small file.", .format(.pdf), .pdf, .pdf, "pdf.compress", ["compress.dpi": .int(110), "quality": .double(0.5)]),82 p("pdf.searchable", "PDF", "Searchable (OCR)", "Adds an invisible text layer recognised on this Mac.", .format(.pdf), .pdf, .pdf, "pdf.ocr", [:]),83 p("pdf.png-300", "PDF", "Pages as PNG 300 dpi", "One PNG per page at 300 dpi.", .format(.pdf), .pdf, .png, nil, ["resolution.dpi": .int(300)]),84 // Documents85 p("doc.word-pdf", "Documents", "Word → PDF", "A Word document laid out as PDF.", .format(.docx), .docx, .pdf, nil, [:]),86 p("doc.markdown-pdf-a4", "Documents", "Markdown → PDF (A4)", "Markdown typeset on A4 pages.", .format(.markdown), .markdown, .pdf, nil, ["page.size": .string("a4")]),87 p("doc.markdown-pdf-letter", "Documents", "Markdown → PDF (Letter)", "Markdown typeset on US Letter pages.", .format(.markdown), .markdown, .pdf, nil, ["page.size": .string("letter")]),88 // Data89 p("data.excel-csv", "Data", "Excel-friendly CSV", "CSV that Excel opens correctly: UTF-8 with BOM, CRLF line endings.", .category(.spreadsheet), .xlsx, .csv, nil, ["csv.preset": .string("excel")]),90 p("data.csv-parquet", "Data", "CSV → Parquet (zstd)", "Typed columns in a Parquet file compressed with Zstandard.", .format(.csv), .csv, .parquet, nil, ["parquet.compression": .string("zstd")]),91 // 3D92 // No unit conversion in the 3D presets: OBJ, STL and PLY state no unit, and the engine refuses to convert to93 // millimetres or metres from an unknown unit rather than guess one.94 p("model.stl-print", "3D", "STL for printing (binary)", "Binary STL, vertices welded, units and orientation unchanged.", .category(.model3D), .obj, .stl, nil, ["encoding": .string("binary"), "weld.mode": .string("exact")]),95 p("model.glb-web", "3D", "GLB for web", "One self-contained binary glTF file with materials and textures.", .category(.model3D), .obj, .glb, nil, ["materials.write": .bool(true), "textures.write": .bool(true)]),96 // Archives (any files and folders)97 p("archive.zip", "Archive", "ZIP (compatible)", "A ZIP archive every system opens; macOS housekeeping files left out.", .any, .folder, .zip, "archive.create",98 ["compression.level": .string("normal"), "exclude.macos": .bool(true)], generic: true),99 p("archive.7z", "Archive", "7z (smallest)", "7z with maximum LZMA2 compression (slow).", .any, .folder, .sevenZip, "archive.create", ["compression.level": .string("maximum")], generic: true),100 p("archive.tar-zst", "Archive", "tar.zst (fast)", "TAR compressed with Zstandard: very fast, good ratio.", .any, .folder, .tzst, "archive.create", ["compression.level": .string("fast")], generic: true),101 ]102103 struct Rejection: Sendable { let key: String; let reason: String }104105 /// Why a preset cannot be offered in this build, or `nil` when everything it names exists.106 static func problem(with preset: BuiltInPreset, registry: FormatRegistry) -> String? {107 guard let plan = try? ConversionPlanner(registry: registry).plan(from: preset.sample, to: preset.destination, operation: preset.operation, allowChaining: false),108 let path = plan.steps.last, let engine = registry.engine(id: path.engine) else {109 return "no \(preset.sample.rawValue) → \(preset.destination.rawValue)\(preset.operation.map { " #" + $0 } ?? "") path in this build"110 }111 let descriptors = Dictionary(engine.options(for: path).map { ($0.id, $0) }, uniquingKeysWith: { first, _ in first })112 for (key, value) in preset.options.sorted(by: { $0.key < $1.key }) {113 guard let descriptor = descriptors[key] else { return "unknown option “\(key)” for \(path.id)" }114 switch (descriptor.kind, value) {115 case (.toggle, .bool): break116 case (.integer(_, let range, _), .int(let v)): if !range.contains(v) { return "“\(key)” = \(v) is outside \(range.lowerBound)…\(range.upperBound)" }117 case (.number(_, let range, _, _), .double(let v)): if !range.contains(v) { return "“\(key)” = \(v) is outside \(range.lowerBound)…\(range.upperBound)" }118 case (.number(_, let range, _, _), .int(let v)): if !range.contains(Double(v)) { return "“\(key)” = \(v) is outside \(range.lowerBound)…\(range.upperBound)" }119 case (.choice(_, let choices), .string(let v)): if !choices.contains(where: { $0.value == v }) { return "“\(key)” has no choice “\(v)” (\(choices.map(\.value).joined(separator: ", ")))" }120 case (.text, .string): break121 default: return "“\(key)” has the wrong type of value"122 }123 }124 return nil125 }126127 /// The presets this build can really run, and the ones left out with the reason (logged).128 static func validated(in registry: FormatRegistry) -> (valid: [BuiltInPreset], rejected: [Rejection]) {129 var valid: [BuiltInPreset] = [], rejected: [Rejection] = []130 for preset in all {131 if let reason = problem(with: preset, registry: registry) {132 rejected.append(Rejection(key: preset.key, reason: reason))133 log.error("Built-in preset \(preset.key, privacy: .public) is not offered: \(reason, privacy: .public)")134 } else {135 valid.append(preset)136 }137 }138 return (valid, rejected)139 }140141 /// Text listing the option descriptors of `source>destination[#operation]` paths (development aid behind142 /// `ORIX_DUMP_OPTIONS`).143 static func describeOptions(_ specs: [String], registry: FormatRegistry) -> String {144 var out = ""145 for spec in specs {146 let halves = spec.split(separator: "#", maxSplits: 1).map(String.init)147 let pair = halves[0].split(separator: ">").map(String.init)148 guard pair.count == 2 else { continue }149 let operation = halves.count > 1 ? halves[1] : nil150 out += "== \(spec)\n"151 guard let plan = try? ConversionPlanner(registry: registry).plan(from: FormatID(pair[0]), to: FormatID(pair[1]), operation: operation, allowChaining: false),152 let path = plan.steps.last, let engine = registry.engine(id: path.engine) else { out += " (no path)\n"; continue }153 for d in engine.options(for: path) {154 let kind: String = switch d.kind {155 case .toggle(let v): "toggle \(v)"156 case .integer(let v, let r, let u): "int \(v) in \(r.lowerBound)…\(r.upperBound) \(u ?? "")"157 case .number(let v, let r, _, let u): "number \(v) in \(r.lowerBound)…\(r.upperBound) \(u ?? "")"158 case .choice(let v, let c): "choice \(v) of [\(c.map(\.value).joined(separator: ", "))]"159 case .text(let v, _): "text “\(v)”"160 }161 out += " \(d.id): \(kind)\n"162 }163 }164 return out165 }166}167