MPPlayerController.m 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499
  1. //
  2. // XSTPlayerController.m
  3. // XStarSDK
  4. //
  5. // Created by Beauty-ruanjian on 2019/7/4.
  6. //
  7. #import "MPPlayerController.h"
  8. #import "MPlayerAttributeManager.h"
  9. #import <KTVHTTPCache.h>
  10. #import "MPPreLoaderModel.h"
  11. @interface MPPlayerController()<KTVHCDataLoaderDelegate>
  12. /// 预加载的模型数组
  13. @property (nonatomic, strong) NSMutableArray<MPPreLoaderModel *> *preloadArr;
  14. @property (nonatomic, assign) BOOL isAnimating;
  15. @property (nonatomic, assign) UIInterfaceOrientation orientation;
  16. @end
  17. @implementation MPPlayerController
  18. // MARK: - Init
  19. + (instancetype)playrWithContainerView:(UIView *)containerView
  20. {
  21. return [[self alloc] initWithContainerView: containerView];
  22. }
  23. - (instancetype)initWithContainerView:(UIView *)containerView
  24. {
  25. if (self = [super init])
  26. {
  27. MPlayerAttributeManager *mgr = [[MPlayerAttributeManager alloc] init];
  28. _player = [[ZFPlayerController alloc] initWithPlayerManager:mgr containerView:containerView];
  29. [_player setCustomAudioSession:YES];
  30. [self setup];
  31. }
  32. return self;
  33. }
  34. + (instancetype)playerWithScrollView:(UIScrollView *)scrollView containerViewTag:(NSInteger)containerViewTag
  35. {
  36. return [[self alloc] initWithScrollView:scrollView containerViewTag:containerViewTag];
  37. }
  38. - (instancetype)initWithScrollView:(UIScrollView *)scrollView containerViewTag:(NSInteger)containerViewTag
  39. {
  40. if (self = [super init])
  41. {
  42. MPlayerAttributeManager *mgr = [[MPlayerAttributeManager alloc] init];
  43. _player = [[ZFPlayerController alloc] initWithScrollView:scrollView playerManager:mgr containerViewTag:containerViewTag];
  44. _player.disableGestureTypes = ZFPlayerDisableGestureTypesPan;
  45. [_player setCustomAudioSession:YES];
  46. [self setup];
  47. }
  48. return self;
  49. }
  50. - (instancetype)init
  51. {
  52. if (self = [super init])
  53. {
  54. [self setup];
  55. }
  56. return self;
  57. }
  58. /// 初始化
  59. - (void)setup
  60. {
  61. _preLoadNum = 2;
  62. _nextLoadNum = 2;
  63. _preloadPrecent = 0.1;
  64. _initPreloadNum = 3;
  65. _player.allowOrentitaionRotation = NO;
  66. _player.playerDisapperaPercent = 0.5;
  67. _player.playerApperaPercent = 0.5;
  68. @weakify(self)
  69. _player.orientationWillChange = ^(ZFPlayerController * _Nonnull player, BOOL isFullScreen) {
  70. RQ_APPDELEGATE.allowOrentitaionRotation = isFullScreen;
  71. };
  72. _player.playerDidToEnd = ^(id<ZFPlayerMediaPlayback> _Nonnull asset) {
  73. @strongify(self)
  74. [self.player.currentPlayerManager replay];
  75. };
  76. }
  77. - (BOOL)prefersStatusBarHidden {
  78. return NO;
  79. }
  80. - (BOOL)shouldAutorotate {
  81. return NO;
  82. }
  83. // MARK: - Method
  84. - (void)stop
  85. {
  86. self.player.scrollView.zf_playingIndexPath = nil;
  87. [self.player stop];
  88. }
  89. - (void)stopCurrentPlayingCell
  90. {
  91. [self.player stopCurrentPlayingCell];
  92. }
  93. - (void)playTheIndexPath:(NSIndexPath *)indexPath playable: (id<XSTPlayable>)playable
  94. {
  95. // 播放前,先停止所有的预加载任务
  96. [self cancelAllPreload];
  97. _currentPlayable = playable;
  98. [self.player playTheIndexPath:indexPath assetURL:[NSURL URLWithString:playable.video_url] scrollToTop:NO];
  99. __weak typeof(self) weakSelf = self;
  100. self.playerReadyToPlay = ^(id<ZFPlayerMediaPlayback> _Nonnull asset, NSURL * _Nonnull assetURL) {
  101. [weakSelf preload: playable];
  102. };
  103. }
  104. - (void)playWithPlayable: (id<XSTPlayable>)playable
  105. {
  106. _currentPlayable = playable;
  107. self.player.assetURL = [NSURL URLWithString:playable.video_url];
  108. }
  109. - (void)setDisapperaPercent: (CGFloat)disappearPercent appearPercent: (CGFloat)appearPercent
  110. {
  111. self.player.playerDisapperaPercent = disappearPercent;
  112. self.player.playerApperaPercent = appearPercent;
  113. }
  114. - (void)enterLandscapeFullScreen:(UIInterfaceOrientation)orientation animated:(BOOL)animated
  115. {
  116. CGFloat cellHeight = RQ_SCREEN_HEIGHT - RQ_APPLICATION_TOP_BAR_HEIGHT;
  117. if (self.isAnimating) {
  118. return;
  119. }
  120. if (self.orientation == orientation) {
  121. return;
  122. }
  123. if (self.player.currentPlayerManager.playState == ZFPlayerPlayStatePlaying ||self.player.currentPlayerManager.playState == ZFPlayerPlayStatePaused
  124. ) {
  125. self.isAnimating = YES;
  126. }
  127. self.orientation = orientation;
  128. CGFloat rotation = 0;
  129. if (orientation == UIInterfaceOrientationLandscapeLeft) {
  130. rotation = M_PI_2;
  131. }else if (orientation == UIInterfaceOrientationLandscapeRight) {
  132. rotation = M_PI_2 * 3;
  133. }
  134. UIView *presentView = self.player.currentPlayerManager.view;
  135. CGRect landRect = CGRectMake(0, 0, cellHeight, RQ_SCREEN_WIDTH);
  136. [UIView animateWithDuration:0.35 animations:^{
  137. presentView.layer.affineTransform = CGAffineTransformMakeRotation(rotation);
  138. } completion:^(BOOL finished) {
  139. self.isAnimating = NO;
  140. }];
  141. presentView.layer.bounds = landRect;
  142. }
  143. - (void)exitFullScreen: (BOOL)isAnimated
  144. {
  145. CGFloat cellHeight = RQ_SCREEN_HEIGHT - RQ_APPLICATION_TAB_BAR_HEIGHT;
  146. if (self.isAnimating) {
  147. return;
  148. }
  149. if (self.orientation == UIInterfaceOrientationPortrait) {
  150. return;
  151. }
  152. CGRect frame = CGRectMake(0, 0, RQ_SCREEN_WIDTH, cellHeight);
  153. UIView *presentView = self.player.currentPlayerManager.view;
  154. if (!isAnimated) {
  155. presentView.layer.affineTransform = CGAffineTransformIdentity;
  156. self.orientation = UIInterfaceOrientationPortrait;
  157. }else {
  158. self.isAnimating = YES;
  159. self.orientation = UIInterfaceOrientationPortrait;
  160. [UIView animateWithDuration:0.35 animations:^{
  161. presentView.layer.affineTransform = CGAffineTransformIdentity;
  162. }completion:^(BOOL finish){
  163. self.isAnimating = NO;
  164. }];
  165. }
  166. self.player.currentPlayerManager.view.layer.bounds = frame;
  167. }
  168. /// Add Player到Cell上
  169. - (void)updateScrollViewPlayerToCell
  170. {
  171. if (self.player.currentPlayerManager.view &&
  172. self.player.scrollView.zf_playingIndexPath &&
  173. self.player.containerViewTag) {
  174. UIView *cell = [self.player.scrollView zf_getCellForIndexPath:self.player.scrollView.zf_playingIndexPath];
  175. UIView *containerView = [cell viewWithTag:self.player.containerViewTag];
  176. [self updateNoramlPlayerWithContainerView:containerView];
  177. }
  178. }
  179. /// 更新Playerc的容器
  180. - (void)updateNoramlPlayerWithContainerView:(UIView *)containerView
  181. {
  182. [self.player addPlayerViewToContainerView:containerView];
  183. }
  184. // MARK: - Preload
  185. /// 根据传入的模型,预加载上几个,下几个的视频
  186. - (void)preload: (id<XSTPlayable>)resource
  187. {
  188. if (self.playableArray.count <= 1)
  189. return;
  190. if (_nextLoadNum == 0 && _preLoadNum == 0)
  191. return;
  192. NSInteger start = [self.playableArray indexOfObject:resource];
  193. if (start == NSNotFound)
  194. return;
  195. [self cancelAllPreload];
  196. NSInteger index = 0;
  197. for (NSInteger i = start + 1; i < self.playableArray.count && index < _nextLoadNum; i++)
  198. {
  199. index += 1;
  200. id<XSTPlayable> model = self.playableArray[i];
  201. MPPreLoaderModel *preModel = [self getPreloadModel: model.video_url];
  202. if (preModel) {
  203. @synchronized (self.preloadArr) {
  204. [self.preloadArr addObject: preModel];
  205. }
  206. }
  207. }
  208. index = 0;
  209. for (NSInteger i = start - 1; i >= 0 && index < _preLoadNum; i--)
  210. {
  211. index += 1;
  212. id<XSTPlayable> model = self.playableArray[i];
  213. MPPreLoaderModel *preModel = [self getPreloadModel: model.video_url];
  214. if (preModel) {
  215. @synchronized (self.preloadArr) {
  216. [self.preloadArr addObject:preModel];
  217. }
  218. }
  219. }
  220. [self processLoader];
  221. }
  222. /// 取消所有的预加载
  223. - (void)cancelAllPreload
  224. {
  225. @synchronized (self.preloadArr) {
  226. if (self.preloadArr.count == 0)
  227. {
  228. return;
  229. }
  230. [self.preloadArr enumerateObjectsUsingBlock:^(MPPreLoaderModel * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
  231. [obj.loader close];
  232. }];
  233. [self.preloadArr removeAllObjects];
  234. }
  235. }
  236. - (MPPreLoaderModel *)getPreloadModel: (NSString *)urlStr
  237. {
  238. if (!urlStr)
  239. return nil;
  240. // 判断是否已在队列中
  241. __block Boolean res = NO;
  242. @synchronized (self.preloadArr) {
  243. [self.preloadArr enumerateObjectsUsingBlock:^(MPPreLoaderModel * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
  244. if ([obj.url isEqualToString:urlStr])
  245. {
  246. res = YES;
  247. *stop = YES;
  248. }
  249. }];
  250. }
  251. if (res)
  252. return nil;
  253. NSURL *proxyUrl = [KTVHTTPCache proxyURLWithOriginalURL: [NSURL URLWithString:urlStr]];
  254. KTVHCDataCacheItem *item = [KTVHTTPCache cacheCacheItemWithURL:proxyUrl];
  255. double cachePrecent = 1.0 * item.cacheLength / item.totalLength;
  256. // 判断缓存已经超过10%了
  257. if (cachePrecent >= self.preloadPrecent)
  258. return nil;
  259. KTVHCDataRequest *req = [[KTVHCDataRequest alloc] initWithURL:proxyUrl headers:[NSDictionary dictionary]];
  260. KTVHCDataLoader *loader = [KTVHTTPCache cacheLoaderWithRequest:req];
  261. MPPreLoaderModel *preModel = [[MPPreLoaderModel alloc] initWithURL:urlStr loader:loader];
  262. return preModel;
  263. }
  264. - (void)processLoader
  265. {
  266. @synchronized (self.preloadArr) {
  267. if (self.preloadArr.count == 0)
  268. return;
  269. MPPreLoaderModel *model = self.preloadArr.firstObject;
  270. model.loader.delegate = self;
  271. [model.loader prepare];
  272. }
  273. }
  274. /// 根据loader,移除预加载任务
  275. - (void)removePreloadTask: (KTVHCDataLoader *)loader
  276. {
  277. @synchronized (self.preloadArr) {
  278. MPPreLoaderModel *target = nil;
  279. for (MPPreLoaderModel *model in self.preloadArr) {
  280. if ([model.loader isEqual:loader])
  281. {
  282. target = model;
  283. break;
  284. }
  285. }
  286. if (target)
  287. [self.preloadArr removeObject:target];
  288. }
  289. }
  290. // MARK: - KTVHCDataLoaderDelegate
  291. - (void)ktv_loaderDidFinish:(KTVHCDataLoader *)loader
  292. {
  293. }
  294. - (void)ktv_loader:(KTVHCDataLoader *)loader didFailWithError:(NSError *)error
  295. {
  296. // 若预加载失败的话,就直接移除任务,开始下一个预加载任务
  297. [self removePreloadTask:loader];
  298. [self processLoader];
  299. }
  300. - (void)ktv_loader:(KTVHCDataLoader *)loader didChangeProgress:(double)progress
  301. {
  302. if (progress >= self.preloadPrecent)
  303. {
  304. [loader close];
  305. [self removePreloadTask:loader];
  306. [self processLoader];
  307. }
  308. }
  309. // MARK: - Getter
  310. - (BOOL)isViewControllerDisappear
  311. {
  312. return self.player.isViewControllerDisappear;
  313. }
  314. - (NSIndexPath *)playingIndexPath
  315. {
  316. return self.player.playingIndexPath;
  317. }
  318. - (NSMutableArray<MPPreLoaderModel *> *)preloadArr
  319. {
  320. if (_preloadArr == nil)
  321. {
  322. _preloadArr = [NSMutableArray array];
  323. }
  324. return _preloadArr;
  325. }
  326. - (id<ZFPlayerMediaPlayback>)currentPlayerManager
  327. {
  328. return self.player.currentPlayerManager;
  329. }
  330. - (BOOL)isPlaying
  331. {
  332. return self.player.currentPlayerManager.isPlaying;
  333. }
  334. - (UIView *)containerView
  335. {
  336. return self.player.containerView;
  337. }
  338. - (BOOL)isWWANAutoPlay
  339. {
  340. return self.player.isWWANAutoPlay;
  341. }
  342. - (void (^)(id<ZFPlayerMediaPlayback> _Nonnull, NSTimeInterval, NSTimeInterval))playerPlayTimeChanged
  343. {
  344. return _player.playerPlayTimeChanged;
  345. }
  346. - (CGFloat)playerApperaPercent
  347. {
  348. return _player.playerApperaPercent;
  349. }
  350. - (CGFloat)playerDisapperaPercent
  351. {
  352. return _player.playerDisapperaPercent;
  353. }
  354. // MARK: - Setter
  355. - (void)setPlayableArray:(NSArray<id<XSTPlayable>> *)playableArray
  356. {
  357. _playableArray = playableArray;
  358. [self cancelAllPreload];
  359. // 默认预加载前几条数据
  360. NSRange range = NSMakeRange(0, _initPreloadNum);
  361. if (range.length > playableArray.count) {
  362. range.length = playableArray.count;
  363. }
  364. NSArray *subArr = [playableArray subarrayWithRange: range];
  365. for (id<XSTPlayable> model in subArr)
  366. {
  367. MPPreLoaderModel *preload = [self getPreloadModel:model.video_url];
  368. if (preload) {
  369. @synchronized (self.preloadArr) {
  370. [self.preloadArr addObject: preload];
  371. }
  372. }
  373. }
  374. [self processLoader];
  375. }
  376. - (void)setWWANAutoPlay:(BOOL)WWANAutoPlay
  377. {
  378. self.player.WWANAutoPlay = WWANAutoPlay;
  379. }
  380. - (void)setControlView:(UIView<ZFPlayerMediaControl> *)controlView
  381. {
  382. _controlView = controlView;
  383. self.player.controlView = controlView;
  384. }
  385. - (void)setViewControllerDisappear:(BOOL)viewControllerDisappear
  386. {
  387. self.player.viewControllerDisappear = viewControllerDisappear;
  388. }
  389. - (void)setPlayingIndexPath:(NSIndexPath * _Nullable)playingIndexPath
  390. {
  391. self.playingIndexPath = playingIndexPath;
  392. }
  393. - (void)setPlayerDidToEnd:(void (^)(id<ZFPlayerMediaPlayback> _Nonnull))playerDidToEnd {
  394. _player.playerDidToEnd = ^(id<ZFPlayerMediaPlayback> _Nonnull asset) {
  395. playerDidToEnd(asset);
  396. };
  397. }
  398. - (void)setPlayerPlayFailed:(void (^)(id<ZFPlayerMediaPlayback> _Nonnull, id _Nonnull))playerPlayFailed {
  399. _player.playerPlayFailed = playerPlayFailed;
  400. }
  401. - (void)setPlayerReadyToPlay:(void (^)(id<ZFPlayerMediaPlayback> _Nonnull, NSURL * _Nonnull))playerReadyToPlay {
  402. _player.playerReadyToPlay = ^(id<ZFPlayerMediaPlayback> _Nonnull asset, NSURL * _Nonnull assetURL) {
  403. playerReadyToPlay(asset, assetURL);
  404. };
  405. }
  406. - (void)setPlayerPlayTimeChanged:(void (^)(id<ZFPlayerMediaPlayback> _Nonnull, NSTimeInterval, NSTimeInterval))playerPlayTimeChanged {
  407. _player.playerPlayTimeChanged = playerPlayTimeChanged;
  408. }
  409. - (void)setPlayerBufferTimeChanged:(void (^)(id<ZFPlayerMediaPlayback> _Nonnull, NSTimeInterval))playerBufferTimeChanged {
  410. _player.playerBufferTimeChanged = playerBufferTimeChanged;
  411. }
  412. - (void)setPresentationSizeChanged:(void (^)(id<ZFPlayerMediaPlayback> _Nonnull, CGSize))presentationSizeChanged {
  413. _player.presentationSizeChanged = presentationSizeChanged;
  414. }
  415. - (void)setPlayerPlayStateChanged:(void (^)(id<ZFPlayerMediaPlayback> _Nonnull, ZFPlayerPlaybackState))playerPlayStateChanged
  416. {
  417. _player.playerPlayStateChanged = playerPlayStateChanged;
  418. }
  419. - (void)setPlayerLoadStateChanged:(void (^)(id<ZFPlayerMediaPlayback> _Nonnull, ZFPlayerLoadState))playerLoadStateChanged
  420. {
  421. _player.playerLoadStateChanged = playerLoadStateChanged;
  422. }
  423. - (void)setZf_playerDisappearingInScrollView:(void (^)(NSIndexPath * _Nonnull, CGFloat))zf_playerDisappearingInScrollView
  424. {
  425. _player.zf_playerDisappearingInScrollView = zf_playerDisappearingInScrollView;
  426. }
  427. - (void)setZf_playerDidDisappearInScrollView:(void (^)(NSIndexPath * _Nonnull))zf_playerDidDisappearInScrollView
  428. {
  429. _player.zf_playerDidDisappearInScrollView = zf_playerDidDisappearInScrollView;
  430. }
  431. - (void)setPlayerApperaPercent:(CGFloat)playerApperaPercent
  432. {
  433. _player.playerApperaPercent = playerApperaPercent;
  434. }
  435. - (void)setPlayerDisapperaPercent:(CGFloat)playerDisapperaPercent
  436. {
  437. _player.playerDisapperaPercent = playerDisapperaPercent;
  438. }
  439. @end