VLCMovieViewController.m 41 KB

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