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. 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 = totalDur + titleS.timelineIn
  113. newTitleSticker.timelineOut = totalDur + titleS.timelineOut
  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 = totalDur + titleS.timelineIn
  160. newTitleSticker.timelineOut = totalDur + titleS.timelineOut
  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. for titleS in titleModels {
  195. let newTitleSticker = PQEditSubTitleModel()
  196. titleStickers.append(newTitleSticker)
  197. newTitleSticker.text = titleS.text
  198. newTitleSticker.setting = titleS.setting
  199. newTitleSticker.timelineIn = totalDur + subDur + titleS.timelineIn - voiceSticker.startTime
  200. newTitleSticker.timelineOut = totalDur + subDur + titleS.timelineOut - voiceSticker.startTime
  201. BFLog(1, message: "timein - \(newTitleSticker.timelineIn)")
  202. }
  203. subDur += range.duration.seconds
  204. }
  205. totalDur += subDur
  206. }
  207. }
  208. }
  209. beginExport(synthesisAll: synthesisAll, videoStickers: videoStickers, voiceList: voiceList, titleStickers: titleStickers)
  210. }
  211. }
  212. public func cancelExport() {
  213. exporter?.cancel()
  214. }
  215. public func clearFileCache() {
  216. data?.forEach { itemModel in
  217. itemModel.voiceStickers.forEach { model in
  218. if let localPath = model.wavFilePath {
  219. try? FileManager.default.removeItem(atPath: localPath)
  220. }
  221. }
  222. }
  223. }
  224. enum DispatchError: Error {
  225. case timeout
  226. }
  227. func getOutputFilePath() -> URL {
  228. var outPutMP4Path = exportVideosDirectory
  229. if !directoryIsExists(dicPath: outPutMP4Path) {
  230. createDirectory(path: outPutMP4Path)
  231. }
  232. outPutMP4Path.append("video_\(String.qe.timestamp()).mp4")
  233. return URL(fileURLWithPath: outPutMP4Path)
  234. }
  235. // 切割素材
  236. func splitBaseMaterial(timelineIn: Double, model_in: Double, duration: Double) -> PQEditVisionTrackMaterialsModel {
  237. let bgMovieInfo: PQEditVisionTrackMaterialsModel = PQEditVisionTrackMaterialsModel()
  238. bgMovieInfo.type = StickerType.VIDEO.rawValue
  239. bgMovieInfo.timelineIn = timelineIn
  240. bgMovieInfo.timelineOut = timelineIn + duration
  241. bgMovieInfo.model_in = model_in
  242. bgMovieInfo.out = model_in + duration
  243. bgMovieInfo.canvasFillType = stickerContentMode.aspectFitStr.rawValue
  244. bgMovieInfo.volumeGain = 1
  245. bgMovieInfo.aptDuration = bgMovieInfo.timelineOut
  246. bgMovieInfo.duration = bgMovieInfo.timelineOut
  247. BFLog(1, message: "hhh- timIn:\(timelineIn), modIn:\(model_in), dur:\(duration)")
  248. return bgMovieInfo
  249. }
  250. // 因为titleStickers 是传递过来的,会修改timelinein,需要重新生成,以免影响原来的数据
  251. // voiceList是考虑到图片有时候没有录音,在保留全部时,需要添加一个2秒的空sticker
  252. func beginExport(synthesisAll: Bool, videoStickers: [PQEditVisionTrackMaterialsModel], voiceList: [PQEditVisionTrackMaterialsModel], titleStickers: [PQEditSubTitleModel]) {
  253. // 输出视频地址
  254. // exprotVideo()
  255. // return;
  256. var outPutMP4Path = exportVideosDirectory
  257. if !directoryIsExists(dicPath: outPutMP4Path) {
  258. createDirectory(path: outPutMP4Path)
  259. }
  260. outPutMP4Path.append("video_\(String.qe.timestamp()).mp4")
  261. let outPutMP4URL = URL(fileURLWithPath: outPutMP4Path)
  262. BFLog(1, message: "导出视频地址 \(outPutMP4URL)")
  263. guard let itemData = data else {
  264. let error = NSError(domain: "err", code: ExportError.DataLost.rawValue, userInfo: ["msg": "所有数据丢失"])
  265. exportCompletion?(error as Error, nil)
  266. return
  267. }
  268. // 处理导出
  269. guard let voiceCount = data?.reduce(0, { partialResult, itemModell in
  270. itemModell.voiceStickers.count + partialResult
  271. }) else {
  272. BFLog(1, message: "voiceStickers count += nil")
  273. let error = NSError(domain: "err", code: ExportError.VoiceLost.rawValue, userInfo: ["msg": "voiceStickers count += nil"])
  274. exportCompletion?(error as Error, nil)
  275. return
  276. }
  277. guard let totalDuration = data?.reduce(0.0, { partialResult, itemModell in
  278. var modelDuraion = 0.0
  279. if itemModell.mediaType == .IMAGE {
  280. if itemModell.voiceStickers.count == 0, synthesisAll {
  281. modelDuraion += 2
  282. } else {
  283. modelDuraion = itemModell.materialDuraion
  284. }
  285. } else if itemModell.mediaType == .VIDEO {
  286. modelDuraion = itemModell.dealedDurationRanges.reduce(0.0) { partialResult, srange in
  287. // partialResult + (!synthesisAll && srange.isRecord) ?
  288. if synthesisAll {
  289. return partialResult + srange.range.duration.seconds
  290. } else {
  291. return partialResult + (srange.isRecord ? srange.range.duration.seconds : 0)
  292. }
  293. }
  294. }
  295. return (partialResult ?? 0) + modelDuraion
  296. }) else {
  297. let error = NSError(domain: "err", code: ExportError.TotalDurError.rawValue, userInfo: ["msg": "时长计算出错"])
  298. exportCompletion?(error as Error, nil)
  299. return
  300. }
  301. // MARK: - 声音合成
  302. // 有录音操作或者多个视频,就会进入合成步骤,否则就是一个没有处理的素材,直接导出就行了
  303. if voiceCount > 0 || videoStickers.count > 1 {
  304. let (audioMix, composition) = mergeAudio(videoStickers: videoStickers, audios: voiceList, synthesisAll: synthesisAll)
  305. var filters: [PQBaseFilter] = Array()
  306. for sticker in videoStickers {
  307. if sticker.type == StickerType.IMAGE.rawValue {
  308. filters.append(PQImageFilter(sticker: sticker))
  309. } else if sticker.type == StickerType.VIDEO.rawValue {
  310. filters.append(PQMovieFilter(movieSticker: sticker))
  311. }
  312. }
  313. let outputSize: CGSize = CGSize(width: 1080, height: Int(1080 * CGFloat(UIScreen.main.bounds.size.height / UIScreen.main.bounds.size.width)))
  314. BFLog(message: "输出视频大小:\(outputSize)")
  315. // add by ak 有字幕数据 & 显示字幕开关打开 添加字幕filter
  316. if titleStickers.count > 0, titleStickers.first?.setting.subtitleIsShow ?? true {
  317. filters.append(PQSubTitleFilter(st: titleStickers, inputSize: outputSize))
  318. }
  319. exporter = PQCompositionExporter(asset: composition, videoComposition: nil, audioMix: audioMix, filters: filters, animationTool: nil, exportURL: outPutMP4URL)
  320. var orgeBitRate = Int(outputSize.width * outputSize.height * 3)
  321. for stick in videoStickers {
  322. if stick.type == StickerType.VIDEO.rawValue, stick.locationPath.count > 0 {
  323. let asset = AVURLAsset(url: URL(fileURLWithPath: stick.locationPath), options: avAssertOptions)
  324. let cbr = asset.tracks(withMediaType: .video).first?.estimatedDataRate
  325. if Int(cbr ?? 0) > orgeBitRate {
  326. orgeBitRate = Int(cbr ?? 0)
  327. }
  328. }
  329. }
  330. BFLog(1, message: String(format: "导出设置的码率为:%.3f MB", Double(orgeBitRate) / 1024.0 / 1024.0 / 8.0))
  331. let preSize = Double(orgeBitRate) * totalDuration / (1024 * 1024 * 8)
  332. let freeSize = PQBridgeObject.getPhoneDiskFreeSize()
  333. if preSize + 100.0 > freeSize { // 存储完后磁盘剩余至少100M
  334. let error = NSError(domain: "err", code: ExportError.DiskNoSpace.rawValue, userInfo: ["msg": "需要\(Int(preSize))MB,可用\(Int(freeSize))MB"])
  335. exportCompletion?(error as Error, nil)
  336. return
  337. }
  338. let tempBeginExport = Date().timeIntervalSince1970
  339. if exporter!.prepare(videoSize: outputSize, videoAverageBitRate: orgeBitRate) {
  340. exporter!.start(playeTimeRange: CMTimeRange(start: CMTime.zero, end: CMTime(seconds: totalDuration, preferredTimescale: 1000)))
  341. }
  342. exporter?.progressClosure = { [weak self] _, _, progress in
  343. // BFLog(message: "正片合成进度 \(progress * 100)%")
  344. let useProgress = progress > 1 ? 1 : progress
  345. if progress > 0 { // 更新进度
  346. self?.progress?(useProgress)
  347. }
  348. }
  349. exporter?.completion = { [weak self] url in
  350. // 输出视频时长
  351. if let url = url {
  352. let outSeconds = CMTimeGetSeconds(AVAsset(url: url).duration)
  353. let exportEndTime = Date().timeIntervalSince1970
  354. // BFLog(1, message: "视频导出完成: \(String(describing: url)) 生成视频时长为:\(outSeconds) 总用时:\(exportEndTime - tempBeginExport)")
  355. print("生成视频时长为:\(outSeconds) 总用时:\(exportEndTime - tempBeginExport)")
  356. if testFor {
  357. cShowHUB(superView: nil, msg: (outSeconds == 0) ? "合成失败请重试。" : "合成成功,总用时:\(exportEndTime - tempBeginExport)")
  358. }
  359. self?.exportCompletion?(nil, url)
  360. } else {
  361. let error = NSError(domain: "err", code: ExportError.ExportExcept.rawValue, userInfo: ["msg": "导出异常失败"])
  362. self?.exportCompletion?(error as Error, nil)
  363. cShowHUB(superView: nil, msg: "导出失败")
  364. }
  365. // 导出完成后取消导出
  366. self?.exporter?.cancel()
  367. }
  368. } else {
  369. // 没有处理,直接copy原文件
  370. if let localPath = data?.first?.localPath {
  371. exportCompletion?(nil, URL(fileURLWithPath: localPath))
  372. }
  373. }
  374. }
  375. func dealAsset() {
  376. // asset?.tracks.first(where: { track in
  377. // if track.mediaType == .audio{
  378. //
  379. // }
  380. // })
  381. }
  382. func getVideoSize(asset: AVURLAsset) -> CGSize {
  383. var size = CGSize.zero
  384. asset.tracks.forEach { track in
  385. if track.mediaType == .video {
  386. let realSize = __CGSizeApplyAffineTransform(track.naturalSize, track.preferredTransform)
  387. size = CGSize(width: ceil(abs(realSize.width)), height: ceil(abs(realSize.height)))
  388. }
  389. }
  390. return size
  391. }
  392. }
  393. extension BFRecordExport {
  394. func mergeAudio(videoStickers: [PQEditVisionTrackMaterialsModel], audios: [PQEditVisionTrackMaterialsModel]?, synthesisAll: Bool) -> (AVMutableAudioMix, AVMutableComposition) {
  395. let composition = AVMutableComposition()
  396. let audioMix = AVMutableAudioMix()
  397. var tempParameters = [AVMutableAudioMixInputParameters]()
  398. var totalDuration: Float64 = 0
  399. for sticker in videoStickers {
  400. if sticker.volumeGain == 0 {
  401. // 如果添加了会有刺啦音
  402. BFLog(message: "音频音量 为0 不添加")
  403. continue
  404. }
  405. // sticker.volumeGain = 50
  406. totalDuration = max(totalDuration, sticker.duration)
  407. tempParameters += PQPlayerViewModel.dealWithMaterialTrack(stickerModel: sticker, composition: composition)
  408. }
  409. if let voices = audios {
  410. if synthesisAll {
  411. tempParameters += mergeRecordVoiceAll(voices: voices, composition)
  412. } else {
  413. tempParameters += mergeRecordVoiceOnly(voices: voices, composition)
  414. }
  415. }
  416. audioMix.inputParameters = tempParameters
  417. return (audioMix, composition)
  418. }
  419. func mergeRecordVoiceOnly(voices: [PQEditVisionTrackMaterialsModel], _ composition: AVMutableComposition) -> [AVMutableAudioMixInputParameters] {
  420. var tempParameters = [AVMutableAudioMixInputParameters]()
  421. var totalDur: Double = 0.0
  422. for model in voices {
  423. if model.volumeGain == 0 {
  424. // 如果添加了会有刺啦音
  425. BFLog(message: "音频音量 为0 不添加")
  426. continue
  427. }
  428. tempParameters += PQPlayerViewModel.dealWithMaterialTrack(stickerModel: model, composition: composition)
  429. totalDur += model.aptDuration
  430. }
  431. return tempParameters
  432. }
  433. func mergeRecordVoiceAll(voices: [PQEditVisionTrackMaterialsModel], _ composition: AVMutableComposition) -> [AVMutableAudioMixInputParameters] {
  434. var tempParameters = [AVMutableAudioMixInputParameters]()
  435. var totalDur = 0.0
  436. for model in voices {
  437. if model.volumeGain == 0 {
  438. // 如果添加了会有刺啦音
  439. BFLog(message: "音频音量 为0 不添加")
  440. continue
  441. }
  442. tempParameters += PQPlayerViewModel.dealWithMaterialTrack(stickerModel: model, composition: composition)
  443. }
  444. return tempParameters
  445. }
  446. }