MPPlayerController.m 15 KB

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