2
0

VideoPlayerKit.m 35 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891
  1. /* Copyright (C) 2012 IGN Entertainment, Inc. */
  2. #import "VideoPlayerKit.h"
  3. #import "FullScreenViewController.h"
  4. #import "WFCUImage.h"
  5. // #import "ShareThis.h"
  6. NSString * const kVideoPlayerVideoChangedNotification = @"VideoPlayerVideoChangedNotification";
  7. NSString * const kVideoPlayerWillHideControlsNotification = @"VideoPlayerWillHideControlsNotitication";
  8. NSString * const kVideoPlayerWillShowControlsNotification = @"VideoPlayerWillShowControlsNotification";
  9. NSString * const kTrackEventVideoStart = @"Video Start";
  10. NSString * const kTrackEventVideoLiveStart = @"Video Live Start";
  11. NSString * const kTrackEventVideoComplete = @"Video Complete";
  12. // Match the controls animation duration with status bar duration
  13. static const NSTimeInterval controlsAnimationDuration = 0.4;
  14. @interface VideoPlayerKit () <UIGestureRecognizerDelegate>
  15. @property (readwrite, strong) NSDictionary *currentVideoInfo;
  16. @property (readwrite, strong) VideoPlayerView *videoPlayerView;
  17. @property (readwrite) BOOL restoreVideoPlayStateAfterScrubbing;
  18. @property (readwrite, strong) id scrubberTimeObserver;
  19. @property (readwrite, strong) id playClockTimeObserver;
  20. @property (readwrite) BOOL seekToZeroBeforePlay;
  21. @property (readwrite) BOOL rotationIsLocked;
  22. @property (readwrite) BOOL playerIsBuffering;
  23. @property (nonatomic, weak) UIView *containingView;
  24. @property (nonatomic, weak) UIView *topView;
  25. @property (readwrite) BOOL fullScreenModeToggled;
  26. @property (nonatomic) BOOL isAlwaysFullscreen;
  27. @property (nonatomic, readwrite) BOOL isPlaying;
  28. @property (nonatomic, strong) FullScreenViewController *fullscreenViewController;
  29. @property (nonatomic) CGRect previousBounds;
  30. @property (nonatomic) BOOL hideTopViewWithControls;
  31. @property (nonatomic) UIStatusBarStyle previousStatusBarStyle;
  32. @end
  33. @implementation VideoPlayerKit {
  34. BOOL playWhenReady;
  35. BOOL scrubBuffering;
  36. BOOL showShareOptions;
  37. }
  38. - (void)setTopView:(UIView *)topView
  39. {
  40. _topView = topView;
  41. if (self.hideTopViewWithControls) {
  42. __weak UIView *weakTopView = _topView;
  43. [[NSNotificationCenter defaultCenter] removeObserver:self];
  44. [[NSNotificationCenter defaultCenter] addObserverForName:kVideoPlayerWillHideControlsNotification
  45. object:self
  46. queue:[NSOperationQueue mainQueue]
  47. usingBlock:^(NSNotification *note) {
  48. [UIView animateWithDuration:controlsAnimationDuration
  49. animations:^{
  50. [weakTopView setAlpha:0.0f];
  51. }];
  52. }];
  53. [[NSNotificationCenter defaultCenter] addObserverForName:kVideoPlayerWillShowControlsNotification
  54. object:self
  55. queue:[NSOperationQueue mainQueue]
  56. usingBlock:^(NSNotification *note) {
  57. [UIView animateWithDuration:controlsAnimationDuration
  58. animations:^{
  59. [weakTopView setAlpha:1.0f];
  60. }];
  61. }];
  62. }
  63. }
  64. - (id)initWithContainingView:(UIView *)containingView optionalTopView:(UIView *)topView hideTopViewWithControls:(BOOL)hideTopViewWithControls
  65. {
  66. if ((self = [super init])) {
  67. self.containingView = containingView;
  68. self.hideTopViewWithControls = hideTopViewWithControls;
  69. self.topView = topView;
  70. self.previousStatusBarStyle = [[UIApplication sharedApplication] statusBarStyle];
  71. self.view.backgroundColor = [UIColor blackColor];
  72. }
  73. return self;
  74. }
  75. + (VideoPlayerKit *)videoPlayerWithContainingViewController:(UIViewController *)containingViewController
  76. optionalTopView:(UIView *)topView
  77. hideTopViewWithControls:(BOOL)hideTopViewWithControls
  78. {
  79. VideoPlayerKit *videoPlayer = [[VideoPlayerKit alloc] initWithContainingView:containingViewController.view
  80. optionalTopView:topView
  81. hideTopViewWithControls:hideTopViewWithControls];
  82. return videoPlayer;
  83. }
  84. + (VideoPlayerKit *)videoPlayerWithContainingView:(UIView *)containingView
  85. optionalTopView:(UIView *)topView
  86. hideTopViewWithControls:(BOOL)hideTopViewWithControls
  87. {
  88. VideoPlayerKit *videoPlayer = [[VideoPlayerKit alloc] initWithContainingView:containingView
  89. optionalTopView:topView
  90. hideTopViewWithControls:hideTopViewWithControls];
  91. return videoPlayer;
  92. }
  93. - (void)setControlsEdgeInsets:(UIEdgeInsets)controlsEdgeInsets
  94. {
  95. if (!self.videoPlayerView) {
  96. self.videoPlayerView = [[VideoPlayerView alloc] initWithFrame:self.containingView.bounds];
  97. }
  98. _controlsEdgeInsets = controlsEdgeInsets;
  99. self.videoPlayerView.controlsEdgeInsets = _controlsEdgeInsets;
  100. [self.view setNeedsLayout];
  101. }
  102. - (void)dealloc
  103. {
  104. [[NSNotificationCenter defaultCenter] removeObserver:self];
  105. [self removeObserversFromVideoPlayerItem];
  106. [self removePlayerTimeObservers];
  107. }
  108. - (void)removeObserversFromVideoPlayerItem
  109. {
  110. [self.videoPlayer.currentItem removeObserver:self forKeyPath:@"status"];
  111. [self.videoPlayer.currentItem removeObserver:self forKeyPath:@"playbackBufferEmpty"];
  112. [self.videoPlayer.currentItem removeObserver:self forKeyPath:@"playbackLikelyToKeepUp"];
  113. [self.videoPlayer.currentItem removeObserver:self forKeyPath:@"loadedTimeRanges"];
  114. [_videoPlayer removeObserver:self forKeyPath:@"externalPlaybackActive"];
  115. [_videoPlayer removeObserver:self forKeyPath:@"airPlayVideoActive"];
  116. }
  117. - (void)loadView
  118. {
  119. if (!self.videoPlayerView) {
  120. self.videoPlayerView = [[VideoPlayerView alloc] initWithFrame:self.containingView.bounds];
  121. }
  122. if (self.topView) {
  123. self.topView.frame = CGRectMake(0, 0, self.videoPlayerView.frame.size.width, self.topView.frame.size.height);
  124. [self.videoPlayerView addSubview:self.topView];
  125. }
  126. self.view = self.videoPlayerView;
  127. }
  128. - (void)viewDidLoad
  129. {
  130. [super viewDidLoad];
  131. _currentVideoInfo = [[NSDictionary alloc] init];
  132. [_videoPlayerView.playPauseButton addTarget:self action:@selector(playPauseHandler) forControlEvents:UIControlEventTouchUpInside];
  133. [_videoPlayerView.fullScreenButton addTarget:self action:@selector(fullScreenButtonHandler) forControlEvents:UIControlEventTouchUpInside];
  134. [self.videoPlayerView.shareButton addTarget:self action:@selector(shareButtonHandler) forControlEvents:UIControlEventTouchUpInside];
  135. [_videoPlayerView.videoScrubber addTarget:self action:@selector(scrubbingDidBegin) forControlEvents:UIControlEventTouchDown];
  136. [_videoPlayerView.videoScrubber addTarget:self action:@selector(scrubberIsScrolling) forControlEvents:UIControlEventValueChanged];
  137. [_videoPlayerView.videoScrubber addTarget:self action:@selector(scrubbingDidEnd) forControlEvents:(UIControlEventTouchUpInside | UIControlEventTouchCancel)];
  138. UITapGestureRecognizer *playerTouchedGesture = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(videoTapHandler)];
  139. playerTouchedGesture.delegate = self;
  140. [_videoPlayerView addGestureRecognizer:playerTouchedGesture];
  141. UIPinchGestureRecognizer *pinchRecognizer = [[UIPinchGestureRecognizer alloc] initWithTarget:self action:@selector(pinchGesture:)];
  142. [pinchRecognizer setDelegate:self];
  143. [self.view addGestureRecognizer:pinchRecognizer];
  144. }
  145. - (BOOL)gestureRecognizer:(UIGestureRecognizer *)gestureRecognizer shouldReceiveTouch:(UITouch *)touch
  146. {
  147. if ([touch.view isDescendantOfView:self.videoPlayerView.playerControlBar] || [touch.view isDescendantOfView:self.videoPlayerView.shareButton]) {
  148. return NO;
  149. }
  150. return YES;
  151. }
  152. - (void)viewWillAppear:(BOOL)animated
  153. {
  154. [super viewWillAppear:animated];
  155. if (self.fullScreenModeToggled) {
  156. BOOL isHidingPlayerControls = self.videoPlayerView.playerControlBar.alpha == 0;
  157. [[UIApplication sharedApplication] setStatusBarHidden:isHidingPlayerControls withAnimation:UIStatusBarAnimationNone];
  158. } else {
  159. [[UIApplication sharedApplication] setStatusBarHidden:NO withAnimation:UIStatusBarAnimationNone];
  160. }
  161. }
  162. - (void)presentShareOptions
  163. {
  164. showShareOptions = NO;
  165. // [ShareThis showShareOptionsToShareUrl:[_currentVideoInfo objectForKey:@"shareURL"] title:[_currentVideoInfo objectForKey:@"title"] image:nil onViewController:[[[UIApplication sharedApplication] keyWindow] rootViewController] forTypeOfContent:STContentTypeVideo];
  166. }
  167. - (void)shareButtonHandler
  168. {
  169. // Minimize the video if fullscreen so that ShareThis can work
  170. if (self.fullScreenModeToggled) {
  171. showShareOptions = YES;
  172. [self minimizeVideo];
  173. } else {
  174. [self presentShareOptions];
  175. }
  176. }
  177. - (void)playVideoWithTitle:(NSString *)title URL:(NSURL *)url videoID:(NSString *)videoID shareURL:(NSURL *)shareURL isStreaming:(BOOL)streaming playInFullScreen:(BOOL)playInFullScreen
  178. {
  179. [self.videoPlayer pause];
  180. [[_videoPlayerView activityIndicator] startAnimating];
  181. // Reset the buffer bar back to 0
  182. [self.videoPlayerView.progressView setProgress:0 animated:NO];
  183. [self showControls];
  184. NSString *vidID = videoID ?: @"";
  185. _currentVideoInfo = @{ @"title": title ?: @"", @"videoID": vidID, @"isStreaming": @(streaming), @"shareURL": shareURL ? @"" : url};
  186. [[NSNotificationCenter defaultCenter] postNotificationName:kVideoPlayerVideoChangedNotification
  187. object:self
  188. userInfo:_currentVideoInfo];
  189. if ([self.delegate respondsToSelector:@selector(trackEvent:videoID:title:)]) {
  190. if (streaming) {
  191. [self.delegate trackEvent:kTrackEventVideoLiveStart videoID:vidID title:title];
  192. } else {
  193. [self.delegate trackEvent:kTrackEventVideoStart videoID:vidID title:title];
  194. }
  195. }
  196. [_videoPlayerView.currentPositionLabel setText:@""];
  197. [_videoPlayerView.timeLeftLabel setText:@""];
  198. _videoPlayerView.videoScrubber.value = 0;
  199. [_videoPlayerView setTitle:title];
  200. [[MPNowPlayingInfoCenter defaultCenter] setNowPlayingInfo:@{
  201. MPMediaItemPropertyTitle: title,
  202. }];
  203. [self setURL:url];
  204. [self syncPlayPauseButtons];
  205. if (playInFullScreen) {
  206. self.isAlwaysFullscreen = YES;
  207. [self launchFullScreen];
  208. } else {
  209. [self.containingView addSubview:self.videoPlayerView];
  210. }
  211. }
  212. - (void)showCannotFetchStreamError
  213. {
  214. UIAlertView *alertView = [[UIAlertView alloc]
  215. initWithTitle:@"Sad Panda says..."
  216. message:@"I can't seem to fetch that stream. Please try again later."
  217. delegate:nil
  218. cancelButtonTitle:@"Bummer!"
  219. otherButtonTitles:nil];
  220. [alertView show];
  221. }
  222. - (void)playPauseHandler
  223. {
  224. if (_seekToZeroBeforePlay) {
  225. _seekToZeroBeforePlay = NO;
  226. [_videoPlayer seekToTime:kCMTimeZero];
  227. }
  228. if ([self isPlaying]) {
  229. [_videoPlayer pause];
  230. } else {
  231. [self playVideo];
  232. [[_videoPlayerView activityIndicator] stopAnimating];
  233. }
  234. [self syncPlayPauseButtons];
  235. [self showControls];
  236. }
  237. - (void)launchFullScreen
  238. {
  239. if (!self.fullScreenModeToggled) {
  240. self.fullScreenModeToggled = YES;
  241. if (!self.isAlwaysFullscreen) {
  242. [self hideControlsAnimated:YES];
  243. }
  244. [[UIApplication sharedApplication] setStatusBarStyle:UIStatusBarStyleLightContent];
  245. [self syncFullScreenButton:[[UIApplication sharedApplication] statusBarOrientation]];
  246. if (!self.fullscreenViewController) {
  247. self.fullscreenViewController = [[FullScreenViewController alloc] init];
  248. self.fullscreenViewController.allowPortraitFullscreen = self.allowPortraitFullscreen;
  249. }
  250. [self.videoPlayerView setFullscreen:YES];
  251. [self.fullscreenViewController.view addSubview:self.videoPlayerView];
  252. if (self.topView) {
  253. [self.topView removeFromSuperview];
  254. [self.fullscreenViewController.view addSubview:self.topView];
  255. }
  256. if (self.isAlwaysFullscreen) {
  257. self.videoPlayerView.alpha = 0.0;
  258. if (self.topView) {
  259. self.topView.alpha = 0.0;
  260. }
  261. } else {
  262. self.previousBounds = self.videoPlayerView.frame;
  263. [UIView animateWithDuration:0.45f
  264. delay:0.0f
  265. options:UIViewAnimationCurveLinear
  266. animations:^{
  267. [self.videoPlayerView setCenter:CGPointMake( self.videoPlayerView.superview.bounds.size.width / 2, ( self.videoPlayerView.superview.bounds.size.height / 2))];
  268. self.videoPlayerView.bounds = self.videoPlayerView.superview.bounds;
  269. }
  270. completion:nil];
  271. }
  272. self.fullscreenViewController.modalPresentationStyle = UIModalPresentationFullScreen;
  273. [[UIApplication sharedApplication].keyWindow.rootViewController presentViewController:self.fullscreenViewController animated:YES completion:^{
  274. if (self.isAlwaysFullscreen) {
  275. self.videoPlayerView.frame = CGRectMake(self.videoPlayerView.superview.bounds.size.width / 2, self.videoPlayerView.superview.bounds.size.height / 2, 0, 0);
  276. self.previousBounds = CGRectMake(self.videoPlayerView.superview.bounds.size.width / 2, self.videoPlayerView.superview.bounds.size.height / 2, 0, 0);
  277. [self.videoPlayerView setCenter:CGPointMake( self.videoPlayerView.superview.bounds.size.width / 2, self.videoPlayerView.superview.bounds.size.height / 2)];
  278. [UIView animateWithDuration:0.25f
  279. delay:0.0f
  280. options:UIViewAnimationCurveLinear
  281. animations:^{
  282. self.videoPlayerView.alpha = 1.0;
  283. self.topView.alpha = 1.0;
  284. }
  285. completion:nil];
  286. self.videoPlayerView.frame = self.videoPlayerView.superview.bounds;
  287. }
  288. if (self.topView) {
  289. self.topView.frame = CGRectMake(0, 0, self.videoPlayerView.frame.size.width, self.topView.frame.size.height);
  290. }
  291. if ([self.delegate respondsToSelector:@selector(setFullScreenToggled:)]) {
  292. [self.delegate setFullScreenToggled:self.fullScreenModeToggled];
  293. }
  294. }];
  295. }
  296. }
  297. - (void)minimizeVideo
  298. {
  299. if (self.fullScreenModeToggled) {
  300. self.fullScreenModeToggled = NO;
  301. [self.videoPlayerView setFullscreen:NO];
  302. [self hideControlsAnimated:NO];
  303. [self syncFullScreenButton:self.interfaceOrientation];
  304. if (self.topView) {
  305. [self.topView removeFromSuperview];
  306. [self.videoPlayerView addSubview:self.topView];
  307. }
  308. if (self.isAlwaysFullscreen) {
  309. [self.videoPlayer pause];
  310. [UIView animateWithDuration:0.45f
  311. delay:0.0f
  312. options:UIViewAnimationCurveLinear
  313. animations:^{
  314. self.videoPlayerView.frame = self.previousBounds;
  315. }
  316. completion:^(BOOL success){
  317. if (showShareOptions) {
  318. [self presentShareOptions];
  319. }
  320. [self.videoPlayerView removeFromSuperview];
  321. [[NSNotificationCenter defaultCenter] postNotificationName:@"kVideoPlayerKitPlayCanceled" object:nil];
  322. }];
  323. } else {
  324. [UIView animateWithDuration:0.45f
  325. delay:0.0f
  326. options:UIViewAnimationCurveLinear
  327. animations:^{
  328. self.videoPlayerView.frame = self.previousBounds;
  329. }
  330. completion:^(BOOL success){
  331. if (showShareOptions) {
  332. [self presentShareOptions];
  333. }
  334. }];
  335. [self.videoPlayerView removeFromSuperview];
  336. [self.containingView addSubview:self.videoPlayerView];
  337. }
  338. [[UIApplication sharedApplication] setStatusBarStyle:self.previousStatusBarStyle];
  339. [[UIApplication sharedApplication].keyWindow.rootViewController dismissViewControllerAnimated:self.isAlwaysFullscreen completion:^{
  340. if (!self.isAlwaysFullscreen) {
  341. [self showControls];
  342. }
  343. [[UIApplication sharedApplication] setStatusBarHidden:NO
  344. withAnimation:UIStatusBarAnimationFade];
  345. if ([self.delegate respondsToSelector:@selector(setFullScreenToggled:)]) {
  346. [self.delegate setFullScreenToggled:self.fullScreenModeToggled];
  347. }
  348. }];
  349. }
  350. }
  351. - (void)fullScreenButtonHandler
  352. {
  353. [self showControls];
  354. if (self.fullScreenModeToggled) {
  355. [self minimizeVideo];
  356. } else {
  357. [self launchFullScreen];
  358. }
  359. }
  360. - (void)pinchGesture:(id)sender
  361. {
  362. if([(UIPinchGestureRecognizer *)sender state] == UIGestureRecognizerStateEnded) {
  363. [self fullScreenButtonHandler];
  364. }
  365. }
  366. - (void)forceOrientationChange
  367. {
  368. _rotationIsLocked = YES;
  369. [self performSelector:@selector(unlockRotationLock) withObject:nil afterDelay:0.5];
  370. if ([[[UIDevice currentDevice] systemVersion] floatValue] < 6.0) {
  371. UIWindow *window = [[UIApplication sharedApplication] keyWindow];
  372. UIView *view = [window.subviews objectAtIndex:0];
  373. [view removeFromSuperview];
  374. [window addSubview:view];
  375. [_videoPlayerView.superview layoutSubviews];
  376. } else {
  377. // Have the VideoPlayerVC's parent VC implement rotation trigger
  378. if ([self.delegate respondsToSelector:@selector(setFullScreenToggled:)]) {
  379. [self.delegate setFullScreenToggled:self.fullScreenModeToggled];
  380. }
  381. }
  382. }
  383. - (void)unlockRotationLock
  384. {
  385. _rotationIsLocked = NO;
  386. }
  387. - (void)videoTapHandler
  388. {
  389. if (_videoPlayerView.playerControlBar.alpha) {
  390. [self hideControlsAnimated:YES];
  391. } else {
  392. [self showControls];
  393. }
  394. }
  395. - (BOOL)gestureRecognizer:(UIGestureRecognizer *)gestureRecognizer shouldRecognizeSimultaneouslyWithGestureRecognizer:(UIGestureRecognizer *)otherGestureRecognizer
  396. {
  397. return YES;
  398. }
  399. - (void)setURL:(NSURL *)url
  400. {
  401. AVPlayerItem *playerItem = [AVPlayerItem playerItemWithURL:url];
  402. [playerItem addObserver:self
  403. forKeyPath:@"status"
  404. options:NSKeyValueObservingOptionNew
  405. context:nil];
  406. [playerItem addObserver:self
  407. forKeyPath:@"playbackBufferEmpty"
  408. options:NSKeyValueObservingOptionNew
  409. context:nil];
  410. [playerItem addObserver:self
  411. forKeyPath:@"playbackLikelyToKeepUp"
  412. options:NSKeyValueObservingOptionNew
  413. context:nil];
  414. [playerItem addObserver:self
  415. forKeyPath:@"loadedTimeRanges"
  416. options:NSKeyValueObservingOptionNew
  417. context:nil];
  418. if (!self.videoPlayer) {
  419. _videoPlayer = [AVPlayer playerWithPlayerItem:playerItem];
  420. [_videoPlayer setAllowsAirPlayVideo:YES];
  421. [_videoPlayer setUsesAirPlayVideoWhileAirPlayScreenIsActive:YES];
  422. if ([_videoPlayer respondsToSelector:@selector(setAllowsExternalPlayback:)]) { // iOS 6 API
  423. [_videoPlayer setAllowsExternalPlayback:YES];
  424. }
  425. [_videoPlayerView setPlayer:_videoPlayer];
  426. } else {
  427. [self removeObserversFromVideoPlayerItem];
  428. [self.videoPlayer replaceCurrentItemWithPlayerItem:playerItem];
  429. }
  430. // iOS 5
  431. [_videoPlayer addObserver:self forKeyPath:@"airPlayVideoActive" options:NSKeyValueObservingOptionNew context:nil];
  432. // iOS 6
  433. [_videoPlayer addObserver:self
  434. forKeyPath:@"externalPlaybackActive"
  435. options:NSKeyValueObservingOptionNew
  436. context:nil];
  437. [[NSNotificationCenter defaultCenter] addObserver:self
  438. selector:@selector(playerItemDidReachEnd:)
  439. name:AVPlayerItemDidPlayToEndTimeNotification
  440. object:self.videoPlayer.currentItem];
  441. [[NSNotificationCenter defaultCenter] addObserver:self
  442. selector:@selector(playerItemDidReachEnd:)
  443. name:AVPlayerItemFailedToPlayToEndTimeNotification
  444. object:self.videoPlayer.currentItem];
  445. }
  446. // Wait for the video player status to change to ready before initializing video player controls
  447. - (void)observeValueForKeyPath:(NSString *)keyPath
  448. ofObject:(id)object
  449. change:(NSDictionary *)change
  450. context:(void *)context
  451. {
  452. if (object == _videoPlayer
  453. && ([keyPath isEqualToString:@"externalPlaybackActive"] || [keyPath isEqualToString:@"airPlayVideoActive"])) {
  454. BOOL externalPlaybackActive = [[change objectForKey:NSKeyValueChangeNewKey] boolValue];
  455. [[_videoPlayerView airplayIsActiveView] setHidden:!externalPlaybackActive];
  456. return;
  457. }
  458. if (object != [_videoPlayer currentItem]) {
  459. return;
  460. }
  461. if ([keyPath isEqualToString:@"status"]) {
  462. AVPlayerStatus status = [[change objectForKey:NSKeyValueChangeNewKey] integerValue];
  463. switch (status) {
  464. case AVPlayerStatusReadyToPlay:
  465. playWhenReady = YES;
  466. if (![self isPlaying]) {
  467. [self playVideo];
  468. }
  469. break;
  470. case AVPlayerStatusFailed:
  471. // TODO:
  472. [self removeObserversFromVideoPlayerItem];
  473. [self removePlayerTimeObservers];
  474. self.videoPlayer = nil;
  475. [self minimizeVideo];
  476. break;
  477. }
  478. } else if ([keyPath isEqualToString:@"playbackBufferEmpty"] && _videoPlayer.currentItem.playbackBufferEmpty) {
  479. self.playerIsBuffering = YES;
  480. [[_videoPlayerView activityIndicator] startAnimating];
  481. [self syncPlayPauseButtons];
  482. } else if ([keyPath isEqualToString:@"playbackLikelyToKeepUp"] && _videoPlayer.currentItem.playbackLikelyToKeepUp) {
  483. if (![self isPlaying] && playWhenReady)
  484. {
  485. if (self.playerIsBuffering || scrubBuffering) {
  486. if (self.restoreVideoPlayStateAfterScrubbing) {
  487. self.restoreVideoPlayStateAfterScrubbing = NO;
  488. [self playVideo];
  489. }
  490. } else {
  491. [self playVideo];
  492. }
  493. }
  494. [[_videoPlayerView activityIndicator] stopAnimating];
  495. } else if ([keyPath isEqualToString:@"loadedTimeRanges"]) {
  496. float durationTime = CMTimeGetSeconds([[self.videoPlayer currentItem] duration]);
  497. float bufferTime = [self availableDuration];
  498. [self.videoPlayerView.progressView setProgress:bufferTime/durationTime animated:YES];
  499. }
  500. return;
  501. }
  502. - (float)availableDuration
  503. {
  504. NSArray *loadedTimeRanges = [[self.videoPlayer currentItem] loadedTimeRanges];
  505. // Check to see if the timerange is not an empty array, fix for when video goes on airplay
  506. // and video doesn't include any time ranges
  507. if ([loadedTimeRanges count] > 0) {
  508. CMTimeRange timeRange = [[loadedTimeRanges objectAtIndex:0] CMTimeRangeValue];
  509. float startSeconds = CMTimeGetSeconds(timeRange.start);
  510. float durationSeconds = CMTimeGetSeconds(timeRange.duration);
  511. return (startSeconds + durationSeconds);
  512. } else {
  513. return 0.0f;
  514. }
  515. }
  516. - (void)playVideo
  517. {
  518. if (self.view.superview) {
  519. self.playerIsBuffering = NO;
  520. scrubBuffering = NO;
  521. playWhenReady = NO;
  522. // Configuration is done, ready to start.
  523. [self.videoPlayer play];
  524. [self updatePlaybackProgress];
  525. }
  526. }
  527. - (void)showControls
  528. {
  529. [[NSNotificationCenter defaultCenter] postNotificationName:kVideoPlayerWillShowControlsNotification
  530. object:self
  531. userInfo:nil];
  532. [UIView animateWithDuration:controlsAnimationDuration animations:^{
  533. self.videoPlayerView.playerControlBar.alpha = 1.0;
  534. self.videoPlayerView.titleLabel.alpha = 1.0;
  535. self.videoPlayerView.shareButton.alpha = 1.0;
  536. } completion:nil];
  537. if (self.fullScreenModeToggled) {
  538. [[UIApplication sharedApplication] setStatusBarHidden:NO
  539. withAnimation:UIStatusBarAnimationFade];
  540. }
  541. [NSObject cancelPreviousPerformRequestsWithTarget:self
  542. selector:@selector(hideControlsAnimated:)
  543. object:[NSString stringWithFormat:@"YES"]];
  544. if ([self isPlaying]) {
  545. [self performSelector:@selector(hideControlsAnimated:)
  546. withObject:[NSString stringWithFormat:@"YES"]
  547. afterDelay:4.0];
  548. }
  549. }
  550. - (void)hideControlsAnimated:(BOOL)animated
  551. {
  552. [[NSNotificationCenter defaultCenter] postNotificationName:kVideoPlayerWillHideControlsNotification
  553. object:self
  554. userInfo:nil];
  555. if (animated) {
  556. [UIView animateWithDuration:controlsAnimationDuration animations:^{
  557. self.videoPlayerView.playerControlBar.alpha = 0;
  558. self.videoPlayerView.titleLabel.alpha = 0;
  559. _videoPlayerView.shareButton.alpha = 0;
  560. } completion:nil];
  561. if (self.fullScreenModeToggled) {
  562. [[UIApplication sharedApplication] setStatusBarHidden:YES
  563. withAnimation:UIStatusBarAnimationFade];
  564. }
  565. } else {
  566. self.videoPlayerView.playerControlBar.alpha = 0;
  567. self.videoPlayerView.titleLabel.alpha = 0;
  568. _videoPlayerView.shareButton.alpha = 0;
  569. if (self.fullScreenModeToggled) {
  570. [[UIApplication sharedApplication] setStatusBarHidden:YES
  571. withAnimation:UIStatusBarAnimationNone];
  572. }
  573. }
  574. }
  575. - (void)updatePlaybackProgress
  576. {
  577. [self syncPlayPauseButtons];
  578. [self showControls];
  579. double interval = .1f;
  580. CMTime playerDuration = [self playerItemDuration];
  581. if (CMTIME_IS_INVALID(playerDuration)) {
  582. return;
  583. }
  584. double duration = CMTimeGetSeconds(playerDuration);
  585. if (CMTIME_IS_INDEFINITE(playerDuration) || duration <= 0) {
  586. [_videoPlayerView.videoScrubber setHidden:YES];
  587. [_videoPlayerView.progressView setHidden:YES];
  588. [self syncPlayClock];
  589. return;
  590. }
  591. [_videoPlayerView.videoScrubber setHidden:NO];
  592. [_videoPlayerView.progressView setHidden:NO];
  593. CGFloat width = CGRectGetWidth([_videoPlayerView.videoScrubber bounds]);
  594. interval = 0.5f * duration / width;
  595. __weak VideoPlayerKit *vpvc = self;
  596. _scrubberTimeObserver = [_videoPlayer addPeriodicTimeObserverForInterval:CMTimeMakeWithSeconds(interval, NSEC_PER_SEC)
  597. queue:NULL
  598. usingBlock:^(CMTime time) {
  599. [vpvc syncScrubber];
  600. }];
  601. // Update the play clock every second
  602. _playClockTimeObserver = [_videoPlayer addPeriodicTimeObserverForInterval:CMTimeMakeWithSeconds(1, NSEC_PER_SEC)
  603. queue:NULL
  604. usingBlock:^(CMTime time) {
  605. [vpvc syncPlayClock];
  606. }];
  607. }
  608. -(void)removePlayerTimeObservers
  609. {
  610. if (_scrubberTimeObserver) {
  611. [_videoPlayer removeTimeObserver:_scrubberTimeObserver];
  612. _scrubberTimeObserver = nil;
  613. }
  614. if (_playClockTimeObserver) {
  615. [_videoPlayer removeTimeObserver:_playClockTimeObserver];
  616. _playClockTimeObserver = nil;
  617. }
  618. }
  619. - (void)playerItemDidReachEnd:(NSNotification *)notification
  620. {
  621. [self syncPlayPauseButtons];
  622. _seekToZeroBeforePlay = YES;
  623. if ([self.delegate respondsToSelector:@selector(trackEvent:videoID:title:)]) {
  624. [self.delegate trackEvent:kTrackEventVideoComplete videoID:[_currentVideoInfo objectForKey:@"videoID"] title:[_currentVideoInfo objectForKey:@"title"]];
  625. }
  626. [self minimizeVideo];
  627. }
  628. - (void)syncScrubber
  629. {
  630. CMTime playerDuration = [self playerItemDuration];
  631. if (CMTIME_IS_INVALID(playerDuration)) {
  632. _videoPlayerView.videoScrubber.minimumValue = 0.0;
  633. return;
  634. }
  635. double duration = CMTimeGetSeconds(playerDuration);
  636. if (isfinite(duration)) {
  637. float minValue = [_videoPlayerView.videoScrubber minimumValue];
  638. float maxValue = [_videoPlayerView.videoScrubber maximumValue];
  639. double time = CMTimeGetSeconds([_videoPlayer currentTime]);
  640. [_videoPlayerView.videoScrubber setValue:(maxValue - minValue) * time / duration + minValue];
  641. }
  642. }
  643. - (void)syncPlayClock
  644. {
  645. CMTime playerDuration = [self playerItemDuration];
  646. if (CMTIME_IS_INVALID(playerDuration)) {
  647. return;
  648. }
  649. if (CMTIME_IS_INDEFINITE(playerDuration)) {
  650. [_videoPlayerView.currentPositionLabel setText:@"LIVE"];
  651. [_videoPlayerView.timeLeftLabel setText:@""];
  652. return;
  653. }
  654. double duration = CMTimeGetSeconds(playerDuration);
  655. if (isfinite(duration)) {
  656. double currentTime = floor(CMTimeGetSeconds([_videoPlayer currentTime]));
  657. double timeLeft = floor(duration - currentTime);
  658. if (currentTime <= 0) {
  659. currentTime = 0;
  660. timeLeft = floor(duration);
  661. }
  662. [_videoPlayerView.currentPositionLabel setText:[NSString stringWithFormat:@"%@ ", [self stringFormattedTimeFromSeconds:&currentTime]]];
  663. if (!self.showStaticEndTime) {
  664. [_videoPlayerView.timeLeftLabel setText:[NSString stringWithFormat:@"-%@", [self stringFormattedTimeFromSeconds:&timeLeft]]];
  665. } else {
  666. [_videoPlayerView.timeLeftLabel setText:[NSString stringWithFormat:@"%@", [self stringFormattedTimeFromSeconds:&duration]]];
  667. }
  668. }
  669. }
  670. - (CMTime)playerItemDuration
  671. {
  672. if (_videoPlayer.status == AVPlayerItemStatusReadyToPlay) {
  673. return([_videoPlayer.currentItem duration]);
  674. }
  675. return(kCMTimeInvalid);
  676. }
  677. - (BOOL)isPlaying
  678. {
  679. return [_videoPlayer rate] != 0.0;
  680. }
  681. - (void)syncPlayPauseButtons
  682. {
  683. if ([self isPlaying]) {
  684. [_videoPlayerView.playPauseButton setImage:[WFCUImage imageNamed:@"pause-button"] forState:UIControlStateNormal];
  685. } else {
  686. [_videoPlayerView.playPauseButton setImage:[WFCUImage imageNamed:@"play-button"] forState:UIControlStateNormal];
  687. }
  688. }
  689. - (void)syncFullScreenButton:(UIInterfaceOrientation)toInterfaceOrientation
  690. {
  691. if (_fullScreenModeToggled) {
  692. [_videoPlayerView.fullScreenButton setImage:[WFCUImage imageNamed:@"minimize-button"] forState:UIControlStateNormal];
  693. } else {
  694. [_videoPlayerView.fullScreenButton setImage:[WFCUImage imageNamed:@"fullscreen-button"] forState:UIControlStateNormal];
  695. }
  696. }
  697. -(void)scrubbingDidBegin
  698. {
  699. if ([self isPlaying]) {
  700. [_videoPlayer pause];
  701. [self syncPlayPauseButtons];
  702. self.restoreVideoPlayStateAfterScrubbing = YES;
  703. [self showControls];
  704. }
  705. }
  706. -(void)scrubberIsScrolling
  707. {
  708. CMTime playerDuration = [self playerItemDuration];
  709. double duration = CMTimeGetSeconds(playerDuration);
  710. if (isfinite(duration)) {
  711. double currentTime = floor(duration * _videoPlayerView.videoScrubber.value);
  712. double timeLeft = floor(duration - currentTime);
  713. if (currentTime <= 0) {
  714. currentTime = 0;
  715. timeLeft = floor(duration);
  716. }
  717. [_videoPlayerView.currentPositionLabel setText:[NSString stringWithFormat:@"%@ ", [self stringFormattedTimeFromSeconds:&currentTime]]];
  718. if (!self.showStaticEndTime) {
  719. [_videoPlayerView.timeLeftLabel setText:[NSString stringWithFormat:@"-%@", [self stringFormattedTimeFromSeconds:&timeLeft]]];
  720. } else {
  721. [_videoPlayerView.timeLeftLabel setText:[NSString stringWithFormat:@"%@", [self stringFormattedTimeFromSeconds:&duration]]];
  722. }
  723. [_videoPlayer seekToTime:CMTimeMakeWithSeconds((float) currentTime, NSEC_PER_SEC)];
  724. }
  725. }
  726. -(void)scrubbingDidEnd
  727. {
  728. if (self.restoreVideoPlayStateAfterScrubbing) {
  729. scrubBuffering = YES;
  730. }
  731. [[_videoPlayerView activityIndicator] startAnimating];
  732. [self showControls];
  733. }
  734. - (NSString *)stringFormattedTimeFromSeconds:(double *)seconds
  735. {
  736. NSDate *date = [NSDate dateWithTimeIntervalSince1970:*seconds];
  737. NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
  738. [formatter setTimeZone:[NSTimeZone timeZoneForSecondsFromGMT:0]];
  739. if (*seconds >= 3600) {
  740. [formatter setDateFormat:@"HH:mm:ss"];
  741. } else {
  742. [formatter setDateFormat:@"mm:ss"];
  743. }
  744. return [formatter stringFromDate:date];
  745. }
  746. @end