BFRecordExport.swift 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512
  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. let testFor = true
  23. public class BFRecordExport {
  24. public var progress: ((Float) -> Void)?
  25. public var exportCompletion: ((Error?, URL?) -> Void)?
  26. public var originSoundVolumn: Float = 1.0 // 无录音时原声大小
  27. public var originSoundInRecordVolumn: Float = 0.0 // 录音时原声大小
  28. public var data: [BFRecordItemModel]? {
  29. didSet {
  30. if data?.count ?? 0 > 0 {
  31. for item in data! {
  32. item.generationTimeRanges()
  33. }
  34. }
  35. }
  36. }
  37. var count = 0
  38. var stickerRanges = [CMTimeRange]()
  39. var exporter: PQCompositionExporter?
  40. // var mStickers = [PQEditVisionTrackMaterialsModel]()
  41. deinit {}
  42. public init() {}
  43. // MARK: -
  44. /// synthesisAll: 合成所有还是只合成录音部分
  45. public func startExprot(synthesisAll: Bool) {
  46. // 1,背景视频素材
  47. if let itemModels = data {
  48. var totalDur = 0.0
  49. var titleStickers = [PQEditSubTitleModel]()
  50. var voiceList = [PQEditVisionTrackMaterialsModel]()
  51. var videoStickers = [PQEditVisionTrackMaterialsModel]()
  52. // 切割视频素材
  53. for (_, itemModel) in itemModels.enumerated() {
  54. // 保留录音部分时,是否按录音顺序合成最终视频;
  55. // 如果需要排序,则排视频的顺序;否则排音频的顺序
  56. let needSort = false
  57. if needSort {
  58. } else {
  59. // 音频排序
  60. itemModel.voiceStickers.sort { m1, m2 in
  61. m1.startCMTime.seconds < m2.startCMTime.seconds
  62. }
  63. // 字幕排序
  64. itemModel.titleStickers.sort { model1, model2 in
  65. model1.timelineIn < model2.timelineIn
  66. }
  67. }
  68. if itemModel.mediaType == .IMAGE {
  69. // 图片素材
  70. if !synthesisAll, itemModel.voiceStickers.count == 0 {
  71. // 图片无录音在保留模式里不合成
  72. continue
  73. }
  74. var duration = itemModel.materialDuraion
  75. if itemModel.voiceStickers.count == 0 {
  76. // 图片无录音保持2s
  77. duration = 2
  78. let voice = PQEditVisionTrackMaterialsModel()
  79. voice.model_in = 0.0
  80. voice.out = 2.0
  81. voice.aptDuration = 2.0
  82. // voice.voiceType = VOICETYPT.None.rawValue
  83. voice.volumeGain = 100
  84. voiceList.append(voice)
  85. } else {
  86. //
  87. for mod in itemModel.voiceStickers {
  88. let sticker = PQEditVisionTrackMaterialsModel()
  89. sticker.model_in = 0
  90. sticker.out = mod.endCMTime.seconds - mod.startCMTime.seconds
  91. sticker.timelineIn = totalDur + mod.startCMTime.seconds
  92. sticker.timelineOut = totalDur + mod.endCMTime.seconds
  93. sticker.aptDuration = sticker.out
  94. sticker.duration = sticker.out
  95. sticker.locationPath = mod.wavFilePath
  96. sticker.volumeGain = 100 // Float64(model.volume)
  97. voiceList.append(sticker)
  98. }
  99. }
  100. let sticker = splitBaseMaterial(timelineIn: totalDur, model_in: 0, duration: duration)
  101. sticker.originalData = itemModel.coverImg?.pngData()
  102. sticker.volumeGain = 0
  103. sticker.type = StickerType.IMAGE.rawValue
  104. videoStickers.append(sticker)
  105. BFLog(1, message: "image sticker - timIn:\(sticker.timelineIn), modIn:\(sticker.model_in), dur:\(duration)")
  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 = titleS.timelineIn + CMTime(seconds: totalDur, preferredTimescale: 1000)
  113. newTitleSticker.timelineOut = titleS.timelineOut + CMTime(seconds: totalDur, preferredTimescale: 1000)
  114. }
  115. totalDur += duration
  116. continue
  117. }
  118. // 视频处理
  119. if let localPath = itemModel.localPath {
  120. if !FileManager.default.fileExists(atPath: localPath) {
  121. let error = NSError(domain: "err", code: ExportError.FileNotExist.rawValue, userInfo: ["msg": "file not exist"])
  122. exportCompletion?(error as Error, nil)
  123. return
  124. }
  125. // voiceList.append(contentsOf: itemModel.voiceStickers)
  126. if synthesisAll {
  127. var subDur = 0.0
  128. let drangs = itemModel.dealedDurationRanges
  129. for srange in drangs {
  130. let range = srange.range
  131. let sticker = splitBaseMaterial(timelineIn: totalDur + subDur, model_in: range.start.seconds, duration: range.duration.seconds)
  132. sticker.locationPath = localPath
  133. sticker.volumeGain = Float64(srange.isRecord ? originSoundInRecordVolumn * 100 : originSoundVolumn * 100)
  134. videoStickers.append(sticker)
  135. subDur += range.duration.seconds
  136. if srange.isRecord {
  137. // 处理voice
  138. if let mod = itemModel.voiceStickers.first(where: { m in
  139. m.startCMTime.seconds == range.start.seconds
  140. }) {
  141. let sticker = PQEditVisionTrackMaterialsModel()
  142. sticker.model_in = 0
  143. sticker.out = mod.endCMTime.seconds - mod.startCMTime.seconds
  144. sticker.timelineIn = totalDur + mod.startCMTime.seconds
  145. sticker.timelineOut = totalDur + mod.endCMTime.seconds
  146. sticker.aptDuration = sticker.out
  147. sticker.duration = sticker.out
  148. sticker.locationPath = mod.wavFilePath
  149. sticker.volumeGain = 100 // Float64(model.volume)
  150. voiceList.append(sticker)
  151. }
  152. }
  153. }
  154. for titleS in itemModel.titleStickers {
  155. let newTitleSticker = PQEditSubTitleModel()
  156. titleStickers.append(newTitleSticker)
  157. newTitleSticker.text = titleS.text
  158. newTitleSticker.setting = titleS.setting
  159. newTitleSticker.timelineIn = titleS.timelineIn + CMTime(seconds: totalDur, preferredTimescale: 1000)
  160. newTitleSticker.timelineOut = titleS.timelineOut + CMTime(seconds: totalDur, preferredTimescale: 1000)
  161. }
  162. totalDur += subDur
  163. } else {
  164. // 只保留录音部分
  165. var subDur = 0.0
  166. var drangs = itemModel.dealedDurationRanges.filter { srange in
  167. srange.isRecord == true
  168. }
  169. if needSort {
  170. drangs.sort { range1, range2 in
  171. range1.index < range2.index
  172. }
  173. }
  174. for (index, srange) in drangs.enumerated() {
  175. let range = srange.range
  176. let sticker = splitBaseMaterial(timelineIn: totalDur + subDur, model_in: range.start.seconds, duration: range.duration.seconds)
  177. sticker.locationPath = localPath
  178. sticker.volumeGain = Float64(srange.isRecord ? originSoundInRecordVolumn * 100 : originSoundVolumn * 100)
  179. videoStickers.append(sticker)
  180. let voiceSticker = itemModel.voiceStickers[index]
  181. let voice = PQEditVisionTrackMaterialsModel()
  182. voice.model_in = 0
  183. voice.out = voiceSticker.endCMTime.seconds - voiceSticker.startCMTime.seconds
  184. voice.timelineIn = totalDur + subDur
  185. voice.timelineOut = totalDur + subDur + voice.out
  186. voice.aptDuration = voice.out
  187. voice.duration = voice.out
  188. voice.locationPath = voiceSticker.wavFilePath
  189. voice.volumeGain = 100 // Float64(model.volume)
  190. voiceList.append(voice)
  191. let titleModels = itemModel.titleStickers.filter { mod in
  192. mod.audioFilePath == voiceSticker.wavFilePath
  193. }
  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 = titleS.timelineIn + CMTime(seconds: totalDur + subDur , preferredTimescale: 1000) - voiceSticker.startCMTime
  201. newTitleSticker.timelineOut = titleS.timelineOut + CMTime(seconds: totalDur + subDur, preferredTimescale: 1000) - voiceSticker.startCMTime
  202. BFLog(1, message: "timein - \(newTitleSticker.timelineIn), out - \(newTitleSticker.timelineOut)")
  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()
  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(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: String(format: "导出设置的码率为:%.3f MB", Double(orgeBitRate) / 1024.0 / 1024.0 / 8.0))
  332. let preSize = Double(orgeBitRate) * totalDuration / (1024 * 1024 * 8)
  333. let freeSize = PQBridgeObject.getPhoneDiskFreeSize()
  334. if preSize + 100.0 > freeSize { // 存储完后磁盘剩余至少100M
  335. let error = NSError(domain: "err", code: ExportError.DiskNoSpace.rawValue, userInfo: ["msg": "需要\(Int(preSize))MB,可用\(Int(freeSize))MB"])
  336. 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. if testFor {
  358. cShowHUB(superView: nil, msg: (outSeconds == 0) ? "合成失败请重试。" : "总用时:\(exportEndTime - tempBeginExport)")
  359. }
  360. self?.exportCompletion?(nil, url)
  361. } else {
  362. let error = NSError(domain: "err", code: ExportError.ExportExcept.rawValue, userInfo: ["msg": "导出异常失败"])
  363. self?.exportCompletion?(error as Error, nil)
  364. cShowHUB(superView: nil, msg: "导出失败")
  365. }
  366. // 导出完成后取消导出
  367. self?.exporter?.cancel()
  368. }
  369. } else {
  370. // 没有处理,直接copy原文件
  371. if let localPath = data?.first?.localPath {
  372. exportCompletion?(nil, URL(fileURLWithPath: localPath))
  373. }
  374. }
  375. }
  376. func dealAsset() {
  377. // asset?.tracks.first(where: { track in
  378. // if track.mediaType == .audio{
  379. //
  380. // }
  381. // })
  382. }
  383. func getVideoSize(asset: AVURLAsset) -> CGSize {
  384. var size = CGSize.zero
  385. asset.tracks.forEach { track in
  386. if track.mediaType == .video {
  387. let realSize = __CGSizeApplyAffineTransform(track.naturalSize, track.preferredTransform)
  388. size = CGSize(width: ceil(abs(realSize.width)), height: ceil(abs(realSize.height)))
  389. }
  390. }
  391. return size
  392. }
  393. }
  394. extension BFRecordExport {
  395. func mergeAudio(videoStickers: [PQEditVisionTrackMaterialsModel], audios: [PQEditVisionTrackMaterialsModel]?, synthesisAll: Bool) -> (AVMutableAudioMix, AVMutableComposition) {
  396. let composition = AVMutableComposition()
  397. let audioMix = AVMutableAudioMix()
  398. var tempParameters = [AVMutableAudioMixInputParameters]()
  399. var totalDuration: Float64 = 0
  400. for sticker in videoStickers {
  401. if sticker.volumeGain == 0 {
  402. // 如果添加了会有刺啦音
  403. BFLog(message: "音频音量 为0 不添加")
  404. continue
  405. }
  406. // sticker.volumeGain = 50
  407. totalDuration = max(totalDuration, sticker.duration)
  408. tempParameters += PQPlayerViewModel.dealWithMaterialTrack(stickerModel: sticker, composition: composition)
  409. }
  410. if let voices = audios {
  411. if synthesisAll {
  412. tempParameters += mergeRecordVoiceAll(voices: voices, composition)
  413. } else {
  414. tempParameters += mergeRecordVoiceOnly(voices: voices, composition)
  415. }
  416. }
  417. audioMix.inputParameters = tempParameters
  418. return (audioMix, composition)
  419. }
  420. func mergeRecordVoiceOnly(voices: [PQEditVisionTrackMaterialsModel], _ composition: AVMutableComposition) -> [AVMutableAudioMixInputParameters] {
  421. var tempParameters = [AVMutableAudioMixInputParameters]()
  422. var totalDur: Double = 0.0
  423. for model in voices {
  424. if model.volumeGain == 0 {
  425. // 如果添加了会有刺啦音
  426. BFLog(message: "音频音量 为0 不添加")
  427. continue
  428. }
  429. tempParameters += PQPlayerViewModel.dealWithMaterialTrack(stickerModel: model, composition: composition)
  430. totalDur += model.aptDuration
  431. }
  432. return tempParameters
  433. }
  434. func mergeRecordVoiceAll(voices: [PQEditVisionTrackMaterialsModel], _ composition: AVMutableComposition) -> [AVMutableAudioMixInputParameters] {
  435. var tempParameters = [AVMutableAudioMixInputParameters]()
  436. var totalDur = 0.0
  437. for model in voices {
  438. if model.volumeGain == 0 {
  439. // 如果添加了会有刺啦音
  440. BFLog(message: "音频音量 为0 不添加")
  441. continue
  442. }
  443. tempParameters += PQPlayerViewModel.dealWithMaterialTrack(stickerModel: model, composition: composition)
  444. }
  445. return tempParameters
  446. }
  447. }