PQStuckPointPublicController.swift 93 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925
  1. //
  2. // PQStuckPointPublicController.swift
  3. // PQSpeed
  4. //
  5. // Created by SanW on 2021/5/6.
  6. // Copyright © 2021 BytesFlow. All rights reserved.
  7. //
  8. import ObjectMapper
  9. import Photos
  10. import UIKit
  11. import WechatOpenSDK
  12. import Kingfisher
  13. import BFCommonKit
  14. import Alamofire
  15. class PQStuckPointPublicController: PQBaseViewController {
  16. private var isShared: Bool = false // 是否在分享
  17. private var isExportSuccess: Bool = false // 是否导出完成
  18. private var isSaveDraftSuccess: Bool = false // 是否保存草稿完成
  19. private var isSaveProjectSuccess: Bool = false // 是否保存项目完成
  20. private var isUploadSuccess: Bool = false // 是否上传完成
  21. private var isPublicSuccess: Bool = false // 是否发布完成
  22. private var exportLocalURL: URL? // 导出的地址
  23. // 再创作数据
  24. private var reCreateData: PQReCreateModel?
  25. // 确定上传的数据
  26. private var uploadData: PQUploadModel?
  27. // 发布成功的视频数据
  28. private var videoData: PQVideoListModel?
  29. // 视频创作埋点数据
  30. private var eventTrackData: PQVideoMakeEventTrackModel?
  31. // 选中的总时长-统计使用
  32. var selectedTotalDuration: Float64 = 0
  33. // 选择的总数-统计使用
  34. var selectedDataCount: Int = 0
  35. // 选择的图片总数-统计使用
  36. var selectedImageDataCount: Int = 0
  37. // 最大的宽度
  38. private var maxWidth: CGFloat = cScreenWidth
  39. // 最大的高度
  40. private var maxHeight: CGFloat = cScreenHeigth > 568 ? 385 : 385*cScreenHeigth/818
  41. // 开始导出的时间
  42. private let startExportDate: Float64 = Date().timeIntervalSince1970
  43. // 导出结束的时间
  44. private var exportEndDate: Float64 = Date().timeIntervalSince1970
  45. // 取到的封面 给发布界面使用
  46. private var coverImage: UIImage?
  47. // 导出视频工具类
  48. private var exporter: PQCompositionExporter!
  49. // 导出进度
  50. private var exportProgrss = 0
  51. var mStickers: [PQEditVisionTrackMaterialsModel]?
  52. var remindView: PQRemindView?
  53. // 已经选择标题内容,加一个属性接收 使用有不在主线不能直接使用 titleLabel text
  54. var selectTitle: String = ""
  55. // add by ak 玩法类型 调用 producevideo/saveProject 时使用
  56. var rhythmMode: createStickersModel = .createStickersModelPoint
  57. // add by ak 设置的速度
  58. var syncedUpVideoSpeedMax: Float = 0.0
  59. var syncedUpVideoSpeedMin: Float = 0.0
  60. // add by ak 是否是再创作模式
  61. var isReCreate: Bool = false
  62. // 最终使用的音频时长,用于拼接音乐使用
  63. var finallyUserAudioTime: Float = 0.0
  64. // 拼接音乐的开始和结束位置
  65. var clipAudioRange: CMTimeRange = CMTimeRange.zero
  66. // 导出的开始的开始和结束时间
  67. var playeTimeRange: CMTimeRange = CMTimeRange()
  68. //---------------------------add by ak 保存系统相册使用的变量
  69. // 导出有水印的正片
  70. private var watermarkMovieExporter: PQCompositionExporter!
  71. // 带水印 MP4 导出地址
  72. private var watermarkMovieLocalURL: URL?
  73. // 导出片尾
  74. private var endMovieExporter: PQCompositionExporter!
  75. // 导出片尾 MP4 地址
  76. private var endMovieLocalURL: URL?
  77. // 保存相册的合成视频地址 水印+片尾 MP4 地址
  78. private var saveMovieLocalURL: URL?
  79. //----------------------------
  80. // 预览大小
  81. private var preViewSize: CGSize {
  82. switch aspectRatio {
  83. case let .origin(width, height):
  84. var tempHeight: CGFloat = 0
  85. var tempWidth: CGFloat = 0
  86. if width > height {
  87. tempWidth = maxWidth
  88. tempHeight = (maxWidth * height / width)
  89. if tempHeight > maxHeight {
  90. tempHeight = maxHeight
  91. tempWidth = (maxHeight * width / height)
  92. }
  93. } else {
  94. tempHeight = maxHeight
  95. tempWidth = (maxHeight * width / height)
  96. if tempWidth > maxWidth {
  97. tempWidth = maxWidth
  98. tempHeight = (maxWidth * height / width)
  99. }
  100. }
  101. if tempHeight.isNaN || tempWidth.isNaN {
  102. return CGSize.zero
  103. } else {
  104. return CGSize(width: tempWidth, height: tempHeight)
  105. }
  106. case .oneToOne:
  107. if maxWidth > maxHeight {
  108. return CGSize(width: maxHeight, height: maxHeight)
  109. } else {
  110. return CGSize(width: maxWidth, height: maxWidth)
  111. }
  112. case .sixteenToNine:
  113. return CGSize(width: maxWidth, height: maxWidth * 9.0 / 16.0)
  114. case .nineToSixteen:
  115. return CGSize(width: maxHeight * 9.0 / 16.0, height: maxHeight)
  116. default:
  117. break
  118. }
  119. return CGSize(width: maxHeight, height: maxHeight)
  120. }
  121. // 背景音乐
  122. var audioMixModel: PQVoiceModel?
  123. // 画面比例
  124. var aspectRatio: aspectRatio?
  125. // 导出的项目数据
  126. var editProjectModel: PQEditProjectModel? {
  127. didSet {
  128. aspectRatio = PQPlayerViewModel.videoCanvasTypeToAspectRatio(projectModel: editProjectModel)
  129. var totalDuration: Float64 = 0
  130. if editProjectModel?.sData?.sections.count ?? 0 > 0 {
  131. for section in (editProjectModel?.sData?.sections)! {
  132. totalDuration = totalDuration + section.sectionDuration
  133. }
  134. }
  135. editProjectModel?.sData?.videoMetaData?.duration = totalDuration
  136. if editProjectModel?.sData?.sections != nil, (editProjectModel?.sData?.sections.count ?? 0) > 0 {
  137. // 查找出背景图并设置
  138. var coverImageMaterialsModel: PQEditVisionTrackMaterialsModel?
  139. for section in (editProjectModel?.sData?.sections)! {
  140. if coverImageMaterialsModel != nil {
  141. break
  142. }
  143. coverImageMaterialsModel = section.sectionTimeline?.visionTrack?.getEnableVisionTrackMaterials().first
  144. }
  145. if coverImageMaterialsModel != nil {
  146. coverImage = coverImageMaterialsModel?.getCoverImage()
  147. playerHeaderView.image = coverImage
  148. playerHeaderView.contentMode = coverImageMaterialsModel!.canvasFillType == stickerContentMode.aspectFitStr.rawValue ? .scaleAspectFill : .scaleAspectFit
  149. }
  150. }
  151. }
  152. }
  153. /// 所有需要导出的filter
  154. var filters: Array = Array<ImageProcessingOperation>.init()
  155. /// 预览背景页
  156. lazy var bgTopView: UIView = {
  157. let bgTopView = UIView(frame: CGRect(x: 0, y: cDevice_iPhoneNavBarAndStatusBarHei, width: cScreenWidth, height: maxHeight))
  158. bgTopView.backgroundColor = PQBFConfig.shared.styleBackGroundColor
  159. return bgTopView
  160. }()
  161. // 预览界面
  162. var playerHeaderView: UIImageView = {
  163. let playerHeaderView = UIImageView(frame: CGRect(x: 0, y: cDevice_iPhoneNavBarAndStatusBarHei, width: cScreenWidth, height: 0))
  164. playerHeaderView.isUserInteractionEnabled = true
  165. playerHeaderView.contentMode = .scaleAspectFit
  166. playerHeaderView.clipsToBounds = true
  167. return playerHeaderView
  168. }()
  169. // add by ak 播放器的封面 为了不和原有的播放器层级单独添加一个 view
  170. lazy var playerHeaderCoverImageView: UIImageView = {
  171. let playerHeaderCoverImageView = UIImageView()
  172. playerHeaderCoverImageView.isUserInteractionEnabled = true
  173. playerHeaderCoverImageView.contentMode = .scaleAspectFit
  174. playerHeaderCoverImageView.clipsToBounds = true
  175. let playBtn = UIButton(type: .custom)
  176. playBtn.setImage(UIImage.moduleImage(named: "icon_video_play", moduleName: "BFFramework",isAssets: false), for: .normal)
  177. playBtn.tag = 4
  178. playBtn.isUserInteractionEnabled = false
  179. playerHeaderCoverImageView.addSubview(playBtn)
  180. playerHeaderCoverImageView.isHidden = true
  181. return playerHeaderCoverImageView
  182. }()
  183. /// 播放器
  184. lazy var avPlayer: AVPlayer = {
  185. let avPlayer = AVPlayer()
  186. NotificationCenter.default.addObserver(forName: .AVPlayerItemDidPlayToEndTime, object: avPlayer.currentItem, queue: .main) { [weak self] notify in
  187. BFLog(message: "AVPlayerItemDidPlayToEndTime = \(notify)")
  188. avPlayer.seek(to: CMTime.zero)
  189. if self?.playerHeaderCoverImageView.image != nil {
  190. self?.playerHeaderCoverImageView.isHidden = false
  191. }
  192. self?.playBtn.isHidden = false
  193. }
  194. NotificationCenter.default.addObserver(forName: .AVPlayerItemNewErrorLogEntry, object: avPlayer.currentItem, queue: .main) { notify in
  195. BFLog(message: "AVPlayerItemNewErrorLogEntry = \(notify)")
  196. }
  197. NotificationCenter.default.addObserver(forName: .AVPlayerItemFailedToPlayToEndTime, object: avPlayer.currentItem, queue: .main) { notify in
  198. BFLog(message: "AVPlayerItemFailedToPlayToEndTime = \(notify)")
  199. }
  200. NotificationCenter.default.addObserver(forName: .AVPlayerItemPlaybackStalled, object: avPlayer.currentItem, queue: .main) { notify in
  201. BFLog(message: "AVPlayerItemPlaybackStalled = \(notify)")
  202. }
  203. avPlayer.addPeriodicTimeObserver(forInterval: CMTime(value: 1, timescale: 1000), queue: .main) { [weak self] _ in
  204. let progress = CMTimeGetSeconds(avPlayer.currentItem?.currentTime() ?? CMTime.zero) / CMTimeGetSeconds(avPlayer.currentItem?.duration ?? CMTime.zero)
  205. if progress >= 1 {
  206. self?.playBtn.isHidden = false
  207. }
  208. }
  209. return avPlayer
  210. }()
  211. /// 预览layer
  212. lazy var playerLayer: AVPlayerLayer = {
  213. let playerLayer = AVPlayerLayer(player: avPlayer)
  214. playerLayer.frame = playerHeaderView.bounds
  215. return playerLayer
  216. }()
  217. /// 播放按钮
  218. lazy var playBtn: UIButton = {
  219. let playBtn = UIButton(type: .custom)
  220. playBtn.frame = CGRect(x: (preViewSize.width - cDefaultMargin * 5) / 2, y: (preViewSize.height - cDefaultMargin * 5) / 2, width: cDefaultMargin * 5, height: cDefaultMargin * 5)
  221. playBtn.setImage(UIImage.moduleImage(named: "icon_video_play", moduleName: "BFFramework",isAssets: false), for: .normal)
  222. playBtn.tag = 4
  223. playBtn.isHidden = true
  224. playBtn.isUserInteractionEnabled = false
  225. return playBtn
  226. }()
  227. // progressTipsLab
  228. lazy var progressTipsLab: UILabel = {
  229. let progressTipsLab = UILabel()
  230. progressTipsLab.textAlignment = .center
  231. progressTipsLab.font = UIFont.systemFont(ofSize: 14, weight: .medium)
  232. progressTipsLab.numberOfLines = 2
  233. progressTipsLab.textColor = UIColor.white
  234. let attributedText = NSMutableAttributedString(string: "0%\n视频正在处理中,请勿离开")
  235. attributedText.addAttributes([.font: UIFont.systemFont(ofSize: 34)], range: NSRange(location: 0, length: 2))
  236. progressTipsLab.attributedText = attributedText
  237. progressTipsLab.addShadow()
  238. return progressTipsLab
  239. }()
  240. // 进度条
  241. lazy var progressView: UIProgressView = {
  242. let progressView = UIProgressView(progressViewStyle: .default)
  243. progressView.trackTintColor = UIColor(white: 0, alpha: 0.5)
  244. progressView.progressTintColor = UIColor.hexColor(hexadecimal: PQBFConfig.shared.styleColor.rawValue)
  245. progressView.transform = CGAffineTransform(scaleX: 1.0, y: playerHeaderView.frame.height)
  246. return progressView
  247. }()
  248. // 提示
  249. lazy var remindLab: UILabel = {
  250. let remindLab = UILabel()
  251. remindLab.font = UIFont.boldSystemFont(ofSize: 18)
  252. remindLab.textColor = PQBFConfig.shared.styleTitleColor
  253. remindLab.textAlignment = .center
  254. remindLab.numberOfLines = 2
  255. remindLab.backgroundColor = .clear
  256. remindLab.text = "为你的大作起个响亮的标题\n分享秀一下🎉"
  257. return remindLab
  258. }()
  259. // 输入框背景
  260. lazy var inputBackView: UIView = {
  261. let inputBackView = UIView()
  262. inputBackView.backgroundColor = .clear
  263. inputBackView.layer.cornerRadius = 7
  264. inputBackView.layer.borderWidth = 2
  265. inputBackView.layer.borderColor = UIColor.hexColor(hexadecimal: PQBFConfig.shared.styleColor.rawValue).cgColor
  266. return inputBackView
  267. }()
  268. // 手势提示
  269. lazy var pinView: UIImageView = {
  270. let pinView = UIImageView()
  271. pinView.kf.setImage(with: URL(fileURLWithPath: (currentBundlePath()!.path(forResource: "editCoverPin", ofType: ".gif")!)))
  272. return pinView
  273. }()
  274. // 封面
  275. lazy var coverImageView: UIImageView = {
  276. let coverImageView = UIImageView()
  277. coverImageView.isUserInteractionEnabled = true
  278. coverImageView.backgroundColor = .clear
  279. coverImageView.contentMode = .scaleToFill
  280. return coverImageView
  281. }()
  282. // 封面标题
  283. lazy var coverImageTitle: UILabel = {
  284. let coverImageTitle = UILabel()
  285. coverImageTitle.text = "换封面"
  286. coverImageTitle.textAlignment = .center
  287. coverImageTitle.backgroundColor = UIColor(red: 0.22, green: 0.26, blue: 0.35, alpha: 0.5)
  288. coverImageTitle.isUserInteractionEnabled = true
  289. coverImageTitle.textColor = .white
  290. coverImageTitle.font = UIFont.boldSystemFont(ofSize: 12)
  291. return coverImageTitle
  292. }()
  293. // 标题
  294. lazy var titleLabel: UILabel = {
  295. let titleLabel = UILabel()
  296. titleLabel.numberOfLines = 2
  297. titleLabel.isUserInteractionEnabled = true
  298. titleLabel.textColor = UIColor.hexColor(hexadecimal: "#ABABAB")
  299. titleLabel.textAlignment = .left
  300. titleLabel.font = UIFont.systemFont(ofSize: 17)
  301. let ges = UITapGestureRecognizer(target: self, action: #selector(titleLabelClick))
  302. titleLabel.addGestureRecognizer(ges)
  303. return titleLabel
  304. }()
  305. // 编辑发布标题
  306. lazy var publicTitleView: PQEditPublicTitleView = {
  307. let publicTitleView = PQEditPublicTitleView()
  308. publicTitleView.isHidden = true
  309. publicTitleView.confirmBtnClock = { [weak self] title in
  310. BFLog(message: "传出的 title is :\(String(describing: title))")
  311. if title?.count != 0 && title != self?.titleLabel.text {
  312. self?.changPlayerIsPause(isPause: false)
  313. // 判断文字是否有效
  314. var inputText = ""
  315. inputText = title?.replacingOccurrences(of: "\n", with: "") ?? ""
  316. inputText = inputText.replacingOccurrences(of: " ", with: "")
  317. if inputText.count > 0 {
  318. self?.setTitleText(text: title ?? "", textColor: .black)
  319. // 更新数据
  320. self?.videoData?.title = title
  321. self?.updateCoverImagegOrTitle()
  322. }
  323. }
  324. }
  325. publicTitleView.viewIsHiddenCallBack = { [weak self] in
  326. self?.changPlayerIsPause(isPause: false)
  327. }
  328. return publicTitleView
  329. }()
  330. // 编辑发布封面
  331. lazy var publicEditCoverView: PQEditPublicCoverImageView = {
  332. let publicEditCoverView = PQEditPublicCoverImageView(frame: CGRect(x: 0, y: 0, width: cScreenWidth, height: cScreenHeigth))
  333. publicEditCoverView.isHidden = true
  334. return publicEditCoverView
  335. }()
  336. // 分享到朋友圈
  337. lazy var shareWechatBtn: UIButton = {
  338. let shareWechatBtn = UIButton(type: .custom)
  339. shareWechatBtn.frame = CGRect(x: 0, y: 0, width: 70, height: 70)
  340. shareWechatBtn.setImage(UIImage.moduleImage(named: "reCreate_opration_wechat", moduleName: "BFFramework",isAssets: false), for: .normal)
  341. shareWechatBtn.backgroundColor = PQBFConfig.shared.styleBackGroundColor
  342. shareWechatBtn.addCorner(corner: 6)
  343. shareWechatBtn.tag = 2
  344. shareWechatBtn.addTarget(self, action: #selector(btnClick(sender:)), for: .touchUpInside)
  345. return shareWechatBtn
  346. }()
  347. // 分享到好友
  348. lazy var shareFriendBtn: UIButton = {
  349. let shareFriendBtn = UIButton(type: .custom)
  350. shareFriendBtn.frame = CGRect(x: 0, y: 0, width: 70, height: 70)
  351. shareFriendBtn.setImage(UIImage.moduleImage(named: PQBFConfig.shared.shareFriendBtnImage, moduleName: "BFFramework",isAssets: false), for: .normal)
  352. shareFriendBtn.addCorner(corner: 6)
  353. shareFriendBtn.tag = 1
  354. shareFriendBtn.addTarget(self, action: #selector(btnClick(sender:)), for: .touchUpInside)
  355. return shareFriendBtn
  356. }()
  357. // 关闭
  358. lazy var finishedBtn: UIButton = {
  359. let finishedBtn = UIButton(type: .custom)
  360. finishedBtn.setTitle("完成", for: .normal)
  361. finishedBtn.setTitleColor(UIColor.hexColor(hexadecimal: PQBFConfig.shared.styleColor.rawValue), for: .normal)
  362. finishedBtn.titleLabel?.font = UIFont.systemFont(ofSize: 16, weight: .medium)
  363. finishedBtn.backgroundColor = .clear
  364. finishedBtn.tag = 3
  365. finishedBtn.addCorner(corner: 3)
  366. finishedBtn.addTarget(self, action: #selector(btnClick(sender:)), for: .touchUpInside)
  367. return finishedBtn
  368. }()
  369. /// 背景View
  370. lazy var oprationBgView: UIView = {
  371. let oprationBgView = UIView(frame: CGRect(x: 0, y: cDevice_iPhoneNavBarAndStatusBarHei, width: cScreenWidth, height: view.frame.height - cDevice_iPhoneNavBarAndStatusBarHei))
  372. oprationBgView.backgroundColor = .clear
  373. return oprationBgView
  374. }()
  375. // 除了播放器以外的 下半部分操作区
  376. lazy var bottomOprationBgView: UIView = {
  377. let bottomOprationBgView = UIView(frame: CGRect(x: 0, y: cDevice_iPhoneNavBarAndStatusBarHei + maxHeight, width: cScreenWidth, height: view.frame.height - cDevice_iPhoneNavBarAndStatusBarHei - maxHeight))
  378. bottomOprationBgView.backgroundColor = .clear
  379. bottomOprationBgView.isHidden = true
  380. return bottomOprationBgView
  381. }()
  382. ///保存视频到相册提示
  383. lazy var saveVideoTipsBgView: UIView = {
  384. let saveVideoTipsBgView = UIView(frame: CGRect(x: 0, y: cDevice_iPhoneNavBarAndStatusBarHei, width: cScreenWidth, height: 40))
  385. saveVideoTipsBgView.backgroundColor = UIColor.init(red: 0, green: 0, blue: 0, alpha: 0.4)
  386. saveVideoTipsBgView.isHidden = true
  387. saveVideoTipsBgView.alpha = 1
  388. return saveVideoTipsBgView
  389. }()
  390. lazy var saveVideoTipsLabel: UILabel = {
  391. let saveVideoTipsLabel = UILabel(frame: CGRect(x: 0, y: 0, width: cScreenWidth, height: 40))
  392. saveVideoTipsLabel.textColor = .white
  393. saveVideoTipsLabel.textAlignment = .center
  394. saveVideoTipsLabel.font = UIFont.boldSystemFont(ofSize: 17)
  395. saveVideoTipsLabel.text = "视频保存中..."
  396. saveVideoTipsLabel.sizeToFit()
  397. return saveVideoTipsLabel
  398. }()
  399. // 保存重试
  400. lazy var saveRetryBtn: UIButton = {
  401. let finishedBtn = UIButton(type: .custom)
  402. finishedBtn.setTitle("重试", for: .normal)
  403. finishedBtn.setTitleColor(UIColor.white, for: .normal)
  404. finishedBtn.titleLabel?.font = UIFont.systemFont(ofSize: 15, weight: .medium)
  405. finishedBtn.backgroundColor = UIColor.hexColor(hexadecimal: PQBFConfig.shared.styleColor.rawValue)
  406. finishedBtn.tag = 97
  407. finishedBtn.isHidden = true
  408. finishedBtn.addCorner(corner: 5)
  409. finishedBtn.addTarget(self, action: #selector(btnClick(sender:)), for: .touchUpInside)
  410. return finishedBtn
  411. }()
  412. override func backBtnClick() {
  413. if isExportSuccess {
  414. navigationController?.popViewController(animated: true)
  415. } else {
  416. view.endEditing(true)
  417. let remindData = PQBaseModel()
  418. remindData.title = "编辑的内容,将不会被保存"
  419. remindView = PQRemindView(frame: CGRect(x: 0, y: 0, width: cScreenWidth, height: cScreenHeigth))
  420. remindView?.isBanned = true
  421. remindView?.confirmBtn.setTitle("确认", for: .normal)
  422. remindView?.cancelBtn.setTitleColor(UIColor.hexColor(hexadecimal: "#333333"), for: .normal)
  423. remindView?.confirmBtn.setTitleColor(UIColor.hexColor(hexadecimal: "#EE0051"), for: .normal)
  424. UIApplication.shared.keyWindow?.addSubview(remindView!)
  425. remindView?.remindData = remindData
  426. remindView?.remindBlock = { [weak self] item, _ in
  427. if item.tag == 2 {
  428. // 取消导出
  429. if self?.exporter != nil {
  430. self?.exporter.cancel()
  431. }
  432. self?.navigationController?.popViewController(animated: true)
  433. }
  434. }
  435. }
  436. }
  437. override func viewDidLoad() {
  438. super.viewDidLoad()
  439. // 注册上传成功的通知
  440. addNotification(self, selector: #selector(uploadSuccess(notify:)), name: cUploadSuccessKey, object: nil)
  441. PQNotification.addObserver(self, selector: #selector(didBecomeActiveNotification), name: UIApplication.didBecomeActiveNotification, object: nil)
  442. leftButton(image: nil, tintColor: PQBFConfig.shared.styleTitleColor)
  443. navHeadImageView?.backgroundColor = UIColor.clear
  444. lineView?.removeFromSuperview()
  445. view.addSubview(bgTopView)
  446. playerHeaderView.frame = CGRect(origin: CGPoint(x: (cScreenWidth - preViewSize.width) / 2, y: (maxHeight - preViewSize.height) / 2), size: preViewSize)
  447. let ges = UITapGestureRecognizer(target: self, action: #selector(playVideo))
  448. playerHeaderView.addGestureRecognizer(ges)
  449. if playerLayer.superlayer == nil {
  450. playerHeaderView.layer.insertSublayer(playerLayer, at: 0)
  451. }
  452. playerHeaderView.addSubview(playBtn)
  453. playerHeaderView.addSubview(progressView)
  454. view.addSubview(oprationBgView)
  455. oprationBgView.addSubview(progressTipsLab)
  456. // 添加导出view
  457. bgTopView.addSubview(playerHeaderView)
  458. playerHeaderCoverImageView.frame = playerHeaderView.frame
  459. playerHeaderCoverImageView.addGestureRecognizer(UITapGestureRecognizer(target: self, action: #selector(playVideo)))
  460. (playerHeaderCoverImageView.viewWithTag(4))?.frame =
  461. CGRect(x: (preViewSize.width - cDefaultMargin * 5) / 2, y: (preViewSize.height - cDefaultMargin * 5) / 2, width: cDefaultMargin * 5, height: cDefaultMargin * 5)
  462. bgTopView.addSubview(playerHeaderCoverImageView)
  463. view.addSubview(bottomOprationBgView)
  464. bottomOprationBgView.addSubview(remindLab)
  465. bottomOprationBgView.addSubview(shareWechatBtn)
  466. bottomOprationBgView.addSubview(shareFriendBtn)
  467. bottomOprationBgView.addSubview(finishedBtn)
  468. bottomOprationBgView.addSubview(inputBackView)
  469. bottomOprationBgView.addSubview(pinView)
  470. inputBackView.addSubview(coverImageView)
  471. coverImageView.addSubview(coverImageTitle)
  472. inputBackView.addSubview(titleLabel)
  473. view.addSubview(publicTitleView)
  474. view.addSubview(publicEditCoverView)
  475. view.addSubview(saveVideoTipsBgView)
  476. saveVideoTipsBgView.addSubview(saveVideoTipsLabel)
  477. saveVideoTipsBgView.addSubview(saveRetryBtn)
  478. saveVideoTipsLabel.snp.makeConstraints { make in
  479. make.top.height.equalToSuperview()
  480. make.centerX.equalToSuperview()
  481. }
  482. saveRetryBtn.snp.makeConstraints { make in
  483. make.left.equalTo(saveVideoTipsLabel.snp.right).offset(10)
  484. make.top.equalTo(6)
  485. make.bottom.equalTo(-6)
  486. make.width.equalTo(50)
  487. }
  488. coverImageTitle.addGestureRecognizer(UITapGestureRecognizer(target: self, action: #selector(settingCoverImage)))
  489. coverImageView.addGestureRecognizer(UITapGestureRecognizer(target: self, action: #selector(settingCoverImage)))
  490. progressView.snp.makeConstraints { make in
  491. make.left.right.centerY.equalTo(playerHeaderView)
  492. make.height.equalTo(3)
  493. }
  494. progressTipsLab.snp.makeConstraints { make in
  495. make.centerX.equalToSuperview()
  496. make.top.equalToSuperview().offset(((preViewSize.height - 90) / 2) + ((maxHeight - preViewSize.height) / 2))
  497. make.width.equalToSuperview()
  498. make.height.equalTo(90)
  499. }
  500. finishedBtn.snp.makeConstraints { make in
  501. make.centerX.equalToSuperview()
  502. make.bottom.equalToSuperview().offset(-cSafeAreaHeight)
  503. make.width.equalTo(100)
  504. make.height.equalTo(22)
  505. }
  506. shareWechatBtn.snp.makeConstraints { make in
  507. make.right.equalTo(view.snp.centerX).offset(-cDefaultMargin)
  508. make.width.equalTo(164)
  509. make.height.equalTo(52)
  510. make.bottom.equalTo(finishedBtn.snp.top).offset(-32)
  511. }
  512. shareFriendBtn.snp.makeConstraints { make in
  513. make.left.equalTo(view.snp.centerX).offset(cDefaultMargin)
  514. make.width.bottom.height.equalTo(shareWechatBtn)
  515. }
  516. inputBackView.snp.makeConstraints { make in
  517. make.centerX.equalToSuperview()
  518. make.bottom.equalTo(shareWechatBtn.snp.top).offset(-16)
  519. make.width.equalTo(343)
  520. make.height.equalTo(109)
  521. }
  522. // 根据横竖屏设置不同的 UI
  523. let isWidth: Bool = (Float(editProjectModel?.sData?.videoMetaData?.videoWidth ?? 0) / Float(editProjectModel?.sData?.videoMetaData?.videoHeight ?? 0)) >= 1
  524. var coverImageViewHeight = 50.0 * Float(editProjectModel?.sData?.videoMetaData?.videoHeight ?? 0) / Float(editProjectModel?.sData?.videoMetaData?.videoWidth ?? 0)
  525. if coverImageViewHeight > 89 {
  526. coverImageViewHeight = 89
  527. }
  528. coverImageView.snp.makeConstraints { make in
  529. make.left.equalToSuperview().offset(12)
  530. make.width.equalTo(50)
  531. make.top.equalToSuperview().offset(10)
  532. make.height.equalTo(coverImageViewHeight)
  533. }
  534. coverImageTitle.snp.makeConstraints { make in
  535. make.left.equalToSuperview()
  536. make.width.equalTo(50)
  537. make.top.equalTo(coverImageView.snp.bottom).offset(isWidth ? 0 : -23)
  538. make.height.equalTo(23)
  539. }
  540. remindLab.snp.makeConstraints { make in
  541. make.centerX.equalToSuperview()
  542. make.bottom.equalTo(inputBackView.snp.top).offset(-16).priorityHigh()
  543. make.height.equalTo(44)
  544. make.top.greaterThanOrEqualTo(5)
  545. make.bottom.lessThanOrEqualTo(inputBackView.snp.top).offset(-5)
  546. }
  547. titleLabel.snp.makeConstraints { make in
  548. make.height.equalTo(48)
  549. make.left.equalTo(coverImageView.snp.right).offset(12)
  550. make.right.equalToSuperview().offset(-14)
  551. make.top.equalToSuperview().offset(10)
  552. }
  553. pinView.snp.makeConstraints { make in
  554. make.height.width.equalTo(72)
  555. make.right.equalToSuperview()
  556. make.bottom.equalTo(inputBackView.snp.bottom)
  557. }
  558. publicTitleView.snp.makeConstraints { make in
  559. make.height.equalTo(cScreenHeigth)
  560. make.width.equalTo(cScreenWidth)
  561. make.bottom.equalToSuperview()
  562. }
  563. // 取消所有的导出
  564. PQSingletoMemoryUtil.shared.allExportSession.forEach { _, exportSession in
  565. exportSession.cancelExport()
  566. }
  567. // 开始导出
  568. appendAudio()
  569. /// 保存草稿
  570. saveDraftbox()
  571. // 曝光上报:窗口曝光
  572. PQEventTrackViewModel.baseReportUpload(businessType: .bt_windowView, objectType: .ot_view_publishSyncedUp, pageSource: .sp_stuck_publishSyncedUp, extParams: nil, remindmsg: "卡点视频数据上报-(曝光上报:窗口曝光)")
  573. // 取推荐标题
  574. getTitles()
  575. networkStausListen()
  576. }
  577. override func viewWillAppear(_ animated: Bool) {
  578. super.viewWillAppear(animated)
  579. PQNotification.addObserver(self, selector: #selector(enterBackground), name: UIApplication.didEnterBackgroundNotification, object: nil)
  580. PQNotification.addObserver(self, selector: #selector(willEnterForeground), name: UIApplication.willEnterForegroundNotification, object: nil)
  581. DispatchQueue.main.async {
  582. UIApplication.shared.isIdleTimerDisabled = true
  583. }
  584. //从相册选择一个照片后回调
  585. addNotification(self, selector: #selector(imageSelectedImage(notify:)), name: cSelectedImageSuccessKey, object: nil)
  586. #if swift(>=4.2)
  587. let memoryNotification = UIApplication.didReceiveMemoryWarningNotification
  588. _ = UIApplication.willTerminateNotification
  589. _ = UIApplication.didEnterBackgroundNotification
  590. #else
  591. let memoryNotification = NSNotification.Name.UIApplicationDidReceiveMemoryWarning
  592. let terminateNotification = NSNotification.Name.UIApplicationWillTerminate
  593. let enterbackgroundNotification = NSNotification.Name.UIApplicationDidEnterBackground
  594. #endif
  595. NotificationCenter.default.addObserver(
  596. self, selector: #selector(clearMemoryCache), name: memoryNotification, object: nil
  597. )
  598. }
  599. @objc public func clearMemoryCache() {
  600. BFLog(message: "收到内存警告")
  601. }
  602. override func viewWillDisappear(_ animated: Bool) {
  603. super.viewWillDisappear(animated)
  604. DispatchQueue.main.async {
  605. UIApplication.shared.isIdleTimerDisabled = false
  606. }
  607. }
  608. deinit {
  609. BFLog(1, message: "发布界面析构release")
  610. view.endEditing(true)
  611. PQNotification.removeObserver(self)
  612. // 取消导出
  613. if exporter != nil {
  614. exporter.cancel()
  615. }
  616. if watermarkMovieExporter != nil{
  617. watermarkMovieExporter.cancel()
  618. }
  619. if endMovieExporter != nil{
  620. endMovieExporter.cancel()
  621. }
  622. exporter?.input?.removeAllTargets()
  623. watermarkMovieExporter?.input?.removeAllTargets()
  624. endMovieExporter?.input?.removeAllTargets()
  625. avPlayer.pause()
  626. avPlayer.replaceCurrentItem(with: nil)
  627. // 点击上报:返回按钮
  628. PQEventTrackViewModel.baseReportUpload(businessType: .bt_buttonClick, objectType: .ot_click_back, pageSource: .sp_stuck_publishSyncedUp, extParams: nil, remindmsg: "卡点视频数据上报-(点击上报:返回按钮)")
  629. }
  630. // MARK: - 网络监控
  631. func networkStausListen(){
  632. manager?.startListening(onUpdatePerforming: { status in
  633. if status == .reachable(.cellular) || status == .reachable(.ethernetOrWiFi) {
  634. cHiddenHUB(superView: nil)
  635. } else {
  636. cShowHUB(superView: nil, msg: "当前网络不佳,请尝试重新连接")
  637. }
  638. })
  639. }
  640. }
  641. // MARK: - 导出/上传/下载及其他方法
  642. /// 导出/上传/下载及其他方法
  643. extension PQStuckPointPublicController {
  644. /// fp1 - 导出视频
  645. /// 开始导出视频
  646. /// 合并声音
  647. /// - Parameter urls: 所有音频的URL 是全路径方便复用
  648. /// - Parameter completeHander: 返回的 URL 全路径的 URL 如果要保存替换掉前缀
  649. func mergeAudios(originAsset: AVURLAsset, mTotalDuration: Float, clipAudioRange: CMTimeRange = CMTimeRange.zero, mStartTime _: CMTime = .zero, completeHander: @escaping (_ fileURL: URL?) -> Void) {
  650. let timeInterval: TimeInterval = Date().timeIntervalSince1970
  651. let composition = AVMutableComposition()
  652. let originaDuration = CMTimeGetSeconds(clipAudioRange.duration)
  653. BFLog(message: "处理主音频 原始时长startTime = \(originaDuration) 要显示时长totalDuration = \(mTotalDuration)")
  654. //originaDuration = 37.616768 mTotalDuration = 37.616776 TODO 都用 INT 微秒级
  655. if Float64(String(format: "%.3f",mTotalDuration)) ?? 0.0 <= Float64(String(format: "%.3f",originaDuration)) ?? 0.0 {
  656. BFLog(message: "不用拼接音频文件 \(originAsset.url) 时长is \(CMTimeGetSeconds(originAsset.duration))")
  657. completeHander(originAsset.url)
  658. return
  659. }
  660. // 整倍数
  661. let count = Int(mTotalDuration) / Int(originaDuration)
  662. // 有余数多 clip 一整段
  663. let row = mTotalDuration - Float(count) * Float(originaDuration)
  664. // 已经拼接的总时长
  665. var totalDuration: CMTime = .zero
  666. // 第一段的时长
  667. var duration: CMTime = .zero
  668. // 第一段的区间
  669. var timeRange: CMTimeRange = CMTimeRange.zero
  670. if count > 0 {
  671. for index in 0 ..< count {
  672. // 第0段从0开始到推荐的结束,播放器的开始时间不是从0开始的
  673. duration = CMTime(value: CMTimeValue((CMTimeGetSeconds(clipAudioRange.end)) * Double(playerTimescaleInt)), timescale: playerTimescaleInt)
  674. BFLog(message: "每一个文件的 duration \(CMTimeGetSeconds(duration))")
  675. var timeRange = CMTimeRangeMake(start: .zero, duration: duration)
  676. if index != 0 {
  677. // (CMTimeGetSeconds(clipAudioRange.end) - CMTimeGetSeconds(mStartTime))为用户选择的第一段时长
  678. timeRange = clipAudioRange
  679. }
  680. BFLog(message: "合并的文件地址: \(originAsset.url)")
  681. let audioAsset = originAsset
  682. let tracks = audioAsset.tracks(withMediaType: .audio)
  683. if tracks.count == 0 {
  684. BFLog(message: "音频数据无效不进行合并,所有任务结束要确保输入的数据都正常! \(originAsset.url)")
  685. completeHander(URL(string: ""))
  686. return
  687. }
  688. let assetTrack: AVAssetTrack = tracks[0]
  689. let compositionAudioTrack: AVMutableCompositionTrack = composition.addMutableTrack(withMediaType: AVMediaType.audio, preferredTrackID: CMPersistentTrackID())!
  690. do {
  691. //
  692. try compositionAudioTrack.insertTimeRange(timeRange, of: assetTrack, at: totalDuration)
  693. } catch {
  694. BFLog(message: "error is \(error)")
  695. completeHander(URL(string: ""))
  696. return
  697. }
  698. totalDuration = CMTimeAdd(totalDuration, timeRange.duration)
  699. }
  700. }
  701. if row > 0 {
  702. duration = CMTime(value: CMTimeValue(Float(CMTimeGetSeconds(totalDuration)) * Float(playerTimescaleInt)), timescale: playerTimescaleInt)
  703. timeRange = CMTimeRange(start: clipAudioRange.start, duration: CMTime(value: Int64(Double(row) * Double(playerTimescaleInt)), timescale: playerTimescaleInt))
  704. BFLog(message: "合并的文件地址: \(originAsset.url)")
  705. let audioAsset = originAsset
  706. let tracks = audioAsset.tracks(withMediaType: .audio)
  707. if tracks.count == 0 {
  708. BFLog(message: "音频数据无效不进行合并,所有任务结束要确保输入的数据都正常! \(originAsset.url)")
  709. completeHander(URL(string: ""))
  710. return
  711. }
  712. let assetTrack: AVAssetTrack = tracks[0]
  713. let compositionAudioTrack: AVMutableCompositionTrack = composition.addMutableTrack(withMediaType: AVMediaType.audio, preferredTrackID: CMPersistentTrackID())!
  714. do {
  715. //
  716. try compositionAudioTrack.insertTimeRange(timeRange, of: assetTrack, at: totalDuration)
  717. } catch {
  718. BFLog(message: "合并音频 error is \(error)")
  719. completeHander(URL(string: ""))
  720. return
  721. }
  722. totalDuration = CMTimeAdd(totalDuration, timeRange.duration)
  723. }
  724. let assetExport = AVAssetExportSession(asset: composition, presetName: AVAssetExportPresetAppleM4A)
  725. BFLog(message: "assetExport.supportedFileTypes is \(String(describing: assetExport?.supportedFileTypes))")
  726. assetExport?.outputFileType = .m4a
  727. // XXXX 注意文件名的后缀要和outputFileType 一致 否则会导出失败
  728. var audioFilePath = exportAudiosDirectory
  729. if !directoryIsExists(dicPath: audioFilePath) {
  730. BFLog(message: "文件夹不存在")
  731. createDirectory(path: audioFilePath)
  732. }
  733. audioFilePath.append("merge_\(timeInterval).m4a")
  734. let fileUrl = URL(fileURLWithPath: audioFilePath)
  735. assetExport?.outputURL = fileUrl
  736. assetExport?.exportAsynchronously {
  737. if assetExport!.status == .completed {
  738. let audioAsset = AVURLAsset(url: fileUrl, options: avAssertOptions)
  739. BFLog(1, message: "拼接声音文件 完成 \(fileUrl) 时长is \(CMTimeGetSeconds(audioAsset.duration))")
  740. completeHander(fileUrl)
  741. } else {
  742. print("拼接出错 \(String(describing: assetExport?.error))")
  743. completeHander(URL(string: ""))
  744. }
  745. }
  746. }
  747. func appendAudio() {
  748. //更新一下假进度
  749. updatePublicCurrentProgress(useProgress: 0.01)
  750. let inputAsset = AVURLAsset(url: URL(fileURLWithPath: documensDirectory + (audioMixModel?.localPath ?? "")), options: nil)
  751. let startMergeTime = CFAbsoluteTimeGetCurrent()
  752. mergeAudios(originAsset: inputAsset, mTotalDuration: finallyUserAudioTime, clipAudioRange: clipAudioRange, mStartTime: CMTime(value: CMTimeValue((mStickers?.first?.timelineIn ?? 0.0) * Float64(playerTimescaleInt)), timescale: playerTimescaleInt)) { [weak self] completURL in
  753. if completURL != nil {
  754. let asset = AVURLAsset(url: completURL!, options: nil)
  755. BFLog(message: "拼接后音频时长\(asset.duration.seconds) url is \(String(describing: completURL)) 用时\(CFAbsoluteTimeGetCurrent() - startMergeTime)")
  756. //导出不带水印的正片
  757. self?.beginExport(inputAsset: asset)
  758. //导出带水印的正片
  759. self?.beginExportWatermarkMovie(inputAsset:asset)
  760. }else{
  761. cShowHUB(superView: self?.view, msg: "合成失败请重试。")
  762. }
  763. }
  764. }
  765. func beginExport(inputAsset: AVURLAsset!) {
  766. if !(editProjectModel?.sData?.sections != nil && (editProjectModel?.sData?.sections.count ?? 0) > 0) {
  767. BFLog(message: "项目段落错误❌")
  768. return
  769. }
  770. // 输出视频地址
  771. var outPutMP4Path = exportVideosDirectory
  772. if !directoryIsExists(dicPath: outPutMP4Path) {
  773. BFLog(message: "文件夹不存在")
  774. createDirectory(path: outPutMP4Path)
  775. }
  776. outPutMP4Path.append("video_\(String.qe.timestamp()).mp4")
  777. let outPutMP4URL = URL(fileURLWithPath: outPutMP4Path)
  778. BFLog(message: "导出视频地址 \(outPutMP4URL)")
  779. exporter = PQCompositionExporter(asset: inputAsset, videoComposition: nil, audioMix: nil, filters: nil, stickers: mStickers, animationTool: nil, exportURL: outPutMP4URL)
  780. var orgeBitRate = (editProjectModel?.sData?.videoMetaData?.videoWidth ?? 0) * (editProjectModel?.sData?.videoMetaData?.videoHeight ?? 0) * 3
  781. if mStickers != nil {
  782. for stick in mStickers! {
  783. if stick.type == StickerType.VIDEO.rawValue {
  784. let asset = AVURLAsset(url: URL(fileURLWithPath: documensDirectory + stick.locationPath), options: avAssertOptions)
  785. let cbr = asset.tracks(withMediaType: .video).first?.estimatedDataRate
  786. if Int(cbr ?? 0) > orgeBitRate {
  787. orgeBitRate = Int(cbr ?? 0)
  788. }
  789. }
  790. }
  791. }
  792. BFLog(message: "导出设置的码率为:\(orgeBitRate)")
  793. exporter.showGaussianBlur = true
  794. if exporter.prepare(videoSize: CGSize(width: editProjectModel?.sData?.videoMetaData?.videoWidth ?? 0, height: editProjectModel?.sData?.videoMetaData?.videoHeight ?? 0), videoAverageBitRate: orgeBitRate) {
  795. BFLog(message: "开始导出 \(String(describing: playeTimeRange.start)) 结束 \(String(describing: playeTimeRange.end))")
  796. exporter.start(playeTimeRange: playeTimeRange)
  797. BFLog(message: "开始导出")
  798. }
  799. exporter.progressClosure = { [weak self] _, _, progress in
  800. BFLog(message: "正片合成进度 \(progress)")
  801. let useProgress = progress > 1 ? 1 : progress
  802. if progress > 0, Int(useProgress * 100) > (self?.exportProgrss ?? 0) {
  803. // 更新进度
  804. self?.updatePublicCurrentProgress(useProgress: useProgress * 0.88)
  805. }
  806. }
  807. exporter.completion = { [weak self] url in
  808. BFLog(message: "无水印的视频导出完成: \(String(describing: url)) 生成视频时长为:\(CMTimeGetSeconds(AVAsset(url: (url ?? URL(string: "https://media.w3.org/2010/05/sintel/trailer.mp4")!)).duration))")
  809. // 导出完成后取消导出
  810. if self?.exporter != nil {
  811. self?.exporter.cancel()
  812. }
  813. self?.remindView?.removeFromSuperview()
  814. if !(self?.isExportSuccess ?? false) {
  815. self?.isExportSuccess = true
  816. self?.exportEndDate = Date().timeIntervalSince1970
  817. BFLog(message: "视频导出完成-开始去发布视频 总时长为\((self?.exportEndDate ?? 0) - (self?.startExportDate ?? 0) * 1000)")
  818. self?.exportLocalURL = url
  819. /// fp2-1-1 - 请求权限
  820. // self?.authorizationStatus()
  821. /// fp2-2 - 保存草稿
  822. // self?.saveDraftbox()
  823. /// fp2 - 处理视频数据
  824. self?.dealWithVideoData()
  825. }
  826. }
  827. }
  828. /// fp2-1-1 - 请求权限
  829. func authorizationStatus() {
  830. let authStatus = PHPhotoLibrary.authorizationStatus()
  831. if authStatus == .notDetermined {
  832. // 第一次触发授权 alert
  833. PHPhotoLibrary.requestAuthorization { [weak self] (status: PHAuthorizationStatus) -> Void in
  834. if status != .authorized {
  835. cShowHUB(superView: nil, msg: "您尚未打开相册权限,请到设置页打开相册权限")
  836. } else {
  837. /// fp2-1-2 - 保存视频到相册
  838. self?.saveStuckPointVideo()
  839. }
  840. }
  841. } else if authStatus == .authorized {
  842. /// fp2-1-2 - 保存视频到相册
  843. saveStuckPointVideo()
  844. } else {
  845. // cShowHUB(superView: nil, msg: "您尚未打开相册权限,请到设置页打开相册权限")
  846. }
  847. }
  848. /// fp2-1-2 - 保存视频到相册
  849. /// - Parameter localPath: localPath description
  850. /// - Returns: <#description#>
  851. func saveStuckPointVideo() {
  852. if(saveMovieLocalURL == nil){
  853. BFLog(message: "保存相册的视频导出地址无效!!!")
  854. saveVideoTipsLabel.text = "视频保存失败"
  855. saveRetryBtn.isHidden = false
  856. saveVideoTipsBgView.isHidden = false
  857. // DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + 0.8) { [weak self] in
  858. // self?.saveVideoTipsBgView.isHidden = true
  859. // }
  860. return
  861. }
  862. let authStatus = PHPhotoLibrary.authorizationStatus()
  863. if authStatus == .authorized {
  864. let photoLibrary = PHPhotoLibrary.shared()
  865. photoLibrary.performChanges({ [weak self] in
  866. PHAssetChangeRequest.creationRequestForAssetFromVideo(atFileURL: (self?.saveMovieLocalURL)!)
  867. }) { [weak self] isFinished, _ in
  868. DispatchQueue.main.async { [weak self] in
  869. if self?.view != nil {
  870. if isFinished {
  871. self?.saveVideoTipsLabel.text = "视频已保存到相册"
  872. self?.saveRetryBtn.isHidden = true
  873. DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + 0.8) { [weak self] in
  874. self?.saveVideoTipsBgView.isHidden = true
  875. }
  876. } else {
  877. self?.saveVideoTipsLabel.text = "视频保存失败"
  878. self?.saveRetryBtn.isHidden = false
  879. // DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + 0.8) { [weak self] in
  880. // self?.saveVideoTipsBgView.isHidden = true
  881. // }
  882. }
  883. }
  884. }
  885. }
  886. } else {
  887. // cShowHUB(superView: nil, msg: "您尚未打开相册权限,请到设置页打开相册权限")
  888. }
  889. }
  890. /// fp2-2 - 保存草稿
  891. /// - Returns: <#description#>
  892. @objc func saveDraftbox() {
  893. let sdata = editProjectModel?.sData?.toJSONString(prettyPrint: false)
  894. if sdata != nil, (sdata?.count ?? 0) > 0 {
  895. DispatchQueue.global().async { [weak self] in
  896. PQBaseViewModel.saveDraftbox(draftboxId: self?.editProjectModel?.draftboxId, title: self?.editProjectModel?.sData?.videoMetaData?.title, coverUrl: self?.editProjectModel?.sData?.videoMetaData?.coverUrl, sdata: sdata!, videoFromScene: .stuckPoint, copyType: (self?.audioMixModel != nil && self?.audioMixModel?.originProjectId != nil && (self?.audioMixModel?.originProjectId?.count ?? 0) > 0) ? 3 : nil, originProjectId: self?.audioMixModel?.originProjectId) { [weak self] draftboxInfo, _ in
  897. if draftboxInfo != nil {
  898. self?.editProjectModel?.draftboxId = draftboxInfo?["draftboxId"] as? String ?? ""
  899. self?.editProjectModel?.sData?.videoMetaData?.title = draftboxInfo?["title"] as? String ?? ""
  900. self?.editProjectModel?.sData?.videoMetaData?.coverUrl = draftboxInfo?["coverUrl"] as? String ?? ""
  901. self?.editProjectModel?.dataVersionCode = draftboxInfo?["dataVersionCode"] as? Int ?? 0
  902. BFLog(message: "保存远程的草稿成功")
  903. self?.isSaveDraftSuccess = true
  904. /// fp3 - 保存项目
  905. self?.saveProject()
  906. } else {
  907. // 保存草稿失败-播放视频
  908. // self?.publicEnd(isError: true)
  909. }
  910. }
  911. }
  912. } else {
  913. cShowHUB(superView: nil, msg: "您尚未打开相册权限,请到设置页打开相册权限")
  914. // 保存草稿失败-播放视频
  915. publicEnd(isError: true)
  916. }
  917. }
  918. /// fp3 - 保存项目
  919. /// - Returns: description
  920. func saveProject() {
  921. if isSaveDraftSuccess {
  922. let sdata = editProjectModel?.sData?.toJSONString(prettyPrint: false) ?? ""
  923. let draftboxId: String? = editProjectModel?.draftboxId
  924. PQBaseViewModel.saveProject(draftboxId: draftboxId, sdata: sdata, videoFromScene: .stuckPoint, rhythmMode: rhythmMode) { [weak self] projectId, msg in
  925. BFLog(message: "生成的项目id1111 :\(projectId ?? ""),msg = \(msg ?? "")")
  926. if projectId == nil || (projectId?.count ?? 0) <= 0 {
  927. PQBaseViewModel.saveProject(draftboxId: draftboxId, sdata: sdata, videoFromScene: .stuckPoint, rhythmMode: self?.rhythmMode ?? .createStickersModelPoint) { [weak self] projectId, msg in
  928. BFLog(message: "生成的项目id222 :\(projectId ?? ""),msg = \(msg ?? "")")
  929. if projectId == nil || (projectId?.count ?? 0) <= 0 {
  930. PQBaseViewModel.saveProject(draftboxId: draftboxId, sdata: sdata, videoFromScene: .stuckPoint, rhythmMode: self?.rhythmMode ?? .createStickersModelPoint) { [weak self] projectId, msg in
  931. BFLog(message: "生成的项目id 3333:\(projectId ?? ""),msg = \(msg ?? "")")
  932. if projectId != nil, (projectId?.count ?? 0) > 0 {
  933. self?.editProjectModel?.projectId = projectId ?? ""
  934. }
  935. /// fp4 - 处理视频数据
  936. // self?.dealWithVideoData()
  937. }
  938. } else {
  939. self?.editProjectModel?.projectId = projectId ?? ""
  940. /// fp4 - 处理视频数据
  941. // self?.dealWithVideoData()
  942. }
  943. }
  944. } else {
  945. self?.editProjectModel?.projectId = projectId ?? ""
  946. /// fp4 - 处理视频数据
  947. // self?.dealWithVideoData()
  948. }
  949. }
  950. }
  951. }
  952. /// fp4 - 处理视频数据
  953. /// - Returns: description
  954. @objc func dealWithVideoData() {
  955. BFLog(message: "开始去发布视频12")
  956. isSaveProjectSuccess = true
  957. if isExportSuccess && exportLocalURL != nil {
  958. BFLog(message: "素材上传完成同时视频导出完成开始发布视频")
  959. // 更新项目
  960. PQBaseViewModel.updateProject(projectId: editProjectModel?.projectId ?? "", produceStatus: "5") { repseon, _ in
  961. BFLog(message: "updateProject 结果 is \(String(describing: repseon))")
  962. }
  963. let asset = AVURLAsset(url: exportLocalURL!, options: nil)
  964. let tempUploadData = PQUploadModel()
  965. tempUploadData.duration = CMTimeGetSeconds(asset.duration)
  966. tempUploadData.localPath = exportLocalURL?.absoluteString
  967. tempUploadData.videoWidth = CGFloat(editProjectModel?.sData?.videoMetaData?.videoWidth ?? 0)
  968. tempUploadData.videoHeight = CGFloat(editProjectModel?.sData?.videoMetaData?.videoHeight ?? 0)
  969. tempUploadData.image = PQVideoSnapshotUtil.videoSnapshot(videoURL: exportLocalURL!, time: 0)
  970. if tempUploadData.image == nil {
  971. tempUploadData.image = coverImage
  972. }
  973. tempUploadData.videoFromScene = .stuckPoint
  974. eventTrackData = getExportEventTrackData()
  975. eventTrackData?.projectId = editProjectModel?.projectId ?? ""
  976. uploadData = tempUploadData
  977. if uploadData?.image == nil {
  978. uploadData?.image = PQVideoSnapshotUtil.videoSnapshot(videoURL: exportLocalURL!, time: 0)
  979. }
  980. if uploadData?.image != nil {
  981. playerHeaderView.image = uploadData?.image
  982. coverImageView.image = uploadData?.image
  983. }
  984. if isExportSuccess, exportLocalURL != nil {
  985. let size = try! exportLocalURL?.resourceValues(forKeys: [.fileSizeKey])
  986. BFLog(message: "size = \(String(describing: size))")
  987. if Float64(size?.fileSize ?? 0) <= maxUploadSize {
  988. /// fp5 - 上传视频
  989. reUploadVideo()
  990. }
  991. }
  992. }
  993. }
  994. /// fp5 - 上传视频
  995. /// - Returns: <#description#>
  996. @objc func reUploadVideo() {
  997. if uploadData?.stsToken != nil {
  998. multipartUpload(response: uploadData?.stsToken)
  999. } else {
  1000. uploadVideo()
  1001. }
  1002. }
  1003. /// fp5-1 - 开始上传视频
  1004. /// - Returns: <#description#>
  1005. func uploadVideo() {
  1006. let uploadRequest: OSSMultipartUploadRequest? = PQAliOssUtil.shared.allTasks[uploadData?.videoBucketKey ?? ""]
  1007. if uploadRequest != nil, "\(uploadRequest?.callbackParam["code"] ?? "0")" == "1" {
  1008. return
  1009. }
  1010. // 更新进度
  1011. updatePublicCurrentProgress(useProgress: 0.89)
  1012. DispatchQueue.global().async {
  1013. PQBaseViewModel.getStsToken { [weak self] response, _ in
  1014. if response == nil {
  1015. self?.showUploadRemindView(isNetCollected: false, msg: "token获取数据失败了哦~")
  1016. return
  1017. }
  1018. // 更新进度
  1019. self?.updatePublicCurrentProgress(useProgress: 0.90)
  1020. BFLog(message: "取我方服务器STS 返回数据 \(String(describing: response))")
  1021. self?.multipartUpload(response: response)
  1022. }
  1023. }
  1024. }
  1025. /// fp5-2 - 继续上传视频
  1026. /// - Parameter response: <#response description#>
  1027. func multipartUpload(response: [String: Any]?) {
  1028. let FileName: String = "\(response?["FileName"] ?? "")"
  1029. let uploadID: String = "\(response?["Upload"] ?? "")"
  1030. uploadData?.stsToken = response
  1031. uploadData?.videoBucketKey = FileName
  1032. uploadData?.uploadID = uploadID
  1033. if uploadData?.asset != nil && isValidURL(url: uploadData?.localPath) {
  1034. PQPHAssetVideoParaseUtil.exportPHAssetToMP4(phAsset: (uploadData?.asset)!, isCancelCurrentExport: true) { [weak self] _, _, filePath, _ in
  1035. if filePath != nil, (filePath?.count ?? 0) > 0 {
  1036. self?.uploadData?.localPath = filePath
  1037. PQAliOssUtil.multipartUpload(localPath: self?.uploadData?.localPath ?? "", response: response)
  1038. }
  1039. }
  1040. } else {
  1041. PQAliOssUtil.multipartUpload(localPath: uploadData?.localPath ?? "", response: response)
  1042. }
  1043. PQAliOssUtil.shared.aliOssHander = { [weak self] isMatarialUpload, materialType, _, code, objectkey, _, _, _, _, _, _, _, _, _ in
  1044. if !isMatarialUpload, materialType == .VIDEO, self?.uploadData?.videoBucketKey == objectkey {
  1045. if code == 6 { // 无网
  1046. let uploadRequest: OSSMultipartUploadRequest? = PQAliOssUtil.shared.allTasks[self?.uploadData?.videoBucketKey ?? ""]
  1047. if !(uploadRequest != nil && "\(uploadRequest?.callbackParam["code"] ?? "0")" == "1") {
  1048. self?.showUploadRemindView(msg:"aliOss")
  1049. }
  1050. } else if code == 260 {
  1051. self?.showUploadRemindView(isNetCollected: false, msg:"aliOss")
  1052. } else if code != 1 {
  1053. // 上传失败-播放视频
  1054. self?.publicEnd(isError: true)
  1055. }
  1056. }
  1057. }
  1058. PQAliOssUtil.shared.aliOssProgressHander = { [weak self] bytesSent, totalBytesSent, totalBytesExpectedToSend, _, _ in
  1059. let progress: Float = 0.90 + Float(Float(totalBytesSent) / Float(totalBytesExpectedToSend)) * 0.09
  1060. BFLog(message: "卡点视频上传:bytesSent = \(bytesSent),totalBytesSent = \(totalBytesSent),totalBytesExpectedToSend = \(totalBytesExpectedToSend),progress = \(progress)")
  1061. if progress >= 0.90, progress <= 0.99 {
  1062. // 更新进度
  1063. self?.updatePublicCurrentProgress(useProgress: progress)
  1064. }
  1065. }
  1066. }
  1067. /// fp6 - 视频上传成功,处理要发布视频数据
  1068. /// - Parameter notify: <#notify description#>
  1069. @objc func uploadSuccess(notify: NSNotification) {
  1070. let objectKey: String = "\(notify.userInfo?["objectKey"] ?? "")"
  1071. BFLog(message: "收到上传成功请求==\(notify.userInfo ?? [:])")
  1072. if uploadData?.videoBucketKey == objectKey {
  1073. // 上传成功
  1074. isUploadSuccess = true
  1075. /// fp7 - 处理要发布视频数据
  1076. dealWithPublicData()
  1077. }
  1078. }
  1079. /// fp7 - 处理要发布视频数据
  1080. /// - Returns: <#description#>
  1081. func dealWithPublicData() {
  1082. if uploadData?.localPath != nil {
  1083. let size = try! URL(string: uploadData?.localPath ?? "")?.resourceValues(forKeys: [.fileSizeKey])
  1084. BFLog(message: "size = \(String(describing: size))")
  1085. if Float64(size?.fileSize ?? 0) > maxUploadSize {
  1086. cShowHUB(superView: nil, msg: "无法发布大于10G的视频,请重新选择/合成发布")
  1087. // 上传失败-播放视频
  1088. publicEnd(isError: true)
  1089. return
  1090. }
  1091. }
  1092. let projectId: String? = editProjectModel?.projectId
  1093. let uploadRequest: OSSMultipartUploadRequest? = PQAliOssUtil.shared.allTasks[uploadData?.videoBucketKey ?? ""]
  1094. if uploadRequest == nil {
  1095. reUploadVideo()
  1096. return
  1097. }
  1098. let tempModel = PQVideoListModel()
  1099. tempModel.title = selectTitle
  1100. tempModel.summary = ""
  1101. tempModel.duration = Float64(uploadData?.duration ?? 0)
  1102. tempModel.uplpadImage = uploadData?.image
  1103. tempModel.uplpadBucketKey = uploadRequest?.objectKey
  1104. tempModel.localPath = uploadData?.localPath
  1105. tempModel.reCreateVideoData = reCreateData
  1106. tempModel.eventTrackData = eventTrackData
  1107. tempModel.uplpadStatus = 1
  1108. tempModel.videoFromScene = .stuckPoint
  1109. tempModel.uid = Int(BFLoginUserInfo.shared.uid) ?? 0
  1110. tempModel.uplpadRequest = PQAliOssUtil.shared.allTasks[uploadData?.videoBucketKey ?? ""]
  1111. tempModel.stsToken = uploadData?.stsToken
  1112. tempModel.projectId = projectId
  1113. /// fp8 - 发布视频
  1114. publicVideo(videoData: tempModel)
  1115. }
  1116. /// fp8 - 发布视频
  1117. /// - Parameter videoData: <#videoData description#>
  1118. func publicVideo(videoData: PQVideoListModel) {
  1119. if videoData.uplpadBucketKey == nil {
  1120. BFLog(message: "发布视频:视频uplpadBucketKey为空-\(String(describing: videoData.uplpadBucketKey))")
  1121. // 上传失败-播放视频
  1122. publicEnd(isError: true)
  1123. return
  1124. }
  1125. BFLog(message: "开始发布")
  1126. if (videoData.eventTrackData?.endUploadDate ?? 0) <= 0 {
  1127. // 结束上传时间
  1128. videoData.eventTrackData?.endUploadDate = Date().timeIntervalSince1970
  1129. }
  1130. DispatchQueue.global().async {
  1131. // PQBaseViewModel.ossTempToken { [weak self] response, _ in
  1132. // let image: UIImage = videoData.uplpadImage ?? UIImage()
  1133. // let data = image.jpegData(compressionQuality: 1)
  1134. // let accessKeyId: String = "\(response?["accessKeyId"] ?? "")"
  1135. // let secretKeyId: String = "\(response?["accessKeySecret"] ?? "")"
  1136. // let securityToken: String = "\(response?["securityToken"] ?? "")"
  1137. // let endpoint: String = "\(response?["uploadDomain"] ?? "")"
  1138. // let bucketName: String = "\(response?["bucketName"] ?? "")"
  1139. // let objectKey: String = "\(response?["objectKey"] ?? "")"
  1140. // BFLog(message: "开始上传视频图片==\(videoData.title ?? ""),uplpadBucketKey = \(videoData.uplpadBucketKey ?? ""),objectKey =\(objectKey)")
  1141. // PQAliOssUtil.shared
  1142. // .startClient(
  1143. // accessKeyId: accessKeyId,
  1144. // secretKeyId: secretKeyId,
  1145. // securityToken: securityToken,
  1146. // endpoint: endpoint
  1147. // )
  1148. // .uploadObjectAsync(bucketName: bucketName, objectKey: objectKey, data: data!, fileExtensions: "png", imageUploadBlock: { _, code, ossObjectKey, _ in
  1149. // BFLog(message: "图片上传完成==\(videoData.title ?? ""),uplpadBucketKey = \(videoData.uplpadBucketKey ?? ""),objectKey =\(objectKey),ossObjectKey = \(ossObjectKey)")
  1150. // if code == 1 && ossObjectKey == objectKey && objectKey.count > 0 {
  1151. // BFLog(message: "开始发布==\(videoData.title ?? ""),uplpadBucketKey = \(videoData.uplpadBucketKey ?? ""),objectKey =\(objectKey),ossObjectKey = \(ossObjectKey)")
  1152. PQUploadViewModel.publishVideo(projectId: videoData.projectId, fileExtensions: videoData.localPath?.pathExtension, title: videoData.title ?? "", videoPath: videoData.uplpadBucketKey ?? "", coverImgPath: nil, descr: videoData.summary ?? "", videoFromScene: .stuckPoint, reCreateData: videoData.reCreateVideoData, eventTrackData: videoData.eventTrackData) { [weak self] newVideoData, _, _ in
  1153. self?.videoData = newVideoData
  1154. self?.videoData?.title = self?.titleLabel.text
  1155. if self?.videoData?.reCreateVideoData == nil {
  1156. let reCreateVideo = PQReCreateModel()
  1157. reCreateVideo.reProduceVideoFlag = 1
  1158. self?.videoData?.reCreateVideoData = reCreateVideo
  1159. }
  1160. postNotification(name: cPublishStuckPointSuccessKey, userInfo: ["newVideoData": self?.videoData ?? PQVideoListModel()])
  1161. BFLog(message: "发布成功==\(videoData.title ?? ""),uplpadBucketKey = \(videoData.uplpadBucketKey ?? "")")
  1162. // cShowHUB(superView: nil, msg: "视频发布成功")
  1163. // 发布成功后续操作
  1164. self?.publicEnd()
  1165. PQEventTrackViewModel.publishReportUpload(projectId: videoData.projectId, businessType: .bt_publish_success, ossInfo: videoData.stsToken ?? [:], params: ["title": videoData.title ?? "", "videoPath": videoData.uplpadBucketKey ?? "", "descr": videoData.summary ?? ""])
  1166. }
  1167. // } else {
  1168. // // 图片上传失败
  1169. // BFLog(message: "图片上传失败重新发布视频==\(videoData.title ?? ""),\(videoData.uplpadBucketKey ?? "")")
  1170. // self?.publicVideo(videoData: videoData)
  1171. // }
  1172. // })
  1173. // }
  1174. }
  1175. }
  1176. /// 发布结束操作
  1177. /// - Parameter isError: <#isError description#>
  1178. /// - Returns: <#description#>
  1179. func publicEnd(isError: Bool = false) {
  1180. UIApplication.shared.keyWindow?.viewWithTag(100_100)?.removeFromSuperview()
  1181. isPublicSuccess = true
  1182. progressView.removeFromSuperview()
  1183. progressTipsLab.removeFromSuperview()
  1184. oprationBgView.removeFromSuperview()
  1185. playBtn.isHidden = true
  1186. avPlayer.replaceCurrentItem(with: AVPlayerItem(url: URL(fileURLWithPath: (exportLocalURL?.absoluteString ?? "").replacingOccurrences(of: "file:///", with: ""))))
  1187. avPlayer.play()
  1188. if isError {
  1189. cShowHUB(superView: nil, msg: "视频发布失败,请重新合成")
  1190. } else {
  1191. bottomOprationBgView.isHidden = false
  1192. //add by ak 发布成功后如果带片尾的视频还没有生成成功时,出提示
  1193. saveVideoTipsBgView.isHidden = false
  1194. self.saveRetryBtn.isHidden = true
  1195. if(saveMovieLocalURL == nil){
  1196. saveVideoTipsLabel.text = "视频保存中..."
  1197. }else{
  1198. self.saveVideoTipsLabel.text = "视频已保存到相册"
  1199. DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + 0.8) { [weak self] in
  1200. self?.saveVideoTipsBgView.isHidden = true
  1201. }
  1202. }
  1203. }
  1204. }
  1205. /// 生成创作工具埋点数据
  1206. /// - Returns: <#description#>
  1207. func getExportEventTrackData() -> PQVideoMakeEventTrackModel? {
  1208. let eventTrackData = PQVideoMakeEventTrackModel(projectModel: editProjectModel, reCreateData: reCreateData)
  1209. eventTrackData.entrance = .entranceStuckPointPublic
  1210. eventTrackData.editTimeCost = 0
  1211. eventTrackData.composeTimeCost = (exportEndDate - startExportDate) * 1000
  1212. eventTrackData.musicName = audioMixModel?.musicName ?? ""
  1213. eventTrackData.syncedUpMusicName = audioMixModel?.musicName ?? ""
  1214. eventTrackData.musicId = audioMixModel?.musicId ?? ""
  1215. eventTrackData.syncedUpMusicId = audioMixModel?.musicId ?? ""
  1216. eventTrackData.musicUrl = audioMixModel?.selectVoiceType == 1 ? (audioMixModel?.musicPath ?? "") : (audioMixModel?.accompanimentPath ?? "")
  1217. eventTrackData.musicType = audioMixModel != nil ? (audioMixModel?.selectVoiceType == 1 ? "original" : "accompaniment") : ""
  1218. eventTrackData.isMusicClip = (audioMixModel?.startTime ?? 0) > 0
  1219. if editProjectModel?.sData?.videoMetaData?.canvasType == videoCanvasType.origin.rawValue {
  1220. eventTrackData.canvasRatio = "original"
  1221. } else if editProjectModel?.sData?.videoMetaData?.canvasType == videoCanvasType.nineToSixteen.rawValue {
  1222. eventTrackData.canvasRatio = "9:16"
  1223. } else if editProjectModel?.sData?.videoMetaData?.canvasType == videoCanvasType.oneToOne.rawValue {
  1224. eventTrackData.canvasRatio = "1:1"
  1225. } else if editProjectModel?.sData?.videoMetaData?.canvasType == videoCanvasType.sixteenToNine.rawValue {
  1226. eventTrackData.canvasRatio = "16:9"
  1227. }
  1228. eventTrackData.syncedUpVideoNumber = selectedDataCount - selectedImageDataCount
  1229. eventTrackData.syncedUpImageNumber = selectedImageDataCount
  1230. eventTrackData.syncedUpOriginalMaterialDuration = selectedTotalDuration * 1000
  1231. eventTrackData.syncedUpRhythmNumber = audioMixModel?.speed ?? 2
  1232. eventTrackData.syncedUpVideoDuration = ((audioMixModel?.endTime ?? 0) - (audioMixModel?.startTime ?? 0)) * 1000
  1233. // add by ak
  1234. eventTrackData.syncedUpVideoType = rhythmMode
  1235. eventTrackData.syncedUpVideoSpeedMax = syncedUpVideoSpeedMax
  1236. eventTrackData.syncedUpVideoSpeedMin = syncedUpVideoSpeedMin
  1237. return eventTrackData
  1238. }
  1239. /// 播放视频
  1240. /// - Returns: description
  1241. @objc func playVideo() {
  1242. playBtn.isHidden = !playBtn.isHidden
  1243. changPlayerIsPause(isPause: !playBtn.isHidden)
  1244. }
  1245. /// 按钮点击事件
  1246. /// - Parameter sender: <#sender description#>
  1247. /// - Returns: <#description#>
  1248. @objc func btnClick(sender: UIButton) {
  1249. switch sender.tag {
  1250. case 1:
  1251. if !(isExportSuccess && isSaveProjectSuccess && isUploadSuccess && isPublicSuccess) {
  1252. cShowHUB(superView: nil, msg: "视频发布失败,请重新合成")
  1253. return
  1254. }
  1255. if !PQSingletoWXApiUtil.shared.isInstallWX() {
  1256. cShowHUB(superView: nil, msg: "您还未安装微信客户端!")
  1257. return
  1258. }
  1259. cShowHUB(superView: nil, msg: nil)
  1260. let shareId = getUniqueId(desc: "\(videoData?.uniqueId ?? "")shareId")
  1261. PQBaseViewModel.wxFriendShareInfo(videoId: (videoData?.uniqueId)!) { [weak self] imagePath, title, shareWeappRawId, msg in
  1262. if msg != nil {
  1263. cShowHUB(superView: nil, msg: "网络不佳哦")
  1264. return
  1265. }
  1266. self?.isShared = true
  1267. PQSingletoWXApiUtil.shared.share(type: 3, scene: Int32(WXSceneSession.rawValue), shareWeappRawId: shareWeappRawId, title: title, description: title, imageUrl: imagePath, path: self?.videoData?.videoPath, videoId: (self?.videoData?.uniqueId)!, pageSource: self?.videoData?.pageSource ?? .sp_category, shareId: shareId).wxApiUtilHander = { _, _ in
  1268. }
  1269. cHiddenHUB(superView: nil)
  1270. }
  1271. // 点击上报:分享微信
  1272. PQEventTrackViewModel.baseReportUpload(businessType: .bt_buttonClick, objectType: .ot_click_shareWechat, pageSource: .sp_stuck_publishSyncedUp, extParams: ["videoId": videoData?.uniqueId ?? ""], remindmsg: "卡点视频数据上报-(点击上报:分享微信)")
  1273. case 2:
  1274. if !(isExportSuccess && isSaveProjectSuccess && isUploadSuccess && isPublicSuccess) {
  1275. cShowHUB(superView: nil, msg: "视频发布失败,请重新合成")
  1276. return
  1277. }
  1278. if !PQSingletoWXApiUtil.shared.isInstallWX() {
  1279. cShowHUB(superView: nil, msg: "您还未安装微信客户端!")
  1280. return
  1281. }
  1282. let shareId = getUniqueId(desc: "\(videoData?.uniqueId ?? "")shareId")
  1283. PQBaseViewModel.h5ShareLinkInfo(videoId: videoData?.uniqueId ?? "", pageSource: videoData?.pageSource ?? .sp_category) { [weak self] path, _ in
  1284. cHiddenHUB(superView: nil)
  1285. if path != nil {
  1286. PQBaseViewModel.wxFriendShareInfo(videoId: (self?.videoData?.uniqueId)!) { [weak self] imagePath, _, _, msg in
  1287. if msg != nil {
  1288. cShowHUB(superView: nil, msg: "网络不佳哦")
  1289. return
  1290. }
  1291. self?.isShared = true
  1292. PQSingletoWXApiUtil.shared.share(type: 1, scene: Int32(WXSceneTimeline.rawValue), title: self?.videoData?.title ?? "\(BFLoginUserInfo.shared.nickName)made a music video for you", description: "", imageUrl: imagePath, path: path, videoId: (self?.videoData?.uniqueId)!, pageSource: self?.videoData?.pageSource ?? .sp_category, shareId: shareId).wxApiUtilHander = { _, _ in
  1293. }
  1294. }
  1295. } else {
  1296. cShowHUB(superView: nil, msg: "网络不佳哦")
  1297. }
  1298. }
  1299. // 点击上报:分享朋友圈
  1300. PQEventTrackViewModel.baseReportUpload(businessType: .bt_buttonClick, objectType: .ot_click_shareWechatMoment, pageSource: .sp_stuck_publishSyncedUp, extParams: ["videoId": videoData?.uniqueId ?? ""], remindmsg: "卡点视频数据上报-(点击上报:分享朋友圈)")
  1301. case 3:
  1302. // 点击上报:完成
  1303. PQEventTrackViewModel.baseReportUpload(businessType: .bt_buttonClick, objectType: .ot_click_finished, pageSource: .sp_stuck_publishSyncedUp, extParams: ["videoId": videoData?.uniqueId ?? ""], remindmsg: "卡点视频数据上报-(点击上报:完成)")
  1304. navigationController?.viewControllers = [(navigationController?.viewControllers.first)!]
  1305. // 发送通知
  1306. postNotification(name: cFinishedPublishedNotiKey)
  1307. case 97:
  1308. saveRetryBtn.isHidden = true
  1309. saveVideoTipsLabel.text = "视频保存中..."
  1310. self.saveStuckPointVideo()
  1311. default:
  1312. break
  1313. }
  1314. }
  1315. /// 添加提示视图
  1316. /// - Parameters:
  1317. /// - isNetCollected: <#isNetCollected description#>
  1318. /// - msg: <#msg description#>
  1319. func showUploadRemindView(isNetCollected _: Bool = true, msg: String? = nil) {
  1320. view.endEditing(true)
  1321. let emptyData = PQEmptyModel()
  1322. emptyData.isRefreshHidden = false
  1323. emptyData.title = "上传失败"
  1324. emptyData.titleColor = UIColor.hexColor(hexadecimal: "#353535")
  1325. emptyData.summary = "建议切换 WIFI/移动网络后再重试"
  1326. emptyData.summaryColor = UIColor.hexColor(hexadecimal: "#353535")
  1327. emptyData.refreshBgColor = UIColor.hexColor(hexadecimal: PQBFConfig.shared.styleColor.rawValue)
  1328. emptyData.refreshTitle = NSMutableAttributedString(string: "立即重试", attributes: [.foregroundColor:UIColor.white])
  1329. emptyData.emptySoureImage = UIImage.moduleImage(named: "stuckPoint_video_empty", moduleName: "BFMaterialKit",isAssets: false)
  1330. emptyData.netDisRefreshBgColor = UIColor.hexColor(hexadecimal: "#FA6400")
  1331. emptyData.netDisTitle = "内容加载失败"
  1332. emptyData.netDisTitleColor = UIColor.hexColor(hexadecimal: "#333333")
  1333. emptyData.netemptyDisImage = UIImage.moduleImage(named: "empty_netDis_icon", moduleName: "BFMaterialKit",isAssets: false)
  1334. emptyData.netDisRefreshTitle = NSMutableAttributedString(string: "重新加载", attributes: [.font: UIFont.systemFont(ofSize: 16, weight: .medium), .foregroundColor: UIColor.white])
  1335. let emptyRemindView = PQEmptyRemindView(frame: CGRect(x: 0, y: cDevice_iPhoneNavBarAndStatusBarHei, width: view.frame.width, height: view.frame.height - cDevice_iPhoneNavBarAndStatusBarHei))
  1336. // emptyRemindView.isHidden = true
  1337. emptyRemindView.emptyData = emptyData
  1338. emptyRemindView.backgroundColor = PQBFConfig.shared.styleBackGroundColor
  1339. emptyRemindView.fullRefreshBloc = {[weak self] _, _ in
  1340. if emptyRemindView.refreshBtn.currentAttributedTitle?.string == "立即重试" {
  1341. emptyRemindView.isHidden = true
  1342. // 重试逻辑
  1343. if let message = msg{
  1344. if message.contains("token") {
  1345. self?.uploadVideo()
  1346. }else if message.contains("aliOss"){
  1347. self?.uploadVideo()
  1348. }
  1349. }
  1350. }
  1351. }
  1352. emptyRemindView.refreshBtn.addCorner(corner: 4)
  1353. view.addSubview(emptyRemindView)
  1354. // PQRemindView.showUploadRemindView(title: "上传失败", summary: (msg != nil ? msg! : "视频文件已丢失"), confirmTitle: "立即重试") { [weak self] _, _ in
  1355. // self?.navigationController?.popToViewController((self?.navigationController?.viewControllers[1])!, animated: true)
  1356. // }
  1357. }
  1358. @objc func enterBackground() {
  1359. BFLog(message: "进入到后台")
  1360. // 取消导出
  1361. if exporter != nil {
  1362. exporter.cancel()
  1363. }
  1364. playBtn.isHidden = false
  1365. avPlayer.pause()
  1366. }
  1367. @objc func willEnterForeground() {
  1368. BFLog(message: "进入到前台")
  1369. if !isExportSuccess {
  1370. appendAudio()
  1371. }
  1372. playBtn.isHidden = true
  1373. playerHeaderCoverImageView.isHidden = true
  1374. avPlayer.play()
  1375. }
  1376. @objc func didBecomeActiveNotification() {
  1377. if isShared {
  1378. DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + 1) { [weak self] in
  1379. self?.isShared = false
  1380. cShowHUB(superView: nil, msg: "分享成功")
  1381. self?.playBtn.isHidden = true
  1382. self?.avPlayer.play()
  1383. }
  1384. }
  1385. }
  1386. /// 更新进度
  1387. /// - Returns: <#description#>
  1388. func updatePublicCurrentProgress(useProgress: Float) {
  1389. exportProgrss = Int(useProgress * 100)
  1390. progressView.setProgress(useProgress, animated: true)
  1391. let attributedText = NSMutableAttributedString(string: "\(exportProgrss)%\n视频正在处理中,请勿离开")
  1392. attributedText.addAttributes([.font: UIFont.systemFont(ofSize: 34)], range: NSRange(location: 0, length: "\(exportProgrss)%".count))
  1393. progressTipsLab.attributedText = attributedText
  1394. }
  1395. func changPlayerIsPause(isPause: Bool) {
  1396. if isPause {
  1397. playBtn.isHidden = false
  1398. avPlayer.pause()
  1399. playerHeaderCoverImageView.isHidden = false
  1400. } else {
  1401. playBtn.isHidden = true
  1402. avPlayer.play()
  1403. playerHeaderCoverImageView.isHidden = true
  1404. }
  1405. }
  1406. @objc func titleLabelClick() {
  1407. BFLog(message: "点击输入框")
  1408. changPlayerIsPause(isPause: true)
  1409. pinView.isHidden = true
  1410. publicTitleView.show()
  1411. if publicTitleView.inputTV.text.count > 0 {
  1412. publicTitleView.inputTV.text = titleLabel.text
  1413. }
  1414. PQEventTrackViewModel.baseReportUpload(businessType: .bt_buttonClick, objectType: .ot_shanyinApp_clickButton_changeTitle, pageSource: .sp_stuck_publishSyncedUp, eventData: ["videoId": videoData?.uniqueId ?? "", "rootPageSource": isReCreate ? "shanyinApp-main-syncedUpMusicRecreate" : "shanyinApp-main-syncedUpMusic"], remindmsg: "")
  1415. }
  1416. @objc func settingCoverImage() {
  1417. if exportLocalURL == nil {
  1418. BFLog(message: "导出的视频地址错误???。。。")
  1419. return
  1420. }
  1421. changPlayerIsPause(isPause: true)
  1422. let asset = AVURLAsset(url: exportLocalURL!, options: nil)
  1423. publicEditCoverView.show(videoURL: exportLocalURL!, duration: CMTimeGetSeconds(asset.duration))
  1424. // 点击了确认 btn
  1425. publicEditCoverView.selectImageCallBack = { [weak self] imageData in
  1426. self?.changPlayerIsPause(isPause: false)
  1427. if imageData != nil {
  1428. self?.coverImageView.image = imageData
  1429. self?.playerHeaderCoverImageView.image = imageData
  1430. self?.uploadData?.image = imageData
  1431. self?.updateCoverImagegOrTitle()
  1432. }
  1433. }
  1434. // 点击了从相册选择
  1435. publicEditCoverView.selectPhotoBtnCallBack = { [weak self] in
  1436. let imageSelected = PQImageSelectedController()
  1437. imageSelected.isAssetImage = true
  1438. imageSelected.videoWidth = CGFloat(self?.editProjectModel?.sData?.videoMetaData?.videoWidth ?? 0)
  1439. imageSelected.videoHeight = CGFloat(self?.editProjectModel?.sData?.videoMetaData?.videoHeight ?? 0)
  1440. // imageSelected.uploadData = uploadData
  1441. // imageSelected.updataVideoData = updataVideoData
  1442. self?.navigationController?.pushViewController(imageSelected, animated: true)
  1443. }
  1444. PQEventTrackViewModel.baseReportUpload(businessType: .bt_buttonClick, objectType: .ot_shanyinApp_clickButton_changeCover, pageSource: .sp_stuck_publishSyncedUp, eventData: ["videoId": videoData?.uniqueId ?? "", "rootPageSource": isReCreate ? "shanyinApp-main-syncedUpMusicRecreate" : "shanyinApp-main-syncedUpMusic"], remindmsg: "")
  1445. }
  1446. // 更新标题或封面
  1447. func updateCoverImagegOrTitle() {
  1448. PQLoadingHUB.shared.showHUB(isMode: true)
  1449. // SanW - 待修改 -
  1450. // PQLoadingHUB.shared.showHUB(isMode: true)
  1451. PQBaseViewModel.ossTempToken { [weak self] response, msg in
  1452. let image: UIImage = (self?.uploadData?.image)!
  1453. let data = image.jpegData(compressionQuality: 1)
  1454. let accessKeyId: String = "\(response?["accessKeyId"] ?? "")"
  1455. let secretKeyId: String = "\(response?["accessKeySecret"] ?? "")"
  1456. let securityToken: String = "\(response?["securityToken"] ?? "")"
  1457. let endpoint: String = "\(response?["endPoint"] ?? "")"
  1458. let bucketName: String = "\(response?["bucketName"] ?? "")"
  1459. let objectKey: String = "\(response?["objectKey"] ?? "")"
  1460. _ = PQAliOssUtil.shared
  1461. .startClient(
  1462. accessKeyId: accessKeyId,
  1463. secretKeyId: secretKeyId,
  1464. securityToken: securityToken,
  1465. endpoint: endpoint
  1466. )
  1467. .uploadObjectAsync(bucketName: bucketName, objectKey: objectKey, data: data!, fileExtensions: "png", imageUploadBlock: { _, code, ossObjectKey, _ in
  1468. if code == 1 && ossObjectKey == objectKey && ossObjectKey.count > 0 {
  1469. //add by ak 这里会在服务器生成分享使用的图片到1-2S 时间
  1470. PQUploadViewModel.updateVideo(title: self?.videoData?.title ?? "", videoId: self?.videoData?.uniqueId ?? "", coverImgPath: objectKey, descr: "") {_, newVideoData, msg in
  1471. if newVideoData == nil {
  1472. cShowHUB(superView: self?.view, msg: msg)
  1473. // 可能有敏感词 要刷一组新标题并自动更新
  1474. let numberRandom: UInt32 = UInt32(arc4random_uniform(UInt32(self?.publicTitleView.titles.count ?? 0)))
  1475. self?.setTitleText(text: self?.publicTitleView.titles[Int(numberRandom)] ?? "")
  1476. self?.updateCoverImagegOrTitle()
  1477. sleep(UInt32(1.5))
  1478. PQLoadingHUB.shared.dismissHUB()
  1479. return
  1480. } else {
  1481. PQLoadingHUB.shared.dismissHUB()
  1482. }
  1483. }
  1484. } else {
  1485. PQLoadingHUB.shared.dismissHUB()
  1486. }
  1487. })
  1488. } }
  1489. func setTitleText(text: String, textColor: UIColor = UIColor.hexColor(hexadecimal: "#ABABAB")) {
  1490. selectTitle = text
  1491. // 更新 UI
  1492. titleLabel.text = text
  1493. titleLabel.textColor = textColor
  1494. publicTitleView.inputTV.placeHolder = text
  1495. // 更新数据
  1496. videoData?.title = text
  1497. }
  1498. // 取推荐的10个标题
  1499. func getTitles() {
  1500. PQBaseViewModel.getBaseConfig(completeHander: { [weak self] titles in
  1501. if (titles?.count ?? 0) > 0 {
  1502. var temp:Array<String> = titles!
  1503. if((titles?.count ?? 0) <= 13){
  1504. for _ in 0 ... (13 - (titles?.count ?? 0)){
  1505. temp.append("")
  1506. }
  1507. }
  1508. self?.publicTitleView.titles = temp
  1509. let numberRandom: UInt32 = UInt32(arc4random_uniform(UInt32(titles!.count)))
  1510. BFLog(message: "接收到的 titles\(String(describing: titles))")
  1511. self?.setTitleText(text: titles?[Int(numberRandom)] ?? "")
  1512. }
  1513. })
  1514. }
  1515. @objc func imageSelectedImage(notify: Notification) {
  1516. let imageData: UIImage? = notify.userInfo?["image"] as? UIImage
  1517. if imageData != nil {
  1518. changPlayerIsPause(isPause: false)
  1519. BFLog(message: "从系统相册选择了一个照片")
  1520. publicEditCoverView.isHidden = true
  1521. coverImageView.image = imageData
  1522. playerHeaderCoverImageView.image = imageData
  1523. uploadData?.image = imageData
  1524. updateCoverImagegOrTitle()
  1525. }
  1526. }
  1527. }
  1528. // MARK: - 导出带水印+片尾的视频相关方法
  1529. extension PQStuckPointPublicController {
  1530. //导出有水印的正片子
  1531. func beginExportWatermarkMovie(inputAsset: AVURLAsset!) {
  1532. if !(editProjectModel?.sData?.sections != nil && (editProjectModel?.sData?.sections.count ?? 0) > 0) {
  1533. BFLog(message: "项目段落错误❌")
  1534. return
  1535. }
  1536. // 输出视频地址
  1537. var outPutMP4Path = exportVideosDirectory
  1538. if !directoryIsExists(dicPath: outPutMP4Path) {
  1539. BFLog(message: "文件夹不存在")
  1540. createDirectory(path: outPutMP4Path)
  1541. }
  1542. outPutMP4Path.append("saveMovie_\(String.qe.timestamp()).mp4")
  1543. let outPutMP4URL = URL(fileURLWithPath: outPutMP4Path)
  1544. BFLog(message: "导出视频地址 \(outPutMP4URL)")
  1545. watermarkMovieExporter = PQCompositionExporter(asset: inputAsset, videoComposition: nil, audioMix: nil, filters: nil, stickers: mStickers, animationTool: nil, exportURL: outPutMP4URL)
  1546. watermarkMovieExporter.isAddWatermark = true
  1547. var orgeBitRate = (editProjectModel?.sData?.videoMetaData?.videoWidth ?? 0) * (editProjectModel?.sData?.videoMetaData?.videoHeight ?? 0) * 3
  1548. if mStickers != nil {
  1549. for stick in mStickers! {
  1550. if stick.type == StickerType.VIDEO.rawValue {
  1551. let asset = AVURLAsset(url: URL(fileURLWithPath: documensDirectory + stick.locationPath), options: avAssertOptions)
  1552. let cbr = asset.tracks(withMediaType: .video).first?.estimatedDataRate
  1553. if Int(cbr ?? 0) > orgeBitRate {
  1554. orgeBitRate = Int(cbr ?? 0)
  1555. }
  1556. }
  1557. }
  1558. }
  1559. BFLog(message: "导出设置的码率为:\(orgeBitRate)")
  1560. watermarkMovieExporter.showGaussianBlur = true
  1561. if watermarkMovieExporter.prepare(videoSize: CGSize(width: editProjectModel?.sData?.videoMetaData?.videoWidth ?? 0, height: editProjectModel?.sData?.videoMetaData?.videoHeight ?? 0), videoAverageBitRate: orgeBitRate) {
  1562. BFLog(message: "开始导出 \(String(describing: playeTimeRange.start)) 结束 \(String(describing: playeTimeRange.end))")
  1563. watermarkMovieExporter.start(playeTimeRange: playeTimeRange)
  1564. BFLog(message: "开始导出")
  1565. }
  1566. watermarkMovieExporter.progressClosure = { _, _, progress in
  1567. BFLog(message: "带水印的合成进度 \(progress) ")
  1568. }
  1569. watermarkMovieExporter.completion = { [weak self] url in
  1570. BFLog(message: "有水印的视频导出完成: \(String(describing: url)) 生成视频时长为:\(CMTimeGetSeconds(AVAsset(url: url ?? URL(string: "https://media.w3.org/2010/05/sintel/trailer.mp4")!).duration))")
  1571. // 导出完成后取消导出
  1572. if self?.watermarkMovieExporter != nil {
  1573. self?.watermarkMovieExporter.cancel()
  1574. }
  1575. self?.watermarkMovieLocalURL = url
  1576. //开始导出片尾 成功后自动保存到相册
  1577. self?.beginExportEndMovie()
  1578. }
  1579. }
  1580. //导出片尾视频
  1581. func beginExportEndMovie() {
  1582. if !(editProjectModel?.sData?.sections != nil && (editProjectModel?.sData?.sections.count ?? 0) > 0) {
  1583. BFLog(message: "项目段落错误❌")
  1584. return
  1585. }
  1586. // 输出视频地址
  1587. var outPutMP4Path = exportVideosDirectory
  1588. if !directoryIsExists(dicPath: outPutMP4Path) {
  1589. BFLog(message: "文件夹不存在")
  1590. createDirectory(path: outPutMP4Path)
  1591. }
  1592. outPutMP4Path.append("endMovie_\(String.qe.timestamp()).mp4")
  1593. let outPutMP4URL = URL(fileURLWithPath: outPutMP4Path)
  1594. BFLog(message: "导出视频地址 \(outPutMP4URL)")
  1595. var orgeBitRate = (editProjectModel?.sData?.videoMetaData?.videoWidth ?? 0) * (editProjectModel?.sData?.videoMetaData?.videoHeight ?? 0) * 3
  1596. //片尾的视频素材地址
  1597. let moveResPath = currentBundlePath()!.path(forResource: (editProjectModel?.sData?.videoMetaData?.videoWidth ?? 0) < (editProjectModel?.sData?.videoMetaData?.videoHeight ?? 0) ? "endMovieB" : "endMovieA", ofType: "mp4")
  1598. if(moveResPath?.count ?? 0 == 0){
  1599. BFLog(message: "片尾的视频素材地址无效!!!")
  1600. return
  1601. }
  1602. let movieAsset = AVURLAsset(url: URL(fileURLWithPath: moveResPath!), options: avAssertOptions)
  1603. let cbr = movieAsset.tracks(withMediaType: .video).first?.estimatedDataRate
  1604. BFLog(message: "cbr is\(cbr ?? 0)")
  1605. if Int(cbr ?? 0) > orgeBitRate {
  1606. orgeBitRate = Int(cbr ?? 0)
  1607. }
  1608. BFLog(message: "导出设置的码率为:\(orgeBitRate)")
  1609. //头像保存沙盒地址
  1610. BFLog(message: "头像的网络地址\(BFLoginUserInfo.shared.avatarUrl)")
  1611. let avatarFilePath = NSHomeDirectory().appending("/Documents/").appending("user_avatar.jpg")
  1612. // warning:给默认头像吧
  1613. ImageDownloader.default.downloadImage(with: URL(string: BFLoginUserInfo.shared.avatarUrl)!, options: nil) {[weak self] result in
  1614. var image : UIImage?
  1615. switch result {
  1616. case let .success(imageResult):
  1617. image = UIImage.nx_circleImage(imageResult.image)
  1618. case let .failure(error):
  1619. image = UIImage.moduleImage(named: "user_avatar_normal", moduleName: "BFFramework", isAssets:false)
  1620. BFLog(message: "下载头像图片失败:\(error.localizedDescription)")
  1621. }
  1622. if(image == nil){
  1623. BFLog(message: "image date is error!!")
  1624. return
  1625. }
  1626. UIImage.saveImage(currentImage: image!, outFilePath: avatarFilePath)
  1627. //1,背景视频素材
  1628. let bgMovieInfo:PQEditVisionTrackMaterialsModel = PQEditVisionTrackMaterialsModel.init()
  1629. bgMovieInfo.type = StickerType.VIDEO.rawValue
  1630. bgMovieInfo.locationPath = moveResPath ?? ""
  1631. bgMovieInfo.timelineIn = 0
  1632. bgMovieInfo.timelineOut = CMTimeGetSeconds(movieAsset.duration)
  1633. bgMovieInfo.model_in = bgMovieInfo.timelineIn
  1634. bgMovieInfo.out = bgMovieInfo.timelineOut
  1635. bgMovieInfo.canvasFillType = stickerContentMode.aspectFitStr.rawValue
  1636. //2,用户头像素材
  1637. BFLog(message: "头像的沙盒地址:\(avatarFilePath)")
  1638. let avatarSticker:PQEditVisionTrackMaterialsModel = PQEditVisionTrackMaterialsModel.init()
  1639. avatarSticker.locationPath = avatarFilePath.replacingOccurrences(of: documensDirectory, with: "")
  1640. avatarSticker.timelineIn = bgMovieInfo.timelineIn
  1641. avatarSticker.timelineOut = bgMovieInfo.timelineOut
  1642. avatarSticker.canvasFillType = stickerContentMode.aspectFitStr.rawValue
  1643. //头像绘制大小\位置
  1644. var avatarSize:Float = 0.0
  1645. var avatarTop:Float = 0.0
  1646. if((self?.editProjectModel?.sData?.videoMetaData?.videoHeight ?? 0) > (self?.editProjectModel?.sData?.videoMetaData?.videoWidth ?? 0)){
  1647. //竖屏
  1648. avatarSize = Float(self?.editProjectModel?.sData?.videoMetaData?.videoWidth ?? 0) * 360.0 / 1080.0
  1649. avatarTop = 430
  1650. }else{
  1651. //横屏屏
  1652. avatarSize = Float(self?.editProjectModel?.sData?.videoMetaData?.videoHeight ?? 0) * 300.0 / 1080.0
  1653. avatarTop = Float(self?.editProjectModel?.sData?.videoMetaData?.videoHeight ?? 0) * 130.0 / 1080.0
  1654. }
  1655. let avatarPostion:PQEditMaterialPositionModel = PQEditMaterialPositionModel.init()
  1656. avatarPostion.width = Int(avatarSize)
  1657. avatarPostion.height = Int(avatarSize)
  1658. avatarPostion.x = ((self?.editProjectModel?.sData?.videoMetaData?.videoWidth ?? 0) - Int(avatarSize)) / 2
  1659. avatarPostion.y = Int(avatarTop)
  1660. avatarSticker.materialPosition = avatarPostion
  1661. //3,用户名素材
  1662. let userNameSticker:PQEditVisionTrackMaterialsModel = PQEditVisionTrackMaterialsModel.init()
  1663. userNameSticker.timelineIn = bgMovieInfo.timelineIn
  1664. userNameSticker.timelineOut = bgMovieInfo.timelineOut
  1665. userNameSticker.type = StickerType.SUBTITLE.rawValue
  1666. //用户名绘制用到的参数
  1667. var userNameTop:Float = 0.0
  1668. var userNameFontSize:Float = 0.0
  1669. if((self?.editProjectModel?.sData?.videoMetaData?.videoHeight ?? 0) > (self?.editProjectModel?.sData?.videoMetaData?.videoWidth ?? 0)){
  1670. //竖屏
  1671. userNameTop = 870
  1672. userNameFontSize = Float(self?.editProjectModel?.sData?.videoMetaData?.videoWidth ?? 0) * 100.0 / 1080.0
  1673. }else{
  1674. //横屏
  1675. userNameTop = Float(self?.editProjectModel?.sData?.videoMetaData?.videoHeight ?? 0) * 480 / 1080.0
  1676. userNameFontSize = Float(self?.editProjectModel?.sData?.videoMetaData?.videoHeight ?? 0) * 70.0 / 1080.0
  1677. }
  1678. let subtitleInfo:PQEditSubtitleInfoModel = PQEditSubtitleInfoModel.init()
  1679. subtitleInfo.fontSize = Int(userNameFontSize)
  1680. subtitleInfo.text = BFLoginUserInfo.shared.nickName
  1681. userNameSticker.subtitleInfo = subtitleInfo
  1682. let userNamePostion:PQEditMaterialPositionModel = PQEditMaterialPositionModel.init()
  1683. userNamePostion.width = Int(userNameFontSize ) * 10
  1684. userNamePostion.height = Int(userNameFontSize ) * 3
  1685. userNamePostion.x = ((self?.editProjectModel?.sData?.videoMetaData?.videoWidth ?? 0) - userNamePostion.width) / 2
  1686. userNamePostion.y = Int(userNameTop)
  1687. userNameSticker.materialPosition = userNamePostion
  1688. //4,音频
  1689. let soundResPath = currentBundlePath()!.path(forResource: "endMovieSound", ofType: "mp3")
  1690. let soundAsset = AVURLAsset(url: URL(fileURLWithPath: soundResPath ?? ""), options: nil)
  1691. self?.endMovieExporter = PQCompositionExporter(asset: soundAsset, videoComposition: nil, audioMix: nil, filters: nil, stickers: [bgMovieInfo,avatarSticker,userNameSticker], animationTool: nil, exportURL: outPutMP4URL)
  1692. self?.endMovieExporter.isEndMovie = true
  1693. if ((self?.endMovieExporter.prepare(videoSize: CGSize(width: self?.editProjectModel?.sData?.videoMetaData?.videoWidth ?? 0, height: self?.editProjectModel?.sData?.videoMetaData?.videoHeight ?? 0), videoAverageBitRate: orgeBitRate)) != nil) {
  1694. self?.endMovieExporter.start(playeTimeRange: CMTimeRange.init(start: CMTime.zero, duration: CMTimeMakeWithSeconds(Float64(bgMovieInfo.out), preferredTimescale: BASE_FILTER_TIMESCALE)))
  1695. BFLog(message: "开始导出")
  1696. }
  1697. self?.endMovieExporter.progressClosure = { _, _, progress in
  1698. BFLog(message: "片尾合成进度 \(progress) ")
  1699. }
  1700. self?.endMovieExporter.completion = { [weak self] url in
  1701. BFLog(message: "片尾的视频导出完成: \(String(describing: url)) 生成视频时长为:\(CMTimeGetSeconds(AVAsset(url: url ?? URL(string: "https://media.w3.org/2010/05/sintel/trailer.mp4")!).duration))")
  1702. // 导出完成后取消导出
  1703. if self?.endMovieExporter != nil {
  1704. self?.endMovieExporter.cancel()
  1705. }
  1706. self?.endMovieLocalURL = url
  1707. //拼接水印正片和片尾
  1708. if(self?.watermarkMovieLocalURL != nil && self?.endMovieLocalURL != nil){
  1709. let videoMerge:NXVideoMerge = NXVideoMerge.init()
  1710. videoMerge.mergeAndExportVideos(withFileURLs: [self!.watermarkMovieLocalURL!,self!.endMovieLocalURL!], renderSize:CGSize(width: self?.editProjectModel?.sData?.videoMetaData?.videoWidth ?? 0, height: self?.editProjectModel?.sData?.videoMetaData?.videoHeight ?? 0)) { isSuccess, outFileURL in
  1711. if(isSuccess){
  1712. BFLog(message: "合并视频成功 outFilePath is \(outFileURL ?? "")")
  1713. self?.saveMovieLocalURL = outFileURL as? URL
  1714. //保存到相册 fp2-1-1 - 请求权限
  1715. self?.authorizationStatus()
  1716. }
  1717. }
  1718. }
  1719. }
  1720. }
  1721. }
  1722. }