// 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 AVFoundationimportCottonMailboximportCottonValuesimportFoundationimportImageIOimportUniformTypeIdentifiers/// 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.publicstructFilmFile: Sendable, Equatable {publicvar url: URLpublicvar sourcePath: String/// What lies in its folder, where it came from one.publicvar beside: FilmFolder?/// An episode's series' folder, above its season's.publicvar seriesBeside: FilmFolder?publicinit(url: URL, sourcePath: String, beside: FilmFolder? = nil, seriesBeside: FilmFolder? = nil) {self.url = urlself.sourcePath = sourcePathself.beside = besideself.seriesBeside = seriesBeside }}/// What the phone read of one file, as `films.capture` takes it.publicstructFilmFacts: Encodable, Sendable, Equatable {publicvar path: Stringpublicvar sourcePath: Stringpublicvar minutes: Double?publicvar video: String?publicvar audio: String?publicvar height: Int?publicvar bitrate: Int?publicvar title: String?publicvar year: String?publicvar posterPath: String?publicvar locked: Bool?/// A title and a year the person typed: they beat every other.publicvar typedTitle: String?publicvar typedYear: String?publicvar beside: FilmFolder?publicvar seriesBeside: FilmFolder?/// The file's own chapter marks.publicvar chapters: [FilmChapter]?publicinit(path: String, sourcePath: String) {self.path = pathself.sourcePath = sourcePath }}/// What one file came to (`films.capture`'s answer).publicstructFilmOutcome: Decodable, Sendable, Equatable {/// `added`, `here`, `better`, `worse`, `refused` or `not_film`.publicvar outcome: Stringpublicvar sourcePath: String?publicvar id: String?publicvar key: String?/// `film` or `film_episode`, where the core names it.publicvar table: String?/// An episode's series (a `film` row), where the core names it.publicvar series: String?publicvar needsMac: Bool?publicvar title: String?publicvar line: String?publicinit(outcome: String, sourcePath: String? = nil, id: String? = nil, table: String? = nil, series: String? = nil, title: String? = nil, line: String? = nil) {self.outcome = outcomeself.sourcePath = sourcePathself.id = idself.table = tableself.series = seriesself.title = titleself.line = line }}/// What a whole intake came to.publicstructFilmIntakeResult: Sendable, Equatable {publicvar outcomes: [FilmOutcome]/// What to tell the person, in the core's words.publicvar 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).publicvar landing: (table: String, id: String)? {let named = { (outcome: FilmOutcome) -> (table: String, id: String)? inif outcome.table == "film_episode", let series = outcome.series { return ("film", series) }guardlet table = outcome.table, let id = outcome.id else { returnnil }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'.publicvar notFilms: [String] { outcomes.filter { $0.outcome == "not_film" }.compactMap(\.sourcePath) }publicstaticfunc == (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.publictypealiasReading = @Sendable (_ file: FilmFile, _ scratch: URL) async -> FilmFactsprivatelet core: any CottonCallingprivatelet 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.privatelet progress: @Sendable (_ done: Int, _ total: Int, _ reading: Bool) -> Voidpublicinit(core: any CottonCalling, read: @escaping Reading = FilmFactsReader.read, progress: @escaping @Sendable (_ done: Int, _ total: Int, _ reading: Bool) -> Void = { _, _, _ in }) {self.core = coreself.read = readself.progress = progress }structRequest: Encodable {var films: [FilmFacts]var onlyFilms: Bool }privatestructAnswer: Decodable {var films: [FilmOutcome]var said: String? }/// The most files one capture takes: the core's own ceiling.publicstaticlet mostInOne = 200/// Bring `files` in: read, then handed over two hundred at a time./// `onlyFilms` (Cotton's drain) keeps only films.publicfunc bring(_ files: [FilmFile], onlyFilms: Bool) asyncthrows -> FilmIntakeResult {guard !files.isEmpty else { returnFilmIntakeResult(outcomes: [], said: nil) }let scratch = FileManager.default.temporaryDirectory.appendingPathComponent("film-intake-\(UUID().uuidString)", isDirectory: true)tryFileManager.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 inSelf.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 = tryawait 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" }.countif added > 0 { said = FilmLines.addedMany(added) } }returnFilmIntakeResult(outcomes: outcomes, said: said) }/// `files` in turns the core takes, in their order.staticfunc 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.publicstaticfunc films(in folder: URL, named name: String) -> [FilmFile] {let root = folder.standardizedFileURL.path(percentEncoded: false)guardlet walk = FileManager.default.enumerator(at: folder, includingPropertiesForKeys: [.isRegularFileKey], options: [.skipsHiddenFiles, .skipsPackageDescendants]) else { return [] }var found: [FilmFile] = []var folders: [URL: FilmFolder] = [:]let read = { (directory: URL) -> FilmFolderiniflet known = folders[directory] { return known }let folder = FilmSidecars.folder(at: directory) folders[directory] = folderreturn folder }forcaselet 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.lastPathComponentlet 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.publicenumFilmFactsReader {/// The containers AVFoundation opens; any other (MKV, AVI) is sent by/// its path alone.staticlet readable: Set<String> = ["mp4", "m4v", "mov"]/// The poster's frame: this far into the film, as a share of its length.staticlet posterAt = 0.1/// The poster's longest side, in pixels.staticlet posterPixels = 1280publicstaticlet read: FilmIntake.Reading = { file, scratch invar facts = FilmFacts(path: file.url.path(percentEncoded: false), sourcePath: file.sourcePath)guardFilmFactsReader.readable.contains(file.url.pathExtension.lowercased()) else { return facts }let asset = AVURLAsset(url: file.url)guardlet loaded = try? await asset.load(.duration, .hasProtectedContent, .commonMetadata) else { return facts }let (length, locked, common) = loadedif length.isNumeric, length.seconds > 0 { facts.minutes = length.seconds / 60 } facts.locked = lockediflet 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()) } }iflet 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 = awaitFilmFactsReader.text(common, .commonIdentifierTitle) facts.year = awaitFilmFactsReader.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 = awaitFilmFactsReader.chapters(asset)let poster = scratch.appendingPathComponent("\(UUID().uuidString).jpg")iflet art = awaitFilmFactsReader.artwork(common), FilmFactsReader.write(art, to: poster) { facts.posterPath = poster.path(percentEncoded: false) } elseiflet frame = awaitFilmFactsReader.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`).staticfunc fourCC(_ code: FourCharCode) -> String {let bytes = [24, 16, 8, 0].map { UInt8((code >> $0) & 0xFF) }returnString(decoding: bytes, as: UTF8.self).trimmingCharacters(in: .whitespaces) }/// A tag's year: the four digits a date begins with.staticfunc year(_ said: String) -> String? {let digits = said.prefix(4)return digits.count == 4 && digits.allSatisfy(\.isNumber) ? String(digits) : nil }privatestaticfunc text(_ items: [AVMetadataItem], _ identifier: AVMetadataIdentifier) async -> String? {guardlet item = AVMetadataItem.metadataItems(from: items, filteredByIdentifier: identifier).first,let said = try? await item.load(.stringValue)?.trimmingCharacters(in: .whitespacesAndNewlines), !said.isEmpty else { returnnil }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.staticfunc chapters(_ asset: AVURLAsset) async -> [FilmChapter]? {guardlet locales = try? await asset.load(.availableChapterLocales), let locale = locales.first,let groups = try? await asset.loadChapterMetadataGroups(withTitleLocale: locale, containingItemsWithCommonKeys: [.commonKeyTitle]), groups.count > 1else { returnnil }var marks: [FilmChapter] = []for (at, group) in groups.enumerated() where group.timeRange.start.isNumeric && group.timeRange.start.seconds >= 0 {let named = awaitFilmFactsReader.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 }privatestaticfunc artwork(_ items: [AVMetadataItem]) async -> CGImage? {guardlet item = AVMetadataItem.metadataItems(from: items, filteredByIdentifier: .commonIdentifierArtwork).first,let data = try? await item.load(.dataValue),let source = CGImageSourceCreateWithData(data as CFData, nil) else { returnnil }let options: [CFString: Any] = [kCGImageSourceCreateThumbnailFromImageAlways: true, kCGImageSourceThumbnailMaxPixelSize: posterPixels, kCGImageSourceCreateThumbnailWithTransform: true]return CGImageSourceCreateThumbnailAtIndex(source, 0, options as CFDictionary) }privatestaticfunc 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) : .zeroreturntry? await generator.image(at: at).image }privatestaticfunc write(_ image: CGImage, to url: URL) -> Bool {guardlet out = CGImageDestinationCreateWithURL(url as CFURL, UTType.jpeg.identifier as CFString, 1, nil) else { returnfalse } 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.enumFilmLines {staticfunc addedMany(_ count: Int) -> String {ShellLines.line("cinemas", "intake.added_many", ["count": String(count)]) }}