// Cotton Cinemas' intake (5 Nov 2026, definition section 6): films come in // through the share sheet, Plus › Add files and Plus › Add a folder, all into // one door. Each file's facts are read here with AVFoundation, off the main // thread: its length, its codecs, its picture's height, its bitrate, its tags' // title and year, whether its seller locked it, and a frame of it (or its // artwork) as a poster. Two hundred at a time they are handed to the core // (`films.capture`), which reads the rest from each file's path // (`Series/Season 02/S02E05 - Title.mkv`) and keeps the file. // // A file from a folder carries what lies beside it (`FilmSidecars`): every // name in its folder, each NFO's text, each subtitle's and picture's path, and // an episode's series' folder the same; the core picks what it keeps. Its // chapter marks are read where AVFoundation opens it; an MKV's only ffprobe // reads, so none are handed for one. // // An MKV or an AVI AVFoundation cannot open: only its path is sent, nothing // guessed. In Cotton (`onlyFilms`) the core keeps only a film, and answers // `not_film` for a clip, which Photos keeps instead (`ShareIntake`). import AVFoundation import CottonMailbox import CottonValues import Foundation import ImageIO import UniformTypeIdentifiers /// One file to bring in: where its bytes are, and the path it came in as /// (`Series/Season 02/S02E05 - Title.mkv` from a folder, its own name from the /// share sheet), which says what it is. public struct FilmFile: Sendable, Equatable { public var url: URL public var sourcePath: String /// What lies in its folder, where it came from one. public var beside: FilmFolder? /// An episode's series' folder, above its season's. public var seriesBeside: FilmFolder? public init(url: URL, sourcePath: String, beside: FilmFolder? = nil, seriesBeside: FilmFolder? = nil) { self.url = url self.sourcePath = sourcePath self.beside = beside self.seriesBeside = seriesBeside } } /// What the phone read of one file, as `films.capture` takes it. public struct FilmFacts: Encodable, Sendable, Equatable { public var path: String public var sourcePath: String public var minutes: Double? public var video: String? public var audio: String? public var height: Int? public var bitrate: Int? public var title: String? public var year: String? public var posterPath: String? public var locked: Bool? /// A title and a year the person typed: they beat every other. public var typedTitle: String? public var typedYear: String? public var beside: FilmFolder? public var seriesBeside: FilmFolder? /// The file's own chapter marks. public var chapters: [FilmChapter]? public init(path: String, sourcePath: String) { self.path = path self.sourcePath = sourcePath } } /// What one file came to (`films.capture`'s answer). public struct FilmOutcome: Decodable, Sendable, Equatable { /// `added`, `here`, `better`, `worse`, `refused` or `not_film`. public var outcome: String public var sourcePath: String? public var id: String? public var key: String? /// `film` or `film_episode`, where the core names it. public var table: String? /// An episode's series (a `film` row), where the core names it. public var series: String? public var needsMac: Bool? public var title: String? public var line: String? public init(outcome: String, sourcePath: String? = nil, id: String? = nil, table: String? = nil, series: String? = nil, title: String? = nil, line: String? = nil) { self.outcome = outcome self.sourcePath = sourcePath self.id = id self.table = table self.series = series self.title = title self.line = line } } /// What a whole intake came to. public struct FilmIntakeResult: Sendable, Equatable { public var outcomes: [FilmOutcome] /// What to tell the person, in the core's words. public var said: String? /// The record to open: the last film or episode that came in, else the /// last already here; only where the core named its table. An episode /// opens its series: a film row, which Cinemas' views draw (an episode's /// own table is no view of theirs, and stood there with no Plus). public var landing: (table: String, id: String)? { let named = { (outcome: FilmOutcome) -> (table: String, id: String)? in if outcome.table == "film_episode", let series = outcome.series { return ("film", series) } guard let table = outcome.table, let id = outcome.id else { return nil } return (table, id) } return outcomes.last(where: { ["added", "better"].contains($0.outcome) && named($0) != nil }).flatMap(named) ?? outcomes.last(where: { ["here", "worse"].contains($0.outcome) && named($0) != nil }).flatMap(named) } /// The files the core said are no films (Cotton's `onlyFilms`): Photos'. public var notFilms: [String] { outcomes.filter { $0.outcome == "not_film" }.compactMap(\.sourcePath) } public static func == (lhs: Self, rhs: Self) -> Bool { lhs.outcomes == rhs.outcomes && lhs.said == rhs.said } } public actor FilmIntake { /// How one file's facts are read; AVFoundation's (`FilmFactsReader`) /// unless a test hands in its own. public typealias Reading = @Sendable (_ file: FilmFile, _ scratch: URL) async -> FilmFacts private let core: any CottonCalling private let read: Reading /// How far it has got: files read and brought in, of all of them, and /// whether the first of them are still being read. private let progress: @Sendable (_ done: Int, _ total: Int, _ reading: Bool) -> Void public init(core: any CottonCalling, read: @escaping Reading = FilmFactsReader.read, progress: @escaping @Sendable (_ done: Int, _ total: Int, _ reading: Bool) -> Void = { _, _, _ in }) { self.core = core self.read = read self.progress = progress } struct Request: Encodable { var films: [FilmFacts] var onlyFilms: Bool } private struct Answer: Decodable { var films: [FilmOutcome] var said: String? } /// The most files one capture takes: the core's own ceiling. public static let mostInOne = 200 /// Bring `files` in: read, then handed over two hundred at a time. /// `onlyFilms` (Cotton's drain) keeps only films. public func bring(_ files: [FilmFile], onlyFilms: Bool) async throws -> FilmIntakeResult { guard !files.isEmpty else { return FilmIntakeResult(outcomes: [], said: nil) } let scratch = FileManager.default.temporaryDirectory.appendingPathComponent("film-intake-\(UUID().uuidString)", isDirectory: true) try FileManager.default.createDirectory(at: scratch, withIntermediateDirectories: true) defer { try? FileManager.default.removeItem(at: scratch) } var outcomes: [FilmOutcome] = [] var said: String? var done = 0 progress(0, files.count, true) for batch in Self.batches(files) { var films: [FilmFacts] = [] for file in batch { var facts = await read(file, scratch) facts.beside = file.beside facts.seriesBeside = file.seriesBeside films.append(facts) } let answer = try await core.call(CottonMethod.filmsCapture, Request(films: films, onlyFilms: onlyFilms), as: Answer.self) outcomes += answer.films said = answer.said ?? said done += batch.count progress(done, files.count, false) } if files.count > Self.mostInOne { let added = outcomes.filter { $0.outcome == "added" }.count if added > 0 { said = FilmLines.addedMany(added) } } return FilmIntakeResult(outcomes: outcomes, said: said) } /// `files` in turns the core takes, in their order. static func batches(_ files: [FilmFile]) -> [[FilmFile]] { stride(from: 0, to: files.count, by: mostInOne).map { Array(files[$0 ..< min($0 + mostInOne, files.count)]) } } /// Every film file under `folder`, deepest too, each named by its path /// under `name` — what the folder is called where it came from (the /// folder above it too, from a picker) — so /// `Series/Season 02/S02E05 - Title.mkv` reads whichever was picked; each /// with what lies beside it, and an episode in a season's folder with its /// series' folder. The caller holds the folder's security-scoped access /// while it brings them in. public static func films(in folder: URL, named name: String) -> [FilmFile] { let root = folder.standardizedFileURL.path(percentEncoded: false) guard let walk = FileManager.default.enumerator(at: folder, includingPropertiesForKeys: [.isRegularFileKey], options: [.skipsHiddenFiles, .skipsPackageDescendants]) else { return [] } var found: [FilmFile] = [] var folders: [URL: FilmFolder] = [:] let read = { (directory: URL) -> FilmFolder in if let known = folders[directory] { return known } let folder = FilmSidecars.folder(at: directory) folders[directory] = folder return folder } for case let url as URL in walk where filmFileExtensions.contains(url.pathExtension.lowercased()) { let full = url.standardizedFileURL.path(percentEncoded: false) let below = full.hasPrefix(root) ? String(full.dropFirst(root.count)) : url.lastPathComponent let path = [name, below].map { $0.trimmingCharacters(in: CharacterSet(charactersIn: "/")) }.filter { !$0.isEmpty }.joined(separator: "/") let series = FilmSidecars.seriesDirectory(of: url, sourcePath: path, root: folder).map(read) found.append(FilmFile(url: url, sourcePath: path, beside: read(url.deletingLastPathComponent().standardizedFileURL), seriesBeside: series)) } return found.sorted { $0.sourcePath.localizedStandardCompare($1.sourcePath) == .orderedAscending } } } /// AVFoundation's reading of a film file. public enum FilmFactsReader { /// The containers AVFoundation opens; any other (MKV, AVI) is sent by /// its path alone. static let readable: Set = ["mp4", "m4v", "mov"] /// The poster's frame: this far into the film, as a share of its length. static let posterAt = 0.1 /// The poster's longest side, in pixels. static let posterPixels = 1280 public static let read: FilmIntake.Reading = { file, scratch in var facts = FilmFacts(path: file.url.path(percentEncoded: false), sourcePath: file.sourcePath) guard FilmFactsReader.readable.contains(file.url.pathExtension.lowercased()) else { return facts } let asset = AVURLAsset(url: file.url) guard let loaded = try? await asset.load(.duration, .hasProtectedContent, .commonMetadata) else { return facts } let (length, locked, common) = loaded if length.isNumeric, length.seconds > 0 { facts.minutes = length.seconds / 60 } facts.locked = locked if let video = try? await asset.loadTracks(withMediaType: .video).first, let loaded = try? await video.load(.formatDescriptions, .naturalSize, .preferredTransform, .estimatedDataRate) { let (formats, size, turn, rate) = loaded facts.video = formats.first.map { FilmFactsReader.fourCC(CMFormatDescriptionGetMediaSubType($0)) } let height = abs(size.applying(turn).height) if height > 0 { facts.height = Int(height.rounded()) } if rate > 0 { facts.bitrate = Int((Double(rate) / 1000).rounded()) } } if let audio = try? await asset.loadTracks(withMediaType: .audio).first, let formats = try? await audio.load(.formatDescriptions) { facts.audio = formats.first.map { FilmFactsReader.fourCC(CMFormatDescriptionGetMediaSubType($0)) } } facts.title = await FilmFactsReader.text(common, .commonIdentifierTitle) facts.year = await FilmFactsReader.text(common, .commonIdentifierCreationDate).flatMap(FilmFactsReader.year) // A locked file is never opened further: no frame is taken of it. guard !locked else { return facts } facts.chapters = await FilmFactsReader.chapters(asset) let poster = scratch.appendingPathComponent("\(UUID().uuidString).jpg") if let art = await FilmFactsReader.artwork(common), FilmFactsReader.write(art, to: poster) { facts.posterPath = poster.path(percentEncoded: false) } else if let frame = await FilmFactsReader.frame(asset, at: length), FilmFactsReader.write(frame, to: poster) { facts.posterPath = poster.path(percentEncoded: false) } return facts } /// A four-character code as AVFoundation names a codec (`avc1`, `mp4a`). static func fourCC(_ code: FourCharCode) -> String { let bytes = [24, 16, 8, 0].map { UInt8((code >> $0) & 0xFF) } return String(decoding: bytes, as: UTF8.self).trimmingCharacters(in: .whitespaces) } /// A tag's year: the four digits a date begins with. static func year(_ said: String) -> String? { let digits = said.prefix(4) return digits.count == 4 && digits.allSatisfy(\.isNumber) ? String(digits) : nil } private static func text(_ items: [AVMetadataItem], _ identifier: AVMetadataIdentifier) async -> String? { guard let item = AVMetadataItem.metadataItems(from: items, filteredByIdentifier: identifier).first, let said = try? await item.load(.stringValue)?.trimmingCharacters(in: .whitespacesAndNewlines), !said.isEmpty else { return nil } return said } /// The file's own chapter marks: where each starts and its title, a mark /// with none named by its number. None where it has fewer than two. static func chapters(_ asset: AVURLAsset) async -> [FilmChapter]? { guard let locales = try? await asset.load(.availableChapterLocales), let locale = locales.first, let groups = try? await asset.loadChapterMetadataGroups(withTitleLocale: locale, containingItemsWithCommonKeys: [.commonKeyTitle]), groups.count > 1 else { return nil } var marks: [FilmChapter] = [] for (at, group) in groups.enumerated() where group.timeRange.start.isNumeric && group.timeRange.start.seconds >= 0 { let named = await FilmFactsReader.text(group.items, .commonIdentifierTitle) marks.append(FilmChapter(startMs: Int((group.timeRange.start.seconds * 1000).rounded()), title: named ?? String(at + 1))) } return marks.count > 1 ? marks : nil } private static func artwork(_ items: [AVMetadataItem]) async -> CGImage? { guard let item = AVMetadataItem.metadataItems(from: items, filteredByIdentifier: .commonIdentifierArtwork).first, let data = try? await item.load(.dataValue), let source = CGImageSourceCreateWithData(data as CFData, nil) else { return nil } let options: [CFString: Any] = [kCGImageSourceCreateThumbnailFromImageAlways: true, kCGImageSourceThumbnailMaxPixelSize: posterPixels, kCGImageSourceCreateThumbnailWithTransform: true] return CGImageSourceCreateThumbnailAtIndex(source, 0, options as CFDictionary) } private static func frame(_ asset: AVURLAsset, at length: CMTime) async -> CGImage? { let generator = AVAssetImageGenerator(asset: asset) generator.appliesPreferredTrackTransform = true generator.maximumSize = CGSize(width: posterPixels, height: posterPixels) let at = length.isNumeric ? CMTimeMultiplyByFloat64(length, multiplier: posterAt) : .zero return try? await generator.image(at: at).image } private static func write(_ image: CGImage, to url: URL) -> Bool { guard let out = CGImageDestinationCreateWithURL(url as CFURL, UTType.jpeg.identifier as CFString, 1, nil) else { return false } CGImageDestinationAddImage(out, image, [kCGImageDestinationLossyCompressionQuality: 0.85] as CFDictionary) return CGImageDestinationFinalize(out) } } /// The intake's words where the core says none: from the shell's cinemas set. enum FilmLines { static func addedMany(_ count: Int) -> String { ShellLines.line("cinemas", "intake.added_many", ["count": String(count)]) } }