BFRecordExport.swift 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508
  1. //
  2. // BFRecordExport.swift
  3. // BFRecordScreenKit
  4. //
  5. // Created by 胡志强 on 2021/11/25.
  6. // 录屏视频导出
  7. import AVFoundation
  8. import BFCommonKit
  9. import BFMediaKit
  10. import Foundation
  11. import GPUImage
  12. import Photos
  13. import UIKit
  14. public enum ExportError : Int {
  15. case FileNotExist = -31001
  16. case DataLost = -31002
  17. case VoiceLost = -31003
  18. case TotalDurError = -31004
  19. case ExportExcept = -31005
  20. case DiskNoSpace = -31006
  21. }
  22. public class BFRecordExport {
  23. public var progress: ((Float) -> Void)?
  24. public var exportCompletion: ((Error?, URL?) -> Void)?
  25. public var originSoundVolumn : Float = 1.0 // 无录音时原声大小
  26. public var originSoundInRecordVolumn : Float = 0.0 // 录音时原声大小
  27. public var data: [BFRecordItemModel]? {
  28. didSet {
  29. if data?.count ?? 0 > 0 {
  30. for item in data! {
  31. item.generationTimeRanges()
  32. }
  33. }
  34. }
  35. }
  36. var count = 0
  37. var stickerRanges = [CMTimeRange]()
  38. var exporter: PQCompositionExporter?
  39. // var mStickers = [PQEditVisionTrackMaterialsModel]()
  40. deinit {}
  41. public init() {}
  42. // MARK: -
  43. /// synthesisAll: 合成所有还是只合成录音部分
  44. public func startExprot(synthesisAll: Bool) {
  45. // 1,背景视频素材
  46. if let itemModels = data {
  47. var totalDur = 0.0
  48. var titleStickers = [PQEditSubTitleModel]()
  49. var voiceList = [PQEditVisionTrackMaterialsModel]()
  50. var videoStickers = [PQEditVisionTrackMaterialsModel]()
  51. // 切割视频素材
  52. for (_, itemModel) in itemModels.enumerated() {
  53. // 保留录音部分时,是否按录音顺序合成最终视频;
  54. // 如果需要排序,则排视频的顺序;否则排音频的顺序
  55. let needSort = false
  56. if needSort {
  57. }else{
  58. // 音频排序
  59. itemModel.voiceStickers.sort { m1, m2 in
  60. m1.startTime < m2.startTime
  61. }
  62. // 字幕排序
  63. itemModel.titleStickers.sort { model1, model2 in
  64. model1.timelineIn < model2.timelineIn
  65. }
  66. }
  67. if itemModel.mediaType == .IMAGE {
  68. // 图片素材
  69. if !synthesisAll && itemModel.voiceStickers.count == 0 {
  70. // 图片无录音在保留模式里不合成
  71. continue
  72. }
  73. var duration = itemModel.materialDuraion
  74. if itemModel.voiceStickers.count == 0 {
  75. // 图片无录音保持2s
  76. duration = 2
  77. let voice = PQEditVisionTrackMaterialsModel()
  78. voice.model_in = 0.0
  79. voice.out = 2.0
  80. voice.aptDuration = 2.0
  81. // voice.voiceType = VOICETYPT.None.rawValue
  82. voice.volumeGain = 100
  83. voiceList.append(voice)
  84. }else{
  85. //
  86. for mod in itemModel.voiceStickers {
  87. let sticker = PQEditVisionTrackMaterialsModel()
  88. sticker.model_in = 0
  89. sticker.out = mod.endTime - mod.startTime
  90. sticker.timelineIn = totalDur + mod.startTime
  91. sticker.timelineOut = totalDur + mod.endTime
  92. sticker.aptDuration = sticker.out
  93. sticker.duration = sticker.out
  94. sticker.locationPath = mod.wavFilePath
  95. sticker.volumeGain = 100 // Float64(model.volume)
  96. voiceList.append(sticker)
  97. }
  98. }
  99. let sticker = splitBaseMaterial(timelineIn: totalDur, model_in: 0, duration: duration)
  100. sticker.originalData = itemModel.coverImg?.pngData()
  101. sticker.volumeGain = 0
  102. sticker.type = StickerType.IMAGE.rawValue
  103. videoStickers.append(sticker)
  104. BFLog(1, message: "image sticker - timIn:\(sticker.timelineIn), modIn:\(sticker.model_in), dur:\(duration)")
  105. var subDur = 0.0
  106. for titleS in itemModel.titleStickers {
  107. let leng = titleS.timelineOut - titleS.timelineIn
  108. let newTitleSticker = PQEditSubTitleModel()
  109. titleStickers.append(newTitleSticker)
  110. newTitleSticker.text = titleS.text
  111. newTitleSticker.setting = titleS.setting
  112. newTitleSticker.timelineIn = totalDur + subDur
  113. newTitleSticker.timelineOut = totalDur + subDur + leng
  114. subDur += leng
  115. }
  116. totalDur += duration
  117. continue
  118. }
  119. // 视频处理
  120. if let localPath = itemModel.localPath {
  121. if !FileManager.default.fileExists(atPath: localPath) {
  122. let error = NSError(domain: "err", code: ExportError.FileNotExist.rawValue, userInfo: ["msg": "file not exist"])
  123. exportCompletion?(error as Error, nil)
  124. return
  125. }
  126. // voiceList.append(contentsOf: itemModel.voiceStickers)
  127. if synthesisAll {
  128. var subDur = 0.0
  129. let drangs = itemModel.dealedDurationRanges
  130. for srange in drangs {
  131. let range = srange.range
  132. let sticker = splitBaseMaterial(timelineIn: totalDur + subDur, model_in: range.start.seconds, duration: range.duration.seconds)
  133. sticker.locationPath = localPath
  134. sticker.volumeGain = Float64(srange.isRecord ? originSoundInRecordVolumn*100 : originSoundVolumn*100)
  135. videoStickers.append(sticker)
  136. subDur += range.duration.seconds
  137. if srange.isRecord {
  138. // 处理voice
  139. if let mod = itemModel.voiceStickers.first(where: { m in
  140. m.startTime == range.start.seconds
  141. }){
  142. let sticker = PQEditVisionTrackMaterialsModel()
  143. sticker.model_in = 0
  144. sticker.out = mod.endTime - mod.startTime
  145. sticker.timelineIn = totalDur + mod.startTime
  146. sticker.timelineOut = totalDur + mod.endTime
  147. sticker.aptDuration = sticker.out
  148. sticker.duration = sticker.out
  149. sticker.locationPath = mod.wavFilePath
  150. sticker.volumeGain = 100 // Float64(model.volume)
  151. voiceList.append(sticker)
  152. }
  153. }
  154. }
  155. for titleS in itemModel.titleStickers {
  156. let newTitleSticker = PQEditSubTitleModel()
  157. titleStickers.append(newTitleSticker)
  158. newTitleSticker.text = titleS.text
  159. newTitleSticker.setting = titleS.setting
  160. newTitleSticker.timelineIn = totalDur + titleS.timelineIn
  161. newTitleSticker.timelineOut = totalDur + titleS.timelineOut
  162. }
  163. totalDur += subDur
  164. } else {
  165. // 只保留录音部分
  166. var subDur = 0.0
  167. var drangs = itemModel.dealedDurationRanges.filter { srange in
  168. srange.isRecord == true
  169. }
  170. if needSort {
  171. drangs.sort { range1, range2 in
  172. range1.index < range2.index
  173. }
  174. }
  175. for (index, srange) in drangs.enumerated() {
  176. let range = srange.range
  177. let sticker = splitBaseMaterial(timelineIn: totalDur + subDur, model_in: range.start.seconds, duration: range.duration.seconds)
  178. sticker.locationPath = localPath
  179. sticker.volumeGain = Float64(srange.isRecord ? originSoundInRecordVolumn*100 : originSoundVolumn*100)
  180. videoStickers.append(sticker)
  181. let voiceSticker = itemModel.voiceStickers[index]
  182. let voice = PQEditVisionTrackMaterialsModel()
  183. voice.model_in = 0
  184. voice.out = voiceSticker.endTime - voiceSticker.startTime
  185. voice.timelineIn = totalDur + subDur
  186. voice.timelineOut = totalDur + subDur + voice.out
  187. voice.aptDuration = voice.out
  188. voice.duration = voice.out
  189. voice.locationPath = voiceSticker.wavFilePath
  190. voice.volumeGain = 100 // Float64(model.volume)
  191. voiceList.append(voice)
  192. let titleModels = itemModel.titleStickers.filter({ mod in
  193. mod.audioFilePath == voiceSticker.wavFilePath
  194. })
  195. for titleS in titleModels {
  196. let newTitleSticker = PQEditSubTitleModel()
  197. titleStickers.append(newTitleSticker)
  198. newTitleSticker.text = titleS.text
  199. newTitleSticker.setting = titleS.setting
  200. newTitleSticker.timelineIn = totalDur + subDur + titleS.timelineIn - voiceSticker.startTime
  201. newTitleSticker.timelineOut = totalDur + subDur + titleS.timelineOut - voiceSticker.startTime
  202. BFLog(1, message: "timein - \(newTitleSticker.timelineIn)")
  203. }
  204. subDur += range.duration.seconds
  205. }
  206. totalDur += subDur
  207. }
  208. }
  209. }
  210. beginExport(synthesisAll: synthesisAll, videoStickers: videoStickers, voiceList:voiceList, titleStickers:titleStickers)
  211. }
  212. }
  213. public func cancelExport() {
  214. exporter?.cancel()
  215. }
  216. public func clearFileCache() {
  217. data?.forEach { itemModel in
  218. itemModel.voiceStickers.forEach { model in
  219. if let localPath = model.wavFilePath {
  220. try? FileManager.default.removeItem(atPath: localPath)
  221. }
  222. }
  223. }
  224. }
  225. enum DispatchError: Error {
  226. case timeout
  227. }
  228. func getOutputFilePath() -> URL {
  229. var outPutMP4Path = exportVideosDirectory
  230. if !directoryIsExists(dicPath: outPutMP4Path) {
  231. createDirectory(path: outPutMP4Path)
  232. }
  233. outPutMP4Path.append("video_\(String.qe.timestamp()).mp4")
  234. return URL(fileURLWithPath: outPutMP4Path)
  235. }
  236. // 切割素材
  237. func splitBaseMaterial(timelineIn: Double, model_in: Double, duration: Double) -> PQEditVisionTrackMaterialsModel {
  238. let bgMovieInfo: PQEditVisionTrackMaterialsModel = PQEditVisionTrackMaterialsModel()
  239. bgMovieInfo.type = StickerType.VIDEO.rawValue
  240. bgMovieInfo.timelineIn = timelineIn
  241. bgMovieInfo.timelineOut = timelineIn + duration
  242. bgMovieInfo.model_in = model_in
  243. bgMovieInfo.out = model_in + duration
  244. bgMovieInfo.canvasFillType = stickerContentMode.aspectFitStr.rawValue
  245. bgMovieInfo.volumeGain = 1
  246. bgMovieInfo.aptDuration = bgMovieInfo.timelineOut
  247. bgMovieInfo.duration = bgMovieInfo.timelineOut
  248. BFLog(1, message: "hhh- timIn:\(timelineIn), modIn:\(model_in), dur:\(duration)")
  249. return bgMovieInfo
  250. }
  251. // 因为titleStickers 是传递过来的,会修改timelinein,需要重新生成,以免影响原来的数据
  252. // voiceList是考虑到图片有时候没有录音,在保留全部时,需要添加一个2秒的空sticker
  253. func beginExport(synthesisAll: Bool, videoStickers: [PQEditVisionTrackMaterialsModel], voiceList: [PQEditVisionTrackMaterialsModel], titleStickers: [PQEditSubTitleModel]) {
  254. // 输出视频地址
  255. // exprotVideo()
  256. // return;
  257. var outPutMP4Path = exportVideosDirectory
  258. if !directoryIsExists(dicPath: outPutMP4Path) {
  259. createDirectory(path: outPutMP4Path)
  260. }
  261. outPutMP4Path.append("video_\(String.qe.timestamp()).mp4")
  262. let outPutMP4URL = URL(fileURLWithPath: outPutMP4Path)
  263. BFLog(1, message: "导出视频地址 \(outPutMP4URL)")
  264. guard let itemData = data else {
  265. let error = NSError(domain: "err", code: ExportError.DataLost.rawValue, userInfo: ["msg": "所有数据丢失"])
  266. exportCompletion?(error as Error, nil)
  267. return
  268. }
  269. // 处理导出
  270. guard let voiceCount = data?.reduce(0, { partialResult, itemModell in
  271. itemModell.voiceStickers.count + partialResult
  272. }) else {
  273. BFLog(1, message: "voiceStickers count += nil")
  274. let error = NSError(domain: "err", code: ExportError.VoiceLost.rawValue, userInfo: ["msg": "voiceStickers count += nil"])
  275. exportCompletion?(error as Error, nil)
  276. return
  277. }
  278. guard let totalDuration = data?.reduce(0.0, { partialResult, itemModell in
  279. var modelDuraion = 0.0
  280. if itemModell.mediaType == .IMAGE {
  281. if itemModell.voiceStickers.count == 0 && synthesisAll {
  282. modelDuraion += 2
  283. }else {
  284. modelDuraion = itemModell.materialDuraion
  285. }
  286. }else if itemModell.mediaType == .VIDEO{
  287. modelDuraion = itemModell.dealedDurationRanges.reduce(0.0) { partialResult, srange in
  288. // partialResult + (!synthesisAll && srange.isRecord) ?
  289. if synthesisAll {
  290. return partialResult + srange.range.duration.seconds
  291. }else {
  292. return partialResult + (srange.isRecord ? srange.range.duration.seconds : 0)
  293. }
  294. }
  295. }
  296. return (partialResult ?? 0) + modelDuraion
  297. }) else {
  298. let error = NSError(domain: "err", code: ExportError.TotalDurError.rawValue, userInfo: ["msg": "时长计算出错"])
  299. exportCompletion?(error as Error, nil)
  300. return
  301. }
  302. // MARK: - 声音合成
  303. // 有录音操作或者多个视频,就会进入合成步骤,否则就是一个没有处理的素材,直接导出就行了
  304. if voiceCount > 0 || videoStickers.count > 1 {
  305. let (audioMix, composition) = mergeAudio(videoStickers: videoStickers, audios: voiceList, synthesisAll: synthesisAll)
  306. var filters:[PQBaseFilter] = Array.init()
  307. for sticker in videoStickers {
  308. if sticker.type == StickerType.IMAGE.rawValue {
  309. filters.append(PQImageFilter(sticker: sticker))
  310. }else if sticker.type == StickerType.VIDEO.rawValue {
  311. filters.append(PQMovieFilter(movieSticker: sticker))
  312. }
  313. }
  314. let outputSize:CGSize = CGSize(width: 1080, height: Int(1080 * CGFloat(UIScreen.main.bounds.size.height / UIScreen.main.bounds.size.width)))
  315. BFLog(message: "输出视频大小:\(outputSize)")
  316. //add by ak 有字幕数据 & 显示字幕开关打开 添加字幕filter
  317. if(titleStickers.count > 0 && ( titleStickers.first?.setting.subtitleIsShow ?? true)){
  318. filters.append(PQSubTitleFilter.init(st: titleStickers, inputSize: outputSize))
  319. }
  320. exporter = PQCompositionExporter(asset: composition, videoComposition: nil, audioMix: audioMix, filters: filters, animationTool: nil, exportURL: outPutMP4URL)
  321. var orgeBitRate = Int(outputSize.width * outputSize.height * 3)
  322. for stick in videoStickers {
  323. if stick.type == StickerType.VIDEO.rawValue, stick.locationPath.count > 0 {
  324. let asset = AVURLAsset(url: URL(fileURLWithPath: stick.locationPath), options: avAssertOptions)
  325. let cbr = asset.tracks(withMediaType: .video).first?.estimatedDataRate
  326. if Int(cbr ?? 0) > orgeBitRate {
  327. orgeBitRate = Int(cbr ?? 0)
  328. }
  329. }
  330. }
  331. BFLog(1, message: "导出设置的码率为:\(Double(orgeBitRate)/1024.0/1024.0)M")
  332. let preSize = Double(orgeBitRate) * totalDuration / (1024*1024)
  333. let freeSize = PQBridgeObject.getPhoneDiskFreeSize()
  334. if preSize + 100.0 > freeSize { // 存储完后磁盘剩余至少100M
  335. let error = NSError(domain: "err", code: ExportError.DiskNoSpace.rawValue, userInfo: ["msg":"磁盘空间不足"])
  336. self.exportCompletion?(error as Error, nil)
  337. return
  338. }
  339. let tempBeginExport = Date().timeIntervalSince1970
  340. if exporter!.prepare(videoSize: outputSize, videoAverageBitRate: orgeBitRate) {
  341. exporter!.start(playeTimeRange: CMTimeRange(start: CMTime.zero, end: CMTime(seconds: totalDuration, preferredTimescale: 1000)))
  342. }
  343. exporter?.progressClosure = { [weak self] _, _, progress in
  344. // BFLog(message: "正片合成进度 \(progress * 100)%")
  345. let useProgress = progress > 1 ? 1 : progress
  346. if progress > 0 { // 更新进度
  347. self?.progress?(useProgress)
  348. }
  349. }
  350. exporter?.completion = { [weak self] url in
  351. // 输出视频时长
  352. if let url = url {
  353. let outSeconds = CMTimeGetSeconds(AVAsset(url: url).duration)
  354. let exportEndTime = Date().timeIntervalSince1970
  355. // BFLog(1, message: "视频导出完成: \(String(describing: url)) 生成视频时长为:\(outSeconds) 总用时:\(exportEndTime - tempBeginExport)")
  356. print("生成视频时长为:\(outSeconds) 总用时:\(exportEndTime - tempBeginExport)")
  357. cShowHUB(superView: nil, msg: (outSeconds == 0) ? "合成失败请重试。" : "合成成功")
  358. self?.exportCompletion?(nil, url)
  359. } else {
  360. let error = NSError(domain: "err", code: ExportError.ExportExcept.rawValue, userInfo: ["msg":"导出异常失败"])
  361. self?.exportCompletion?(error as Error, nil)
  362. cShowHUB(superView: nil, msg: "导出失败")
  363. }
  364. // 导出完成后取消导出
  365. self?.exporter?.cancel()
  366. }
  367. } else {
  368. // 没有处理,直接copy原文件
  369. if let localPath = data?.first?.localPath {
  370. exportCompletion?(nil, URL(fileURLWithPath: localPath))
  371. }
  372. }
  373. }
  374. func dealAsset() {
  375. // asset?.tracks.first(where: { track in
  376. // if track.mediaType == .audio{
  377. //
  378. // }
  379. // })
  380. }
  381. func getVideoSize(asset: AVURLAsset) -> CGSize {
  382. var size = CGSize.zero
  383. asset.tracks.forEach { track in
  384. if track.mediaType == .video {
  385. let realSize = __CGSizeApplyAffineTransform(track.naturalSize, track.preferredTransform)
  386. size = CGSize(width: ceil(abs(realSize.width)), height: ceil(abs(realSize.height)))
  387. }
  388. }
  389. return size
  390. }
  391. }
  392. extension BFRecordExport {
  393. func mergeAudio(videoStickers: [PQEditVisionTrackMaterialsModel], audios: [PQEditVisionTrackMaterialsModel]?, synthesisAll: Bool) -> (AVMutableAudioMix, AVMutableComposition) {
  394. let composition = AVMutableComposition()
  395. let audioMix = AVMutableAudioMix()
  396. var tempParameters = [AVMutableAudioMixInputParameters]()
  397. var totalDuration: Float64 = 0
  398. for sticker in videoStickers {
  399. if sticker.volumeGain == 0 {
  400. // 如果添加了会有刺啦音
  401. BFLog(message: "音频音量 为0 不添加")
  402. continue
  403. }
  404. // sticker.volumeGain = 50
  405. totalDuration = max(totalDuration, sticker.duration)
  406. tempParameters += PQPlayerViewModel.dealWithMaterialTrack(stickerModel: sticker, composition: composition)
  407. }
  408. if let voices = audios {
  409. if synthesisAll {
  410. tempParameters += mergeRecordVoiceAll(voices: voices, composition)
  411. } else {
  412. tempParameters += mergeRecordVoiceOnly(voices: voices, composition)
  413. }
  414. }
  415. audioMix.inputParameters = tempParameters
  416. return (audioMix, composition)
  417. }
  418. func mergeRecordVoiceOnly(voices: [PQEditVisionTrackMaterialsModel], _ composition: AVMutableComposition) -> [AVMutableAudioMixInputParameters] {
  419. var tempParameters = [AVMutableAudioMixInputParameters]()
  420. var totalDur: Double = 0.0
  421. for model in voices {
  422. if model.volumeGain == 0 {
  423. // 如果添加了会有刺啦音
  424. BFLog(message: "音频音量 为0 不添加")
  425. continue
  426. }
  427. tempParameters += PQPlayerViewModel.dealWithMaterialTrack(stickerModel: model, composition: composition)
  428. totalDur += model.aptDuration
  429. }
  430. return tempParameters
  431. }
  432. func mergeRecordVoiceAll(voices: [PQEditVisionTrackMaterialsModel], _ composition: AVMutableComposition) -> [AVMutableAudioMixInputParameters] {
  433. var tempParameters = [AVMutableAudioMixInputParameters]()
  434. var totalDur = 0.0
  435. for model in voices {
  436. if model.volumeGain == 0 {
  437. // 如果添加了会有刺啦音
  438. BFLog(message: "音频音量 为0 不添加")
  439. continue
  440. }
  441. tempParameters += PQPlayerViewModel.dealWithMaterialTrack(stickerModel: model, composition: composition)
  442. }
  443. return tempParameters
  444. }
  445. }