VLCMovieViewController.m 40 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072
  1. //
  2. // VLCMovieViewController.m
  3. // AspenProject
  4. //
  5. // Created by Felix Paul Kühne on 27.02.13.
  6. // Copyright (c) 2013 VideoLAN. All rights reserved.
  7. //
  8. // Refer to the COPYING file of the official project for license.
  9. //
  10. #import "VLCMovieViewController.h"
  11. #import "VLCExternalDisplayController.h"
  12. #import <AVFoundation/AVFoundation.h>
  13. #import <CommonCrypto/CommonDigest.h>
  14. #import "UIDevice+SpeedCategory.h"
  15. #import "VLCBugreporter.h"
  16. #import <MediaPlayer/MediaPlayer.h>
  17. #define INPUT_RATE_DEFAULT 1000.
  18. @interface VLCMovieViewController () <UIGestureRecognizerDelegate, AVAudioSessionDelegate>
  19. {
  20. VLCMediaPlayer *_mediaPlayer;
  21. BOOL _controlsHidden;
  22. BOOL _videoFiltersHidden;
  23. BOOL _playbackSpeedViewHidden;
  24. UIActionSheet *_subtitleActionSheet;
  25. UIActionSheet *_audiotrackActionSheet;
  26. float _currentPlaybackRate;
  27. NSArray *_aspectRatios;
  28. NSUInteger _currentAspectRatioMask;
  29. NSTimer *_idleTimer;
  30. BOOL _shouldResumePlaying;
  31. BOOL _viewAppeared;
  32. BOOL _displayRemainingTime;
  33. BOOL _positionSet;
  34. BOOL _playerIsSetup;
  35. }
  36. @property (nonatomic, strong) UIPopoverController *masterPopoverController;
  37. @property (nonatomic, strong) UIWindow *externalWindow;
  38. @end
  39. @implementation VLCMovieViewController
  40. + (void)initialize
  41. {
  42. NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
  43. NSDictionary *appDefaults = @{kVLCShowRemainingTime : @(YES)};
  44. [defaults registerDefaults:appDefaults];
  45. }
  46. - (void)dealloc
  47. {
  48. [[NSNotificationCenter defaultCenter] removeObserver:self];
  49. }
  50. #pragma mark - Managing the media item
  51. - (void)setMediaItem:(id)newMediaItem
  52. {
  53. if (_mediaItem != newMediaItem) {
  54. [self _stopPlayback];
  55. _mediaItem = newMediaItem;
  56. if (_viewAppeared)
  57. [self _startPlayback];
  58. }
  59. if (self.masterPopoverController != nil)
  60. [self.masterPopoverController dismissPopoverAnimated:YES];
  61. }
  62. - (void)setUrl:(NSURL *)url
  63. {
  64. if (_url != url) {
  65. [self _stopPlayback];
  66. _url = url;
  67. if (_viewAppeared)
  68. [self _startPlayback];
  69. }
  70. }
  71. - (void)viewDidLoad
  72. {
  73. [super viewDidLoad];
  74. self.wantsFullScreenLayout = YES;
  75. self.videoFilterView.hidden = YES;
  76. _videoFiltersHidden = YES;
  77. _hueLabel.text = NSLocalizedString(@"VFILTER_HUE", @"");
  78. _hueSlider.accessibilityLabel = _hueLabel.text;
  79. _hueSlider.isAccessibilityElement = YES;
  80. _contrastLabel.text = NSLocalizedString(@"VFILTER_CONTRAST", @"");
  81. _contrastSlider.accessibilityLabel = _contrastLabel.text;
  82. _contrastSlider.isAccessibilityElement = YES;
  83. _brightnessLabel.text = NSLocalizedString(@"VFILTER_BRIGHTNESS", @"");
  84. _brightnessSlider.accessibilityLabel = _brightnessLabel.text;
  85. _brightnessSlider.isAccessibilityElement = YES;
  86. _saturationLabel.text = NSLocalizedString(@"VFILTER_SATURATION", @"");
  87. _saturationSlider.accessibilityLabel = _saturationLabel.text;
  88. _saturationSlider.isAccessibilityElement = YES;
  89. _gammaLabel.text = NSLocalizedString(@"VFILTER_GAMMA", @"");
  90. _gammaSlider.accessibilityLabel = _gammaLabel.text;
  91. _gammaSlider.isAccessibilityElement = YES;
  92. _playbackSpeedLabel.text = NSLocalizedString(@"PLAYBACK_SPEED", @"");
  93. _playbackSpeedSlider.accessibilityLabel = _playbackSpeedLabel.text;
  94. _playbackSpeedSlider.isAccessibilityElement = YES;
  95. _positionSlider.accessibilityLabel = NSLocalizedString(@"PLAYBACK_POSITION", @"");
  96. _positionSlider.isAccessibilityElement = YES;
  97. _timeDisplay.isAccessibilityElement = YES;
  98. _audioSwitcherButton.accessibilityLabel = NSLocalizedString(@"CHOOSE_AUDIO_TRACK", @"");
  99. _audioSwitcherButton.isAccessibilityElement = YES;
  100. _subtitleSwitcherButton.accessibilityLabel = NSLocalizedString(@"CHOOSE_SUBTITLE_TRACK", @"");
  101. _subtitleSwitcherButton.isAccessibilityElement = YES;
  102. _playbackSpeedButton.accessibilityLabel = _playbackSpeedLabel.text;
  103. _playbackSpeedButton.isAccessibilityElement = YES;
  104. _videoFilterButton.accessibilityLabel = NSLocalizedString(@"VIDEO_FILTER", @"");
  105. _videoFilterButton.isAccessibilityElement = YES;
  106. _resetVideoFilterButton.accessibilityLabel = NSLocalizedString(@"VIDEO_FILTER_RESET_BUTTON", @"");
  107. _resetVideoFilterButton.isAccessibilityElement = YES;
  108. _aspectRatioButton.accessibilityLabel = NSLocalizedString(@"VIDEO_ASPECT_RATIO_BUTTON", @"");
  109. _aspectRatioButton.isAccessibilityElement = YES;
  110. _playPauseButton.accessibilityLabel = NSLocalizedString(@"PLAY_PAUSE_BUTTON", @"");
  111. _playPauseButton.isAccessibilityElement = YES;
  112. _bwdButton.accessibilityLabel = NSLocalizedString(@"BWD_BUTTON", @"");
  113. _bwdButton.isAccessibilityElement = YES;
  114. _fwdButton.accessibilityLabel = NSLocalizedString(@"FWD_BUTTON", @"");
  115. _fwdButton.isAccessibilityElement = YES;
  116. _scrubHelpLabel.text = NSLocalizedString(@"PLAYBACK_SCRUB_HELP", @"");
  117. self.playbackSpeedView.hidden = YES;
  118. _playbackSpeedViewHidden = YES;
  119. NSNotificationCenter *center = [NSNotificationCenter defaultCenter];
  120. [center addObserver:self selector:@selector(handleExternalScreenDidConnect:)
  121. name:UIScreenDidConnectNotification object:nil];
  122. [center addObserver:self selector:@selector(handleExternalScreenDidDisconnect:)
  123. name:UIScreenDidDisconnectNotification object:nil];
  124. [center addObserver:self selector:@selector(applicationWillResignActive:)
  125. name:UIApplicationWillResignActiveNotification object:nil];
  126. [center addObserver:self selector:@selector(applicationDidBecomeActive:)
  127. name:UIApplicationDidBecomeActiveNotification object:nil];
  128. [center addObserver:self selector:@selector(applicationDidEnterBackground:)
  129. name:UIApplicationDidEnterBackgroundNotification object:nil];
  130. _playingExternallyTitle.text = NSLocalizedString(@"PLAYING_EXTERNALLY_TITLE", @"");
  131. _playingExternallyDescription.text = NSLocalizedString(@"PLAYING_EXTERNALLY_DESC", @"");
  132. if ([self hasExternalDisplay])
  133. [self showOnExternalDisplay];
  134. self.trackNameLabel.text = self.artistNameLabel.text = self.albumNameLabel.text = @"";
  135. _movieView.userInteractionEnabled = NO;
  136. UITapGestureRecognizer *tapOnVideoRecognizer = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(toggleControlsVisible)];
  137. tapOnVideoRecognizer.delegate = self;
  138. [self.view addGestureRecognizer:tapOnVideoRecognizer];
  139. _displayRemainingTime = [[[NSUserDefaults standardUserDefaults] objectForKey:kVLCShowRemainingTime] boolValue];
  140. UIPinchGestureRecognizer *pinchRecognizer = [[UIPinchGestureRecognizer alloc] initWithTarget:self action:@selector(handlePinchGesture:)];
  141. pinchRecognizer.delegate = self;
  142. [self.view addGestureRecognizer:pinchRecognizer];
  143. #if 0 // FIXME: trac #8742
  144. UISwipeGestureRecognizer *leftSwipeRecognizer = [[VLCHorizontalSwipeGestureRecognizer alloc] initWithTarget:self action:nil];
  145. leftSwipeRecognizer.direction = UISwipeGestureRecognizerDirectionLeft;
  146. leftSwipeRecognizer.delegate = self;
  147. [self.view addGestureRecognizer:leftSwipeRecognizer];
  148. UISwipeGestureRecognizer *rightSwipeRecognizer = [[VLCHorizontalSwipeGestureRecognizer alloc] initWithTarget:self action:nil];
  149. rightSwipeRecognizer.direction = UISwipeGestureRecognizerDirectionRight;
  150. rightSwipeRecognizer.delegate = self;
  151. [self.view addGestureRecognizer:rightSwipeRecognizer];
  152. UISwipeGestureRecognizer *upSwipeRecognizer = [[VLCVerticalSwipeGestureRecognizer alloc] initWithTarget:self action:nil];
  153. upSwipeRecognizer.direction = UISwipeGestureRecognizerDirectionUp;
  154. upSwipeRecognizer.delegate = self;
  155. [self.view addGestureRecognizer:upSwipeRecognizer];
  156. UISwipeGestureRecognizer *downSwipeRecognizer = [[VLCVerticalSwipeGestureRecognizer alloc] initWithTarget:self action:nil];
  157. downSwipeRecognizer.direction = UISwipeGestureRecognizerDirectionDown;
  158. downSwipeRecognizer.delegate = self;
  159. [self.view addGestureRecognizer:downSwipeRecognizer];
  160. #endif
  161. _aspectRatios = @[@"DEFAULT", @"4:3", @"16:9", @"16:10", @"2.21:1", @"FILL_TO_SCREEN"];
  162. [self.aspectRatioButton setBackgroundImage:[UIImage imageNamed:@"ratioButton"] forState:UIControlStateNormal];
  163. [self.aspectRatioButton setBackgroundImage:[UIImage imageNamed:@"ratioButtonHighlight"] forState:UIControlStateHighlighted];
  164. [self.aspectRatioButton setImage:[UIImage imageNamed:@"ratioIcon"] forState:UIControlStateNormal];
  165. [self.toolbar setBackgroundImage:[UIImage imageNamed:@"seekbarBg"] forBarMetrics:UIBarMetricsDefault];
  166. [self.backButton setBackgroundImage:[UIImage imageNamed:@"playbackDoneButton"] forState:UIControlStateNormal barMetrics:UIBarMetricsDefault];
  167. [self.backButton setBackgroundImage:[UIImage imageNamed:@"playbackDoneButtonHighlight"] forState:UIControlStateHighlighted barMetrics:UIBarMetricsDefault];
  168. /* this looks a bit weird, but we need to support iOS 5 and should show the same appearance */
  169. UISlider *volumeSlider = nil;
  170. for (id aView in self.volumeView.subviews){
  171. if ([[[aView class] description] isEqualToString:@"MPVolumeSlider"]){
  172. volumeSlider = (UISlider *)aView;
  173. break;
  174. }
  175. }
  176. [volumeSlider setMinimumTrackImage:[[UIImage imageNamed:@"sliderminiValue"]resizableImageWithCapInsets:UIEdgeInsetsMake(0, 4, 0, 0)] forState:UIControlStateNormal];
  177. [volumeSlider setMaximumTrackImage:[[UIImage imageNamed:@"slidermaxValue"] resizableImageWithCapInsets:UIEdgeInsetsMake(0, 0, 0, 4)] forState:UIControlStateNormal];
  178. [volumeSlider setThumbImage:[UIImage imageNamed:@"volumeballslider"] forState:UIControlStateNormal];
  179. [volumeSlider addTarget:self
  180. action:@selector(volumeSliderAction:)
  181. forControlEvents:UIControlEventValueChanged];
  182. [[AVAudioSession sharedInstance] setDelegate:self];
  183. if (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPad)
  184. self.positionSlider.scrubbingSpeedChangePositions = @[@(0.), @(100.), @(200.), @(300)];
  185. _playerIsSetup = NO;
  186. [self.movieView setAccessibilityLabel:NSLocalizedString(@"VO_VIDEOPLAYER_TITLE", @"")];
  187. [self.movieView setAccessibilityHint:NSLocalizedString(@"VO_VIDEOPLAYER_DOUBLETAP", @"")];
  188. }
  189. - (BOOL)_blobCheck
  190. {
  191. NSArray *searchPaths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
  192. NSString *directoryPath = searchPaths[0];
  193. if (![[NSFileManager defaultManager] fileExistsAtPath:[directoryPath stringByAppendingPathComponent:@"blob.bin"]])
  194. return NO;
  195. NSData *data = [NSData dataWithContentsOfFile:[directoryPath stringByAppendingPathComponent:@"blob.bin"]];
  196. uint8_t digest[CC_SHA1_DIGEST_LENGTH];
  197. CC_SHA1(data.bytes, data.length, digest);
  198. NSMutableString *hash = [NSMutableString stringWithCapacity:CC_SHA1_DIGEST_LENGTH * 2];
  199. for (unsigned int u = 0; u < CC_SHA1_DIGEST_LENGTH; u++)
  200. [hash appendFormat:@"%02x", digest[u]];
  201. if ([hash isEqualToString:kBlobHash])
  202. return YES;
  203. else
  204. return NO;
  205. }
  206. - (void)viewWillAppear:(BOOL)animated
  207. {
  208. [super viewWillAppear:animated];
  209. [self.navigationController setNavigationBarHidden:YES animated:YES];
  210. if (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPhone)
  211. [UIApplication sharedApplication].statusBarStyle = UIStatusBarStyleBlackTranslucent;
  212. [self _startPlayback];
  213. [self setControlsHidden:NO animated:YES];
  214. _viewAppeared = YES;
  215. }
  216. - (void)_startPlayback
  217. {
  218. if (_playerIsSetup)
  219. return;
  220. NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
  221. _mediaPlayer = [[VLCMediaPlayer alloc] initWithOptions:@[[NSString stringWithFormat:@"--%@=%@", kVLCSettingSubtitlesFont, [defaults objectForKey:kVLCSettingSubtitlesFont]], [NSString stringWithFormat:@"--%@=%@", kVLCSettingSubtitlesFontColor, [defaults objectForKey:kVLCSettingSubtitlesFontColor]], [NSString stringWithFormat:@"--%@=%@", kVLCSettingSubtitlesFontSize, [defaults objectForKey:kVLCSettingSubtitlesFontSize]], [NSString stringWithFormat:@"--%@=%@", kVLCSettingDeinterlace, [defaults objectForKey:kVLCSettingDeinterlace]]]];
  222. [_mediaPlayer setDelegate:self];
  223. [_mediaPlayer setDrawable:self.movieView];
  224. if (!self.mediaItem && !self.url) {
  225. [self _stopPlayback];
  226. return;
  227. }
  228. VLCMedia *media;
  229. if (self.mediaItem) {
  230. self.title = [self.mediaItem title];
  231. media = [VLCMedia mediaWithURL:[NSURL URLWithString:self.mediaItem.url]];
  232. self.mediaItem.unread = @(NO);
  233. if (self.mediaItem.isAlbumTrack) {
  234. self.trackNameLabel.text = self.mediaItem.albumTrack.title;
  235. self.artistNameLabel.text = self.mediaItem.albumTrack.artist;
  236. self.albumNameLabel.text = self.mediaItem.albumTrack.album.name;
  237. } else
  238. self.trackNameLabel.text = self.artistNameLabel.text = self.albumNameLabel.text = @"";
  239. } else {
  240. media = [VLCMedia mediaWithURL:self.url];
  241. self.title = @"Network Stream";
  242. }
  243. [media addOptions:
  244. @{kVLCSettingStretchAudio :
  245. [[defaults objectForKey:kVLCSettingStretchAudio] boolValue] ? kVLCSettingStretchAudioOnValue : kVLCSettingStretchAudioOffValue, kVLCSettingTextEncoding : [defaults objectForKey:kVLCSettingTextEncoding], kVLCSettingSkipLoopFilter : [defaults objectForKey:kVLCSettingSkipLoopFilter]}];
  246. [NSTimeZone resetSystemTimeZone];
  247. NSString *tzName = [[NSTimeZone systemTimeZone] name];
  248. NSArray *tzNames = @[@"America/Adak", @"America/Anchorage", @"America/Boise", @"America/Chicago", @"America/Denver", @"America/Detroit", @"America/Indiana/Indianapolis", @"America/Indiana/Knox", @"America/Indiana/Marengo", @"America/Indiana/Petersburg", @"America/Indiana/Tell_City", @"America/Indiana/Vevay", @"America/Indiana/Vincennes", @"America/Indiana/Winamac", @"America/Juneau", @"America/Kentucky/Louisville", @"America/Kentucky/Monticello", @"America/Los_Angeles", @"America/Menominee", @"America/Metlakatla", @"America/New_York", @"America/Nome", @"America/North_Dakota/Beulah", @"America/North_Dakota/Center", @"America/North_Dakota/New_Salem", @"America/Phoenix", @"America/Puerto_Rico", @"America/Shiprock", @"America/Sitka", @"America/St_Thomas", @"America/Thule", @"America/Yakutat", @"Pacific/Guam", @"Pacific/Honolulu", @"Pacific/Johnston", @"Pacific/Kwajalein", @"Pacific/Midway", @"Pacific/Pago_Pago", @"Pacific/Saipan", @"Pacific/Wake"];
  249. if ([tzNames containsObject:tzName] || [[tzName stringByDeletingLastPathComponent] isEqualToString:@"US"]) {
  250. NSArray *tracksInfo = media.tracksInformation;
  251. for (NSUInteger x = 0; x < tracksInfo.count; x++) {
  252. if ([[tracksInfo[x] objectForKey:VLCMediaTracksInformationType] isEqualToString:VLCMediaTracksInformationTypeAudio])
  253. {
  254. NSInteger fourcc = [[tracksInfo[x] objectForKey:VLCMediaTracksInformationCodec] integerValue];
  255. switch (fourcc) {
  256. case 540161377:
  257. case 1647457633:
  258. case 858612577:
  259. case 862151027:
  260. case 2126701:
  261. case 544437348:
  262. case 542331972:
  263. case 1651733604:
  264. case 1668510820:
  265. case 1702065252:
  266. case 1752396900:
  267. case 1819505764:
  268. case 18903917:
  269. case 862151013:
  270. {
  271. if (![self _blobCheck]) {
  272. [media addOptions:@{@"no-audio" : [NSNull null]}];
  273. APLog(@"audio playback disabled because an unsupported codec was found");
  274. }
  275. break;
  276. }
  277. default:
  278. break;
  279. }
  280. }
  281. }
  282. }
  283. [_mediaPlayer setMedia:media];
  284. self.positionSlider.value = 0.;
  285. [self.timeDisplay setTitle:@"" forState:UIControlStateNormal];
  286. self.timeDisplay.accessibilityLabel = @"";
  287. if (![self _isMediaSuitableForDevice]) {
  288. UIAlertView * alert = [[UIAlertView alloc] initWithTitle:NSLocalizedString(@"DEVICE_TOOSLOW_TITLE", @"") message:[NSString stringWithFormat:NSLocalizedString(@"DEVICE_TOOSLOW", @""), [[UIDevice currentDevice] model], self.mediaItem.title] delegate:self cancelButtonTitle:NSLocalizedString(@"BUTTON_CANCEL", @"") otherButtonTitles:NSLocalizedString(@"BUTTON_OPEN", @""), nil];
  289. [alert show];
  290. } else
  291. [self _playNewMedia];
  292. if (![self hasExternalDisplay])
  293. self.brightnessSlider.value = [UIScreen mainScreen].brightness * 2.;
  294. }
  295. - (BOOL)_isMediaSuitableForDevice
  296. {
  297. if (!self.mediaItem)
  298. return YES;
  299. NSUInteger totalNumberOfPixels = [[[self.mediaItem videoTrack] valueForKey:@"width"] doubleValue] * [[[self.mediaItem videoTrack] valueForKey:@"height"] doubleValue];
  300. NSInteger speedCategory = [[UIDevice currentDevice] speedCategory];
  301. if (speedCategory == 1) {
  302. // iPhone 3GS, iPhone 4, first gen. iPad, 3rd and 4th generation iPod touch
  303. return (totalNumberOfPixels < 600000); // between 480p and 720p
  304. } else if (speedCategory == 2) {
  305. // iPhone 4S, iPad 2 and 3, iPod 4 and 5
  306. return (totalNumberOfPixels < 922000); // 720p
  307. } else if (speedCategory == 3) {
  308. // iPhone 5, iPad 4
  309. return (totalNumberOfPixels < 2074000); // 1080p
  310. }
  311. return YES;
  312. }
  313. - (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
  314. {
  315. if (buttonIndex == 1)
  316. [self _playNewMedia];
  317. else {
  318. [self _stopPlayback];
  319. [self closePlayback:nil];
  320. }
  321. }
  322. - (void)_playNewMedia
  323. {
  324. NSNumber *playbackPositionInTime = @(0);
  325. if (self.mediaItem.lastPosition && [self.mediaItem.lastPosition floatValue] < .95) {
  326. if (self.mediaItem.duration.intValue != 0)
  327. playbackPositionInTime = @(self.mediaItem.lastPosition.floatValue * (self.mediaItem.duration.intValue / 1000.));
  328. }
  329. [_mediaPlayer.media addOptions:@{@"start-time": playbackPositionInTime}];
  330. APLog(@"set starttime to %i", playbackPositionInTime.intValue);
  331. [_mediaPlayer play];
  332. if (self.mediaItem) {
  333. if (self.mediaItem.lastAudioTrack.intValue > 0)
  334. _mediaPlayer.currentAudioTrackIndex = self.mediaItem.lastAudioTrack.intValue;
  335. if (self.mediaItem.lastSubtitleTrack.intValue > 0)
  336. _mediaPlayer.currentVideoSubTitleIndex = self.mediaItem.lastSubtitleTrack.intValue;
  337. }
  338. self.playbackSpeedSlider.value = [self _playbackSpeed];
  339. [self _updatePlaybackSpeedIndicator];
  340. [self performSelectorInBackground:@selector(_updateExportedPlaybackInformation) withObject:nil];
  341. _currentAspectRatioMask = 0;
  342. _mediaPlayer.videoAspectRatio = NULL;
  343. [self _resetIdleTimer];
  344. _playerIsSetup = YES;
  345. }
  346. - (void)viewWillDisappear:(BOOL)animated
  347. {
  348. [self _stopPlayback];
  349. _viewAppeared = NO;
  350. if (_idleTimer) {
  351. [_idleTimer invalidate];
  352. _idleTimer = nil;
  353. }
  354. [self.navigationController setNavigationBarHidden:NO animated:YES];
  355. [UIApplication sharedApplication].statusBarStyle = UIStatusBarStyleBlackOpaque;
  356. [[UIApplication sharedApplication] setStatusBarHidden:NO withAnimation:UIStatusBarAnimationFade];
  357. [super viewWillDisappear:animated];
  358. // hide filter UI for next run
  359. if (!_videoFiltersHidden)
  360. _videoFiltersHidden = YES;
  361. if (!_playbackSpeedViewHidden)
  362. _playbackSpeedViewHidden = YES;
  363. }
  364. - (void)_stopPlayback
  365. {
  366. if (_mediaPlayer) {
  367. [_mediaPlayer pause];
  368. [self _saveCurrentState];
  369. [_mediaPlayer stop];
  370. _mediaPlayer = nil; // save memory and some CPU time
  371. }
  372. if (_mediaItem)
  373. _mediaItem = nil;
  374. _playerIsSetup = NO;
  375. }
  376. - (void)_saveCurrentState
  377. {
  378. if (self.mediaItem) {
  379. self.mediaItem.lastPosition = @([_mediaPlayer position]);
  380. self.mediaItem.lastAudioTrack = @(_mediaPlayer.currentAudioTrackIndex);
  381. self.mediaItem.lastSubtitleTrack = @(_mediaPlayer.currentVideoSubTitleIndex);
  382. }
  383. }
  384. #pragma mark - remote events
  385. - (void)viewDidAppear:(BOOL)animated
  386. {
  387. [super viewDidAppear:animated];
  388. [[UIApplication sharedApplication] beginReceivingRemoteControlEvents];
  389. [self becomeFirstResponder];
  390. }
  391. - (void)viewDidDisappear:(BOOL)animated
  392. {
  393. [super viewDidDisappear:animated];
  394. [[UIApplication sharedApplication] endReceivingRemoteControlEvents];
  395. [self resignFirstResponder];
  396. [[NSUserDefaults standardUserDefaults] setBool:_displayRemainingTime forKey:kVLCShowRemainingTime];
  397. }
  398. - (BOOL)canBecomeFirstResponder
  399. {
  400. return YES;
  401. }
  402. - (void)motionEnded:(UIEventSubtype)motion withEvent:(UIEvent *)event
  403. {
  404. if (motion == UIEventSubtypeMotionShake)
  405. [[VLCBugreporter sharedInstance] handleBugreportRequest];
  406. }
  407. - (void)remoteControlReceivedWithEvent:(UIEvent *)event
  408. {
  409. switch (event.subtype) {
  410. case UIEventSubtypeRemoteControlPlay:
  411. [_mediaPlayer play];
  412. break;
  413. case UIEventSubtypeRemoteControlPause:
  414. [_mediaPlayer pause];
  415. break;
  416. case UIEventSubtypeRemoteControlTogglePlayPause:
  417. [self playPause];
  418. break;
  419. default:
  420. break;
  421. }
  422. }
  423. #pragma mark - controls visibility
  424. - (void)handlePinchGesture:(UIPinchGestureRecognizer *)recognizer
  425. {
  426. if (recognizer.velocity < 0.)
  427. [self closePlayback:nil];
  428. }
  429. - (BOOL)gestureRecognizer:(UIGestureRecognizer *)gestureRecognizer shouldReceiveTouch:(UITouch *)touch
  430. {
  431. if (touch.view != self.view)
  432. return NO;
  433. return YES;
  434. }
  435. - (void)setControlsHidden:(BOOL)hidden animated:(BOOL)animated
  436. {
  437. _controlsHidden = hidden;
  438. CGFloat alpha = _controlsHidden? 0.0f: 1.0f;
  439. if (!_controlsHidden) {
  440. _controllerPanel.alpha = 0.0f;
  441. _controllerPanel.hidden = !_videoFiltersHidden;
  442. _toolbar.alpha = 0.0f;
  443. _toolbar.hidden = NO;
  444. _videoFilterView.alpha = 0.0f;
  445. _videoFilterView.hidden = _videoFiltersHidden;
  446. _playbackSpeedView.alpha = 0.0f;
  447. _playbackSpeedView.hidden = _playbackSpeedViewHidden;
  448. }
  449. void (^animationBlock)() = ^() {
  450. _controllerPanel.alpha = alpha;
  451. _toolbar.alpha = alpha;
  452. _videoFilterView.alpha = alpha;
  453. _playbackSpeedView.alpha = alpha;
  454. };
  455. void (^completionBlock)(BOOL finished) = ^(BOOL finished) {
  456. if (_videoFiltersHidden)
  457. _controllerPanel.hidden = _controlsHidden;
  458. else
  459. _controllerPanel.hidden = NO;
  460. _toolbar.hidden = _controlsHidden;
  461. _videoFilterView.hidden = _videoFiltersHidden;
  462. _playbackSpeedView.hidden = _playbackSpeedViewHidden;
  463. };
  464. UIStatusBarAnimation animationType = animated? UIStatusBarAnimationFade: UIStatusBarAnimationNone;
  465. NSTimeInterval animationDuration = animated? 0.3: 0.0;
  466. [[UIApplication sharedApplication] setStatusBarHidden:_viewAppeared ? _controlsHidden : NO withAnimation:animationType];
  467. [UIView animateWithDuration:animationDuration animations:animationBlock completion:completionBlock];
  468. _volumeView.hidden = _controllerPanel.hidden;
  469. }
  470. - (void)toggleControlsVisible
  471. {
  472. if (_controlsHidden && !_videoFiltersHidden)
  473. _videoFiltersHidden = YES;
  474. [self setControlsHidden:!_controlsHidden animated:YES];
  475. }
  476. - (void)_resetIdleTimer
  477. {
  478. if (!_idleTimer)
  479. _idleTimer = [NSTimer scheduledTimerWithTimeInterval:4.
  480. target:self
  481. selector:@selector(idleTimerExceeded)
  482. userInfo:nil
  483. repeats:NO];
  484. else {
  485. if (fabs([_idleTimer.fireDate timeIntervalSinceNow]) < 4.)
  486. [_idleTimer setFireDate:[NSDate dateWithTimeIntervalSinceNow:4.]];
  487. }
  488. }
  489. - (void)idleTimerExceeded
  490. {
  491. _idleTimer = nil;
  492. if (!_controlsHidden)
  493. [self toggleControlsVisible];
  494. if (!_videoFiltersHidden)
  495. _videoFiltersHidden = YES;
  496. if (!_playbackSpeedViewHidden)
  497. _playbackSpeedViewHidden = YES;
  498. if (self.scrubIndicatorView.hidden == NO)
  499. self.scrubIndicatorView.hidden = YES;
  500. }
  501. - (UIResponder *)nextResponder
  502. {
  503. [self _resetIdleTimer];
  504. return [super nextResponder];
  505. }
  506. #pragma mark - controls
  507. - (IBAction)closePlayback:(id)sender
  508. {
  509. [self setControlsHidden:NO animated:NO];
  510. [self.navigationController popViewControllerAnimated:YES];
  511. }
  512. - (IBAction)positionSliderAction:(UISlider *)sender
  513. {
  514. /* we need to limit the number of events sent by the slider, since otherwise, the user
  515. * wouldn't see the I-frames when seeking on current mobile devices. This isn't a problem
  516. * within the Simulator, but especially on older ARMv7 devices, it's clearly noticeable. */
  517. [self performSelector:@selector(_setPositionForReal) withObject:nil afterDelay:0.3];
  518. VLCTime *newPosition = [VLCTime timeWithInt:(int)(_positionSlider.value * self.mediaItem.duration.intValue)];
  519. [self.timeDisplay setTitle:newPosition.stringValue forState:UIControlStateNormal];
  520. self.timeDisplay.accessibilityLabel = [NSString stringWithFormat:@"%@: %@", NSLocalizedString(@"PLAYBACK_POSITION", @""), newPosition.stringValue];
  521. _positionSet = NO;
  522. [self _resetIdleTimer];
  523. }
  524. - (void)_setPositionForReal
  525. {
  526. if (!_positionSet) {
  527. _mediaPlayer.position = _positionSlider.value;
  528. _positionSet = YES;
  529. }
  530. }
  531. - (IBAction)positionSliderTouchDown:(id)sender
  532. {
  533. [self _updateScrubLabel];
  534. self.scrubIndicatorView.hidden = NO;
  535. }
  536. - (IBAction)positionSliderTouchUp:(id)sender
  537. {
  538. self.scrubIndicatorView.hidden = YES;
  539. }
  540. - (void)_updateScrubLabel
  541. {
  542. float speed = self.positionSlider.scrubbingSpeed;
  543. if (speed == 1.)
  544. self.currentScrubSpeedLabel.text = NSLocalizedString(@"PLAYBACK_SCRUB_HIGH", @"");
  545. else if (speed == .5)
  546. self.currentScrubSpeedLabel.text = NSLocalizedString(@"PLAYBACK_SCRUB_HALF", @"");
  547. else if (speed == .25)
  548. self.currentScrubSpeedLabel.text = NSLocalizedString(@"PLAYBACK_SCRUB_QUARTER", @"");
  549. else
  550. self.currentScrubSpeedLabel.text = NSLocalizedString(@"PLAYBACK_SCRUB_FINE", @"");
  551. [self _resetIdleTimer];
  552. }
  553. - (IBAction)positionSliderDrag:(id)sender
  554. {
  555. [self _updateScrubLabel];
  556. }
  557. - (IBAction)volumeSliderAction:(id)sender
  558. {
  559. [self _resetIdleTimer];
  560. }
  561. - (void)mediaPlayerTimeChanged:(NSNotification *)aNotification {
  562. self.positionSlider.value = [_mediaPlayer position];
  563. if (_displayRemainingTime)
  564. [self.timeDisplay setTitle:[[_mediaPlayer remainingTime] stringValue] forState:UIControlStateNormal];
  565. else
  566. [self.timeDisplay setTitle:[[_mediaPlayer time] stringValue] forState:UIControlStateNormal];
  567. }
  568. - (void)mediaPlayerStateChanged:(NSNotification *)aNotification
  569. {
  570. VLCMediaPlayerState currentState = _mediaPlayer.state;
  571. if (currentState == VLCMediaPlayerStateError) {
  572. [self.statusLabel showStatusMessage:NSLocalizedString(@"PLAYBACK_FAILED", @"")];
  573. [self performSelector:@selector(closePlayback:) withObject:nil afterDelay:2.];
  574. }
  575. if (currentState == VLCMediaPlayerStateEnded || currentState == VLCMediaPlayerStateStopped)
  576. [self performSelector:@selector(closePlayback:) withObject:nil afterDelay:2.];
  577. UIImage *playPauseImage = [_mediaPlayer isPlaying]? [UIImage imageNamed:@"pauseIcon"] : [UIImage imageNamed:@"playIcon"];
  578. [_playPauseButton setImage:playPauseImage forState:UIControlStateNormal];
  579. if ([[_mediaPlayer audioTrackIndexes] count] > 2)
  580. self.audioSwitcherButton.hidden = NO;
  581. else
  582. self.audioSwitcherButton.hidden = YES;
  583. if ([[_mediaPlayer videoSubTitlesIndexes] count] > 1)
  584. self.subtitleSwitcherButton.hidden = NO;
  585. else
  586. self.subtitleSwitcherButton.hidden = YES;
  587. }
  588. - (IBAction)playPause
  589. {
  590. if ([_mediaPlayer isPlaying])
  591. [_mediaPlayer pause];
  592. else
  593. [_mediaPlayer play];
  594. }
  595. - (IBAction)forward:(id)sender
  596. {
  597. [_mediaPlayer mediumJumpForward];
  598. }
  599. - (IBAction)backward:(id)sender
  600. {
  601. [_mediaPlayer mediumJumpBackward];
  602. }
  603. - (IBAction)switchAudioTrack:(id)sender
  604. {
  605. _audiotrackActionSheet = [[UIActionSheet alloc] initWithTitle:NSLocalizedString(@"CHOOSE_AUDIO_TRACK", @"audio track selector") delegate:self cancelButtonTitle:nil destructiveButtonTitle:nil otherButtonTitles: nil];
  606. NSArray *audioTracks = [_mediaPlayer audioTrackNames];
  607. NSArray *audioTrackIndexes = [_mediaPlayer audioTrackIndexes];
  608. NSUInteger count = [audioTracks count];
  609. for (NSUInteger i = 0; i < count; i++) {
  610. NSString *indexIndicator = ([audioTrackIndexes[i] intValue] == [_mediaPlayer currentAudioTrackIndex])? @"\u2713": @"";
  611. NSString *buttonTitle = [NSString stringWithFormat:@"%@ %@", indexIndicator, audioTracks[i]];
  612. [_audiotrackActionSheet addButtonWithTitle:buttonTitle];
  613. }
  614. [_audiotrackActionSheet addButtonWithTitle:NSLocalizedString(@"BUTTON_CANCEL", @"cancel button")];
  615. [_audiotrackActionSheet setCancelButtonIndex:[_audiotrackActionSheet numberOfButtons] - 1];
  616. [_audiotrackActionSheet showInView:self.audioSwitcherButton];
  617. }
  618. - (IBAction)switchSubtitleTrack:(id)sender
  619. {
  620. NSArray *spuTracks = [_mediaPlayer videoSubTitlesNames];
  621. NSArray *spuTrackIndexes = [_mediaPlayer videoSubTitlesIndexes];
  622. NSUInteger count = [spuTracks count];
  623. if (count <= 1)
  624. return;
  625. _subtitleActionSheet = [[UIActionSheet alloc] initWithTitle:NSLocalizedString(@"CHOOSE_SUBTITLE_TRACK", @"subtitle track selector") delegate:self cancelButtonTitle:nil destructiveButtonTitle:nil otherButtonTitles: nil];
  626. for (NSUInteger i = 0; i < count; i++) {
  627. NSString *indexIndicator = ([spuTrackIndexes[i] intValue] == [_mediaPlayer currentVideoSubTitleIndex])? @"\u2713": @"";
  628. NSString *buttonTitle = [NSString stringWithFormat:@"%@ %@", indexIndicator, spuTracks[i]];
  629. [_subtitleActionSheet addButtonWithTitle:buttonTitle];
  630. }
  631. [_subtitleActionSheet addButtonWithTitle:NSLocalizedString(@"BUTTON_CANCEL", @"cancel button")];
  632. [_subtitleActionSheet setCancelButtonIndex:[_subtitleActionSheet numberOfButtons] - 1];
  633. [_subtitleActionSheet showInView: self.subtitleSwitcherButton];
  634. }
  635. - (void)actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex {
  636. if (buttonIndex == [actionSheet cancelButtonIndex])
  637. return;
  638. NSArray *indexArray;
  639. if (actionSheet == _subtitleActionSheet) {
  640. indexArray = _mediaPlayer.videoSubTitlesIndexes;
  641. if (buttonIndex <= indexArray.count) {
  642. _mediaPlayer.currentVideoSubTitleIndex = [indexArray[buttonIndex] intValue];
  643. }
  644. } else if (actionSheet == _audiotrackActionSheet) {
  645. indexArray = _mediaPlayer.audioTrackIndexes;
  646. if (buttonIndex <= indexArray.count) {
  647. _mediaPlayer.currentAudioTrackIndex = [indexArray[buttonIndex] intValue];
  648. }
  649. }
  650. }
  651. - (IBAction)toggleTimeDisplay:(id)sender
  652. {
  653. _displayRemainingTime = !_displayRemainingTime;
  654. [self _resetIdleTimer];
  655. }
  656. #pragma mark - swipe gestures
  657. - (void)horizontalSwipePercentage:(CGFloat)percentage inView:(UIView *)view
  658. {
  659. if (percentage != 0.) {
  660. _mediaPlayer.position = _mediaPlayer.position + percentage;
  661. }
  662. }
  663. - (void)verticalSwipePercentage:(CGFloat)percentage inView:(UIView *)view half:(NSUInteger)half
  664. {
  665. if (percentage != 0.) {
  666. if (half > 0) {
  667. CGFloat currentValue = self.brightnessSlider.value;
  668. currentValue = currentValue + percentage;
  669. self.brightnessSlider.value = currentValue;
  670. if ([self hasExternalDisplay])
  671. _mediaPlayer.brightness = currentValue;
  672. else
  673. [[UIScreen mainScreen] setBrightness:currentValue / 2];
  674. } else
  675. NSLog(@"volume setting through swipe not implemented");//_mediaPlayer.audio.volume = percentage * 200;
  676. }
  677. }
  678. #pragma mark - Video Filter UI
  679. - (IBAction)videoFilterToggle:(id)sender
  680. {
  681. if (!_playbackSpeedViewHidden)
  682. self.playbackSpeedView.hidden = _playbackSpeedViewHidden = YES;
  683. if (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPhone) {
  684. if (!_controlsHidden)
  685. self.controllerPanel.hidden = _controlsHidden = YES;
  686. }
  687. self.videoFilterView.hidden = !_videoFiltersHidden;
  688. _videoFiltersHidden = self.videoFilterView.hidden;
  689. }
  690. - (IBAction)videoFilterSliderAction:(id)sender
  691. {
  692. if (sender == self.hueSlider)
  693. _mediaPlayer.hue = (int)self.hueSlider.value;
  694. else if (sender == self.contrastSlider)
  695. _mediaPlayer.contrast = self.contrastSlider.value;
  696. else if (sender == self.brightnessSlider) {
  697. if ([self hasExternalDisplay])
  698. _mediaPlayer.brightness = self.brightnessSlider.value;
  699. else
  700. [[UIScreen mainScreen] setBrightness:(self.brightnessSlider.value / 2.)];
  701. } else if (sender == self.saturationSlider)
  702. _mediaPlayer.saturation = self.saturationSlider.value;
  703. else if (sender == self.gammaSlider)
  704. _mediaPlayer.gamma = self.gammaSlider.value;
  705. else if (sender == self.resetVideoFilterButton) {
  706. _mediaPlayer.hue = self.hueSlider.value = 0.;
  707. _mediaPlayer.contrast = self.contrastSlider.value = 1.;
  708. _mediaPlayer.brightness = self.brightnessSlider.value = 1.;
  709. [[UIScreen mainScreen] setBrightness:(self.brightnessSlider.value / 2.)];
  710. _mediaPlayer.saturation = self.saturationSlider.value = 1.;
  711. _mediaPlayer.gamma = self.gammaSlider.value = 1.;
  712. } else
  713. APLog(@"unknown sender for videoFilterSliderAction");
  714. [self _resetIdleTimer];
  715. }
  716. #pragma mark - playback view
  717. - (IBAction)playbackSpeedSliderAction:(UISlider *)sender
  718. {
  719. double speed = pow(2, sender.value / 17.);
  720. float rate = INPUT_RATE_DEFAULT / speed;
  721. if (_currentPlaybackRate != rate)
  722. [_mediaPlayer setRate:INPUT_RATE_DEFAULT / rate];
  723. _currentPlaybackRate = rate;
  724. [self _updatePlaybackSpeedIndicator];
  725. [self _resetIdleTimer];
  726. }
  727. - (void)_updatePlaybackSpeedIndicator
  728. {
  729. float f_value = self.playbackSpeedSlider.value;
  730. double speed = pow(2, f_value / 17.);
  731. self.playbackSpeedIndicator.text = [NSString stringWithFormat:@"%.2fx", speed];
  732. /* rate changed, so update the exported info */
  733. [self performSelectorInBackground:@selector(_updateExportedPlaybackInformation) withObject:nil];
  734. }
  735. - (float)_playbackSpeed
  736. {
  737. float f_rate = _mediaPlayer.rate;
  738. double value = 17 * log(f_rate) / log(2.);
  739. float returnValue = (int) ((value > 0) ? value + .5 : value - .5);
  740. if (returnValue < -34.)
  741. returnValue = -34.;
  742. else if (returnValue > 34.)
  743. returnValue = 34.;
  744. _currentPlaybackRate = returnValue;
  745. return returnValue;
  746. }
  747. - (IBAction)videoDimensionAction:(id)sender
  748. {
  749. if (sender == self.playbackSpeedButton) {
  750. if (!_videoFiltersHidden)
  751. self.videoFilterView.hidden = _videoFiltersHidden = YES;
  752. self.playbackSpeedView.hidden = !_playbackSpeedViewHidden;
  753. _playbackSpeedViewHidden = self.playbackSpeedView.hidden;
  754. [self _resetIdleTimer];
  755. } else if (sender == self.aspectRatioButton) {
  756. NSUInteger count = [_aspectRatios count];
  757. if (_currentAspectRatioMask + 1 > count - 1) {
  758. _mediaPlayer.videoAspectRatio = NULL;
  759. _mediaPlayer.videoCropGeometry = NULL;
  760. _currentAspectRatioMask = 0;
  761. [self.statusLabel showStatusMessage:[NSString stringWithFormat:NSLocalizedString(@"AR_CHANGED", @""), NSLocalizedString(@"DEFAULT", @"")]];
  762. } else {
  763. _currentAspectRatioMask++;
  764. if ([_aspectRatios[_currentAspectRatioMask] isEqualToString:@"FILL_TO_SCREEN"]) {
  765. UIScreen *screen;
  766. if (![self hasExternalDisplay])
  767. screen = [UIScreen mainScreen];
  768. else
  769. screen = [UIScreen screens][1];
  770. float f_ar = screen.bounds.size.width / screen.bounds.size.height;
  771. if (f_ar == (float)(640./1136.)) // iPhone 5 aka 16:9.01
  772. _mediaPlayer.videoCropGeometry = "16:9";
  773. else if (f_ar == (float)(2./3.)) // all other iPhones
  774. _mediaPlayer.videoCropGeometry = "16:10"; // libvlc doesn't support 2:3 crop
  775. else if (f_ar == .75) // all iPads
  776. _mediaPlayer.videoCropGeometry = "4:3";
  777. else if (f_ar == .5625) // AirPlay
  778. _mediaPlayer.videoCropGeometry = "16:9";
  779. else
  780. APLog(@"unknown screen format %f, can't crop", f_ar);
  781. [self.statusLabel showStatusMessage:NSLocalizedString(@"FILL_TO_SCREEN", @"")];
  782. return;
  783. }
  784. _mediaPlayer.videoCropGeometry = NULL;
  785. _mediaPlayer.videoAspectRatio = (char *)[_aspectRatios[_currentAspectRatioMask] UTF8String];
  786. [self.statusLabel showStatusMessage:[NSString stringWithFormat:NSLocalizedString(@"AR_CHANGED", @""), _aspectRatios[_currentAspectRatioMask]]];
  787. }
  788. }
  789. }
  790. #pragma mark - background interaction
  791. - (void)applicationWillResignActive:(NSNotification *)aNotification
  792. {
  793. [self _saveCurrentState];
  794. if (![[[NSUserDefaults standardUserDefaults] objectForKey:kVLCSettingContinueAudioInBackgroundKey] boolValue]) {
  795. [_mediaPlayer pause];
  796. _shouldResumePlaying = YES;
  797. } else
  798. _mediaPlayer.currentVideoTrackIndex = 0;
  799. }
  800. - (void)applicationDidEnterBackground:(NSNotification *)notification
  801. {
  802. _shouldResumePlaying = NO;
  803. }
  804. - (void)applicationDidBecomeActive:(NSNotification *)notification
  805. {
  806. if (_shouldResumePlaying) {
  807. _shouldResumePlaying = NO;
  808. [_mediaPlayer play];
  809. } else
  810. _mediaPlayer.currentVideoTrackIndex = 1;
  811. }
  812. - (void)_updateExportedPlaybackInformation
  813. {
  814. if (!_mediaItem) {
  815. [MPNowPlayingInfoCenter defaultCenter].nowPlayingInfo = nil;
  816. return;
  817. }
  818. MLFile * currentFile = _mediaItem;
  819. /* we omit artwork for now since we had to read it from storage as we can't access
  820. * the artwork cache at the moment - FIXME? */
  821. NSDictionary *currentlyPlayingTrackInfo = @{ MPMediaItemPropertyTitle : currentFile.title,
  822. MPMediaItemPropertyPlaybackDuration : @(currentFile.duration.intValue / 1000.),
  823. MPNowPlayingInfoPropertyElapsedPlaybackTime : @(_mediaPlayer.time.intValue / 1000.),
  824. MPNowPlayingInfoPropertyPlaybackRate : @(_mediaPlayer.rate) };
  825. [MPNowPlayingInfoCenter defaultCenter].nowPlayingInfo = currentlyPlayingTrackInfo;
  826. }
  827. #pragma mark - autorotation
  828. - (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)toInterfaceOrientation {
  829. return UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPad
  830. || toInterfaceOrientation != UIInterfaceOrientationPortraitUpsideDown;
  831. }
  832. #pragma mark - AVSession delegate
  833. - (void)beginInterruption
  834. {
  835. if ([[[NSUserDefaults standardUserDefaults] objectForKey:kVLCSettingContinueAudioInBackgroundKey] boolValue])
  836. _shouldResumePlaying = YES;
  837. [_mediaPlayer pause];
  838. }
  839. - (void)endInterruption
  840. {
  841. if (_shouldResumePlaying) {
  842. [_mediaPlayer play];
  843. _shouldResumePlaying = NO;
  844. }
  845. }
  846. #pragma mark - External Display
  847. - (BOOL)hasExternalDisplay
  848. {
  849. return ([[UIScreen screens] count] > 1);
  850. }
  851. - (void)showOnExternalDisplay
  852. {
  853. UIScreen *screen = [UIScreen screens][1];
  854. screen.overscanCompensation = UIScreenOverscanCompensationInsetApplicationFrame;
  855. self.externalWindow = [[UIWindow alloc] initWithFrame:screen.bounds];
  856. UIViewController *controller = [[VLCExternalDisplayController alloc] init];
  857. self.externalWindow.rootViewController = controller;
  858. [controller.view addSubview:_movieView];
  859. controller.view.frame = screen.bounds;
  860. _movieView.frame = screen.bounds;
  861. self.playingExternallyView.hidden = NO;
  862. self.externalWindow.screen = screen;
  863. self.externalWindow.hidden = NO;
  864. }
  865. - (void)hideFromExternalDisplay
  866. {
  867. [self.view addSubview:_movieView];
  868. [self.view sendSubviewToBack:_movieView];
  869. _movieView.frame = self.view.frame;
  870. self.playingExternallyView.hidden = YES;
  871. self.externalWindow.hidden = YES;
  872. self.externalWindow = nil;
  873. }
  874. - (void)handleExternalScreenDidConnect:(NSNotification *)notification
  875. {
  876. [self showOnExternalDisplay];
  877. }
  878. - (void)handleExternalScreenDidDisconnect:(NSNotification *)notification
  879. {
  880. [self hideFromExternalDisplay];
  881. }
  882. @end