Created
June 2, 2020 22:25
-
-
Save pd95/434989d926e3e8a5fd7c852b5981419a to your computer and use it in GitHub Desktop.
Swift Playground code showing how to convert a video from H264 (in my case) to HEVC/H265 using AVFoundation
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import AVFoundation | |
// Get test video from bundle | |
let url = Bundle.main.url(forResource: "test", withExtension: "mp4")! | |
let anAsset = AVURLAsset(url: url) | |
// get properties of video track | |
let track = anAsset.tracks(withMediaType: AVMediaType.video).first! | |
let size = track.naturalSize.applying(track.preferredTransform) | |
let frameSize = CGSize(width: abs(size.width), height: abs(size.height)) | |
let frameRate = track.nominalFrameRate | |
let bps = track.estimatedDataRate | |
let duration = anAsset.duration.seconds | |
let fileSize = Double(bps) * duration / 8 | |
// We want half the size... | |
let desiredHEVCFileSize = Int64(fileSize / 2) | |
// Location of exported HEVC file | |
let outputUrl = FileManager.default.urls(for: .moviesDirectory, in: .userDomainMask).first!.appendingPathComponent("RocketSim/output-\(Int(Date().timeIntervalSinceReferenceDate)).mp4") | |
//print("All export presets: ", AVAssetExportSession.exportPresets(compatibleWith: anAsset)) | |
var preset = AVAssetExportPresetHEVCHighestQuality | |
let outFileType = AVFileType.m4v | |
AVAssetExportSession.determineCompatibility(ofExportPreset: preset, with: anAsset, outputFileType: outFileType, completionHandler: { (isCompatible) in | |
if !isCompatible { | |
print("incompatible") | |
return | |
} | |
guard let export = AVAssetExportSession(asset: anAsset, presetName: preset) else { | |
print("Unable to create AVAssetExportSession...") | |
return | |
} | |
export.shouldOptimizeForNetworkUse = true | |
export.canPerformMultiplePassesOverSourceMediaData = true | |
export.fileLengthLimit = desiredHEVCFileSize | |
export.outputFileType = outFileType | |
export.outputURL = outputUrl | |
print("Exporting...") | |
export.exportAsynchronously { () -> Void in | |
// Handle export results. | |
print("Done exporting to \(outputUrl.path)") | |
} | |
} | |
) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment