-
Notifications
You must be signed in to change notification settings - Fork 8
/
Copy pathVideoEditor.swift
205 lines (177 loc) · 7.4 KB
/
VideoEditor.swift
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
import Foundation
import AVFoundation
import UIKit
@objc public class VideoEditor: NSObject {
var exportSession: AVAssetExportSession!
var exportProgressBarTimer = Timer()
@objc public func edit(
srcFile: URL,
outFile: URL,
trimSettings: TrimSettings,
transcodeSettings: TranscodeSettings,
completionHandler: @escaping (URL) -> (),
progressHandler: @escaping (Float) -> (),
errorHandler: @escaping (String) -> ()
) {
let avAsset = AVURLAsset(url: srcFile, options: nil)
let videoTrack = avAsset.tracks(withMediaType: AVMediaType.video).first!
let transformedVideoSize = videoTrack.naturalSize.applying(videoTrack.preferredTransform)
let mediaSize = CGSize(width: abs(transformedVideoSize.width), height: abs(transformedVideoSize.height))
// Resolution
let targetVideoSize:CGSize = calculateTargetVideoSize(sourceVideoSize: mediaSize, transcodeSettings: transcodeSettings);
// Trim
let start = CMTimeMake(value: Int64(trimSettings.getStartsAt()), timescale: 1000)
let end = trimSettings.getEndsAt() > 0
? CMTimeMake(value: Int64(trimSettings.getEndsAt()), timescale: 1000)
: avAsset.duration
let duration = min((end - start), (avAsset.duration - start))
let range = CMTimeRangeMake(start: start, duration: duration)
// Exporter
let exporter = SimpleSessionExporter(withAsset: avAsset)
exporter.outputFileType = AVFileType.mp4
exporter.outputURL = outFile
exporter.timeRange = range
exporter.videoOutputConfiguration = [
AVVideoWidthKey: NSNumber(integerLiteral: Int(targetVideoSize.width)),
AVVideoHeightKey: NSNumber(integerLiteral: Int(targetVideoSize.height)),
]
let progressUpdater = DispatchQueue.main.schedule(
after: .init(.now()),
interval: .milliseconds(250),
{
progressHandler(exporter.progress)
}
)
exporter.export(
completionHandler: { status in
progressUpdater.cancel()
switch status {
case .completed:
completionHandler(exporter.outputURL!)
break
case .failed:
errorHandler("Failed to transcode")
break
default:
errorHandler("Unknow export status: \(status)")
}
}
)
}
@objc public func thumbnail(
srcFile: URL,
outFile: URL,
atMs: Int,
width: Int,
height: Int
) throws {
let asset = AVURLAsset(url: srcFile, options: nil)
let imgGenerator = AVAssetImageGenerator(asset: asset)
imgGenerator.appliesPreferredTrackTransform = true
let cgImage = try imgGenerator.copyCGImage(
at: min(
asset.duration,
CMTimeMake(value: Int64(atMs), timescale: 1000)
),
actualTime: nil
)
let thumbnail = cropToBounds(
image: UIImage(cgImage: cgImage),
width: Double(width),
height: Double(height)
)
if let data = thumbnail.jpegData(compressionQuality: 0.8) {
try data.write(to: outFile)
}
}
func cropToBounds(image: UIImage, width: Double, height: Double) -> UIImage {
let cgimage = image.cgImage!
let contextImage: UIImage = UIImage(cgImage: cgimage)
let contextSize: CGSize = contextImage.size
var posX: CGFloat = 0.0
var posY: CGFloat = 0.0
var cgwidth: CGFloat = CGFloat(width)
var cgheight: CGFloat = CGFloat(height)
// See what size is longer and create the center off of that
if contextSize.width > contextSize.height {
posX = ((contextSize.width - contextSize.height) / 2)
posY = 0
cgwidth = contextSize.height
cgheight = contextSize.height
} else {
posX = 0
posY = ((contextSize.height - contextSize.width) / 2)
cgwidth = contextSize.width
cgheight = contextSize.width
}
let rect: CGRect = CGRect(x: posX, y: posY, width: cgwidth, height: cgheight)
// Create bitmap image from context using the rect
let imageRef: CGImage = cgimage.cropping(to: rect)!
// Create a new image based on the imageRef and rotate back to the original orientation
let image: UIImage = UIImage(cgImage: imageRef, scale: image.scale, orientation: image.imageOrientation)
return image
}
func getOrientationForTrack(avAsset: AVAsset) -> String {
let videoTrack = avAsset.tracks(withMediaType: AVMediaType.video).first!
let size = videoTrack.naturalSize
let txf = videoTrack.preferredTransform
if (size.width == txf.tx && size.height == txf.ty) {
return "landscape";
} else if (txf.tx == 0 && txf.ty == 0) {
return "landscape";
} else if (txf.tx == 0 && txf.ty == size.width) {
return "portrait";
}
return "portrait";
}
func calculateTargetVideoSize(sourceVideoSize: CGSize, transcodeSettings: TranscodeSettings) -> CGSize {
if (transcodeSettings.isKeepAspectRatio()) {
let mostSize = transcodeSettings.getWidth() == 0 && transcodeSettings.getHeight() == 0
? 1280
: max(transcodeSettings.getWidth(), transcodeSettings.getHeight());
return calculateVideoSizeAtMost(sourceVideoSize: sourceVideoSize, mostSize: mostSize);
} else {
if (transcodeSettings.getWidth() > 0 && transcodeSettings.getHeight() > 0) {
return CGSize(
width: transcodeSettings.getWidth(),
height: transcodeSettings.getHeight()
);
} else {
return calculateVideoSizeAtMost(sourceVideoSize: sourceVideoSize, mostSize: 720);
}
}
}
func calculateVideoSizeAtMost(sourceVideoSize: CGSize, mostSize: Int) -> CGSize{
let sourceMajor = Int(max(sourceVideoSize.width, sourceVideoSize.height));
if (sourceMajor <= mostSize) {
// No resize needed
return CGSize(
width: sourceVideoSize.width,
height: sourceVideoSize.height
);
}
var outWidth: Int;
var outHeight: Int;
if (sourceVideoSize.width >= sourceVideoSize.height) {
// Landscape
let inputRatio:Float = Float(sourceVideoSize.height) / Float(sourceVideoSize.width);
outWidth = mostSize;
outHeight = Int(Float(mostSize) * inputRatio);
} else {
// Portrait
let inputRatio: Float = Float(sourceVideoSize.width) / Float(sourceVideoSize.height);
outHeight = mostSize;
outWidth = Int(Float(mostSize) * inputRatio);
}
if (outWidth % 2 != 0) {
outWidth -= 1;
}
if (outHeight % 2 != 0) {
outHeight -= 1;
}
return CGSize(
width: outWidth,
height: outHeight
);
}
}