MPPlayerController.m 15 KB

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