BFRecordExport.swift 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501
  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.startCMTime.seconds < m2.startCMTime.seconds
  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.seconds
  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.endCMTime.seconds - mod.startCMTime.seconds
  90. sticker.timelineIn = totalDur + mod.startCMTime.seconds
  91. sticker.timelineOut = totalDur + mod.endCMTime.seconds
  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. for titleS in itemModel.titleStickers {
  106. // let leng = titleS.timelineOut - titleS.timelineIn
  107. let newTitleSticker = PQEditSubTitleModel()
  108. titleStickers.append(newTitleSticker)
  109. newTitleSticker.text = titleS.text
  110. newTitleSticker.setting = titleS.setting
  111. newTitleSticker.timelineIn = titleS.timelineIn + CMTime(seconds: totalDur, preferredTimescale: 1000)
  112. newTitleSticker.timelineOut = titleS.timelineOut + CMTime(seconds: totalDur, preferredTimescale: 1000)
  113. }
  114. totalDur += duration
  115. continue
  116. }
  117. // 视频处理
  118. if let localPath = itemModel.localPath {
  119. if !FileManager.default.fileExists(atPath: localPath) {
  120. let error = NSError(domain: "err", code: ExportError.FileNotExist.rawValue, userInfo: ["msg": "file not exist"])
  121. exportCompletion?(error as Error, nil)
  122. return
  123. }
  124. // voiceList.append(contentsOf: itemModel.voiceStickers)
  125. if synthesisAll {
  126. var subDur = 0.0
  127. let drangs = itemModel.dealedDurationRanges
  128. for srange in drangs {
  129. let range = srange.range
  130. let sticker = splitBaseMaterial(timelineIn: totalDur + subDur, model_in: range.start.seconds, duration: range.duration.seconds)
  131. sticker.locationPath = localPath
  132. sticker.volumeGain = Float64(srange.isRecord ? originSoundInRecordVolumn * 100 : originSoundVolumn * 100)
  133. videoStickers.append(sticker)
  134. subDur += range.duration.seconds
  135. if srange.isRecord {
  136. // 处理voice
  137. if let mod = itemModel.voiceStickers.first(where: { m in
  138. m.startCMTime.seconds == range.start.seconds
  139. }) {
  140. let sticker = PQEditVisionTrackMaterialsModel()
  141. sticker.model_in = 0
  142. sticker.out = mod.endCMTime.seconds - mod.startCMTime.seconds
  143. sticker.timelineIn = totalDur + mod.startCMTime.seconds
  144. sticker.timelineOut = totalDur + mod.endCMTime.seconds
  145. sticker.aptDuration = sticker.out
  146. sticker.duration = sticker.out
  147. sticker.locationPath = mod.wavFilePath
  148. sticker.volumeGain = 100 // Float64(model.volume)
  149. voiceList.append(sticker)
  150. }
  151. }
  152. }
  153. for titleS in itemModel.titleStickers {
  154. let newTitleSticker = PQEditSubTitleModel()
  155. titleStickers.append(newTitleSticker)
  156. newTitleSticker.text = titleS.text
  157. newTitleSticker.setting = titleS.setting
  158. newTitleSticker.timelineIn = titleS.timelineIn + CMTime(seconds: totalDur, preferredTimescale: 1000)
  159. newTitleSticker.timelineOut = titleS.timelineOut + CMTime(seconds: totalDur, preferredTimescale: 1000)
  160. }
  161. totalDur += subDur
  162. } else {
  163. // 只保留录音部分
  164. var subDur = 0.0
  165. var drangs = itemModel.dealedDurationRanges.filter { srange in
  166. srange.isRecord == true
  167. }
  168. if needSort {
  169. drangs.sort { range1, range2 in
  170. range1.index < range2.index
  171. }
  172. }
  173. for (index, srange) in drangs.enumerated() {
  174. let range = srange.range
  175. let sticker = splitBaseMaterial(timelineIn: totalDur + subDur, model_in: range.start.seconds, duration: range.duration.seconds)
  176. sticker.locationPath = localPath
  177. sticker.volumeGain = Float64(srange.isRecord ? originSoundInRecordVolumn * 100 : originSoundVolumn * 100)
  178. videoStickers.append(sticker)
  179. let voiceSticker = itemModel.voiceStickers[index]
  180. let voice = PQEditVisionTrackMaterialsModel()
  181. voice.model_in = 0
  182. voice.out = voiceSticker.endCMTime.seconds - voiceSticker.startCMTime.seconds
  183. voice.timelineIn = totalDur + subDur
  184. voice.timelineOut = totalDur + subDur + voice.out
  185. voice.aptDuration = voice.out
  186. voice.duration = voice.out
  187. voice.locationPath = voiceSticker.wavFilePath
  188. voice.volumeGain = 100 // Float64(model.volume)
  189. voiceList.append(voice)
  190. let titleModels = itemModel.titleStickers.filter { mod in
  191. mod.recordId == voiceSticker.recordId
  192. }
  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 = titleS.timelineIn + CMTime(seconds: totalDur + subDur , preferredTimescale: 1000) - voiceSticker.startCMTime
  200. newTitleSticker.timelineOut = titleS.timelineOut + CMTime(seconds: totalDur + subDur, preferredTimescale: 1000) - voiceSticker.startCMTime
  201. BFLog(1, message: "timein - \(newTitleSticker.timelineIn), out - \(newTitleSticker.timelineOut)")
  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": "compose_fail_lost".BFLocale])
  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.seconds
  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. let outputSize: CGSize = CGSize(width: 1080, height: Int(1080 * CGFloat(UIScreen.main.bounds.size.height / UIScreen.main.bounds.size.width)))
  306. BFLog(message: "输出视频大小:\(outputSize)")
  307. // add by ak 有字幕数据 & 显示字幕开关打开 添加字幕filter
  308. var subtitleFilter:PQSubTitleFilter?
  309. if titleStickers.count > 0,titleStickers.first?.setting.subtitleIsShow ?? true {
  310. subtitleFilter = PQSubTitleFilter(st: titleStickers, inputSize: outputSize)
  311. }
  312. exporter = PQCompositionExporter(asset: composition, videoComposition: nil, audioMix: audioMix, filters:nil,stickers: videoStickers, animationTool: nil, exportURL: outPutMP4URL,subTitleFilter:subtitleFilter)
  313. var orgeBitRate = Int(outputSize.width * outputSize.height * 3)
  314. for stick in videoStickers {
  315. if stick.type == StickerType.VIDEO.rawValue, stick.locationPath.count > 0 {
  316. let asset = AVURLAsset(url: URL(fileURLWithPath: stick.locationPath), options: avAssertOptions)
  317. let cbr = asset.tracks(withMediaType: .video).first?.estimatedDataRate
  318. if Int(cbr ?? 0) > orgeBitRate {
  319. orgeBitRate = Int(cbr ?? 0)
  320. }
  321. }
  322. }
  323. BFLog(1, message: String(format: "导出设置的码率为:%.3f MB", Double(orgeBitRate) / 1024.0 / 1024.0 / 8.0))
  324. let preSize = Double(orgeBitRate) * totalDuration / (1024 * 1024 * 8)
  325. let freeSize = PQBridgeObject.getPhoneDiskFreeSize()
  326. if preSize + 100.0 > freeSize { // 存储完后磁盘剩余至少100M
  327. let error = NSError(domain: "err", code: ExportError.DiskNoSpace.rawValue, userInfo: ["msg": "需要\(Int(preSize))MB,可用\(Int(freeSize))MB"])
  328. exportCompletion?(error as Error, nil)
  329. return
  330. }
  331. let tempBeginExport = Date().timeIntervalSince1970
  332. if exporter!.prepare(videoSize: outputSize, videoAverageBitRate: orgeBitRate) {
  333. exporter!.start(playeTimeRange: CMTimeRange(start: CMTime.zero, end: CMTime(seconds: totalDuration, preferredTimescale: 1000)))
  334. }
  335. exporter?.progressClosure = { [weak self] _, _, progress in
  336. // BFLog(message: "正片合成进度 \(progress * 100)%")
  337. let useProgress = progress > 1 ? 1 : progress
  338. if progress > 0 { // 更新进度
  339. self?.progress?(useProgress)
  340. }
  341. }
  342. exporter?.completion = { [weak self] url in
  343. // 输出视频时长
  344. if let url = url {
  345. let outSeconds = CMTimeGetSeconds(AVAsset(url: url).duration)
  346. let exportEndTime = Date().timeIntervalSince1970
  347. BFLog(1, message: "生成视频时长为:\(outSeconds) 总用时:\(exportEndTime - tempBeginExport)")
  348. if(PQENVUtil.shared.channel == "Development"){
  349. cShowHUB(superView: nil, msg: (outSeconds == 0) ? "compose_retry3".BFLocale : String(format: "总用时: %.2f", exportEndTime - tempBeginExport))
  350. }
  351. self?.exportCompletion?(nil, url)
  352. } else {
  353. let error = NSError(domain: "err", code: ExportError.ExportExcept.rawValue, userInfo: ["msg": "compose_fail_export".BFLocale])
  354. self?.exportCompletion?(error as Error, nil)
  355. cShowHUB(superView: nil, msg: "compose_fail_export".BFLocale)
  356. }
  357. // 导出完成后取消导出
  358. self?.exporter?.cancel()
  359. }
  360. } else {
  361. // 没有处理,直接copy原文件
  362. if let localPath = data?.first?.localPath {
  363. exportCompletion?(nil, URL(fileURLWithPath: localPath))
  364. }
  365. }
  366. }
  367. func dealAsset() {
  368. // asset?.tracks.first(where: { track in
  369. // if track.mediaType == .audio{
  370. //
  371. // }
  372. // })
  373. }
  374. func getVideoSize(asset: AVURLAsset) -> CGSize {
  375. var size = CGSize.zero
  376. asset.tracks.forEach { track in
  377. if track.mediaType == .video {
  378. let realSize = __CGSizeApplyAffineTransform(track.naturalSize, track.preferredTransform)
  379. size = CGSize(width: ceil(abs(realSize.width)), height: ceil(abs(realSize.height)))
  380. }
  381. }
  382. return size
  383. }
  384. }
  385. extension BFRecordExport {
  386. func mergeAudio(videoStickers: [PQEditVisionTrackMaterialsModel], audios: [PQEditVisionTrackMaterialsModel]?, synthesisAll: Bool) -> (AVMutableAudioMix, AVMutableComposition) {
  387. let composition = AVMutableComposition()
  388. let audioMix = AVMutableAudioMix()
  389. var tempParameters = [AVMutableAudioMixInputParameters]()
  390. var totalDuration: Float64 = 0
  391. for sticker in videoStickers {
  392. if sticker.volumeGain == 0 {
  393. // 如果添加了会有刺啦音
  394. BFLog(message: "音频音量 为0 不添加")
  395. continue
  396. }
  397. // sticker.volumeGain = 50
  398. totalDuration = max(totalDuration, sticker.duration)
  399. tempParameters += PQPlayerViewModel.dealWithMaterialTrack(stickerModel: sticker, composition: composition)
  400. }
  401. if let voices = audios {
  402. if synthesisAll {
  403. tempParameters += mergeRecordVoiceAll(voices: voices, composition)
  404. } else {
  405. tempParameters += mergeRecordVoiceOnly(voices: voices, composition)
  406. }
  407. }
  408. audioMix.inputParameters = tempParameters
  409. return (audioMix, composition)
  410. }
  411. func mergeRecordVoiceOnly(voices: [PQEditVisionTrackMaterialsModel], _ composition: AVMutableComposition) -> [AVMutableAudioMixInputParameters] {
  412. var tempParameters = [AVMutableAudioMixInputParameters]()
  413. var totalDur: Double = 0.0
  414. for model in voices {
  415. if model.volumeGain == 0 {
  416. // 如果添加了会有刺啦音
  417. BFLog(message: "音频音量 为0 不添加")
  418. continue
  419. }
  420. tempParameters += PQPlayerViewModel.dealWithMaterialTrack(stickerModel: model, composition: composition)
  421. totalDur += model.aptDuration
  422. }
  423. return tempParameters
  424. }
  425. func mergeRecordVoiceAll(voices: [PQEditVisionTrackMaterialsModel], _ composition: AVMutableComposition) -> [AVMutableAudioMixInputParameters] {
  426. var tempParameters = [AVMutableAudioMixInputParameters]()
  427. var totalDur = 0.0
  428. for model in voices {
  429. if model.volumeGain == 0 {
  430. // 如果添加了会有刺啦音
  431. BFLog(message: "音频音量 为0 不添加")
  432. continue
  433. }
  434. tempParameters += PQPlayerViewModel.dealWithMaterialTrack(stickerModel: model, composition: composition)
  435. }
  436. return tempParameters
  437. }
  438. }