PQStuckPointPublicController.swift 75 KB

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