VLCMovieViewController.m 41 KB

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