PQStuckPointEditerController.swift 99 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938
  1. //
  2. // PQStuckPointEditerController.swift
  3. // PQSpeed
  4. //
  5. // Created by ak on 2021/4/26.
  6. // Copyright © 2021 BytesFlow. All rights reserved.
  7. // 功能:卡点音乐编辑界面
  8. // 创建不同玩法的类型 (1:跳跃卡点,2:快慢速,3:仅配乐)
  9. public enum createStickersModel: Int {
  10. case createStickersModelPoint = 1 // 跳跃卡点
  11. case createStickersModelSpeed = 2 // 快慢速
  12. case createStickersModelOnlyMusic = 3 // 仅配乐
  13. }
  14. import Foundation
  15. import ObjectMapper
  16. import RealmSwift
  17. import UIKit
  18. class PQStuckPointEditerController: PQBaseViewController {
  19. // 是否导出视频成功
  20. var isExportVideosSuccess: Bool = false
  21. // 是否请求卡点数据成功
  22. var isStuckPointDataSuccess: Bool = false
  23. // 是否同步音乐成功
  24. var isSynchroMusicInfoSuccess: Bool = false
  25. /// 当前所有的filter
  26. var filters: Array = Array<ImageProcessingOperation>.init()
  27. // 选中所有素材的的总时长 再进入编辑界面时已经不包括图片的时长
  28. var selectedTotalDuration: Float64 = 0
  29. // 选择的总数
  30. var selectedDataCount: Int = 0
  31. // 选择的图片总数
  32. var selectedImageDataCount: Int = 0
  33. // 选中的素材数据
  34. var selectedPhotoData: [PQEditVisionTrackMaterialsModel]?
  35. // 选中的音乐数据
  36. var stuckPointMusicData: PQVoiceModel?
  37. // 保存所有段的所有贴纸,音频信息,用于播放器的渲染使用
  38. var projectModel: PQEditProjectModel = PQEditProjectModel()
  39. // 从草稿箱进入的项目数据
  40. var draftProjectModel: PQEditProjectModel?
  41. var mStickers: [PQEditVisionTrackMaterialsModel]?
  42. // 播放器的开始和结束时间,1,刚进界面使用推荐的开始结束时间,2,用户修改起结点时修改
  43. var playeTimeRange: CMTimeRange = CMTimeRange()
  44. // 首帧图片
  45. var firstFrameImage: UIImage?{
  46. didSet{
  47. if firstFrameImage != nil {
  48. self.playerView.layer.contents = firstFrameImage?.cgImage
  49. }
  50. }
  51. }
  52. // add by ak 是否是再创作模式
  53. var isReCreate: Bool = false
  54. public var reCreateVideoData: PQReCreateModel? // 再创作数据
  55. // 最后一个选择的模式 BTN 用于还原选中状态
  56. var lastEditModelBtn: UIButton?
  57. // add by ak 最大、最小速度 有固定值和自定义,当快慢速下两个值都有效,当跳跃卡点只有maxSpeed有效
  58. var maxSpeed: Float = 1
  59. var minSpeed: Float = 1
  60. // 快慢速最后一次选择的速度位置
  61. var lastSpeedSelectIndex: Int = 0
  62. // 跳跃卡点最后一次选择的速度位置
  63. var lastJumpSpeedSelectIndex: Int = 0
  64. // 循环次数设置最后一次选择的位置
  65. var lastCyclesSelectIndex: Int = -1
  66. // 当前选择的玩法模式
  67. var currentCreateStickersModel: createStickersModel = .createStickersModelSpeed
  68. // 最终使用的卡点数据
  69. var finallyStuckPoints: Array = Array<Float>.init()
  70. var finallyStuckPointsInt64: Array = Array<Int64>.init()
  71. // 最终使用的音频时长
  72. var finallyUserAudioTime: Float = 0.0
  73. // 注意推荐时间位置和后面最近的卡点时间与0.3的关系
  74. // 保存丢卡点处理后的卡点信息推荐开始到最后倒数第二个
  75. // 经过档位处理后的卡点信息
  76. var stuckPointsTemp: Array = Array<Float>.init()
  77. var stuckPointsTempInt64: Array = Array<Int64>.init()
  78. // 下一步
  79. lazy var nextBtn: UIButton = {
  80. let nextBtn = UIButton(type: .custom)
  81. nextBtn.frame = CGRect(x: cScreenWidth - 16 - cDefaultMargin * 6, y: cDevice_iPhoneStatusBarHei + (cDevice_iPhoneNavBarHei - cDefaultMargin * 3) / 2, width: cDefaultMargin * 6, height: cDefaultMargin * 3)
  82. nextBtn.setTitle("合成", for: .normal)
  83. nextBtn.titleLabel?.font = UIFont.systemFont(ofSize: 15, weight: .medium)
  84. nextBtn.addTarget(self, action: #selector(nextBtnClick(sender:)), for: .touchUpInside)
  85. nextBtn.backgroundColor = UIColor.hexColor(hexadecimal: PQBFConfig.shared.styleColor.rawValue)
  86. nextBtn.setTitleColor(UIColor.hexColor(hexadecimal: "#FFFFFF"), for: .normal)
  87. nextBtn.uxy_acceptEventInterval = 0.5
  88. nextBtn.addCorner(corner: 3)
  89. return nextBtn
  90. }()
  91. // 播放器显示 view
  92. lazy var playerView: PQGPUImagePlayerView = {
  93. let playerView = PQGPUImagePlayerView(frame: .zero)
  94. playerView.backgroundColor = PQBFConfig.shared.styleBackGroundColor
  95. playerView.isShowLine = false
  96. playerView.showGaussianBlur = true
  97. playerView.pause()
  98. playerView.renderViewOnClickHandle = { [weak self] in
  99. self?.musicEditBGView.pausePlayer()
  100. }
  101. playerView.playerEmptyView.isHidden = true
  102. return playerView
  103. }()
  104. /// 节奏选择视图
  105. lazy var sustomSwitchView: PQCustomSwitchView = {
  106. let sustomSwitchView = PQCustomSwitchView(frame: CGRect(x: 16, y: 0, width: 180, height: 30), titles: ["慢节奏", "适中", "快节奏"], defaultIndex: stuckPointMusicData?.speed ?? 2)
  107. sustomSwitchView.switchChangeHandle = { [weak self] sender in
  108. // 改变速率,.只有快慢速且非只有图片素材时自动+1处理
  109. self?.stuckPointMusicData?.speed = sender.tag
  110. self?.musicEditBGView.pausePlayer()
  111. self?.projectModel.sData?.getBGMSession()?.sectionTimeline?.audioTrack?.audioTrackMaterials.first?.bgmInfo?.rhythmMusicSpeed = sender.tag
  112. // 播放前先暂停
  113. // self?.playerView.stop()
  114. // 开始播放
  115. self?.settingPlayerView()
  116. // 下面都是统计
  117. if self?.currentCreateStickersModel == .createStickersModelPoint {
  118. PQEventTrackViewModel.baseReportUpload(businessType: .bt_buttonClick, objectType: .ot_shanyinApp_musicVideoPreview_selectMusicVideoRhythm, pageSource: .sp_stuck_previewSyncedUp, extParams: nil, remindmsg: "点击上报:选择节奏")
  119. } else if self?.currentCreateStickersModel == .createStickersModelSpeed {
  120. PQEventTrackViewModel.baseReportUpload(businessType: .bt_buttonClick, objectType: .ot_shanyinApp_musicVideoPreview_selectSpeedRhythm, pageSource: .sp_stuck_previewSyncedUp, extParams: nil, remindmsg: "点击上报:选择节奏")
  121. } else if self?.currentCreateStickersModel == .createStickersModelOnlyMusic {
  122. PQEventTrackViewModel.baseReportUpload(businessType: .bt_buttonClick, objectType: .ot_shanyinApp_musicVideoPreview_selectMusicVideoRepeatRhythm, pageSource: .sp_stuck_previewSyncedUp, extParams: nil, remindmsg: "点击上报:选择节奏")
  123. }
  124. }
  125. return sustomSwitchView
  126. }()
  127. /// 裁剪视图
  128. lazy var stuckPointCuttingView: PQStuckPointCuttingView = {
  129. let stuckPointCuttingView = PQStuckPointCuttingView(frame: CGRect(x: 0, y: optionlineView.frame.minY - 85 - 28, width: view.frame.width, height: 80), duration: CGFloat(Float(stuckPointMusicData?.duration ?? "0") ?? 0), suggestRhythmStartTime: CGFloat(stuckPointMusicData?.suggestRhythmStartTime ?? 0))
  130. /// 裁剪进度回调
  131. stuckPointCuttingView.videoDidBeginDrag = { [weak self] in
  132. BFLog(message: "开始划动")
  133. self?.playerView.pause()
  134. }
  135. /// 播放进度回调
  136. stuckPointCuttingView.videoProgressDidChanged = { [weak self] progress in
  137. BFLog(message: "进度更新返回--progress = \(progress) \(String(describing: self?.playerView.mPlayeTimeRange))")
  138. }
  139. /// 拖缀结束的回调 type - 1-拖动左边裁剪结束 2--拖动右边裁剪结束 3-进度条拖动结束 4-滑动结束
  140. stuckPointCuttingView.videoDidEndDragging = { [weak self] type, startTime, endTime, progress in
  141. BFLog(1, message: "拖拽结束返回--type = \(type),startTime = \(startTime),endTime = \(endTime),progress = \(progress)")
  142. self?.playerView.pause()
  143. self?.musicEditBGView.pausePlayer()
  144. // 修改最新值
  145. self?.stuckPointMusicData?.startTime = Float64(startTime)
  146. self?.stuckPointMusicData?.endTime = Float64(endTime)
  147. // 红的指针完成
  148. if type == 3 {
  149. if CMTimeGetSeconds(self?.playerView.mPlayeTimeRange?.end ?? .zero) == 0 {
  150. BFLog(message: "mPlayeTimeRange is error")
  151. return
  152. }
  153. let newBeginSconds = (Double(startTime) + (Double(endTime) - Double(startTime)) * Double(progress)) * 600
  154. BFLog(message: " newBeginSconds is \(newBeginSconds)")
  155. let seekTimeRange: CMTimeRange = CMTimeRange(start: CMTime(value: CMTimeValue(Int64(newBeginSconds)), timescale: 600), end:
  156. CMTime(value: CMTimeValue(Int64(endTime * 600)), timescale: 600))
  157. BFLog(message: "修改的开始 \(CMTimeGetSeconds(seekTimeRange.start)) 结束 \(CMTimeGetSeconds(seekTimeRange.end))")
  158. // 重新设置有效缓存
  159. self?.playerView.configCache(beginTime: CMTimeGetSeconds(seekTimeRange.start))
  160. self?.playerView.play(pauseFirstFrame: false, playeTimeRange: seekTimeRange)
  161. } else {
  162. // 更改素材开始时间及结束时间
  163. self?.projectModel.sData?.getBGMSession()?.sectionTimeline?.audioTrack?.audioTrackMaterials.first?.out = Float64(endTime)
  164. self?.projectModel.sData?.getBGMSession()?.sectionTimeline?.audioTrack?.audioTrackMaterials.first?.model_in = Float64(startTime)
  165. self?.projectModel.sData?.getBGMSession()?.sectionTimeline?.audioTrack?.audioTrackMaterials.first?.timelineIn = Float64(startTime)
  166. self?.projectModel.sData?.getBGMSession()?.sectionTimeline?.audioTrack?.audioTrackMaterials.first?.timelineOut = Float64(endTime)
  167. BFLog(message: "调整后总时长: \(endTime - startTime) startTime:\(startTime) endTime:\(endTime)")
  168. // 初始化音频的开始和结束时间
  169. self?.playeTimeRange = CMTimeRange(start: CMTimeMakeWithSeconds(Float64(startTime), preferredTimescale: BASE_FILTER_TIMESCALE), end: CMTimeMakeWithSeconds(Float64(endTime), preferredTimescale: BASE_FILTER_TIMESCALE))
  170. self?.dealParameter(model: self?.currentCreateStickersModel ?? .createStickersModelSpeed)
  171. if((self?.finallyStuckPoints.count ?? 0) < 1){
  172. BFLog(message: "finallyStuckPoints data is error!!!!")
  173. return
  174. }
  175. DispatchQueue.global().async { // 并行、异步
  176. let beginTime = Date()
  177. self?.mStickers = self?.createStickers(sections: self?.projectModel.sData?.sections ?? List(), inputSize: CGSize(width: CGFloat(self?.projectModel.sData?.videoMetaData?.videoWidth ?? 0), height: CGFloat(self?.projectModel.sData?.videoMetaData?.videoHeight ?? 0)), model: self?.currentCreateStickersModel ?? .createStickersModelSpeed)
  178. DispatchQueue.main.async { // 串行、异步
  179. self?.playerView.mStickers = self?.mStickers
  180. BFLog(message: "endTime is endTimeendTime \(Date().timeIntervalSince(beginTime))")
  181. self?.playerView.play(pauseFirstFrame: false, playeTimeRange: self!.playeTimeRange)
  182. // 更新一下时间条的UI总时间 及数据
  183. self?.stuckPointCuttingView.videoDuration = CGFloat(self?.finallyUserAudioTime ?? 0)
  184. self?.stuckPointCuttingView.stuckPointStartTime = CGFloat(CMTimeGetSeconds(self?.playeTimeRange.start ?? .zero))
  185. self?.stuckPointCuttingView.stuckPointEndTime = CGFloat(CMTimeGetSeconds(self?.playeTimeRange.end ?? .zero))
  186. self?.stuckPointCuttingView.tatalTimeLabel.text = "\(Float64(CMTimeGetSeconds(self?.playeTimeRange.end ?? .zero) - CMTimeGetSeconds(self?.playeTimeRange.start ?? .zero)).formatDurationToHMS())"
  187. }
  188. }
  189. }
  190. }
  191. return stuckPointCuttingView
  192. }()
  193. /// 卡点模式标题
  194. lazy var pointEditRemindLab: UILabel = {
  195. let pointEditRemindLab = UILabel()
  196. pointEditRemindLab.backgroundColor = .clear
  197. pointEditRemindLab.textAlignment = .left
  198. pointEditRemindLab.font = UIFont.boldSystemFont(ofSize: 14)
  199. pointEditRemindLab.textColor = .black
  200. pointEditRemindLab.text = "卡点模式"
  201. return pointEditRemindLab
  202. }()
  203. /// 卡点模式标题
  204. lazy var speedTitleLab: UILabel = {
  205. let speedTitleLab = UILabel()
  206. speedTitleLab.backgroundColor = .clear
  207. speedTitleLab.textAlignment = .left
  208. speedTitleLab.font = UIFont.boldSystemFont(ofSize: 14)
  209. speedTitleLab.textColor = .black
  210. speedTitleLab.text = "节奏变化"
  211. return speedTitleLab
  212. }()
  213. /// 卡点模式下方操作区背景
  214. lazy var pointEditBGView: UIView = {
  215. let pointEditBGView = UIView()
  216. pointEditBGView.backgroundColor = .clear
  217. return pointEditBGView
  218. }()
  219. /// 下方音乐编辑操作区背景
  220. lazy var musicEditBGView: PQSelecteMusicView = {
  221. let musicEditBGView = PQSelecteMusicView()
  222. musicEditBGView.backgroundColor = .clear
  223. musicEditBGView.isUserInteractionEnabled = true
  224. musicEditBGView.isHidden = true
  225. musicEditBGView.musicSearchBtn.addTarget(self, action: #selector(musicSearchBtnClick(sender:)), for: .touchUpInside)
  226. musicEditBGView.didSelectItemHandle = { [weak self] status in
  227. self?.playerView.pause()
  228. if status == .isSelected{
  229. self?.playerView.RenderViewOnclick()
  230. }
  231. }
  232. musicEditBGView.btnClickHandle = { [weak self] _, bgmData in
  233. // 使用音乐
  234. self?.userstuckPointMusic(musicData: bgmData as? PQVoiceModel)
  235. }
  236. return musicEditBGView
  237. }()
  238. // 卡点编辑 btn
  239. lazy var pointEditerBtn: UIButton = {
  240. let pointEdterBtn = UIButton(type: .custom)
  241. pointEdterBtn.setImage(UIImage().BF_Image(named: "pointEditerBtn_n"), for: .normal)
  242. pointEdterBtn.setImage(UIImage().BF_Image(named: "pointEditerBtn_h"), for: .selected)
  243. pointEdterBtn.addTarget(self, action: #selector(pointEditerBtnClick(sender:)), for: .touchUpInside)
  244. pointEdterBtn.isSelected = true
  245. pointEdterBtn.adjustsImageWhenHighlighted = false
  246. return pointEdterBtn
  247. }()
  248. // 音乐编辑 btn
  249. lazy var musicEditerBtn: UIButton = {
  250. let musicEditerBtn = UIButton(type: .custom)
  251. musicEditerBtn.setImage(UIImage().BF_Image(named: "musicEditerBtn_n"), for: .normal)
  252. musicEditerBtn.setImage(UIImage().BF_Image(named: "musicEditerBtn_h"), for: .selected)
  253. musicEditerBtn.addTarget(self, action: #selector(musicEditerBtnClick(sender:)), for: .touchUpInside)
  254. musicEditerBtn.adjustsImageWhenHighlighted = false
  255. return musicEditerBtn
  256. }()
  257. // 快慢速卡点模式 btn
  258. lazy var speedStuckBtn: UIButton = {
  259. let speedStuckBtn = UIButton(type: .custom)
  260. speedStuckBtn.addTarget(self, action: #selector(editModelClick1(sender:)), for: .touchUpInside)
  261. speedStuckBtn.setBackgroundImage(UIImage().BF_Image(named: "speedstuck_n"), for: .normal)
  262. speedStuckBtn.setBackgroundImage(UIImage().BF_Image(named: "speedstuck_h"), for: .selected)
  263. speedStuckBtn.tag = 1
  264. speedStuckBtn.adjustsImageWhenHighlighted = false
  265. return speedStuckBtn
  266. }()
  267. //
  268. lazy var speedStuckBtnGif: UIImageView = {
  269. let speedStuckBtnGif = UIImageView()
  270. speedStuckBtnGif.kf.setImage(with: URL(fileURLWithPath: Bundle().BF_mainbundle().path(forResource: "speedstuck_h", ofType: "gif")!))
  271. speedStuckBtnGif.isHidden = true
  272. return speedStuckBtnGif
  273. }()
  274. // 跳转卡点模式 btn
  275. lazy var jumpPointBtn: UIButton = {
  276. let jumpPointBtn = UIButton(type: .custom)
  277. jumpPointBtn.setImage(UIImage().BF_Image(named: "jumpPoint_n"), for: .normal)
  278. jumpPointBtn.setImage(UIImage().BF_Image(named: "jumpPoint_h"), for: .selected)
  279. jumpPointBtn.tag = 2
  280. jumpPointBtn.addTarget(self, action: #selector(editModelClick1(sender:)), for: .touchUpInside)
  281. jumpPointBtn.adjustsImageWhenHighlighted = false
  282. return jumpPointBtn
  283. }()
  284. lazy var jumpPointBtnGif: UIImageView = {
  285. let jumpPointBtnGif = UIImageView()
  286. jumpPointBtnGif.kf.setImage(with: URL(fileURLWithPath: Bundle().BF_mainbundle().path(forResource: "jumpPoint_n", ofType: "gif")!))
  287. jumpPointBtnGif.isHidden = true
  288. return jumpPointBtnGif
  289. }()
  290. // 仅配乐模式 btn
  291. lazy var onlyMusicBtn: UIButton = {
  292. let onlyMusicBtn = UIButton(type: .custom)
  293. onlyMusicBtn.setImage(UIImage().BF_Image(named: "onlyMusic_n"), for: .normal)
  294. onlyMusicBtn.setImage(UIImage().BF_Image(named: "onlyMusic_h"), for: .selected)
  295. onlyMusicBtn.tag = 3
  296. onlyMusicBtn.addTarget(self, action: #selector(editModelClick1(sender:)), for: .touchUpInside)
  297. onlyMusicBtn.adjustsImageWhenHighlighted = false
  298. return onlyMusicBtn
  299. }()
  300. // 操作面板上的分割线
  301. lazy var optionlineView: UIView = {
  302. let optionlineView = UIView()
  303. optionlineView.backgroundColor = UIColor.hexColor(hexadecimal: "#EFEFEF")
  304. return optionlineView
  305. }()
  306. // 固定速度 UI
  307. lazy var speedSettingView: PQSpeedSettingView = {
  308. let speedSetView = PQSpeedSettingView()
  309. speedSetView.backgroundColor = .clear
  310. speedSetView.selectSpeedCallBack = { [weak self] maxSpeed, minSpeed, selectIndex, isSettingPlayer in
  311. BFLog(message: "固定maxSpeed is\(maxSpeed) minSpeed \(minSpeed)")
  312. self?.musicEditBGView.pausePlayer()
  313. if maxSpeed == -1.0 && minSpeed == -1.0 {
  314. self?.customSpeedSettingView.isHidden = false
  315. self?.customSpeedSettingView.viewType = self?.speedSettingView.viewType ?? 2
  316. } else {
  317. if maxSpeed != 0.0 {
  318. // 更新最后一次选择的位置恢复时使用
  319. if self?.speedSettingView.viewType == 1 {
  320. self?.lastSpeedSelectIndex = selectIndex
  321. } else if self?.speedSettingView.viewType == 2 {
  322. self?.lastJumpSpeedSelectIndex = selectIndex
  323. } else {
  324. self?.lastCyclesSelectIndex = selectIndex
  325. }
  326. self?.maxSpeed = maxSpeed
  327. self?.minSpeed = minSpeed
  328. } else {
  329. BFLog(message: "设置速度无效")
  330. }
  331. }
  332. if isSettingPlayer {
  333. self?.settingPlayerView()
  334. }
  335. }
  336. return speedSetView
  337. }()
  338. // 自定义速度
  339. lazy var customSpeedSettingView: PQCustomSpeedSettingView = {
  340. let customSpeedSetView = PQCustomSpeedSettingView(frame: CGRect(x: 0, y: cScreenHeigth - 354, width: cScreenWidth, height: 354))
  341. customSpeedSetView.isHidden = true
  342. customSpeedSetView.selectSpeedCallBack = { [weak self, weak customSpeedSetView] maxSpeed, minSpeed, isJumpSpeedModel, isCancle in
  343. if !isCancle {
  344. self?.maxSpeed = maxSpeed
  345. self?.minSpeed = minSpeed
  346. BFLog(message: "自定义速度maxSpeed is\(maxSpeed) minSpeed \(minSpeed) \(isJumpSpeedModel)")
  347. self?.musicEditBGView.pausePlayer()
  348. // 自定定义的更新一下最后的选择位置
  349. if self?.speedSettingView.viewType == 1 {
  350. self?.lastSpeedSelectIndex = -1
  351. } else if self?.speedSettingView.viewType == 2 {
  352. self?.lastJumpSpeedSelectIndex = -1
  353. } else {
  354. self?.lastCyclesSelectIndex = Int(maxSpeed - 1)
  355. }
  356. self?.settingPlayerView()
  357. // 确认后 选中自定义
  358. self?.speedSettingView.selectCustom()
  359. } else {
  360. // 取消后恢复上一次选择的位置
  361. if self?.speedSettingView.viewType == 1 {
  362. self?.speedSettingView.setSelectItem(index: self?.lastSpeedSelectIndex ?? 0, isSettingPlayer: false)
  363. } else if self?.speedSettingView.viewType == 2 {
  364. self?.speedSettingView.setSelectItem(index: self?.lastJumpSpeedSelectIndex ?? 0, isSettingPlayer: false)
  365. } else {
  366. self?.speedSettingView.setSelectItem(index: self?.lastCyclesSelectIndex ?? 0, isSettingPlayer: false)
  367. }
  368. customSpeedSetView?.isHidden = true
  369. }
  370. }
  371. return customSpeedSetView
  372. }()
  373. /// 音乐标题
  374. lazy var musicNameView: UIView = {
  375. let musicNameView = UIView()
  376. musicNameView.addSubview(musicNameLab)
  377. let nameWidth: CGFloat = musicNameLab.frame.width + (25 + cDefaultMargin * 3)
  378. musicNameView.frame = CGRect(x: (view.frame.width - nameWidth) / 2, y: cDevice_iPhoneStatusBarHei + (cDevice_iPhoneNavBarHei - cDefaultMargin * 3) / 2, width: nameWidth, height: cDefaultMargin * 3)
  379. // musicNameView.backgroundColor = UIColor.hexColor(hexadecimal: "#333333")
  380. musicNameView.addCorner(corner: musicNameView.frame.height / 2)
  381. let musicImageView = UIImageView()
  382. musicImageView.tintColor = PQBFConfig.shared.styleTitleColor
  383. musicImageView.image = UIImage().BF_Image(named: "stuckPoint_reCreate_music").withRenderingMode(.alwaysTemplate)
  384. musicImageView.frame = CGRect(x: musicNameView.frame.height / 2 - 5, y: (musicNameView.frame.height - 22) / 2, width: 22, height: 22)
  385. musicNameView.addSubview(musicImageView)
  386. musicNameLab.frame.origin.x = musicImageView.frame.maxX + 5
  387. return musicNameView
  388. }()
  389. /// 音乐歌曲名称
  390. lazy var musicNameLab: LMJHorizontalScrollText = {
  391. let nameWidth: CGFloat = sizeWithText(text: "\(stuckPointMusicData?.musicName ?? "")", font: UIFont.systemFont(ofSize: 13), size: CGSize(width: view.frame.width - ((cDefaultMargin * 6 + 16 * 2) * 2) - (25 + cDefaultMargin * 3), height: cDefaultMargin * 3)).width
  392. let musicNameLab = LMJHorizontalScrollText(frame: CGRect(x: 0, y: 0, width: nameWidth < cDefaultMargin * 4 ? cDefaultMargin * 4 : nameWidth, height: cDefaultMargin * 3))
  393. musicNameLab.textColor = PQBFConfig.shared.styleTitleColor
  394. musicNameLab.textFont = UIFont.systemFont(ofSize: 13)
  395. musicNameLab.speed = 0.03
  396. musicNameLab.moveDirection = LMJTextScrollMoveLeft
  397. musicNameLab.moveMode = LMJTextScrollContinuous
  398. if nameWidth < cDefaultMargin * 4 {
  399. musicNameLab.text = " \(stuckPointMusicData?.musicName ?? "") "
  400. } else {
  401. musicNameLab.text = " \(stuckPointMusicData?.musicName ?? "") "
  402. }
  403. return musicNameLab
  404. }()
  405. /// 同步进度显示
  406. lazy var synchroMarskView: PQStuckPointLoadingView = {
  407. var synchroMarskView = PQStuckPointLoadingView(frame: CGRect(x: 0, y: 0, width: cScreenWidth, height: cScreenHeigth))
  408. synchroMarskView.cancelHandle = { [weak self] _ in
  409. self?.navigationController?.popViewController(animated: true)
  410. }
  411. return synchroMarskView
  412. }()
  413. @objc func willEnterForeground() {
  414. BFLog(message: "进入到前台")
  415. if(self.navigationController?.topViewController == self){
  416. if projectModel.sData!.sections.count > 0 {
  417. settingPlayerView()
  418. }else {
  419. prepareMeta()
  420. }
  421. }
  422. }
  423. @objc func enterBackground() {
  424. BFLog(message: "进入到后台")
  425. // 取消导出
  426. if(self.navigationController?.topViewController == self){
  427. playerView.pause()
  428. }
  429. }
  430. override func backBtnClick() {
  431. super.backBtnClick()
  432. // playerView.pause()
  433. // 点击上报:返回按钮
  434. PQEventTrackViewModel.baseReportUpload(businessType: .bt_buttonClick, objectType: .ot_click_back, pageSource: .sp_stuck_previewSyncedUp, extParams: nil, remindmsg: "卡点视频数据上报-(点击上报:返回按钮)")
  435. }
  436. // 使用选择音乐 调用情况:1,操作面板直接选择 ,2 搜索界面点击使用
  437. func userstuckPointMusic(musicData: PQVoiceModel?) {
  438. // 1,音乐面板点击了使用
  439. stuckPointMusicData = musicData
  440. // 2,同步最新音乐数据
  441. synchroMusicInfoData(resetSelectIndex: false)
  442. // 3,更新音乐标题UI
  443. let nameWidth: CGFloat = sizeWithText(text: "\(stuckPointMusicData?.musicName ?? "")", font: UIFont.systemFont(ofSize: 13), size: CGSize(width: (view.frame.width) - ((cDefaultMargin * 6 + 16 * 2) * 2) - (25 + cDefaultMargin * 3), height: cDefaultMargin * 3)).width
  444. if nameWidth < cDefaultMargin * 4 {
  445. musicNameLab.text = " \(stuckPointMusicData?.musicName ?? "") "
  446. } else {
  447. musicNameLab.text = " \(stuckPointMusicData?.musicName ?? "") "
  448. }
  449. // 更新一下节奏的 UI
  450. sustomSwitchView.selectOneBtn(Index: (stuckPointMusicData?.speed ?? 2))
  451. }
  452. // 点击搜索音乐
  453. @objc func musicSearchBtnClick(sender _: UIButton) {
  454. let searchVC = PQEditMusicSearchController()
  455. searchVC.btnClickHandle = { [weak self] _, bgmData in
  456. // 使用音乐
  457. BFLog(message: "搜索音乐点击了使用")
  458. self?.musicEditBGView.insertSearchMusic(model: bgmData as! PQVoiceModel)
  459. self?.userstuckPointMusic(musicData: bgmData as? PQVoiceModel)
  460. }
  461. let navigationController: UINavigationController = UINavigationController(rootViewController: searchVC)
  462. navigationController.modalPresentationStyle = .fullScreen
  463. present(navigationController, animated: true, completion: nil)
  464. }
  465. // 卡点编辑
  466. @objc func pointEditerBtnClick(sender: UIButton) {
  467. if sender.isSelected { return }
  468. sender.isSelected = !sender.isSelected
  469. musicEditerBtn.isSelected = false
  470. pointEditBGView.isHidden = false
  471. musicEditBGView.isHidden = true
  472. PQEventTrackViewModel.baseReportUpload(businessType: .bt_buttonClick, objectType: .ot_shanyinApp_musicVideoPreview_videoTab, pageSource: .sp_shanyinApp_main, extParams: nil, remindmsg: "")
  473. }
  474. // 音乐编辑
  475. @objc func musicEditerBtnClick(sender: UIButton) {
  476. if sender.isSelected { return }
  477. sender.isSelected = !sender.isSelected
  478. pointEditerBtn.isSelected = false
  479. pointEditBGView.isHidden = true
  480. musicEditBGView.showData()
  481. PQEventTrackViewModel.baseReportUpload(businessType: .bt_buttonClick, objectType: .ot_shanyinApp_musicVideoPreview_musicTab, pageSource: .sp_shanyinApp_main, extParams: nil, remindmsg: "")
  482. }
  483. @objc func editModelClick1(sender: UIButton) {
  484. editModelClick(sender: sender)
  485. }
  486. // 三种模式修改
  487. @objc func editModelClick(sender: UIButton, reportLog: Bool = true) {
  488. // if sender.isSelected {
  489. // BFLog(message: "已经是选中状态")
  490. // return “”
  491. // }
  492. self.musicEditBGView.pausePlayer()
  493. if sender == jumpPointBtn && selectedTotalDuration < 6 && selectedDataCount != selectedImageDataCount {
  494. cShowHUB(superView: view, msg: "素材时长需要大于6秒才\n可选择“跳跃卡点”模式")
  495. return
  496. }
  497. lastEditModelBtn?.isSelected = false
  498. sender.isSelected = !sender.isSelected
  499. lastEditModelBtn = sender
  500. BFLog(message: "sender tag is \(sender.tag)")
  501. // 1 ui 调整
  502. if sender.tag == 1 || sender.tag == 2 {
  503. speedSettingView.viewType = sender.tag
  504. customSpeedSettingView.viewType = speedSettingView.viewType
  505. speedSettingView.snp.remakeConstraints { make in
  506. make.left.equalToSuperview().offset(16)
  507. make.right.equalToSuperview()
  508. make.top.equalTo(onlyMusicBtn.snp_bottom).offset(10)
  509. make.height.equalTo(sender.tag == 1 ? 44 : 30)
  510. }
  511. speedSettingView.isHidden = false
  512. speedTitleLab.isHidden = false
  513. sustomSwitchView.isHidden = false
  514. } else {
  515. speedTitleLab.isHidden = true
  516. speedSettingView.isHidden = true
  517. sustomSwitchView.isHidden = true
  518. }
  519. // 2素材全是图片的时候三个模式都显示循环设置 UI
  520. if selectedDataCount == selectedImageDataCount {
  521. speedSettingView.viewType = 3
  522. customSpeedSettingView.viewType = speedSettingView.viewType
  523. speedSettingView.snp.remakeConstraints { make in
  524. make.left.equalToSuperview().offset(16)
  525. make.right.equalToSuperview()
  526. make.top.equalTo(onlyMusicBtn.snp_bottom).offset(10)
  527. make.height.equalTo(30)
  528. }
  529. speedSettingView.isHidden = false
  530. speedTitleLab.isHidden = false
  531. sustomSwitchView.isHidden = false
  532. if lastCyclesSelectIndex != -1 {
  533. speedSettingView.setSelectItem(index: lastCyclesSelectIndex, isSettingPlayer: false)
  534. }
  535. } else {
  536. if sender.tag == 1 { // 快慢速
  537. speedSettingView.setSelectItem(index: lastSpeedSelectIndex, isSettingPlayer: false, setDisable: (selectedTotalDuration < 6 && selectedDataCount != selectedImageDataCount) ? true : false)
  538. } else if sender.tag == 2 { // 跳跃卡点
  539. speedSettingView.setSelectItem(index: lastJumpSpeedSelectIndex, isSettingPlayer: false)
  540. } else if sender.tag == 3 { // 仅音乐
  541. // customSpeedSettingView.isJumpSpeedModel = false
  542. }
  543. }
  544. // 3 设置 btn 不同显示状态
  545. var speedStuckBtnGifName = ""
  546. var jumpPointBtnGifName = ""
  547. if sender.tag == 1 { // 快慢速
  548. speedStuckBtnGifName = "speedstuck_h"
  549. jumpPointBtnGifName = "jumpPoint_n"
  550. currentCreateStickersModel = .createStickersModelSpeed
  551. if reportLog {
  552. PQEventTrackViewModel.baseReportUpload(businessType: .bt_buttonClick, objectType: .ot_shanyinApp_musicVideoPreview_selectPatternSpeed, pageSource: .sp_shanyinApp_main, extParams: nil, remindmsg: "")
  553. }
  554. } else if sender.tag == 2 { // 跳跃卡点
  555. speedStuckBtnGifName = "speedstuck_n"
  556. jumpPointBtnGifName = "jumpPoint_h"
  557. currentCreateStickersModel = .createStickersModelPoint
  558. if reportLog {
  559. PQEventTrackViewModel.baseReportUpload(businessType: .bt_buttonClick, objectType: .ot_shanyinApp_musicVideoPreview_selectPatternMusicVideo, pageSource: .sp_shanyinApp_main, extParams: nil, remindmsg: "")
  560. }
  561. } else if sender.tag == 3 { // 仅音乐
  562. speedStuckBtnGifName = "speedstuck_n"
  563. jumpPointBtnGifName = "jumpPoint_n"
  564. currentCreateStickersModel = .createStickersModelOnlyMusic
  565. if reportLog {
  566. PQEventTrackViewModel.baseReportUpload(businessType: .bt_buttonClick, objectType: .ot_shanyinApp_musicVideoPreview_selectPatternBgm, pageSource: .sp_shanyinApp_main, extParams: nil, remindmsg: "")
  567. }
  568. }
  569. speedStuckBtnGif.kf.setImage(with: URL(fileURLWithPath: Bundle().BF_mainbundle().path(forResource: speedStuckBtnGifName, ofType: "gif")!))
  570. jumpPointBtnGif.kf.setImage(with: URL(fileURLWithPath: Bundle().BF_mainbundle().path(forResource: jumpPointBtnGifName, ofType: "gif")!))
  571. speedStuckBtnGif.isHidden = false
  572. jumpPointBtnGif.isHidden = false
  573. settingPlayerView()
  574. }
  575. override func viewWillAppear(_ animated: Bool) {
  576. super.viewWillAppear(animated)
  577. lineView?.isHidden = true
  578. UIApplication.shared.isIdleTimerDisabled = true
  579. musicNameLab.move()
  580. PQNotification.addObserver(self, selector: #selector(enterBackground), name: UIApplication.didEnterBackgroundNotification, object: nil)
  581. PQNotification.addObserver(self, selector: #selector(willEnterForeground), name: UIApplication.willEnterForegroundNotification, object: nil)
  582. }
  583. override func viewWillDisappear(_ animated: Bool) {
  584. super.viewWillDisappear(animated)
  585. UIApplication.shared.isIdleTimerDisabled = false
  586. musicNameLab.stop()
  587. playerView.pause()
  588. musicEditBGView.pausePlayer()
  589. PQNotification.removeObserver(self)
  590. self.synchroMarskView.removeMarskView()
  591. }
  592. override func viewDidLoad() {
  593. super.viewDidLoad()
  594. leftButton(image: "icon_detail_back", tintColor: PQBFConfig.shared.styleTitleColor)
  595. navHeadImageView?.addSubview(nextBtn)
  596. navHeadImageView?.addSubview(musicNameView)
  597. // 添加子视图
  598. addSubViews()
  599. prepareMeta()
  600. // 曝光上报:预览页面曝光上报
  601. PQEventTrackViewModel.baseReportUpload(businessType: .bt_windowView, objectType: .ot_view_previewSyncedUp, pageSource: .sp_stuck_previewSyncedUp, extParams: nil, remindmsg: "卡点视频数据上报-(曝光上报:预览页面曝光上报)")
  602. }
  603. override func viewDidLayoutSubviews() {
  604. super.viewDidLayoutSubviews()
  605. playerView.resetCanvasFrame(frame: coculationPlayViewRect())
  606. }
  607. func prepareMeta(){
  608. // 导出相册视频
  609. exportPhotoData()
  610. // 同步音乐数据
  611. synchroMusicInfoData()
  612. // 插入选择的音乐信息
  613. musicEditBGView.firstInsertVoiceModel = stuckPointMusicData!
  614. }
  615. /// 添加子视图
  616. /// - Returns: <#description#>
  617. func addSubViews() {
  618. if (stuckPointMusicData?.rhythmSdata.count ?? 0) <= 0 {
  619. return
  620. }
  621. view.addSubview(playerView)
  622. view.addSubview(pointEditBGView)
  623. view.addSubview(musicEditBGView)
  624. view.addSubview(optionlineView)
  625. view.addSubview(pointEditerBtn)
  626. view.addSubview(musicEditerBtn)
  627. view.addSubview(customSpeedSettingView)
  628. // 卡点
  629. pointEditBGView.addSubview(pointEditRemindLab)
  630. pointEditBGView.addSubview(speedTitleLab)
  631. pointEditBGView.addSubview(speedStuckBtn)
  632. speedStuckBtn.addSubview(speedStuckBtnGif)
  633. pointEditBGView.addSubview(jumpPointBtn)
  634. jumpPointBtn.addSubview(jumpPointBtnGif)
  635. pointEditBGView.addSubview(onlyMusicBtn)
  636. pointEditBGView.addSubview(speedSettingView)
  637. pointEditBGView.addSubview(sustomSwitchView)
  638. // 音乐
  639. musicEditBGView.addSubview(stuckPointCuttingView)
  640. pointEditerBtn.snp.makeConstraints { make in
  641. make.left.equalToSuperview().offset(100)
  642. make.bottom.equalToSuperview().offset(-(14 + cAKSafeAreaHeight))
  643. make.height.equalTo(24)
  644. make.width.equalTo(24)
  645. }
  646. musicEditerBtn.snp.makeConstraints { make in
  647. make.right.equalToSuperview().offset(-100)
  648. make.top.equalTo(pointEditerBtn.snp_top)
  649. make.height.equalTo(24)
  650. make.width.equalTo(24)
  651. }
  652. pointEditBGView.snp.makeConstraints { make in
  653. make.left.right.equalTo(view)
  654. make.bottom.equalTo(pointEditerBtn.snp_top).offset(-7)
  655. make.height.equalTo(290)
  656. }
  657. musicEditBGView.snp.makeConstraints { make in
  658. make.left.right.equalToSuperview()
  659. make.bottom.equalTo(pointEditerBtn.snp_top).offset(-7)
  660. make.height.equalTo(290)
  661. }
  662. optionlineView.snp.makeConstraints { make in
  663. make.left.right.equalToSuperview()
  664. make.bottom.equalTo(pointEditBGView.snp_bottom).offset(-1)
  665. make.height.equalTo(1)
  666. }
  667. stuckPointCuttingView.snp.makeConstraints { make in
  668. make.left.right.equalToSuperview()
  669. make.bottom.equalTo(musicEditBGView.snp_bottom).offset(-1)
  670. make.height.equalTo(85)
  671. }
  672. pointEditRemindLab.snp.makeConstraints { make in
  673. make.left.equalToSuperview().offset(16)
  674. make.top.equalToSuperview().offset(16)
  675. make.height.equalTo(20)
  676. make.width.equalTo(80)
  677. }
  678. speedStuckBtn.snp.makeConstraints { make in
  679. make.left.equalToSuperview().offset(16)
  680. make.top.equalTo(pointEditRemindLab.snp_bottom).offset(8)
  681. make.height.equalTo(80)
  682. make.width.equalTo(80)
  683. }
  684. speedStuckBtnGif.snp.makeConstraints { make in
  685. make.height.width.equalTo(46)
  686. make.top.equalToSuperview().offset(8)
  687. make.centerX.equalToSuperview()
  688. }
  689. jumpPointBtn.snp.makeConstraints { make in
  690. make.left.equalTo(speedStuckBtn.snp_right).offset(10)
  691. make.top.equalTo(speedStuckBtn.snp_top)
  692. make.height.equalTo(80)
  693. make.width.equalTo(80)
  694. }
  695. jumpPointBtnGif.snp.makeConstraints { make in
  696. make.height.width.equalTo(46)
  697. make.top.equalToSuperview().offset(8)
  698. make.centerX.equalToSuperview()
  699. }
  700. onlyMusicBtn.snp.makeConstraints { make in
  701. make.left.equalTo(jumpPointBtn.snp_right).offset(10)
  702. make.top.equalTo(speedStuckBtn.snp_top)
  703. make.height.equalTo(80)
  704. make.width.equalTo(64)
  705. }
  706. speedSettingView.snp.makeConstraints { make in
  707. make.left.equalToSuperview().offset(16)
  708. make.right.equalToSuperview()
  709. make.top.equalTo(onlyMusicBtn.snp_bottom).offset(10)
  710. make.height.equalTo(44)
  711. }
  712. speedTitleLab.snp.makeConstraints { make in
  713. make.left.equalToSuperview().offset(16)
  714. make.top.equalToSuperview().offset(190)
  715. make.height.equalTo(20)
  716. make.width.equalTo(80)
  717. }
  718. sustomSwitchView.snp.makeConstraints { make in
  719. make.left.equalToSuperview().offset(16)
  720. make.top.equalTo(speedTitleLab.snp_bottom).offset(8)
  721. make.height.equalTo(30)
  722. make.width.equalTo(180)
  723. }
  724. }
  725. @objc func nextBtnClick(sender _: UIButton) {
  726. BFLog(message: "去发布")
  727. playerView.pause()
  728. let videoExporter = PQStuckPointPublicController()
  729. videoExporter.rhythmMode = currentCreateStickersModel
  730. videoExporter.syncedUpVideoSpeedMin = minSpeed
  731. videoExporter.syncedUpVideoSpeedMax = maxSpeed
  732. videoExporter.isReCreate = isReCreate
  733. videoExporter.selectedTotalDuration = selectedTotalDuration
  734. videoExporter.selectedDataCount = selectedDataCount
  735. videoExporter.selectedImageDataCount = selectedImageDataCount
  736. videoExporter.finallyUserAudioTime = Float(finallyStuckPoints.last ?? 0) - Float(finallyStuckPoints.first ?? 0)
  737. videoExporter.clipAudioRange = getClipAudioRange()
  738. videoExporter.playeTimeRange = playeTimeRange
  739. // 使用深 copy
  740. let json = projectModel.toJSONString(prettyPrint: false)
  741. if json == nil {
  742. BFLog(message: "数据转换有问题 跳转")
  743. return
  744. }
  745. let tempModel: PQEditProjectModel? = Mapper<PQEditProjectModel>().map(JSONString: json!)
  746. videoExporter.mStickers = mStickers
  747. videoExporter.audioMixModel = stuckPointMusicData
  748. videoExporter.editProjectModel = tempModel
  749. navigationController?.pushViewController(videoExporter, animated: true)
  750. // 点击上报:去合成
  751. PQEventTrackViewModel.baseReportUpload(businessType: .bt_buttonClick, objectType: .ot_click_commit, pageSource: .sp_stuck_previewSyncedUp, extParams: ["musicName": stuckPointMusicData?.musicName ?? "", "musicId": stuckPointMusicData?.musicId ?? "", "rhythmNumber": stuckPointMusicData?.speed ?? 2, "duration": ((stuckPointMusicData?.endTime ?? 0) - (stuckPointMusicData?.startTime ?? 0)) * 1000], remindmsg: "点击上报:去合成")
  752. }
  753. override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
  754. super.touchesBegan(touches, with: event)
  755. if touches.first?.view != self.customSpeedSettingView {
  756. if !customSpeedSettingView.isHidden {
  757. customSpeedSettingView.isHidden = true
  758. }
  759. }
  760. }
  761. // MARK: - 播放器相关操作
  762. /// seek 播放器
  763. /// - Parameter playeTimeRange: 开始和结束时间
  764. func seekPlayer(playeTimeRange: CMTimeRange) {
  765. playerView.setEnableSeek(isSeek: true)
  766. playerView.play(pauseFirstFrame: false, playeTimeRange: playeTimeRange)
  767. }
  768. /// 通过传入的 selectedPhotoData 、 stuckPointMusicData 创建 projectModel 模型 后面都使用 projectModel 参数
  769. func createPorjectData() {
  770. // 1,添加选择的视觉素材
  771. if projectModel.sData?.sections.count == 0 {
  772. let section: PQEditSectionModel = PQEditSectionModel()
  773. selectedPhotoData?.forEach { model in
  774. let json = model.toJSONString(prettyPrint: false)
  775. if json == nil {
  776. BFLog(message: "数据转换有问题 跳转")
  777. return
  778. }
  779. let tempModel: PQEditVisionTrackMaterialsModel = Mapper<PQEditVisionTrackMaterialsModel>().map(JSONString: json!)!
  780. section.sectionTimeline?.visionTrack?.visionTrackMaterials.append(tempModel)
  781. }
  782. projectModel.sData?.sections.append(section)
  783. }
  784. // 2,添加背景音乐
  785. projectModel.sData?.addBGM(audioMix: stuckPointMusicData!)
  786. }
  787. // 计算拼接音乐的开始和结束点
  788. func getClipAudioRange() -> CMTimeRange {
  789. // 设置音乐的拼接范围,开始:推荐的卡点 结束:点到的倒数第二位
  790. let lastSecondPoint = Float((stuckPointMusicData!.rhythmSdata[0].pointTimes[stuckPointMusicData!.rhythmSdata[0].pointTimes.count - 2])) / Float(BASE_FILTER_TIMESCALE)
  791. let clipAudioRange =
  792. CMTimeRange(start: CMTime(value: CMTimeValue(Float(stuckPointMusicData?.startTime ?? 0) * Float(BASE_FILTER_TIMESCALE)), timescale: BASE_FILTER_TIMESCALE), end: CMTime(value: CMTimeValue((Float(lastSecondPoint)) * Float(BASE_FILTER_TIMESCALE)), timescale: BASE_FILTER_TIMESCALE))
  793. return clipAudioRange
  794. }
  795. // 设置播放器
  796. func coculationPlayViewRect() -> CGRect {
  797. let playerShowHeight = pointEditBGView.frame.minY - (navHeadImageView?.frame.maxY ?? 0)
  798. var showRect: CGRect = CGRect(x: (cScreenWidth - playerShowHeight) / 2, y: 0, width: playerShowHeight, height: playerShowHeight)
  799. if self.firstFrameImage != nil {
  800. let w = self.firstFrameImage!.size.width
  801. let h = self.firstFrameImage!.size.height
  802. let ratioMaterial: Float = Float(w / max(h, 1))
  803. if ratioMaterial > 1 {
  804. // 横屏
  805. let tempPlayerHeight = min(cScreenWidth * CGFloat(h / w), playerShowHeight)
  806. showRect = CGRect(x: (cScreenWidth - tempPlayerHeight * CGFloat(ratioMaterial)) / 2, y: (playerShowHeight - tempPlayerHeight) / 2, width: tempPlayerHeight * CGFloat(ratioMaterial), height: tempPlayerHeight)
  807. } else {
  808. // 竖屏
  809. let playerViewWidth = (CGFloat(w) / CGFloat(h)) * playerShowHeight
  810. showRect = CGRect(x: (cScreenWidth - playerViewWidth) / 2, y: 0, width: playerViewWidth, height: playerShowHeight)
  811. }
  812. }
  813. if showRect.size.width == showRect.size.height {
  814. if cScreenWidth > playerShowHeight {
  815. showRect.origin.x = (cScreenWidth - playerShowHeight) / 2
  816. showRect.size.width = playerShowHeight
  817. showRect.size.height = playerShowHeight
  818. } else {
  819. showRect.origin.x = 0
  820. showRect.size.width = cScreenWidth
  821. showRect.size.height = cScreenWidth
  822. }
  823. }
  824. if showRect.size.width != 0, showRect.size.height != 0 {
  825. if(Int(showRect.height) % 2 != 0){
  826. showRect.size.height = showRect.size.height + 1.0
  827. }
  828. if(Int(showRect.width) % 2 != 0){
  829. showRect.size.width = showRect.size.width + 1.0
  830. }
  831. }
  832. showRect.origin.y = (playerShowHeight - showRect.size.height) / 2.0 + (navHeadImageView?.frame.maxY ?? 0)
  833. return showRect
  834. }
  835. func settingPlayerView() {
  836. stuckPointCuttingView.resetDefaultsColor()
  837. synchroMarskView.removeFromSuperview()
  838. if synchroMarskView.superview == nil {
  839. UIApplication.shared.keyWindow?.addSubview(synchroMarskView)
  840. synchroMarskView.show()
  841. }
  842. // 1,设置播放器的显示区域 和画布大小
  843. // - 按第一个素材尺寸自适应
  844. playerView.pause()
  845. var firstModel: PQEditVisionTrackMaterialsModel?
  846. for part in projectModel.sData!.sections {
  847. if part.sectionTimeline?.visionTrack?.getEnableVisionTrackMaterials().count ?? 0 > 0 {
  848. firstModel = part.sectionTimeline?.visionTrack?.getEnableVisionTrackMaterials().first
  849. break
  850. }
  851. }
  852. var videoSize: CGSize = CGSize(width: Int(firstModel?.width ?? 0), height: Int(firstModel?.height ?? 0))
  853. var minSlider = min(videoSize.width, videoSize.height)
  854. var maxSlider = max(videoSize.width, videoSize.height)
  855. let ration = 1080 / minSlider
  856. minSlider = minSlider * ration
  857. maxSlider = maxSlider * ration
  858. if videoSize.width > videoSize.height { // 宽屏
  859. videoSize = CGSize(width: maxSlider, height: minSlider)
  860. } else {
  861. videoSize = CGSize(width: minSlider, height: maxSlider)
  862. }
  863. if videoSize.width.isNaN || videoSize.height.isNaN {
  864. BFLog(1, message: "宽高无效NaN")
  865. return
  866. }
  867. let maxValue = max(videoSize.width, videoSize.height)
  868. if maxValue > 1920 {
  869. let maxRation = 1920 / maxValue
  870. videoSize = CGSize(width: videoSize.width * CGFloat(maxRation), height: videoSize.height * CGFloat(maxRation))
  871. BFLog(message: "最长边已经超过 1920 要等比缩小 缩放后\(videoSize)")
  872. }
  873. if (Int(videoSize.width) % 2) != 0 {
  874. videoSize.width = videoSize.width - 1
  875. }
  876. if (Int(videoSize.height) % 2) != 0 {
  877. videoSize.height = videoSize.height - 1
  878. }
  879. projectModel.sData?.videoMetaData?.videoWidth = Int(videoSize.width)
  880. projectModel.sData?.videoMetaData?.videoHeight = Int(videoSize.height)
  881. let beginTime = Date()
  882. dealParameter(model: currentCreateStickersModel)
  883. // 更新裁剪时间条的的ui数据
  884. stuckPointCuttingView.videoDuration = max(CGFloat(finallyUserAudioTime), CGFloat(finallyStuckPoints.last!))
  885. let counn = (stuckPointMusicData?.rhythmSdata[0].pointTimes.count)! - 2
  886. let suggestRhythmStartTime = CGFloat(stuckPointMusicData?.suggestRhythmStartTime ?? 0)
  887. let suggestRhythmEndTime = max(suggestRhythmStartTime, CGFloat(stuckPointMusicData?.rhythmSdata[0].pointTimes[max(counn, 0)] ?? 0)/CGFloat(BASE_FILTER_TIMESCALE))
  888. stuckPointCuttingView.updateEndTime(
  889. startTime: CGFloat(CMTimeGetSeconds(playeTimeRange.start)),
  890. endTime: CGFloat(CMTimeGetSeconds(playeTimeRange.end)),
  891. suggestRhythmStartTime: suggestRhythmStartTime,
  892. suggestRhythmEndTime: suggestRhythmEndTime)
  893. // 2,创建滤镜
  894. DispatchQueue.global().async {
  895. self.mStickers = self.createStickers(sections: self.projectModel.sData?.sections ?? List(), inputSize: CGSize(width: CGFloat(self.projectModel.sData?.videoMetaData?.videoWidth ?? 0), height: CGFloat(self.projectModel.sData?.videoMetaData?.videoHeight ?? 0)), model: self.currentCreateStickersModel)
  896. DispatchQueue.main.async { // 串行、异步
  897. self.playerView.mStickers = self.mStickers
  898. BFLog(message: "createStickers tiskskskskme \(Date().timeIntervalSince(beginTime))")
  899. // 3,设置音频
  900. let audioPath = self.stuckPointMusicData?.localPath ?? ""
  901. BFLog(message: "初始化音频播放器的音频地址为:\(audioPath)")
  902. self.playerView.stop()
  903. // 这里的测试这个音乐播放有问题
  904. // self.playerView.updateAsset(URL(fileURLWithPath: "63930549652d74e477141e3b79c8d29a9ef8af81625053214516.mp3", relativeTo:Bundle.main.resourceURL!), videoComposition: nil, audioMixModel: nil)
  905. self.playerView.updateAsset(URL(fileURLWithPath: documensDirectory + audioPath), videoComposition: nil, audioMixModel: nil, originMusicDuration: self.finallyUserAudioTime, clipAudioRange: self.getClipAudioRange())
  906. // 4, 设置播放器的输出画布大小
  907. self.playerView.movie?.mShowVidoSize = CGSize(width: CGFloat(self.projectModel.sData?.videoMetaData?.videoWidth ?? 0), height: CGFloat(self.projectModel.sData?.videoMetaData?.videoHeight ?? 0))
  908. // 传给movie 音频的原始卡点
  909. let fir = Int64(self.stuckPointsTemp.first ?? 0)
  910. let endd = Int64(self.stuckPointsTemp.last ?? 0)
  911. self.playerView.movie?.orginStuckRange = CMTimeRange(start: CMTime(value: Int64(fir) * Int64(BASE_FILTER_TIMESCALE), timescale: BASE_FILTER_TIMESCALE), end: CMTime(value: Int64(endd) * Int64(BASE_FILTER_TIMESCALE), timescale: BASE_FILTER_TIMESCALE))
  912. // 5,开始播放
  913. self.playerView.isLoop = false
  914. self.playerView.showProgressLab = true
  915. // 初始化音频的开始和结束时间
  916. BFLog(message: "播放的器 开始\(String(describing: CMTimeGetSeconds(self.playeTimeRange.start))) 结束 \(String(describing: CMTimeGetSeconds(self.playeTimeRange.end)))")
  917. let end3: TimeInterval = Date().timeIntervalSince1970
  918. self.playerView.play(pauseFirstFrame: false, playeTimeRange: CMTimeRange(start: self.playeTimeRange.start, end: self.playeTimeRange.end))
  919. self.stuckPointCuttingView.updateProgress(progress: 0)
  920. let end4: TimeInterval = Date().timeIntervalSince1970
  921. BFLog(message: " playerView.play tiskskskskme \(end4 - end3)")
  922. // 6,进度回调
  923. self.playerView.progress = { [weak self] currentTime, tatolTime, percent in
  924. if percent == 1 {
  925. self?.stuckPointCuttingView.resetDefaultsColor(clearData: false)
  926. return
  927. }
  928. if(CMTimeGetSeconds(self?.playeTimeRange.duration ?? .zero) <= 0.0){
  929. BFLog(message: "时长错误!!!!")
  930. return
  931. }
  932. // 更新进度
  933. let progress = (currentTime - CMTimeGetSeconds(self?.playeTimeRange.start ?? .zero)) / CMTimeGetSeconds(self?.playeTimeRange.duration ?? .zero)
  934. BFLog(message: "\(currentTime) \(tatolTime) 显示播放器进度为: \(progress)")
  935. self?.stuckPointCuttingView.updateProgress(progress: CGFloat(progress))
  936. self?.synchroMarskView.removeMarskView()
  937. }
  938. }
  939. }
  940. }
  941. deinit {
  942. musicNameLab.stop()
  943. // playerView.pause()
  944. // 取消所有的导出
  945. PQSingletoMemoryUtil.shared.allExportSession.forEach { _, exportSession in
  946. exportSession.cancelExport()
  947. }
  948. self.synchroMarskView.removeMarskView()
  949. BFLog(1, message: "卡点视频预览界面release")
  950. }
  951. }
  952. // MARK: - 视频渲染相关逻辑方法
  953. extension PQStuckPointEditerController {
  954. /// 分割视频 这里只设置视频类型的 in 和 out 并不设置显示的开始和结束时间 mp4 ,png ,png ,mp4
  955. /// - Parameter section: 当前段
  956. /// - Parameter stuckPoints: 用户选择的,或推荐的卡点数
  957. /// - Returns: 返回分割后的所有 stickers 和卡点数是一致的
  958. func clipVideoMerage(section: PQEditSectionModel, stuckPoints: [Float]) -> [PQEditVisionTrackMaterialsModel] {
  959. var stickers: Array = Array<PQEditVisionTrackMaterialsModel>.init()
  960. // 第二种情况:有视频要进行分割
  961. /*
  962. 1, 确定每个视频素材需要切的段数p
  963. 2, 将所有视频时长相加,得到总视频素材时长L = l1 + l2 + ... + ln
  964. 3, 视频素材a1需要切分的个数clipNum = max (round (kongduan * a1 / L) , 1)
  965. */
  966. // 要补的空位数
  967. let kongduan: Int = Int(stuckPoints.count) - Int(section.sectionTimeline!.visionTrack?.getEnableVisionTrackMaterials().count ?? 0)
  968. // 所有视频总时长
  969. var videoTotalDuration: Float64 = 0.0
  970. for video in section.sectionTimeline!.visionTrack!.getEnableVisionTrackMaterials(type: "video") {
  971. let asset: AVURLAsset = AVURLAsset(url: URL(fileURLWithPath: documensDirectory + video.locationPath), options: nil)
  972. videoTotalDuration = videoTotalDuration + Float64(CMTimeGetSeconds(asset.duration))
  973. }
  974. if videoTotalDuration == 0 {
  975. BFLog(message: "视频总时长出现错误!!!!这里应该有视频素材的")
  976. return stickers
  977. }
  978. for sticker in section.sectionTimeline!.visionTrack!.getEnableVisionTrackMaterials() {
  979. if sticker.type == StickerType.VIDEO.rawValue {
  980. let asset: AVURLAsset = AVURLAsset(url: URL(fileURLWithPath: documensDirectory + sticker.locationPath), options: nil)
  981. // 要分割的段落
  982. let clipNum = Int(max(round(Double(kongduan) * CMTimeGetSeconds(asset.duration) / videoTotalDuration), 1))
  983. sticker.duration = CMTimeGetSeconds(asset.duration)
  984. BFLog(message: "单个视频\(sticker.locationPath)时长::\(CMTimeGetSeconds(asset.duration)) ,clipNum is:\(clipNum)")
  985. for clipindex in 0 ... clipNum - 1 {
  986. // deep copy sticker model 防止只有一个对象
  987. let deepCopySticker:PQEditVisionTrackMaterialsModel? = sticker.copy() as? PQEditVisionTrackMaterialsModel
  988. // 设置循环模式和适配模式
  989. deepCopySticker?.generateDefaultValues()
  990. deepCopySticker?.model_in = clipindex == 0 ? 0 : CMTimeGetSeconds(asset.duration) / Double(clipNum) * Double(clipindex)
  991. deepCopySticker?.out = (deepCopySticker?.model_in ?? 0) + CMTimeGetSeconds(asset.duration) / Double(clipNum)
  992. if (deepCopySticker?.model_in ?? 0) >= CMTimeGetSeconds(asset.duration) || (deepCopySticker?.out ?? 0) >= CMTimeGetSeconds(asset.duration) {
  993. deepCopySticker?.model_in = CMTimeGetSeconds(asset.duration) - CMTimeGetSeconds(asset.duration) / Double(clipNum)
  994. deepCopySticker?.out = CMTimeGetSeconds(asset.duration)
  995. }
  996. BFLog(message: " crilp is in \(deepCopySticker?.model_in ?? 0) out \(deepCopySticker?.out ?? 0) 总时长\(CMTimeGetSeconds(asset.duration))")
  997. if deepCopySticker != nil {
  998. stickers.append(deepCopySticker!)
  999. }
  1000. }
  1001. } else if sticker.type == StickerType.IMAGE.rawValue {
  1002. sticker.generateDefaultValues()
  1003. stickers.append(sticker)
  1004. }
  1005. }
  1006. return stickers
  1007. }
  1008. /// 创建sticker
  1009. /// - Parameters:
  1010. /// - sections: 项目所有段落数据信息
  1011. /// - inputSize: 画布大小
  1012. /// - Returns: filters 数据 播放器可直接使用
  1013. func createStickers(sections: List<PQEditSectionModel>, inputSize _: CGSize = .zero, model: createStickersModel = .createStickersModelPoint) -> [PQEditVisionTrackMaterialsModel] {
  1014. // 推荐卡点数
  1015. let beginDecoderTime: TimeInterval = Date().timeIntervalSince1970
  1016. // 保存滤镜对象数据
  1017. var stickers: Array = Array<PQEditVisionTrackMaterialsModel>.init()
  1018. for section in sections {
  1019. if section.sectionType == "normal" {
  1020. // 第一种情况:全是图片,三种模式都进行图片回环播放
  1021. if section.sectionTimeline!.visionTrack!.getEnableVisionTrackMaterials(type: "video").count == 0, section.sectionTimeline!.visionTrack!.getEnableVisionTrackMaterials(type: "image").count > 0 {
  1022. for (index, _) in finallyStuckPoints.enumerated() {
  1023. let sticker: PQEditVisionTrackMaterialsModel = section.sectionTimeline!.visionTrack!.getEnableVisionTrackMaterials()[index % section.sectionTimeline!.visionTrack!.getEnableVisionTrackMaterials().count]
  1024. BFLog(message: "stickerlocationPath sticker : \(sticker.locationPath)")
  1025. //
  1026. let deepCopySticker:PQEditVisionTrackMaterialsModel? = sticker.copy() as? PQEditVisionTrackMaterialsModel
  1027. if deepCopySticker!.type == StickerType.IMAGE.rawValue {
  1028. if index + 1 < finallyStuckPoints.count {
  1029. deepCopySticker!.timelineIn = Float64(String(format: "%.6f",finallyStuckPoints[index])) ?? 0.0
  1030. deepCopySticker!.timelineOut = Float64(String(format: "%.6f",finallyStuckPoints[index + 1])) ?? 0.0
  1031. if deepCopySticker != nil {
  1032. deepCopySticker?.generateDefaultValues()
  1033. stickers.append(deepCopySticker!)
  1034. BFLog(1, message: "测试人员index is 纯图片 timelineOut:\(deepCopySticker!.timelineIn) timelineOut :\(deepCopySticker!.timelineOut)")
  1035. }
  1036. }
  1037. }
  1038. }
  1039. } else { // 第二种情况:视频 + 图片情况、视频要分段+图片按卡点时长创建
  1040. if model == .createStickersModelPoint { // 跳跃卡点
  1041. // 第二种情况:有视频要进行分割
  1042. let clipFilters = clipVideoMerage(section: section, stuckPoints: finallyStuckPoints)
  1043. for (index, point) in finallyStuckPoints.enumerated() {
  1044. BFLog(message: "aaaaaindexindeindexxindexindexindex \(index) \(point)")
  1045. if index + 1 < finallyStuckPoints.count, index < clipFilters.count {
  1046. BFLog(message: "bbbbbindexindeindexxindexindexindex \(index) \(point)")
  1047. let sticker: PQEditVisionTrackMaterialsModel = clipFilters[index]
  1048. if(sticker.type == StickerType.IMAGE.rawValue){
  1049. BFLog(message: "当前是image filter !!!!!")
  1050. }
  1051. sticker.timelineIn = Float64(String(format: "%.6f",finallyStuckPoints[index])) ?? 0.0
  1052. sticker.timelineOut = Float64(String(format: "%.6f",finallyStuckPoints[index + 1])) ?? 0.0
  1053. // 卡点的时间 > in out 值 这里就会出现鬼畜效果
  1054. let timelineInterval = sticker.timelineOut - sticker.timelineIn
  1055. let inOutInterval = sticker.out - sticker.model_in
  1056. if timelineInterval > inOutInterval {
  1057. BFLog(message: "实际要显示卡点时长\(timelineInterval) 素材裁剪时长:\(inOutInterval)")
  1058. sticker.out = sticker.model_in + timelineInterval
  1059. // 下面只是 LOG 方便查问题
  1060. let stickerInOut = sticker.out - sticker.model_in
  1061. let stickerTimelineInOut = sticker.timelineOut - sticker.timelineIn
  1062. if stickerInOut != stickerTimelineInOut {
  1063. BFLog(message: "sticker.timelineIn \(sticker.timelineIn) stickerTimelineInOut is\(stickerTimelineInOut) stickerInOut is\(stickerInOut) 相差\(stickerTimelineInOut - stickerInOut)")
  1064. }
  1065. }
  1066. // out > 素材的总时长in out 进行前移操作
  1067. let offsetAssetDuration = sticker.out - sticker.duration
  1068. if offsetAssetDuration > 0 {
  1069. sticker.model_in = sticker.model_in - offsetAssetDuration
  1070. sticker.out = sticker.out - offsetAssetDuration
  1071. }
  1072. BFLog(message: "跳跃卡点测试人员index is \(index)分割后 创建 filter timelineIn :\(sticker.timelineIn) timelineOut :\(sticker.timelineOut) in :\(sticker.model_in) out:\(sticker.out) type is \(sticker.type) 显示总时长为:\(sticker.timelineOut - sticker.timelineIn) 裁剪总时长\(sticker.out - sticker.model_in)")
  1073. stickers.append(sticker)
  1074. }
  1075. }
  1076. } else if model == .createStickersModelOnlyMusic || model == .createStickersModelSpeed { // 仅音乐 和 快慢速卡点
  1077. BFLog(message: "stuckPoints count is \(finallyStuckPoints.count)")
  1078. for sticker in section.sectionTimeline!.visionTrack!.getEnableVisionTrackMaterials() {
  1079. if sticker.type == StickerType.VIDEO.rawValue {
  1080. let asset: AVURLAsset = AVURLAsset(url: URL(fileURLWithPath: documensDirectory + sticker.locationPath), options: nil)
  1081. BFLog(message: "单个视频\(sticker.locationPath)时长::\(CMTimeGetSeconds(asset.duration)) ,clipNum is:\(sticker.clipCount)")
  1082. var lastOutTime: Float64 = 0.0
  1083. for _ in 0 ... sticker.clipCount {
  1084. // deep copy sticker model 防止只有一个对象
  1085. let deepCopyStickerDecoderTime: TimeInterval = Date().timeIntervalSince1970
  1086. let deepCopySticker:PQEditVisionTrackMaterialsModel? = sticker.copy() as? PQEditVisionTrackMaterialsModel
  1087. BFLog(message: "生成stickers 总时长为 aaa\(Date().timeIntervalSince1970 - deepCopyStickerDecoderTime)")
  1088. // 设置循环模式和适配模式
  1089. deepCopySticker?.generateDefaultValues()
  1090. deepCopySticker?.materialDurationFit?.fitType = adapterMode.staticFrame.rawValue
  1091. // 当前分段的速度
  1092. var tempSpeed: Float = 1.0
  1093. if model == .createStickersModelSpeed {
  1094. tempSpeed = (stickers.count % 2) == 0 ? maxSpeed : minSpeed
  1095. }
  1096. if stickers.count + 1 < finallyStuckPoints.count {
  1097. deepCopySticker?.speedRate = tempSpeed
  1098. // 定义临时使用的变量
  1099. // 素材显示的开始时间和结束时间
  1100. let tempTimelineIn:Float64 = Float64(String(format: "%.6f",finallyStuckPoints[stickers.count])) ?? 0.0
  1101. let timelineOut:Float64 = Float64(String(format: "%.6f",finallyStuckPoints[stickers.count + 1])) ?? 0.0
  1102. // 素材分割的开始时间和结束时间
  1103. let tempModel_In = lastOutTime
  1104. var tempOut = lastOutTime + Float64(tempSpeed) * (timelineOut - tempTimelineIn)
  1105. // 处理最后一点视频素材不够卡点时长 e.g. 0.3 卡点时长0.5
  1106. if tempOut > CMTimeGetSeconds(asset.duration) {
  1107. BFLog(message: "最后一点视频素材不够卡点时长要做变速C处理 差\(tempOut - CMTimeGetSeconds(asset.duration))")
  1108. // 最后一点素材时长
  1109. let lastAssetDuration = CMTimeGetSeconds(asset.duration) - lastOutTime
  1110. let pointDuration = timelineOut - tempTimelineIn
  1111. // 要适应到卡点内要使用的C速度
  1112. let needSpeed = lastAssetDuration / pointDuration
  1113. // 当前卡点段为快速
  1114. if tempSpeed >= 1 {
  1115. if needSpeed >= 0.4 * Double(tempSpeed) {
  1116. deepCopySticker?.speedRate = Float(needSpeed)
  1117. } else {
  1118. continue
  1119. }
  1120. } else { // 当前卡点段为慢速
  1121. if needSpeed >= 0.4 * Double(tempSpeed) && needSpeed >= 0.2 {
  1122. deepCopySticker?.speedRate = Float(needSpeed)
  1123. } else {
  1124. continue
  1125. }
  1126. }
  1127. tempOut = CMTimeGetSeconds(asset.duration)
  1128. }
  1129. deepCopySticker?.model_in = tempModel_In
  1130. deepCopySticker?.out = tempOut
  1131. deepCopySticker?.timelineIn = tempTimelineIn
  1132. deepCopySticker?.timelineOut = timelineOut
  1133. lastOutTime = deepCopySticker?.out ?? 0
  1134. }
  1135. BFLog(message: "测试人员创建 sticker crilp is in 视频 \(String(format: "%.6f", deepCopySticker?.model_in ?? 0)) out \(String(format: "%.6f", deepCopySticker?.out ?? 0)) ,分段素材时长:\(String(format: "%.6f", (deepCopySticker?.out ?? 0) - (deepCopySticker?.model_in ?? 0))) ,分段显示时长:\(String(format: "%.6f", (deepCopySticker?.timelineOut ?? 0) - (deepCopySticker?.timelineIn ?? 0))), 视频素材原时长\(CMTimeGetSeconds(asset.duration)) timelineIN: \(String(format: "%.6f", deepCopySticker?.timelineIn ?? 0)) timelineOUT:\(String(format: "%.6f", deepCopySticker?.timelineOut ?? 0)) speedRate:\(deepCopySticker?.speedRate ?? 0.0)")
  1136. if deepCopySticker != nil {
  1137. stickers.append(deepCopySticker!)
  1138. }
  1139. }
  1140. } else if sticker.type == StickerType.IMAGE.rawValue {
  1141. if stickers.count + 1 >= finallyStuckPoints.count {
  1142. BFLog(message: "数据出现错误!!!查正") // 155.318253
  1143. break
  1144. }
  1145. sticker.generateDefaultValues()
  1146. sticker.timelineIn = Float64(String(format: "%.6f",finallyStuckPoints[stickers.count])) ?? 0.0
  1147. sticker.timelineOut = Float64(String(format: "%.6f",finallyStuckPoints[stickers.count + 1])) ?? 0.0
  1148. stickers.append(sticker)
  1149. BFLog(1, message: "测试人员创建 sticker crilp is in 图片 \(String(format: "%.6f", sticker.model_in)) out \(String(format: "%.6f", sticker.out)) ,分段素材时长:\(String(format: "%.6f", (sticker.out) - (sticker.model_in))) ,分段显示时长:\(String(format: "%.6f", (sticker.timelineOut) - (sticker.timelineIn))), timelineIN: \(String(format: "%.6f", sticker.timelineIn)) timelineOUT:\(String(format: "%.6f", sticker.timelineOut)) speedRate:\(sticker.speedRate)")
  1150. }
  1151. }
  1152. }
  1153. }
  1154. }
  1155. }
  1156. BFLog(message: "生成stickers 总时长为:\(Date().timeIntervalSince1970 - beginDecoderTime)")
  1157. return stickers
  1158. }
  1159. /// 根据档位取最后使用的卡点数据
  1160. /// - Parameter seed: 档位速度
  1161. /// - Returns: 最后使用的卡点
  1162. func getUsedStuckPoint(seed: Int) -> Array<Float> {
  1163. // 推荐卡点数
  1164. var stuckPoints: Array = Array<Float>.init()
  1165. var pointsTemp = Array<Float>.init()
  1166. //
  1167. // 最后一个卡点时间(原推荐卡点的倒数第二位时间)
  1168. let lastPoint = stuckPointMusicData!.rhythmSdata[0].pointTimes[stuckPointMusicData!.rhythmSdata[0].pointTimes.count - 2]
  1169. for (index, dunshu) in stuckPointMusicData!.rhythmSdata[0].pointTimes.enumerated() {
  1170. if dunshu >= Int64((stuckPointMusicData?.startTime ?? 0) * Float64(BASE_FILTER_TIMESCALE)) && dunshu < lastPoint {
  1171. let savePointStr = String(format: "%.6f", Float(dunshu) / Float(BASE_FILTER_TIMESCALE))
  1172. BFLog(message: "原所有卡点数:\(index) \(savePointStr)")
  1173. pointsTemp.append(Float(savePointStr) ?? 0.0)
  1174. }
  1175. }
  1176. /*
  1177. 一,快慢速模式下取卡点 2 3 4
  1178. 二,跳跃卡点模式下根据不同速度 取卡点 1,2,3
  1179. 快节奏为选中区域的所有点位,即0,1,2,3,4 5 6 7 8 9 10 ……
  1180. 适中为每两个点位取一个,即0,2,4,6……
  1181. 慢节奏为每三个点位取一个,即0,3,6,9……
  1182. */
  1183. // 不丢
  1184. if seed == 1 {
  1185. stuckPoints = pointsTemp
  1186. } else {
  1187. // 根据档位要丢
  1188. for (index, point) in pointsTemp.enumerated() {
  1189. if index % seed == 0 {
  1190. stuckPoints.append(point)
  1191. }
  1192. }
  1193. }
  1194. for point in stuckPoints {
  1195. BFLog(message: "没有 start end 计算后的卡点数\(point)")
  1196. }
  1197. // 若音乐起点至第一个卡点点位之间时长t0<0.3时,此段时长与下一个点位时长合并,故第一段卡点部分时长为t0+d
  1198. if Float(stuckPointMusicData?.startTime ?? 0) - (stuckPoints.first ?? 0.0) < 0.3 {
  1199. if stuckPoints.first != nil {
  1200. stuckPoints.removeFirst()
  1201. }
  1202. }
  1203. stuckPoints.insert(Float(stuckPointMusicData?.startTime ?? 0), at: 0)
  1204. for point in stuckPoints {
  1205. BFLog(message: "有 start end 计算后的卡点数\(point)")
  1206. }
  1207. BFLog(message: "处理节奏后 stuckPoints count is \(stuckPoints.count) seed \(seed), start time:\(stuckPoints.first ?? 0.0),end time:\(stuckPoints.last ?? 0.0) 总时长为:\((stuckPoints.last ?? 0.0) - (stuckPoints.first ?? 0.0))")
  1208. return stuckPoints
  1209. }
  1210. func clipPoint(clipCount: Int, oldPoints: Array<Float>) {
  1211. BFLog(message: "拼接卡点数:\(clipCount)")
  1212. if(clipCount < 0 || oldPoints.count < 2){
  1213. BFLog(message: "clipCount is error!!!! \(clipCount)")
  1214. return
  1215. }
  1216. // 如果是第一次拼接先补第0位
  1217. if finallyStuckPoints.count == 0 {
  1218. finallyStuckPoints.append(stuckPointsTemp.first ?? 0.0)
  1219. }
  1220. for i in finallyStuckPoints.count ... clipCount + finallyStuckPoints.count {
  1221. if (i % (oldPoints.count - 1)) != 1 {
  1222. let value = String(format: "%.6f", finallyStuckPoints[i - 1] + oldPoints[((i-1) % (oldPoints.count - 1)) + 1] - oldPoints[((i - 2) % (oldPoints.count - 1)) + 1])
  1223. finallyStuckPoints.append(Float(value) ?? 0.0)
  1224. } else {
  1225. let value = String(format: "%.6f", finallyStuckPoints[i - 1] + oldPoints[1] - oldPoints[0])
  1226. finallyStuckPoints.append(Float(value) ?? 0.0)
  1227. }
  1228. }
  1229. }
  1230. /// 根据不同模式model, maxSpeed ,minSpeed, self?.stuckPointMusicData?.speed 档位,生成音乐时长和最终使用的卡点信息
  1231. func dealParameter(model: createStickersModel) {
  1232. // 清空上一次使用的卡点数据
  1233. finallyStuckPoints.removeAll()
  1234. // 已经取到的视频素材总长度,用于和原视频素材时长做对比,不够多加一个点
  1235. var useAssestDuration: Float = 0.0
  1236. switch model {
  1237. case .createStickersModelPoint: // 跳跃卡点
  1238. stuckPointsTemp = getUsedStuckPoint(seed: stuckPointMusicData?.speed ?? 0)
  1239. // 要拼接的段数
  1240. var clipNum: Int = 0
  1241. var i: Int = 0
  1242. // L/(n+1) L -原视觉素材总时长 n-抛留倍数 lastJumpSpeedSelectIndex 是位置 对应的值要+1
  1243. // 根据公式计划出的总时长
  1244. let jumpTime = Float(selectedTotalDuration) / Float(maxSpeed + 1)
  1245. // 只有图片素材时会为0
  1246. if jumpTime > 0 {
  1247. while useAssestDuration < Float(jumpTime) {
  1248. // 回环从头取\
  1249. if i + 1 >= stuckPointsTemp.count {
  1250. i = 0
  1251. }
  1252. // 快速段
  1253. let LA = (stuckPointsTemp[i + 1] - stuckPointsTemp[i])
  1254. useAssestDuration = useAssestDuration + Float(LA)
  1255. i = i + 1
  1256. clipNum = clipNum + 1
  1257. }
  1258. // 拼接要使用的卡点信息
  1259. clipPoint(clipCount: clipNum, oldPoints: stuckPointsTemp)
  1260. }
  1261. break
  1262. case .createStickersModelSpeed, .createStickersModelOnlyMusic: // 快慢速
  1263. // 快慢速 (2:快节奏,3:适中,4:慢节奏)
  1264. var tempMaxSpeed: Float = 1
  1265. var tempMinSpeed: Float = 1
  1266. //速度有为0 会出现在切换模式时,目前是共用一个参数值,会清掉老值 TODO
  1267. if((maxSpeed == 0.0 && minSpeed == 0.0) && selectedDataCount != selectedImageDataCount && model == .createStickersModelSpeed){
  1268. BFLog(message: "速度参数有错误 要重新计算!!!")
  1269. dealWithDataSuccess()
  1270. return
  1271. }
  1272. if model == .createStickersModelSpeed {
  1273. // 改变速率,.只有快慢速且非只有图片素材时自动+1处理
  1274. if model == .createStickersModelSpeed && selectedDataCount != selectedImageDataCount {
  1275. stuckPointsTemp = getUsedStuckPoint(seed: (stuckPointMusicData?.speed ?? 0) + 1)
  1276. } else {
  1277. stuckPointsTemp = getUsedStuckPoint(seed: (stuckPointMusicData?.speed ?? 0))
  1278. }
  1279. tempMaxSpeed = maxSpeed
  1280. tempMinSpeed = minSpeed
  1281. } else {
  1282. stuckPointsTemp = getUsedStuckPoint(seed: (stuckPointMusicData?.speed ?? 0))
  1283. }
  1284. /*
  1285. - A-视频中的快速片段
  1286. - B-视频中的慢速片段
  1287. - d-在一档下音乐每个点位时长
  1288. - n-不同音乐档位对应的d倍数,快节奏时,n=1;适中时,n=3;慢节奏时,n=5
  1289. - L-原视觉素材时长
  1290. - x-视频在A片段的播放倍速
  1291. - y-视频在B片段的播放倍速
  1292. */
  1293. // LA=x*n*d,LB=y*n*d (n=1/3/5) 注:视频经过快慢速处理后的总时长约=L*2/(x+y)
  1294. BFLog(message: "Ax快速为:\(tempMaxSpeed) By慢速为:\(tempMinSpeed) 档位 N为:\(stuckPointMusicData?.speed ?? 0) 使用的卡点总数:\(stuckPointsTemp.count)")
  1295. // 使用新方法取使用的卡点数据
  1296. for section in projectModel.sData?.sections ?? List() {
  1297. if section.sectionType == "normal" {
  1298. for sticker in section.sectionTimeline!.visionTrack!.getEnableVisionTrackMaterials() {
  1299. if sticker.type == StickerType.VIDEO.rawValue {
  1300. let asset: AVURLAsset = AVURLAsset(url: URL(fileURLWithPath: documensDirectory + sticker.locationPath), options: nil)
  1301. let assetDuration = Float(CMTimeGetSeconds(asset.duration))
  1302. BFLog(message: "输入素材时长 \(assetDuration)")
  1303. if(finallyStuckPoints.count == 0){
  1304. finallyStuckPoints.append(stuckPointsTemp[0])
  1305. }
  1306. var j = finallyStuckPoints.count
  1307. // 添加卡点的段数 用于判断当前卡点是快/慢速
  1308. var pointCount:Int = 0
  1309. // 已经取到的视频素材总长度,用于和原视频素材时长做对比,不够多加一个卡点
  1310. var useAssestDurationTemp: Float = 0.0
  1311. while useAssestDurationTemp < assetDuration {
  1312. //当前段的应该使用的速度 A/B
  1313. let useSpeed = (pointCount % 2 == 0 ) ? tempMaxSpeed : tempMinSpeed
  1314. // 计算卡点
  1315. //要添加的卡点数值
  1316. var sub:Float = 0.0
  1317. if stuckPointsTemp.count > 2 {
  1318. if ((j - 1) % (stuckPointsTemp.count - 1)) != 0{
  1319. sub = stuckPointsTemp[((j - 1) % (stuckPointsTemp.count-1)) + 1] - stuckPointsTemp[(j - 1) % (stuckPointsTemp.count - 1)]
  1320. }else {
  1321. sub = stuckPointsTemp[1] - stuckPointsTemp[0]
  1322. }
  1323. finallyStuckPoints.append(finallyStuckPoints[j - 1] + sub)
  1324. j += 1
  1325. }
  1326. useAssestDurationTemp += sub * useSpeed
  1327. if(useAssestDurationTemp > assetDuration){
  1328. useAssestDurationTemp -= sub * useSpeed
  1329. break
  1330. }
  1331. pointCount += 1
  1332. FilterLog(message: "finallyStuckPoints last ;\((finallyStuckPoints.last ?? 0.0) - (finallyStuckPoints.first ?? 0.0)), tmp:\(useAssestDurationTemp)")
  1333. }
  1334. // 2拼接要使用的卡点信息
  1335. sticker.clipCount = pointCount
  1336. if stuckPointsTemp.count < 1 {
  1337. //todo 和产品沟通提示
  1338. BFLog(message: "卡点数据有错误!!!")
  1339. return
  1340. }
  1341. BFLog(message: "finallyStuckPoints\(finallyStuckPoints)")
  1342. // 3,多补一个卡点 做 C级 速处理,要根据条件不满足 要删除最后一位,
  1343. if useAssestDurationTemp < assetDuration {
  1344. // 下一个卡的的速度性质快、慢
  1345. var tempSpeed: Float = 1.0
  1346. if model == .createStickersModelSpeed {
  1347. tempSpeed = (sticker.clipCount) % 2 == 0 ? maxSpeed : minSpeed
  1348. }
  1349. // 最后一点素材时长
  1350. let lastAssetDuration = Float(CMTimeGetSeconds(asset.duration)) - useAssestDurationTemp
  1351. let lastPointIndex = (sticker.clipCount % stuckPointsTemp.count)
  1352. // 两个卡点
  1353. let a: Float = stuckPointsTemp[lastPointIndex]
  1354. var b: Float = 0.0
  1355. if lastPointIndex + 1 < stuckPointsTemp.count {
  1356. b = stuckPointsTemp[lastPointIndex + 1]
  1357. let pointDuration = b - a
  1358. // 要适应到卡点内要使用的C速度
  1359. let needSpeed = lastAssetDuration / pointDuration
  1360. // 当前卡点段为快速
  1361. if tempSpeed >= 1 {
  1362. if needSpeed < 0.4 * tempSpeed {
  1363. BFLog(message: "条件不满足不用补位 删除多加的一位")
  1364. finallyStuckPoints.removeLast()
  1365. }
  1366. } else { // 当前卡点段为慢速
  1367. if needSpeed >= 0.4 * tempSpeed && needSpeed >= 0.2 {
  1368. // 查找使用的最后一个卡点在原数组中的位置
  1369. } else {
  1370. BFLog(message: "条件不满足不用补位 删除多加的一位")
  1371. finallyStuckPoints.removeLast()
  1372. }
  1373. }
  1374. }
  1375. }else {
  1376. //出现在第一个卡点X 倍速 > 原素材
  1377. finallyStuckPoints.removeLast()
  1378. }
  1379. }
  1380. }
  1381. }
  1382. }
  1383. break
  1384. }
  1385. // 拼接图片所使用的时长.选择一组图片 按图片数量计算卡点的总时长
  1386. if selectedImageDataCount > 0 {
  1387. clipPoint(clipCount: selectedImageDataCount - 1, oldPoints: stuckPointsTemp)
  1388. }
  1389. // 全是图片时数组里放着的一定都是图片的使用的卡点
  1390. // 定义一次循环的总时长
  1391. var oneSelectImageDuration: Float = 0.0
  1392. if selectedDataCount == selectedImageDataCount {
  1393. oneSelectImageDuration = (finallyStuckPoints.last ?? 0) - (finallyStuckPoints.first ?? 0)
  1394. }
  1395. // 3)素材全是图片处理
  1396. if selectedDataCount == selectedImageDataCount{
  1397. // lastCyclesSelectIndex != -1 已经设置过循环次数 应该是手动设置的值
  1398. if lastCyclesSelectIndex != -1 {
  1399. // 纯图片时 已经默认添加一次循环 所以要用lastCyclesSelectIndex - 1
  1400. if(lastCyclesSelectIndex != 0){
  1401. clipPoint(clipCount: selectedImageDataCount * lastCyclesSelectIndex - 1, oldPoints: stuckPointsTemp)
  1402. }
  1403. } else {
  1404. if(oneSelectImageDuration < 10 ){
  1405. lastCyclesSelectIndex = 0
  1406. while oneSelectImageDuration < 10 {
  1407. // 不够10S 时 一次加图片数量的卡点数
  1408. clipPoint(clipCount: selectedImageDataCount - 1, oldPoints: stuckPointsTemp)
  1409. oneSelectImageDuration = Float((finallyStuckPoints.last ?? 0) - (finallyStuckPoints.first ?? 0))
  1410. lastCyclesSelectIndex = lastCyclesSelectIndex + 1
  1411. }
  1412. speedSettingView.setSelectItem(index: lastCyclesSelectIndex, isSettingPlayer: false,enableInsert: true)
  1413. }else{
  1414. lastCyclesSelectIndex = 0
  1415. }
  1416. }
  1417. }
  1418. // 设置速度选择的位置
  1419. if speedSettingView.viewType == 1 {
  1420. speedSettingView.setSelectItem(index: lastSpeedSelectIndex, isSettingPlayer: false)
  1421. } else if speedSettingView.viewType == 2 {
  1422. speedSettingView.setSelectItem(index: lastJumpSpeedSelectIndex, isSettingPlayer: false)
  1423. } else if speedSettingView.viewType == 3 {
  1424. if lastCyclesSelectIndex != -1 {
  1425. speedSettingView.setSelectItem(index: lastCyclesSelectIndex, isSettingPlayer: false)
  1426. } else {
  1427. speedSettingView.setSelectItem(index: 0, isSettingPlayer: false)
  1428. }
  1429. }
  1430. // 四,背景音乐时长处理)计算最后使用的音频时长, 如果不用拼接音频时长度是卡点的倒数第二位时间
  1431. let asset = AVURLAsset(url: URL(fileURLWithPath: documensDirectory + (stuckPointMusicData?.localPath ?? "")), options: nil)
  1432. // 原推荐卡点的倒数第二位时间
  1433. let lastSecondPoint = Float((stuckPointMusicData!.rhythmSdata[0].pointTimes[stuckPointMusicData!.rhythmSdata[0].pointTimes.count - 2])) / Float(BASE_FILTER_TIMESCALE)
  1434. finallyUserAudioTime = Float(lastSecondPoint)
  1435. if (finallyStuckPoints.last ?? 0) > Float(CMTimeGetSeconds(asset.duration)) {
  1436. finallyUserAudioTime = Float(finallyStuckPoints.last ?? 0) + (Float(CMTimeGetSeconds(asset.duration)) - Float(lastSecondPoint))
  1437. }
  1438. playeTimeRange = CMTimeRange(start: CMTime(value: CMTimeValue(Float64(finallyStuckPoints.first ?? 0) * Float64(BASE_FILTER_TIMESCALE)), timescale: BASE_FILTER_TIMESCALE), end: CMTime(value: CMTimeValue((Float64(finallyStuckPoints.last ?? 0)) * Float64(BASE_FILTER_TIMESCALE)), timescale: BASE_FILTER_TIMESCALE))
  1439. for (index, usePoint) in finallyStuckPoints.enumerated() {
  1440. BFLog(message: "测试人员最后使用的卡点信息 \(index) : \(usePoint)")
  1441. }
  1442. BFLog(message: "计算后给播放器使用的开始:\(CMTimeGetSeconds(playeTimeRange.start)) 结束时间\(CMTimeGetSeconds(playeTimeRange.end)) 播放总时长:\(CMTimeGetSeconds(playeTimeRange.end) - CMTimeGetSeconds(playeTimeRange.start))")
  1443. }
  1444. }
  1445. // MARK: - 同步/下载素材相关
  1446. /// 同步/下载素材相关
  1447. extension PQStuckPointEditerController {
  1448. /// 同步音乐相关数据
  1449. /// - Returns: <#description#>
  1450. func synchroMusicInfoData(resetSelectIndex:Bool = true) {
  1451. if (stuckPointMusicData?.rhythmSdata.count ?? 0) <= 0 {
  1452. if synchroMarskView.superview == nil {
  1453. UIApplication.shared.keyWindow?.addSubview(synchroMarskView)
  1454. synchroMarskView.show()
  1455. }
  1456. PQStuckPointViewModel.stuckPointMusicDetailData(musicId: stuckPointMusicData?.musicId ?? "", originType: stuckPointMusicData?.originType ?? 1) { [weak self] newMusicData, _ in
  1457. if newMusicData != nil, (newMusicData?.rhythmSdata.count ?? 0) > 0 {
  1458. self?.isStuckPointDataSuccess = true
  1459. self?.stuckPointMusicData?.rhythmSdata = newMusicData?.rhythmSdata ?? []
  1460. self?.stuckPointMusicData?.startTime = newMusicData?.startTime ?? 0
  1461. self?.stuckPointMusicData?.endTime = newMusicData?.endTime ?? 0
  1462. if newMusicData?.speed != nil {
  1463. self?.stuckPointMusicData?.speed = newMusicData?.speed ?? 2
  1464. }
  1465. if self?.stuckPointMusicData?.localPath == nil || (self?.stuckPointMusicData?.localPath?.count ?? 0) > 0 {
  1466. PQDownloadManager.downLoadFile(url: self?.stuckPointMusicData?.musicPath ?? "") { [weak self] filePath, error in
  1467. if error == nil, filePath != nil {
  1468. self?.isSynchroMusicInfoSuccess = true
  1469. self?.stuckPointMusicData?.localPath = filePath?.replacingOccurrences(of: documensDirectory, with: "")
  1470. // 处理所有数据完成
  1471. self?.dealWithDataSuccess(resetSelectIndex: resetSelectIndex)
  1472. }
  1473. self?.synchroMarskView.removeMarskView()
  1474. }
  1475. } else {
  1476. self?.isSynchroMusicInfoSuccess = true
  1477. // 处理所有数据完成
  1478. self?.dealWithDataSuccess(resetSelectIndex: resetSelectIndex)
  1479. }
  1480. // 添加子视图
  1481. self?.addSubViews()
  1482. } else {
  1483. self?.synchroMarskView.removeMarskView()
  1484. }
  1485. }
  1486. } else if stuckPointMusicData?.localPath == nil || (stuckPointMusicData?.localPath?.count ?? 0) > 0 {
  1487. if synchroMarskView.superview == nil {
  1488. UIApplication.shared.keyWindow?.addSubview(synchroMarskView)
  1489. synchroMarskView.show()
  1490. }
  1491. isStuckPointDataSuccess = true
  1492. PQDownloadManager.downLoadFile(url: stuckPointMusicData?.musicPath ?? "") { [weak self] filePath, error in
  1493. if error == nil, filePath != nil {
  1494. self?.isSynchroMusicInfoSuccess = true
  1495. self?.stuckPointMusicData?.localPath = filePath?.replacingOccurrences(of: documensDirectory, with: "")
  1496. // 处理所有数据完成
  1497. self?.dealWithDataSuccess(resetSelectIndex: resetSelectIndex)
  1498. } else {
  1499. self?.synchroMarskView.removeMarskView()
  1500. // PQUploadRemindView.showUploadRemindView(title: nil, attributedTitle: NSAttributedString(string: "加载音乐失败,请重新选择音乐"), summary: "", confirmTitle: nil) { [weak self] _, _ in
  1501. // self?.navigationController?.popViewController(animated: true)
  1502. // }
  1503. }
  1504. }
  1505. } else {
  1506. isStuckPointDataSuccess = true
  1507. // 处理所有数据完成
  1508. dealWithDataSuccess(resetSelectIndex: resetSelectIndex)
  1509. }
  1510. }
  1511. /// 导出相册数据
  1512. /// - Returns: <#description#>
  1513. func exportPhotoData() {
  1514. // 取消所有的导出
  1515. PQSingletoMemoryUtil.shared.allExportSession.forEach { _, exportSession in
  1516. exportSession.cancelExport()
  1517. }
  1518. var isHaveVideo: Bool = false
  1519. if selectedPhotoData != nil, (selectedPhotoData?.count ?? 0) > 0 {
  1520. if synchroMarskView.superview == nil {
  1521. UIApplication.shared.keyWindow?.addSubview(synchroMarskView)
  1522. }
  1523. let dispatchGroup = DispatchGroup()
  1524. for photo in selectedPhotoData! {
  1525. if photo.asset != nil, photo.asset?.mediaType == .video {
  1526. if !isHaveVideo {
  1527. isHaveVideo = true
  1528. }
  1529. dispatchGroup.enter()
  1530. PQPHAssetVideoParaseUtil.parasToAVAsset(phAsset: photo.asset!) { avAsset, _, _, _ in
  1531. if avAsset is AVURLAsset {
  1532. // 创建目录
  1533. let fileName = (avAsset as! AVURLAsset).url.absoluteString
  1534. BFLog(message: "video fileName is\(fileName)")
  1535. let tempPhoto = self.selectedPhotoData?.first(where: { material in
  1536. material.asset == photo.asset
  1537. })
  1538. if (fileName.count) > 0 {
  1539. createDirectory(path: photoLibraryDirectory)
  1540. let outFilePath = photoLibraryDirectory + fileName.md5 + ".mp4"
  1541. // 文件存在先删除老文件
  1542. if FileManager.default.fileExists(atPath: outFilePath) {
  1543. do {
  1544. try FileManager.default.removeItem(at: NSURL.fileURL(withPath: outFilePath))
  1545. } catch {
  1546. BFLog(message: "导出相册视频-error == \(error)")
  1547. }
  1548. }
  1549. do {
  1550. try FileManager.default.copyItem(atPath: fileName.replacingOccurrences(of: "file:///", with: ""), toPath: outFilePath)
  1551. print("Success to copy file.")
  1552. } catch {
  1553. print("Failed to copy file.")
  1554. }
  1555. tempPhoto?.locationPath = outFilePath.replacingOccurrences(of: documensDirectory, with: "")
  1556. BFLog(message: "导出视频相册地址为 \(String(describing: tempPhoto?.locationPath))")
  1557. dispatchGroup.leave()
  1558. }
  1559. }else {
  1560. // 结束loading动画
  1561. DispatchQueue.main.async {
  1562. self.synchroMarskView.removeMarskView()
  1563. }
  1564. }
  1565. }
  1566. }
  1567. }
  1568. dispatchGroup.notify(queue: DispatchQueue.main) { [weak self] in
  1569. self?.isExportVideosSuccess = true
  1570. BFLog(message: "所有相册视频导出成功")
  1571. // 处理所有数据完成
  1572. if isHaveVideo {
  1573. self?.dealWithDataSuccess()
  1574. }
  1575. }
  1576. // 只有图片
  1577. if !isHaveVideo {
  1578. isExportVideosSuccess = true
  1579. BFLog(message: "所有相册视频导出成功")
  1580. dealWithDataSuccess()
  1581. }
  1582. }
  1583. }
  1584. /// 处理所有数据完成
  1585. /// - Returns: <#description#>
  1586. /// resetSelectIndex : 是否重置用户选择的速度设置,在编辑界面切换音乐时不重置
  1587. func dealWithDataSuccess(resetSelectIndex:Bool = true) {
  1588. BFLog(message: "三组参数:\(isSynchroMusicInfoSuccess) \(isStuckPointDataSuccess) \(isExportVideosSuccess)")
  1589. if !isSynchroMusicInfoSuccess || !isStuckPointDataSuccess || !isExportVideosSuccess {
  1590. return
  1591. }
  1592. createPorjectData()
  1593. BFLog(1, message: "界面编辑界面时参数 选择素材时长:\(selectedTotalDuration) 选择素材总数:\(selectedDataCount) 选择图片总数\(selectedImageDataCount) 再创建类型:\(String(describing: reCreateVideoData?.rhythmMode))")
  1594. if(resetSelectIndex){
  1595. // 1 生成默认参数值
  1596. /*
  1597. - 当素材总时长∈[0-6)s 时,提示推荐仅配乐模式 or 快慢速模式
  1598. - 当素材总时长∈[6-80)s 时,卡点抛留倍数为1x
  1599. - 当素材总时长∈[80,120)s 时,卡点抛留倍数为2x
  1600. - 当素材总时长∈[120,160)s 时,卡点抛留倍数为3x
  1601. - 当素材总时长∈[160,200)s 时,卡点抛留倍数为4x
  1602. - 当素材总时长∈[200,240)s 时,卡点抛留倍数为5x
  1603. - 当素材总时长∈[240,∞)s 时,卡点抛留倍数为5x
  1604. */
  1605. // 1.1) 生成跳跃卡点的默认值
  1606. if selectedTotalDuration >= 6 && selectedTotalDuration < 80 {
  1607. lastJumpSpeedSelectIndex = 0
  1608. } else if selectedTotalDuration >= 80 && selectedTotalDuration < 120 {
  1609. lastJumpSpeedSelectIndex = 1
  1610. } else if selectedTotalDuration >= 120 && selectedTotalDuration < 160 {
  1611. lastJumpSpeedSelectIndex = 2
  1612. } else if selectedTotalDuration >= 160 && selectedTotalDuration < 200 {
  1613. lastJumpSpeedSelectIndex = 3
  1614. } else if (selectedTotalDuration >= 200 && selectedTotalDuration < 240) || selectedTotalDuration >= 240 {
  1615. lastJumpSpeedSelectIndex = 4
  1616. }
  1617. /* 默认进入快慢速模式
  1618. - 当素材总时长∈[120,144]s 时,快慢速处理方式:快速为 6x,慢速为 1.2x,效果是快&快
  1619. - 当素材总时长∈[70,120)s 时,快慢速处理方式:快速为5x,慢速为 1x,效果是快&正常
  1620. - 当素材总时长∈[56,70)s 时,快慢速处理方式:快速为3x,慢速为 0.5x,效果是快&慢
  1621. - 当素材总时长∈[17.5,56)s 时,快慢速处理方式:快速为 2.4x,慢速为 0.4x,效果是快&慢
  1622. - 当素材总时长∈[10.5,17.5)s 时,快慢速处理方式:快速为 1.8x,慢速为 0.3x,效果是快&慢
  1623. - 当素材总时长∈(0,10.5)s 时,快慢速处理方式:快速为 1x,慢速为 0.2x,效果是正常&慢
  1624. */
  1625. // 1.2)生成快慢速的默认值
  1626. if selectedTotalDuration >= 120 && selectedTotalDuration <= 144 || selectedTotalDuration > 144 {
  1627. lastSpeedSelectIndex = 5
  1628. } else if selectedTotalDuration >= 70 && selectedTotalDuration < 120 {
  1629. lastSpeedSelectIndex = 4
  1630. } else if selectedTotalDuration >= 56 && selectedTotalDuration < 70 {
  1631. lastSpeedSelectIndex = 3
  1632. } else if selectedTotalDuration >= 17.5 && selectedTotalDuration < 56 {
  1633. lastSpeedSelectIndex = 2
  1634. } else if selectedTotalDuration >= 10.5 && selectedTotalDuration < 17.5 {
  1635. lastSpeedSelectIndex = 1
  1636. } else if selectedTotalDuration > 0 && selectedTotalDuration < 10.5 {
  1637. lastSpeedSelectIndex = 0
  1638. }
  1639. // 如果是再创作进来的安原视频的模式
  1640. if reCreateVideoData != nil {
  1641. BFLog(message: "是再创作进来的 \(reCreateVideoData!.rhythmMode)")
  1642. switch reCreateVideoData!.rhythmMode {
  1643. case 1:
  1644. editModelClick(sender: jumpPointBtn, reportLog: false)
  1645. break
  1646. case 2:
  1647. editModelClick(sender: speedStuckBtn, reportLog: false)
  1648. break
  1649. case 3:
  1650. editModelClick(sender: onlyMusicBtn, reportLog: false)
  1651. break
  1652. default: break
  1653. }
  1654. return
  1655. }
  1656. // 跳跃卡点不可用
  1657. if selectedTotalDuration < 6 && selectedDataCount != selectedImageDataCount {
  1658. jumpPointBtn.setImage(UIImage().BF_Image(named: "jumpPoint_disable"), for: .normal)
  1659. jumpPointBtn.setImage(UIImage().BF_Image(named: "jumpPoint_disable"), for: .selected)
  1660. jumpPointBtnGif.isHidden = true
  1661. }
  1662. /*
  1663. 文档规则 https://w42nne6hzg.feishu.cn/docs/doccnQZm1uCfkU4QtJb5fLxYk4d#
  1664. */
  1665. // 2,根据所选择所有素材时长进入默认模式
  1666. // 全是图片
  1667. if selectedDataCount == selectedImageDataCount {
  1668. BFLog(message: "全是图片 \(selectedDataCount) \(selectedImageDataCount)")
  1669. // 默认进入跳跃卡点模式
  1670. editModelClick(sender: jumpPointBtn, reportLog: false)
  1671. } else {
  1672. // 默认进入快慢速模式
  1673. if selectedTotalDuration > 0 && selectedTotalDuration <= 144 {
  1674. editModelClick(sender: speedStuckBtn, reportLog: false)
  1675. } else {
  1676. // 默认进入卡点模式
  1677. editModelClick(sender: jumpPointBtn, reportLog: false)
  1678. }
  1679. }
  1680. }else{
  1681. editModelClick(sender: lastEditModelBtn ?? jumpPointBtn, reportLog: false)
  1682. }
  1683. }
  1684. }