VLCMovieViewController.m 40 KB

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