PQStuckPointPublicController.swift 93 KB

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