PQStuckPointEditerController.swift 104 KB

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