BFRecordExport.swift.swift 7.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191
  1. //
  2. // BFRecordExport.swift.swift
  3. // BFRecordScreenKit
  4. //
  5. // Created by 胡志强 on 2021/11/25.
  6. //
  7. import Foundation
  8. import AVFoundation
  9. import BFFramework
  10. import BFVideoEditKit
  11. import Photos
  12. import GPUImage
  13. public class BFRecordExport {
  14. public var progress : ((Float)->Void)?
  15. public var exportCompletion : ((Error?, URL?)->Void)?
  16. public var asset:AVURLAsset?
  17. public var voiceList:[PQVoiceModel]? {
  18. didSet {
  19. audioAssets = voiceList?.map({ model in
  20. AVURLAsset(url: URL(fileURLWithPath: model.wavFilePath))
  21. })
  22. }
  23. }
  24. var count = 0
  25. var audioAssets : [AVURLAsset]?
  26. var exporter : PQCompositionExporter?
  27. var mStickers = [PQEditVisionTrackMaterialsModel]()
  28. deinit {
  29. }
  30. public init(){}
  31. //MARK: -
  32. public func start(){
  33. // 1,背景视频素材
  34. let bgMovieInfo: PQEditVisionTrackMaterialsModel = PQEditVisionTrackMaterialsModel()
  35. bgMovieInfo.type = StickerType.VIDEO.rawValue
  36. bgMovieInfo.locationPath = (asset?.url.absoluteString)?.removingPercentEncoding ?? ""
  37. bgMovieInfo.timelineIn = 0
  38. bgMovieInfo.timelineOut = CMTimeGetSeconds(asset?.duration ?? CMTime.zero)
  39. bgMovieInfo.model_in = bgMovieInfo.timelineIn
  40. bgMovieInfo.out = bgMovieInfo.timelineOut
  41. bgMovieInfo.canvasFillType = stickerContentMode.aspectFitStr.rawValue
  42. mStickers.append(bgMovieInfo)
  43. beginExport(videoStickers: mStickers, audioAsset: self.audioAssets)
  44. }
  45. enum DispatchError: Error {
  46. case timeout
  47. }
  48. func beginExport(videoStickers:[PQEditVisionTrackMaterialsModel], audioAsset: [AVURLAsset]?) {
  49. // 输出视频地址
  50. var outPutMP4Path = exportVideosDirectory
  51. if !directoryIsExists(dicPath: outPutMP4Path) {
  52. createDirectory(path: outPutMP4Path)
  53. }
  54. outPutMP4Path.append("video_\(String.qe.timestamp()).mp4")
  55. let outPutMP4URL = URL(fileURLWithPath: outPutMP4Path)
  56. BFLog(1, message: "导出视频地址 \(outPutMP4URL)")
  57. // 处理导出
  58. if (audioAsset?.count ?? 0 ) > 0 || videoStickers.count > 1 {
  59. var audioUrl:URL?
  60. if audioAsset?.count ?? 0 > 0 {
  61. // 多音频合成
  62. if let list = voiceList?.map({ model in
  63. URL(fileURLWithPath: model.wavFilePath)
  64. }){
  65. if list.count == 1 {
  66. audioUrl = list.first
  67. }else {
  68. let semaphore = DispatchSemaphore(value: 0)
  69. PQPlayerViewModel.mergeAudios(urls: list) { completURL in
  70. audioUrl = completURL
  71. BFLog(1, message: "异步做同步")
  72. semaphore.signal()
  73. }
  74. _ = semaphore.wait(timeout: .now() + 5)
  75. }
  76. }
  77. }
  78. // 每次初始化的时候设置初始值 为 nIl
  79. var audioMix: AVMutableAudioMix?
  80. var composition: AVMutableComposition?
  81. let filter = mStickers.map { sticker in
  82. PQMovieFilter(movieSticker: sticker)
  83. }
  84. // 有
  85. if let completURL = audioUrl {
  86. let inputAsset = AVURLAsset(url: completURL, options: avAssertOptions)
  87. (audioMix, composition) = PQVideoEditViewModel.setupAudioMix(originAsset: inputAsset, bgmData: nil, videoStickers: videoStickers)
  88. if composition != nil {
  89. exporter = PQCompositionExporter(asset: composition!, videoComposition: nil, audioMix: audioMix, filters: filter, animationTool: nil, exportURL: outPutMP4URL)
  90. }else {
  91. exporter = PQCompositionExporter(asset: inputAsset, videoComposition: nil, audioMix: nil, filters: filter, animationTool: nil, exportURL: outPutMP4URL)
  92. }
  93. }
  94. let size = getVideoSize()
  95. var orgeBitRate = Int(size.width * size.height * 3)
  96. for stick in mStickers {
  97. if stick.type == StickerType.VIDEO.rawValue {
  98. let asset = AVURLAsset(url: URL(fileURLWithPath: documensDirectory + stick.locationPath), options: avAssertOptions)
  99. let cbr = asset.tracks(withMediaType: .video).first?.estimatedDataRate
  100. if Int(cbr ?? 0) > orgeBitRate {
  101. orgeBitRate = Int(cbr ?? 0)
  102. }
  103. }
  104. }
  105. BFLog(message: "导出设置的码率为:\(orgeBitRate)")
  106. if exporter!.prepare(videoSize: size, videoAverageBitRate: orgeBitRate) {
  107. exporter!.start(playeTimeRange: CMTimeRange(start: CMTime.zero, end: asset?.duration ?? CMTime.zero))
  108. }
  109. exporter?.progressClosure = { [weak self] _, _, progress in
  110. // BFLog(message: "正片合成进度 \(progress * 100)%")
  111. let useProgress = progress > 1 ? 1 : progress
  112. if progress > 0 { // 更新进度
  113. self?.progress?(useProgress)
  114. }
  115. }
  116. exporter?.completion = { [weak self] url in
  117. // 输出视频时长
  118. if let url = url {
  119. let outSeconds = CMTimeGetSeconds(AVAsset(url: url).duration)
  120. BFLog(1, message: "无水印的视频导出完成: \(String(describing: url)) 生成视频时长为:\(outSeconds)")
  121. cShowHUB(superView: nil, msg: ( outSeconds == 0) ? "合成失败请重试。" : "合成成功")
  122. self?.saveVideoToPhoto(url: url)
  123. self?.exportCompletion?(nil, url)
  124. }else{
  125. let error = NSError(domain: "err", code: -1, userInfo: nil)
  126. self?.exportCompletion?(error as Error, nil)
  127. }
  128. // 导出完成后取消导出
  129. self?.exporter?.cancel()
  130. }
  131. } else {
  132. // 没有处理,直接copy原文件
  133. self.exportCompletion?(nil, self.asset?.url)
  134. }
  135. }
  136. func saveVideoToPhoto(url:URL){
  137. PHPhotoLibrary.shared().performChanges {
  138. PHAssetChangeRequest.creationRequestForAssetFromVideo(atFileURL: url)
  139. } completionHandler: { isFinished, _ in
  140. DispatchQueue.main.async {
  141. cShowHUB(superView: nil, msg: "保存成功")
  142. }
  143. }
  144. }
  145. func dealAsset(){
  146. // asset?.tracks.first(where: { track in
  147. // if track.mediaType == .audio{
  148. //
  149. // }
  150. // })
  151. }
  152. func getVideoSize() -> CGSize{
  153. var size = CGSize.zero
  154. self.asset?.tracks.forEach({ track in
  155. if track.mediaType == .video{
  156. let realSize = __CGSizeApplyAffineTransform(track.naturalSize, track.preferredTransform)
  157. size = CGSize(width: abs(realSize.width), height: abs(realSize.height))
  158. }
  159. })
  160. return size
  161. }
  162. }