-
Notifications
You must be signed in to change notification settings - Fork 245
/
SwiftVideoCompressPlugin.swift
253 lines (213 loc) · 10.4 KB
/
SwiftVideoCompressPlugin.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
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
import Flutter
import AVFoundation
public class SwiftVideoCompressPlugin: NSObject, FlutterPlugin {
private let channelName = "video_compress"
private var exporter: AVAssetExportSession? = nil
private var stopCommand = false
private let channel: FlutterMethodChannel
private let avController = AvController()
init(channel: FlutterMethodChannel) {
self.channel = channel
}
public static func register(with registrar: FlutterPluginRegistrar) {
let channel = FlutterMethodChannel(name: "video_compress", binaryMessenger: registrar.messenger())
let instance = SwiftVideoCompressPlugin(channel: channel)
registrar.addMethodCallDelegate(instance, channel: channel)
}
public func handle(_ call: FlutterMethodCall, result: @escaping FlutterResult) {
let args = call.arguments as? Dictionary<String, Any>
switch call.method {
case "getByteThumbnail":
let path = args!["path"] as! String
let quality = args!["quality"] as! NSNumber
let position = args!["position"] as! NSNumber
getByteThumbnail(path, quality, position, result)
case "getFileThumbnail":
let path = args!["path"] as! String
let quality = args!["quality"] as! NSNumber
let position = args!["position"] as! NSNumber
getFileThumbnail(path, quality, position, result)
case "getMediaInfo":
let path = args!["path"] as! String
getMediaInfo(path, result)
case "compressVideo":
let path = args!["path"] as! String
let quality = args!["quality"] as! NSNumber
let deleteOrigin = args!["deleteOrigin"] as! Bool
let startTime = args!["startTime"] as? Double
let duration = args!["duration"] as? Double
let includeAudio = args!["includeAudio"] as? Bool
let frameRate = args!["frameRate"] as? Int
compressVideo(path, quality, deleteOrigin, startTime, duration, includeAudio,
frameRate, result)
case "cancelCompression":
cancelCompression(result)
case "deleteAllCache":
Utility.deleteFile(Utility.basePath(), clear: true)
result(true)
case "setLogLevel":
result(true)
default:
result(FlutterMethodNotImplemented)
}
}
private func getBitMap(_ path: String,_ quality: NSNumber,_ position: NSNumber,_ result: FlutterResult)-> Data? {
let url = Utility.getPathUrl(path)
let asset = avController.getVideoAsset(url)
guard let track = avController.getTrack(asset) else { return nil }
let assetImgGenerate = AVAssetImageGenerator(asset: asset)
assetImgGenerate.appliesPreferredTrackTransform = true
let timeScale = CMTimeScale(track.nominalFrameRate)
let time = CMTimeMakeWithSeconds(Float64(truncating: position),preferredTimescale: timeScale)
guard let img = try? assetImgGenerate.copyCGImage(at:time, actualTime: nil) else {
return nil
}
let thumbnail = UIImage(cgImage: img)
let compressionQuality = CGFloat(0.01 * Double(truncating: quality))
return thumbnail.jpegData(compressionQuality: compressionQuality)
}
private func getByteThumbnail(_ path: String,_ quality: NSNumber,_ position: NSNumber,_ result: FlutterResult) {
if let bitmap = getBitMap(path,quality,position,result) {
result(bitmap)
}
}
private func getFileThumbnail(_ path: String,_ quality: NSNumber,_ position: NSNumber,_ result: FlutterResult) {
let fileName = Utility.getFileName(path)
let url = Utility.getPathUrl("\(Utility.basePath())/\(fileName).jpg")
Utility.deleteFile(path)
if let bitmap = getBitMap(path,quality,position,result) {
guard (try? bitmap.write(to: url)) != nil else {
return result(FlutterError(code: channelName,message: "getFileThumbnail error",details: "getFileThumbnail error"))
}
result(Utility.excludeFileProtocol(url.absoluteString))
}
}
public func getMediaInfoJson(_ path: String)->[String : Any?] {
let url = Utility.getPathUrl(path)
let asset = avController.getVideoAsset(url)
guard let track = avController.getTrack(asset) else { return [:] }
let playerItem = AVPlayerItem(url: url)
let metadataAsset = playerItem.asset
let orientation = avController.getVideoOrientation(path)
let title = avController.getMetaDataByTag(metadataAsset,key: "title")
let author = avController.getMetaDataByTag(metadataAsset,key: "author")
let duration = asset.duration.seconds * 1000
let filesize = track.totalSampleDataLength
let size = track.naturalSize.applying(track.preferredTransform)
let width = abs(size.width)
let height = abs(size.height)
let dictionary = [
"path":Utility.excludeFileProtocol(path),
"title":title,
"author":author,
"width":width,
"height":height,
"duration":duration,
"filesize":filesize,
"orientation":orientation
] as [String : Any?]
return dictionary
}
private func getMediaInfo(_ path: String,_ result: FlutterResult) {
let json = getMediaInfoJson(path)
let string = Utility.keyValueToJson(json)
result(string)
}
@objc private func updateProgress(timer:Timer) {
let asset = timer.userInfo as! AVAssetExportSession
if(!stopCommand) {
channel.invokeMethod("updateProgress", arguments: "\(String(describing: asset.progress * 100))")
}
}
private func getExportPreset(_ quality: NSNumber)->String {
switch(quality) {
case 1:
return AVAssetExportPresetLowQuality
case 2:
return AVAssetExportPresetMediumQuality
case 3:
return AVAssetExportPresetHighestQuality
default:
return AVAssetExportPresetMediumQuality
}
}
private func getComposition(_ isIncludeAudio: Bool,_ timeRange: CMTimeRange, _ sourceVideoTrack: AVAssetTrack)->AVAsset {
let composition = AVMutableComposition()
if !isIncludeAudio {
let compressionVideoTrack = composition.addMutableTrack(withMediaType: AVMediaType.video, preferredTrackID: kCMPersistentTrackID_Invalid)
compressionVideoTrack!.preferredTransform = sourceVideoTrack.preferredTransform
try? compressionVideoTrack!.insertTimeRange(timeRange, of: sourceVideoTrack, at: CMTime.zero)
} else {
return sourceVideoTrack.asset!
}
return composition
}
private func compressVideo(_ path: String,_ quality: NSNumber,_ deleteOrigin: Bool,_ startTime: Double?,
_ duration: Double?,_ includeAudio: Bool?,_ frameRate: Int?,
_ result: @escaping FlutterResult) {
let sourceVideoUrl = Utility.getPathUrl(path)
let sourceVideoType = "mp4"
let sourceVideoAsset = avController.getVideoAsset(sourceVideoUrl)
let sourceVideoTrack = avController.getTrack(sourceVideoAsset)
let compressionUrl =
Utility.getPathUrl("\(Utility.basePath())/\(Utility.getFileName(path)).\(sourceVideoType)")
let timescale = sourceVideoAsset.duration.timescale
let minStartTime = Double(startTime ?? 0)
let videoDuration = sourceVideoAsset.duration.seconds
let minDuration = Double(duration ?? videoDuration)
let maxDurationTime = minStartTime + minDuration < videoDuration ? minDuration : videoDuration
let cmStartTime = CMTimeMakeWithSeconds(minStartTime, preferredTimescale: timescale)
let cmDurationTime = CMTimeMakeWithSeconds(maxDurationTime, preferredTimescale: timescale)
let timeRange: CMTimeRange = CMTimeRangeMake(start: cmStartTime, duration: cmDurationTime)
let isIncludeAudio = includeAudio != nil ? includeAudio! : true
let session = getComposition(isIncludeAudio, timeRange, sourceVideoTrack!)
let exporter = AVAssetExportSession(asset: session, presetName: getExportPreset(quality))!
exporter.outputURL = compressionUrl
exporter.outputFileType = AVFileType.mp4
exporter.shouldOptimizeForNetworkUse = true
if frameRate != nil {
let videoComposition = AVMutableVideoComposition(propertiesOf: sourceVideoAsset)
videoComposition.frameDuration = CMTimeMake(value: 1, timescale: Int32(frameRate!))
exporter.videoComposition = videoComposition
}
if !isIncludeAudio {
exporter.timeRange = timeRange
}
Utility.deleteFile(compressionUrl.absoluteString)
let timer = Timer.scheduledTimer(timeInterval: 0.1, target: self, selector: #selector(self.updateProgress),
userInfo: exporter, repeats: true)
exporter.exportAsynchronously(completionHandler: {
if(self.stopCommand) {
timer.invalidate()
self.stopCommand = false
var json = self.getMediaInfoJson(path)
json["isCancel"] = true
let jsonString = Utility.keyValueToJson(json)
return result(jsonString)
}
if deleteOrigin {
timer.invalidate()
let fileManager = FileManager.default
do {
if fileManager.fileExists(atPath: path) {
try fileManager.removeItem(atPath: path)
}
self.exporter = nil
self.stopCommand = false
}
catch let error as NSError {
print(error)
}
}
var json = self.getMediaInfoJson(compressionUrl.absoluteString)
json["isCancel"] = false
let jsonString = Utility.keyValueToJson(json)
result(jsonString)
})
}
private func cancelCompression(_ result: FlutterResult) {
exporter?.cancelExport()
stopCommand = true
result("")
}
}