VideoPlayerKit.m 35 KB

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