VLCMovieViewController.m 41 KB

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