|
| 1 | +import AVFoundation |
| 2 | + |
| 3 | +// MARK: - UpscalingExportSession |
| 4 | + |
| 5 | +public class UpscalingExportSession { |
| 6 | + // MARK: Lifecycle |
| 7 | + |
| 8 | + public init( |
| 9 | + asset: AVAsset, |
| 10 | + outputURL: URL, |
| 11 | + outputFileType: AVFileType, |
| 12 | + outputSize: CGSize |
| 13 | + ) { |
| 14 | + self.asset = asset |
| 15 | + self.outputURL = outputURL |
| 16 | + self.outputFileType = outputFileType |
| 17 | + self.outputSize = outputSize |
| 18 | + } |
| 19 | + |
| 20 | + // MARK: Public |
| 21 | + |
| 22 | + public static let maxSize = 16384 |
| 23 | + |
| 24 | + public let asset: AVAsset |
| 25 | + public let outputURL: URL |
| 26 | + public let outputFileType: AVFileType |
| 27 | + public let outputSize: CGSize |
| 28 | + |
| 29 | + public func export() async throws { |
| 30 | + guard !FileManager.default.fileExists(atPath: outputURL.path(percentEncoded: false)) else { |
| 31 | + throw Error.outputURLAlreadyExists |
| 32 | + } |
| 33 | + let assetReader = try AVAssetReader(asset: asset) |
| 34 | + let assetWriter = try AVAssetWriter(outputURL: outputURL, fileType: outputFileType) |
| 35 | + assetWriter.metadata = try await asset.load(.metadata) |
| 36 | + |
| 37 | + let assetDuration = try await asset.load(.duration) |
| 38 | + |
| 39 | + for track in try await asset.load(.tracks) { |
| 40 | + switch track.mediaType { |
| 41 | + case .video: |
| 42 | + let naturalSize = try await track.load(.naturalSize) |
| 43 | + let nominalFrameRate = try await track.load(.nominalFrameRate) |
| 44 | + let formatDescription = try await track.load(.formatDescriptions).first |
| 45 | + |
| 46 | + let videoOutput = AVAssetReaderVideoCompositionOutput( |
| 47 | + videoTracks: [track], |
| 48 | + videoSettings: nil |
| 49 | + ) |
| 50 | + |
| 51 | + videoOutput.alwaysCopiesSampleData = false |
| 52 | + videoOutput.videoComposition = { |
| 53 | + let videoComposition = AVMutableVideoComposition() |
| 54 | + videoComposition.customVideoCompositorClass = UpscalingCompositor.self |
| 55 | + videoComposition.colorPrimaries = formatDescription?.colorPrimaries |
| 56 | + videoComposition.colorTransferFunction = formatDescription?.colorTransferFunction |
| 57 | + videoComposition.colorYCbCrMatrix = formatDescription?.colorYCbCrMatrix |
| 58 | + videoComposition.frameDuration = CMTime( |
| 59 | + value: 1, |
| 60 | + timescale: nominalFrameRate > 0 ? CMTimeScale(nominalFrameRate) : 30 |
| 61 | + ) |
| 62 | + videoComposition.renderSize = outputSize |
| 63 | + let instruction = AVMutableVideoCompositionInstruction() |
| 64 | + instruction.timeRange = CMTimeRange(start: .zero, duration: assetDuration) |
| 65 | + let layerInstruction = AVMutableVideoCompositionLayerInstruction(assetTrack: track) |
| 66 | + instruction.layerInstructions = [layerInstruction] |
| 67 | + videoComposition.instructions = [instruction] |
| 68 | + return videoComposition |
| 69 | + }() |
| 70 | + (videoOutput.customVideoCompositor as! UpscalingCompositor).inputSize = naturalSize |
| 71 | + (videoOutput.customVideoCompositor as! UpscalingCompositor).outputSize = outputSize |
| 72 | + |
| 73 | + if assetReader.canAdd(videoOutput) { |
| 74 | + assetReader.add(videoOutput) |
| 75 | + } else { |
| 76 | + throw Error.couldNotAddAssetReaderVideoOutput |
| 77 | + } |
| 78 | + |
| 79 | + let videoCodec = formatDescription?.videoCodecType ?? .hevc |
| 80 | + let videoInput = AVAssetWriterInput(mediaType: .video, outputSettings: [ |
| 81 | + AVVideoWidthKey: outputSize.width, |
| 82 | + AVVideoHeightKey: outputSize.height, |
| 83 | + AVVideoCodecKey: videoCodec |
| 84 | + ]) |
| 85 | + videoInput.expectsMediaDataInRealTime = false |
| 86 | + if assetWriter.canAdd(videoInput) { |
| 87 | + assetWriter.add(videoInput) |
| 88 | + } else { |
| 89 | + throw Error.couldNotAddAssetWriterVideoInput |
| 90 | + } |
| 91 | + case .audio: |
| 92 | + let audioOutput = AVAssetReaderAudioMixOutput(audioTracks: [track], audioSettings: nil) |
| 93 | + audioOutput.alwaysCopiesSampleData = false |
| 94 | + if assetReader.canAdd(audioOutput) { |
| 95 | + assetReader.add(audioOutput) |
| 96 | + } else { |
| 97 | + throw Error.couldNotAddAssetReaderAudioOutput |
| 98 | + } |
| 99 | + |
| 100 | + let audioInput = AVAssetWriterInput(mediaType: .audio, outputSettings: nil) |
| 101 | + audioInput.expectsMediaDataInRealTime = false |
| 102 | + if assetWriter.canAdd(audioInput) { |
| 103 | + assetWriter.add(audioInput) |
| 104 | + } else { |
| 105 | + throw Error.couldNotAddAssetWriterAudioInput |
| 106 | + } |
| 107 | + default: continue |
| 108 | + } |
| 109 | + } |
| 110 | + |
| 111 | + assert(assetWriter.inputs.count == assetReader.outputs.count) |
| 112 | + |
| 113 | + assetWriter.startWriting() |
| 114 | + assetReader.startReading() |
| 115 | + assetWriter.startSession(atSourceTime: .zero) |
| 116 | + |
| 117 | + await withCheckedContinuation { continuation in |
| 118 | + // - Returns: Whether or not the input has read all available media data |
| 119 | + @Sendable func copyReadySamples(from output: AVAssetReaderOutput, to input: AVAssetWriterInput) -> Bool { |
| 120 | + while input.isReadyForMoreMediaData { |
| 121 | + if let sampleBuffer = output.copyNextSampleBuffer() { |
| 122 | + if !input.append(sampleBuffer) { |
| 123 | + return true |
| 124 | + } |
| 125 | + } else { |
| 126 | + input.markAsFinished() |
| 127 | + return true |
| 128 | + } |
| 129 | + } |
| 130 | + return false |
| 131 | + } |
| 132 | + |
| 133 | + @Sendable func finish() { |
| 134 | + if assetWriter.status == .failed { |
| 135 | + try? FileManager.default.removeItem(at: outputURL) |
| 136 | + continuation.resume() |
| 137 | + } else if assetReader.status == .failed { |
| 138 | + assetWriter.cancelWriting() |
| 139 | + if [.cancelled, .failed].contains(assetWriter.status) { |
| 140 | + try? FileManager.default.removeItem(at: outputURL) |
| 141 | + } |
| 142 | + continuation.resume() |
| 143 | + } else { |
| 144 | + assetWriter.finishWriting { |
| 145 | + if [.cancelled, .failed].contains(assetWriter.status) { |
| 146 | + try? FileManager.default.removeItem(at: self.outputURL) |
| 147 | + } |
| 148 | + continuation.resume() |
| 149 | + } |
| 150 | + } |
| 151 | + } |
| 152 | + |
| 153 | + actor FinishCount { |
| 154 | + var isFinished: Bool { count >= finishCount } |
| 155 | + private var count = 0 |
| 156 | + private let finishCount: Int |
| 157 | + func increment() { count += 1 } |
| 158 | + init(finishCount: Int) { self.finishCount = finishCount } |
| 159 | + } |
| 160 | + let finishCount = FinishCount(finishCount: assetWriter.inputs.count) |
| 161 | + |
| 162 | + let queue = DispatchQueue(label: String(describing: Self.self)) |
| 163 | + for (input, output) in zip(assetWriter.inputs, assetReader.outputs) { |
| 164 | + input.requestMediaDataWhenReady(on: queue) { |
| 165 | + let finishedReading = copyReadySamples(from: output, to: input) |
| 166 | + if finishedReading { |
| 167 | + Task { |
| 168 | + await finishCount.increment() |
| 169 | + if await finishCount.isFinished { finish() } |
| 170 | + } |
| 171 | + } |
| 172 | + } |
| 173 | + } |
| 174 | + } as Void |
| 175 | + } |
| 176 | +} |
| 177 | + |
| 178 | +// MARK: UpscalingExportSession.Error |
| 179 | + |
| 180 | +extension UpscalingExportSession { |
| 181 | + enum Error: Swift.Error { |
| 182 | + case outputURLAlreadyExists |
| 183 | + case couldNotAddAssetReaderVideoOutput |
| 184 | + case couldNotAddAssetWriterVideoInput |
| 185 | + case couldNotAddAssetReaderAudioOutput |
| 186 | + case couldNotAddAssetWriterAudioInput |
| 187 | + } |
| 188 | +} |
0 commit comments