VLCMovieViewController.m 60 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555
  1. /*****************************************************************************
  2. * VLCMovieViewController.m
  3. * VLC for iOS
  4. *****************************************************************************
  5. * Copyright (c) 2013-2014 VideoLAN. All rights reserved.
  6. * $Id$
  7. *
  8. * Authors: Felix Paul Kühne <fkuehne # videolan.org>
  9. * Gleb Pinigin <gpinigin # gmail.com>
  10. * Ahmad Harb <harb.dev.leb # gmail.com>
  11. * Fabio Ritrovato <sephiroth87 # videolan.org>
  12. * Pierre SAGASPE <pierre.sagaspe # me.com>
  13. * Jean-Baptiste Kempf <jb # videolan.org>
  14. *
  15. * Refer to the COPYING file of the official project for license.
  16. *****************************************************************************/
  17. #import "VLCMovieViewController.h"
  18. #import "VLCExternalDisplayController.h"
  19. #import <AVFoundation/AVFoundation.h>
  20. #import <CommonCrypto/CommonDigest.h>
  21. #import "UIDevice+SpeedCategory.h"
  22. #import "VLCBugreporter.h"
  23. #import "VLCThumbnailsCache.h"
  24. #import "OBSlider.h"
  25. #import "VLCStatusLabel.h"
  26. #define INPUT_RATE_DEFAULT 1000.
  27. #define FORWARD_SWIPE_DURATION 30
  28. #define BACKWARD_SWIPE_DURATION 10
  29. @interface VLCMovieViewController () <UIGestureRecognizerDelegate, AVAudioSessionDelegate, VLCMediaDelegate>
  30. {
  31. VLCMediaListPlayer *_listPlayer;
  32. VLCMediaPlayer *_mediaPlayer;
  33. BOOL _controlsHidden;
  34. BOOL _videoFiltersHidden;
  35. BOOL _playbackSpeedViewHidden;
  36. UIActionSheet *_subtitleActionSheet;
  37. UIActionSheet *_audiotrackActionSheet;
  38. float _currentPlaybackRate;
  39. NSArray *_aspectRatios;
  40. NSUInteger _currentAspectRatioMask;
  41. NSTimer *_idleTimer;
  42. BOOL _shouldResumePlaying;
  43. BOOL _viewAppeared;
  44. BOOL _displayRemainingTime;
  45. BOOL _positionSet;
  46. BOOL _playerIsSetup;
  47. BOOL _isScrubbing;
  48. BOOL _swipeGesturesEnabled;
  49. NSString * panType;
  50. UIPinchGestureRecognizer *_pinchRecognizer;
  51. UIPanGestureRecognizer *_panRecognizer;
  52. UISwipeGestureRecognizer *_swipeRecognizerLeft;
  53. UISwipeGestureRecognizer *_swipeRecognizerRight;
  54. UITapGestureRecognizer *_tapRecognizer;
  55. UITapGestureRecognizer *_tapOnVideoRecognizer;
  56. }
  57. @property (nonatomic, strong) UIPopoverController *masterPopoverController;
  58. @property (nonatomic, strong) UIWindow *externalWindow;
  59. @end
  60. @implementation VLCMovieViewController
  61. + (void)initialize
  62. {
  63. NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
  64. NSDictionary *appDefaults = @{kVLCShowRemainingTime : @(YES)};
  65. [defaults registerDefaults:appDefaults];
  66. }
  67. - (void)dealloc
  68. {
  69. [[NSNotificationCenter defaultCenter] removeObserver:self];
  70. if (_tapRecognizer)
  71. [self.view removeGestureRecognizer:_tapRecognizer];
  72. if (_swipeRecognizerLeft)
  73. [self.view removeGestureRecognizer:_swipeRecognizerLeft];
  74. if (_swipeRecognizerRight)
  75. [self.view removeGestureRecognizer:_swipeRecognizerRight];
  76. if (_panRecognizer)
  77. [self.view removeGestureRecognizer:_panRecognizer];
  78. if (_pinchRecognizer)
  79. [self.view removeGestureRecognizer:_pinchRecognizer];
  80. [self.view removeGestureRecognizer:_tapOnVideoRecognizer];
  81. _tapRecognizer = nil;
  82. _swipeRecognizerLeft = nil;
  83. _swipeRecognizerRight = nil;
  84. _panRecognizer = nil;
  85. _pinchRecognizer = nil;
  86. _tapOnVideoRecognizer = nil;
  87. [[NSNotificationCenter defaultCenter] removeObserver:self];
  88. }
  89. #pragma mark - Managing the media item
  90. - (void)setFileFromMediaLibrary:(id)newFile
  91. {
  92. if (_fileFromMediaLibrary != newFile) {
  93. [self _stopPlayback];
  94. _fileFromMediaLibrary = newFile;
  95. if (_viewAppeared)
  96. [self _startPlayback];
  97. }
  98. if (self.masterPopoverController != nil)
  99. [self.masterPopoverController dismissPopoverAnimated:YES];
  100. }
  101. - (void)setUrl:(NSURL *)url
  102. {
  103. [self _stopPlayback];
  104. _url = url;
  105. _playerIsSetup = NO;
  106. if (_viewAppeared)
  107. [self _startPlayback];
  108. }
  109. - (void)setMediaList:(VLCMediaList *)mediaList
  110. {
  111. [self _stopPlayback];
  112. _mediaList = mediaList;
  113. _playerIsSetup = NO;
  114. if (_viewAppeared)
  115. [self _startPlayback];
  116. }
  117. - (void)viewDidLoad
  118. {
  119. [super viewDidLoad];
  120. self.wantsFullScreenLayout = YES;
  121. self.videoFilterView.hidden = YES;
  122. _videoFiltersHidden = YES;
  123. _hueLabel.text = NSLocalizedString(@"VFILTER_HUE", @"");
  124. _hueSlider.accessibilityLabel = _hueLabel.text;
  125. _hueSlider.isAccessibilityElement = YES;
  126. _contrastLabel.text = NSLocalizedString(@"VFILTER_CONTRAST", @"");
  127. _contrastSlider.accessibilityLabel = _contrastLabel.text;
  128. _contrastSlider.isAccessibilityElement = YES;
  129. _brightnessLabel.text = NSLocalizedString(@"VFILTER_BRIGHTNESS", @"");
  130. _brightnessSlider.accessibilityLabel = _brightnessLabel.text;
  131. _brightnessSlider.isAccessibilityElement = YES;
  132. _saturationLabel.text = NSLocalizedString(@"VFILTER_SATURATION", @"");
  133. _saturationSlider.accessibilityLabel = _saturationLabel.text;
  134. _saturationSlider.isAccessibilityElement = YES;
  135. _gammaLabel.text = NSLocalizedString(@"VFILTER_GAMMA", @"");
  136. _gammaSlider.accessibilityLabel = _gammaLabel.text;
  137. _gammaSlider.isAccessibilityElement = YES;
  138. _playbackSpeedLabel.text = NSLocalizedString(@"PLAYBACK_SPEED", @"");
  139. _playbackSpeedSlider.accessibilityLabel = _playbackSpeedLabel.text;
  140. _playbackSpeedSlider.isAccessibilityElement = YES;
  141. _positionSlider.accessibilityLabel = NSLocalizedString(@"PLAYBACK_POSITION", @"");
  142. _positionSlider.isAccessibilityElement = YES;
  143. _timeDisplay.isAccessibilityElement = YES;
  144. _audioSwitcherButton.accessibilityLabel = NSLocalizedString(@"CHOOSE_AUDIO_TRACK", @"");
  145. _audioSwitcherButton.isAccessibilityElement = YES;
  146. _audioSwitcherButtonLandscape.accessibilityLabel = NSLocalizedString(@"CHOOSE_AUDIO_TRACK", @"");
  147. _audioSwitcherButtonLandscape.isAccessibilityElement = YES;
  148. _subtitleSwitcherButton.accessibilityLabel = NSLocalizedString(@"CHOOSE_SUBTITLE_TRACK", @"");
  149. _subtitleSwitcherButton.isAccessibilityElement = YES;
  150. _subtitleSwitcherButtonLandscape.accessibilityLabel = NSLocalizedString(@"CHOOSE_SUBTITLE_TRACK", @"");
  151. _subtitleSwitcherButtonLandscape.isAccessibilityElement = YES;
  152. _playbackSpeedButton.accessibilityLabel = _playbackSpeedLabel.text;
  153. _playbackSpeedButton.isAccessibilityElement = YES;
  154. _playbackSpeedButtonLandscape.accessibilityLabel = _playbackSpeedLabel.text;
  155. _playbackSpeedButtonLandscape.isAccessibilityElement = YES;
  156. _videoFilterButton.accessibilityLabel = NSLocalizedString(@"VIDEO_FILTER", @"");
  157. _videoFilterButton.isAccessibilityElement = YES;
  158. _videoFilterButtonLandscape.accessibilityLabel = NSLocalizedString(@"VIDEO_FILTER", @"");
  159. _videoFilterButtonLandscape.isAccessibilityElement = YES;
  160. _resetVideoFilterButton.accessibilityLabel = NSLocalizedString(@"VIDEO_FILTER_RESET_BUTTON", @"");
  161. _resetVideoFilterButton.isAccessibilityElement = YES;
  162. _aspectRatioButton.accessibilityLabel = NSLocalizedString(@"VIDEO_ASPECT_RATIO_BUTTON", @"");
  163. _aspectRatioButton.isAccessibilityElement = YES;
  164. _playPauseButton.accessibilityLabel = NSLocalizedString(@"PLAY_PAUSE_BUTTON", @"");
  165. _playPauseButton.isAccessibilityElement = YES;
  166. _playPauseButtonLandscape.accessibilityLabel = NSLocalizedString(@"PLAY_PAUSE_BUTTON", @"");
  167. _playPauseButtonLandscape.isAccessibilityElement = YES;
  168. _bwdButton.accessibilityLabel = NSLocalizedString(@"BWD_BUTTON", @"");
  169. _bwdButton.isAccessibilityElement = YES;
  170. _bwdButtonLandscape.accessibilityLabel = NSLocalizedString(@"BWD_BUTTON", @"");
  171. _bwdButtonLandscape.isAccessibilityElement = YES;
  172. _fwdButton.accessibilityLabel = NSLocalizedString(@"FWD_BUTTON", @"");
  173. _fwdButton.isAccessibilityElement = YES;
  174. _fwdButtonLandscape.accessibilityLabel = NSLocalizedString(@"FWD_BUTTON", @"");
  175. _fwdButtonLandscape.isAccessibilityElement = YES;
  176. _repeatButton.accessibilityLabel = NSLocalizedString(@"BUTTON_REPEAT", @"");
  177. _repeatButton.isAccessibilityElement = YES;
  178. _scrubHelpLabel.text = NSLocalizedString(@"PLAYBACK_SCRUB_HELP", @"");
  179. self.playbackSpeedView.hidden = YES;
  180. _playbackSpeedViewHidden = YES;
  181. NSNotificationCenter *center = [NSNotificationCenter defaultCenter];
  182. [center addObserver:self selector:@selector(handleExternalScreenDidConnect:)
  183. name:UIScreenDidConnectNotification object:nil];
  184. [center addObserver:self selector:@selector(handleExternalScreenDidDisconnect:)
  185. name:UIScreenDidDisconnectNotification object:nil];
  186. [center addObserver:self selector:@selector(applicationWillResignActive:)
  187. name:UIApplicationWillResignActiveNotification object:nil];
  188. [center addObserver:self selector:@selector(applicationDidBecomeActive:)
  189. name:UIApplicationDidBecomeActiveNotification object:nil];
  190. [center addObserver:self selector:@selector(applicationDidEnterBackground:)
  191. name:UIApplicationDidEnterBackgroundNotification object:nil];
  192. [center addObserver:self selector:@selector(audioSessionRouteChange:)
  193. name:AVAudioSessionRouteChangeNotification object:nil];
  194. _playingExternallyTitle.text = NSLocalizedString(@"PLAYING_EXTERNALLY_TITLE", @"");
  195. _playingExternallyDescription.text = NSLocalizedString(@"PLAYING_EXTERNALLY_DESC", @"");
  196. if ([self hasExternalDisplay])
  197. [self showOnExternalDisplay];
  198. self.trackNameLabel.text = self.artistNameLabel.text = self.albumNameLabel.text = @"";
  199. _movieView.userInteractionEnabled = NO;
  200. _tapOnVideoRecognizer = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(toggleControlsVisible)];
  201. _tapOnVideoRecognizer.delegate = self;
  202. [self.view addGestureRecognizer:_tapOnVideoRecognizer];
  203. NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
  204. _displayRemainingTime = [[defaults objectForKey:kVLCShowRemainingTime] boolValue];
  205. _swipeGesturesEnabled = [[defaults objectForKey:kVLCSettingPlaybackGestures] boolValue];
  206. if (_swipeGesturesEnabled) {
  207. _pinchRecognizer = [[UIPinchGestureRecognizer alloc] initWithTarget:self action:@selector(handlePinchGesture:)];
  208. _pinchRecognizer.delegate = self;
  209. [self.view addGestureRecognizer:_pinchRecognizer];
  210. _tapRecognizer = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tapRecognized)];
  211. [_tapRecognizer setNumberOfTouchesRequired:2];
  212. _panRecognizer = [[UIPanGestureRecognizer alloc] initWithTarget:self action:@selector(panRecognized:)];
  213. [_panRecognizer setMinimumNumberOfTouches:1];
  214. [_panRecognizer setMaximumNumberOfTouches:1];
  215. _swipeRecognizerLeft = [[UISwipeGestureRecognizer alloc] initWithTarget:self action:@selector(swipeRecognized:)];
  216. _swipeRecognizerLeft.direction = UISwipeGestureRecognizerDirectionLeft;
  217. _swipeRecognizerRight = [[UISwipeGestureRecognizer alloc] initWithTarget:self action:@selector(swipeRecognized:)];
  218. _swipeRecognizerRight.direction = UISwipeGestureRecognizerDirectionRight;
  219. [self.view addGestureRecognizer:_swipeRecognizerLeft];
  220. [self.view addGestureRecognizer:_swipeRecognizerRight];
  221. [self.view addGestureRecognizer:_panRecognizer];
  222. [self.view addGestureRecognizer:_tapRecognizer];
  223. [_panRecognizer requireGestureRecognizerToFail:_swipeRecognizerLeft];
  224. [_panRecognizer requireGestureRecognizerToFail:_swipeRecognizerRight];
  225. _panRecognizer.delegate = self;
  226. _swipeRecognizerRight.delegate = self;
  227. _swipeRecognizerLeft.delegate = self;
  228. _tapRecognizer.delegate = self;
  229. }
  230. _aspectRatios = @[@"DEFAULT", @"FILL_TO_SCREEN", @"4:3", @"16:9", @"16:10", @"2.21:1"];
  231. [self.aspectRatioButton setImage:[UIImage imageNamed:@"ratioIcon"] forState:UIControlStateNormal];
  232. if (SYSTEM_RUNS_IOS7_OR_LATER) {
  233. self.backButton.tintColor = [UIColor colorWithRed:(190.0f/255.0f) green:(190.0f/255.0f) blue:(190.0f/255.0f) alpha:1.];
  234. self.toolbar.tintColor = [UIColor whiteColor];
  235. self.toolbar.barStyle = UIBarStyleBlack;
  236. CGRect rect = self.resetVideoFilterButton.frame;
  237. rect.origin.y = rect.origin.y + 5.;
  238. self.resetVideoFilterButton.frame = rect;
  239. rect = self.toolbar.frame;
  240. rect.size.height = rect.size.height + rect.origin.y;
  241. rect.origin.y = 0;
  242. self.toolbar.frame = rect;
  243. rect = self.aspectRatioButton.frame;
  244. rect.size.width -= 19.;
  245. rect.origin.x += 19.;
  246. self.aspectRatioButton.frame = rect;
  247. rect = self.timeDisplay.frame;
  248. rect.origin.x += 19.;
  249. self.timeDisplay.frame = rect;
  250. rect = self.positionSlider.frame;
  251. rect.size.width += 19.;
  252. self.positionSlider.frame = rect;
  253. } else {
  254. CGRect rect = self.positionSlider.frame;
  255. rect.origin.y = rect.origin.y + 3.;
  256. self.positionSlider.frame = rect;
  257. [self.aspectRatioButton setBackgroundImage:[UIImage imageNamed:@"ratioButton"] forState:UIControlStateNormal];
  258. [self.aspectRatioButton setBackgroundImage:[UIImage imageNamed:@"ratioButtonHighlight"] forState:UIControlStateHighlighted];
  259. [self.toolbar setBackgroundImage:[UIImage imageNamed:@"seekbarBg"] forBarMetrics:UIBarMetricsDefault];
  260. [self.backButton setBackgroundImage:[UIImage imageNamed:@"playbackDoneButton"] forState:UIControlStateNormal barMetrics:UIBarMetricsDefault];
  261. [self.backButton setBackgroundImage:[UIImage imageNamed:@"playbackDoneButtonHighlight"] forState:UIControlStateHighlighted barMetrics:UIBarMetricsDefault];
  262. }
  263. /* FIXME: there is a saner iOS 6+ API for this! */
  264. /* this looks a bit weird, but we need to support iOS 5 and should show the same appearance */
  265. void (^initVolumeSlider)(MPVolumeView *) = ^(MPVolumeView *volumeView){
  266. UISlider *volumeSlider = nil;
  267. for (id aView in volumeView.subviews){
  268. if ([[[aView class] description] isEqualToString:@"MPVolumeSlider"]){
  269. volumeSlider = (UISlider *)aView;
  270. break;
  271. }
  272. }
  273. if (!SYSTEM_RUNS_IOS7_OR_LATER) {
  274. [volumeSlider setMinimumTrackImage:[[UIImage imageNamed:@"sliderminiValue"]resizableImageWithCapInsets:UIEdgeInsetsMake(0, 4, 0, 0)] forState:UIControlStateNormal];
  275. [volumeSlider setMaximumTrackImage:[[UIImage imageNamed:@"slidermaxValue"] resizableImageWithCapInsets:UIEdgeInsetsMake(0, 0, 0, 4)] forState:UIControlStateNormal];
  276. [volumeSlider setThumbImage:[UIImage imageNamed:@"volumeballslider"] forState:UIControlStateNormal];
  277. } else
  278. [volumeView setVolumeThumbImage:[UIImage imageNamed:@"modernSliderKnob"] forState:UIControlStateNormal];
  279. [volumeSlider addTarget:self
  280. action:@selector(volumeSliderAction:)
  281. forControlEvents:UIControlEventValueChanged];
  282. };
  283. initVolumeSlider(self.volumeView);
  284. initVolumeSlider(self.volumeViewLandscape);
  285. [[AVAudioSession sharedInstance] setDelegate:self];
  286. if (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPad)
  287. self.positionSlider.scrubbingSpeedChangePositions = @[@(0.), @(100.), @(200.), @(300)];
  288. _playerIsSetup = NO;
  289. [self.movieView setAccessibilityLabel:NSLocalizedString(@"VO_VIDEOPLAYER_TITLE", @"")];
  290. [self.movieView setAccessibilityHint:NSLocalizedString(@"VO_VIDEOPLAYER_DOUBLETAP", @"")];
  291. }
  292. - (BOOL)_blobCheck
  293. {
  294. NSArray *searchPaths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
  295. NSString *directoryPath = searchPaths[0];
  296. if (![[NSFileManager defaultManager] fileExistsAtPath:[directoryPath stringByAppendingPathComponent:@"blob.bin"]])
  297. return NO;
  298. NSData *data = [NSData dataWithContentsOfFile:[directoryPath stringByAppendingPathComponent:@"blob.bin"]];
  299. uint8_t digest[CC_SHA1_DIGEST_LENGTH];
  300. CC_SHA1(data.bytes, (unsigned int)data.length, digest);
  301. NSMutableString *hash = [NSMutableString stringWithCapacity:CC_SHA1_DIGEST_LENGTH * 2];
  302. for (unsigned int u = 0; u < CC_SHA1_DIGEST_LENGTH; u++)
  303. [hash appendFormat:@"%02x", digest[u]];
  304. if ([hash isEqualToString:kBlobHash])
  305. return YES;
  306. else
  307. return NO;
  308. }
  309. - (void)viewWillAppear:(BOOL)animated
  310. {
  311. [super viewWillAppear:animated];
  312. _swipeGesturesEnabled = [[[NSUserDefaults standardUserDefaults] objectForKey:kVLCSettingPlaybackGestures] boolValue];
  313. [self.navigationController setNavigationBarHidden:YES animated:YES];
  314. if (!SYSTEM_RUNS_IOS7_OR_LATER) {
  315. if (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPhone)
  316. [UIApplication sharedApplication].statusBarStyle = UIStatusBarStyleBlackTranslucent;
  317. }
  318. [self _startPlayback];
  319. [self setControlsHidden:NO animated:YES];
  320. _viewAppeared = YES;
  321. }
  322. - (void)viewWillLayoutSubviews
  323. {
  324. if (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPhone) {
  325. CGSize viewSize = self.view.frame.size;
  326. if (UIDeviceOrientationIsLandscape([UIDevice currentDevice].orientation)) {
  327. [_controllerPanel removeFromSuperview];
  328. _controllerPanelLandscape.frame = (CGRect){CGPointMake(0, viewSize.height - _controllerPanelLandscape.frame.size.height), CGSizeMake(viewSize.width, _controllerPanelLandscape.frame.size.height)};
  329. [self.view addSubview:_controllerPanelLandscape];
  330. } else {
  331. [_controllerPanelLandscape removeFromSuperview];
  332. _controllerPanel.frame = (CGRect){CGPointMake(0, viewSize.height - _controllerPanel.frame.size.height), CGSizeMake(viewSize.width, _controllerPanel.frame.size.height)};
  333. [self.view addSubview:_controllerPanel];
  334. }
  335. }
  336. }
  337. - (void)_startPlayback
  338. {
  339. if (_playerIsSetup)
  340. return;
  341. NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
  342. if (!self.fileFromMediaLibrary && !self.url && !self.mediaList) {
  343. [self _stopPlayback];
  344. return;
  345. }
  346. NSMutableDictionary *mediaDictionary = [[NSMutableDictionary alloc] init];
  347. _listPlayer = [[VLCMediaListPlayer alloc] initWithOptions:@[[NSString stringWithFormat:@"--%@=%@", kVLCSettingSubtitlesFont, [self _resolveFontName]], [NSString stringWithFormat:@"--%@=%@", kVLCSettingSubtitlesFontColor, [defaults objectForKey:kVLCSettingSubtitlesFontColor]], [NSString stringWithFormat:@"--%@=%@", kVLCSettingSubtitlesFontSize, [defaults objectForKey:kVLCSettingSubtitlesFontSize]], [NSString stringWithFormat:@"--%@=%@", kVLCSettingNetworkCaching, [defaults objectForKey:kVLCSettingNetworkCaching]]]];
  348. _mediaPlayer = _listPlayer.mediaPlayer;
  349. [_mediaPlayer setDelegate:self];
  350. [_mediaPlayer setDrawable:self.movieView];
  351. if ([[defaults objectForKey:kVLCSettingDeinterlace] intValue] != 0)
  352. [_mediaPlayer setDeinterlaceFilter:@"blend"];
  353. else
  354. [_mediaPlayer setDeinterlaceFilter:nil];
  355. self.trackNameLabel.text = self.artistNameLabel.text = self.albumNameLabel.text = @"";
  356. VLCMedia *media;
  357. if (self.fileFromMediaLibrary) {
  358. MLFile *item = self.fileFromMediaLibrary;
  359. media = [VLCMedia mediaWithURL:[NSURL URLWithString:item.url]];
  360. } else if (self.mediaList) {
  361. media = [self.mediaList mediaAtIndex:self.itemInMediaListToBePlayedFirst];
  362. [media parse];
  363. } else {
  364. media = [VLCMedia mediaWithURL:self.url];
  365. [media parse];
  366. }
  367. [mediaDictionary setObject:[[defaults objectForKey:kVLCSettingStretchAudio] boolValue] ? kVLCSettingStretchAudioOnValue : kVLCSettingStretchAudioOffValue forKey:kVLCSettingStretchAudio];
  368. [mediaDictionary setObject:[defaults objectForKey:kVLCSettingTextEncoding] forKey:kVLCSettingTextEncoding];
  369. [mediaDictionary setObject:[defaults objectForKey:kVLCSettingSkipLoopFilter] forKey:kVLCSettingSkipLoopFilter];
  370. [NSTimeZone resetSystemTimeZone];
  371. NSString *tzName = [[NSTimeZone systemTimeZone] name];
  372. 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"];
  373. if ([tzNames containsObject:tzName] || [[tzName stringByDeletingLastPathComponent] isEqualToString:@"US"]) {
  374. NSArray *tracksInfo = media.tracksInformation;
  375. for (NSUInteger x = 0; x < tracksInfo.count; x++) {
  376. if ([[tracksInfo[x] objectForKey:VLCMediaTracksInformationType] isEqualToString:VLCMediaTracksInformationTypeAudio])
  377. {
  378. NSInteger fourcc = [[tracksInfo[x] objectForKey:VLCMediaTracksInformationCodec] integerValue];
  379. switch (fourcc) {
  380. case 540161377:
  381. case 1647457633:
  382. case 858612577:
  383. case 862151027:
  384. case 862151013:
  385. case 1684566644:
  386. case 2126701:
  387. {
  388. if (![self _blobCheck]) {
  389. [mediaDictionary setObject:[NSNull null] forKey:@"no-audio"];
  390. APLog(@"audio playback disabled because an unsupported codec was found");
  391. }
  392. break;
  393. }
  394. default:
  395. break;
  396. }
  397. }
  398. }
  399. }
  400. if (self.mediaList) {
  401. VLCMediaList *list = self.mediaList;
  402. NSUInteger count = list.count;
  403. for (NSUInteger x = 0; x < count; x++)
  404. [[list mediaAtIndex:x] addOptions:mediaDictionary];
  405. [_listPlayer setMediaList:self.mediaList];
  406. } else {
  407. [media addOptions:mediaDictionary];
  408. [_listPlayer setRootMedia:media];
  409. }
  410. [_listPlayer setRepeatMode:VLCDoNotRepeat];
  411. self.positionSlider.value = 0.;
  412. [self.timeDisplay setTitle:@"" forState:UIControlStateNormal];
  413. self.timeDisplay.accessibilityLabel = @"";
  414. [self.repeatButton setImage:[UIImage imageNamed:@"repeat"] forState:UIControlStateNormal];
  415. [self.repeatButtonLandscape setImage:[UIImage imageNamed:@"repeat"] forState:UIControlStateNormal];
  416. if (![self _isMediaSuitableForDevice]) {
  417. UIAlertView * alert = [[UIAlertView alloc] initWithTitle:NSLocalizedString(@"DEVICE_TOOSLOW_TITLE", @"") message:[NSString stringWithFormat:NSLocalizedString(@"DEVICE_TOOSLOW", @""), [[UIDevice currentDevice] model], self.fileFromMediaLibrary.title] delegate:self cancelButtonTitle:NSLocalizedString(@"BUTTON_CANCEL", @"") otherButtonTitles:NSLocalizedString(@"BUTTON_OPEN", @""), nil];
  418. [alert show];
  419. } else
  420. [self _playNewMedia];
  421. if (![self hasExternalDisplay])
  422. self.brightnessSlider.value = [UIScreen mainScreen].brightness * 2.;
  423. }
  424. - (BOOL)_isMediaSuitableForDevice
  425. {
  426. if (!self.fileFromMediaLibrary)
  427. return YES;
  428. NSUInteger totalNumberOfPixels = [[[self.fileFromMediaLibrary videoTrack] valueForKey:@"width"] doubleValue] * [[[self.fileFromMediaLibrary videoTrack] valueForKey:@"height"] doubleValue];
  429. NSInteger speedCategory = [[UIDevice currentDevice] speedCategory];
  430. if (speedCategory == 1) {
  431. // iPhone 3GS, iPhone 4, first gen. iPad, 3rd and 4th generation iPod touch
  432. return (totalNumberOfPixels < 600000); // between 480p and 720p
  433. } else if (speedCategory == 2) {
  434. // iPhone 4S, iPad 2 and 3, iPod 4 and 5
  435. return (totalNumberOfPixels < 922000); // 720p
  436. } else if (speedCategory == 3) {
  437. // iPhone 5, iPad 4
  438. return (totalNumberOfPixels < 2074000); // 1080p
  439. }
  440. return YES;
  441. }
  442. - (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
  443. {
  444. if (buttonIndex == 1)
  445. [self _playNewMedia];
  446. else {
  447. [self _stopPlayback];
  448. [self closePlayback:nil];
  449. }
  450. }
  451. - (void)_playNewMedia
  452. {
  453. NSNumber *playbackPositionInTime = @(0);
  454. CGFloat lastPosition = .0;
  455. NSInteger duration = 0;
  456. MLFile *matchedFile;
  457. if (self.fileFromMediaLibrary)
  458. matchedFile = self.fileFromMediaLibrary;
  459. else if (self.mediaList) {
  460. NSArray *matches = [MLFile fileForURL:[[[self.mediaList mediaAtIndex:self.itemInMediaListToBePlayedFirst] url] absoluteString]];
  461. if (matches.count > 0) {
  462. matchedFile = matches[0];
  463. lastPosition = matchedFile.lastPosition.floatValue;
  464. }
  465. }
  466. if (matchedFile.lastPosition)
  467. lastPosition = matchedFile.lastPosition.floatValue;
  468. duration = matchedFile.duration.intValue;
  469. if (lastPosition < .95) {
  470. if (duration != 0)
  471. playbackPositionInTime = @(lastPosition * (duration / 1000.));
  472. }
  473. if (playbackPositionInTime.intValue > 0 && (duration * lastPosition - duration) < -60000) {
  474. [_mediaPlayer.media addOptions:@{@"start-time": playbackPositionInTime}];
  475. APLog(@"set starttime to %i", playbackPositionInTime.intValue);
  476. }
  477. [_mediaPlayer addObserver:self forKeyPath:@"time" options:0 context:nil];
  478. [_mediaPlayer addObserver:self forKeyPath:@"remainingTime" options:0 context:nil];
  479. if (self.mediaList)
  480. [_listPlayer playItemAtIndex:self.itemInMediaListToBePlayedFirst];
  481. else
  482. [_listPlayer playMedia:_listPlayer.rootMedia];
  483. if (matchedFile) {
  484. if (matchedFile.lastAudioTrack.intValue > 0)
  485. _mediaPlayer.currentAudioTrackIndex = matchedFile.lastAudioTrack.intValue;
  486. if (matchedFile.lastSubtitleTrack.intValue > 0)
  487. _mediaPlayer.currentVideoSubTitleIndex = matchedFile.lastSubtitleTrack.intValue;
  488. }
  489. self.playbackSpeedSlider.value = [self _playbackSpeed];
  490. [self _updatePlaybackSpeedIndicator];
  491. _currentAspectRatioMask = 0;
  492. _mediaPlayer.videoAspectRatio = NULL;
  493. /* some demuxers don't respect :start-time, so re-try here */
  494. if (lastPosition < .95 && _mediaPlayer.position < lastPosition && (duration * lastPosition - duration) < -60000)
  495. _mediaPlayer.position = lastPosition;
  496. [self _resetIdleTimer];
  497. _playerIsSetup = YES;
  498. }
  499. - (void)viewWillDisappear:(BOOL)animated
  500. {
  501. [self _stopPlayback];
  502. _viewAppeared = NO;
  503. if (_idleTimer) {
  504. [_idleTimer invalidate];
  505. _idleTimer = nil;
  506. }
  507. [self.navigationController setNavigationBarHidden:NO animated:YES];
  508. if (!SYSTEM_RUNS_IOS7_OR_LATER)
  509. [UIApplication sharedApplication].statusBarStyle = UIStatusBarStyleBlackOpaque;
  510. [[UIApplication sharedApplication] setStatusBarHidden:NO withAnimation:UIStatusBarAnimationFade];
  511. [super viewWillDisappear:animated];
  512. // hide filter UI for next run
  513. if (!_videoFiltersHidden)
  514. _videoFiltersHidden = YES;
  515. if (!_playbackSpeedViewHidden)
  516. _playbackSpeedViewHidden = YES;
  517. }
  518. - (void)_stopPlayback
  519. {
  520. if (_mediaPlayer) {
  521. @try {
  522. [_mediaPlayer removeObserver:self forKeyPath:@"time"];
  523. [_mediaPlayer removeObserver:self forKeyPath:@"remainingTime"];
  524. }
  525. @catch (NSException *exception) {
  526. APLog(@"we weren't an observer yet");
  527. }
  528. if (_mediaPlayer.media) {
  529. [_mediaPlayer pause];
  530. [self _saveCurrentState];
  531. [_mediaPlayer stop];
  532. }
  533. if (_mediaPlayer)
  534. _mediaPlayer = nil;
  535. if (_listPlayer)
  536. _listPlayer = nil;
  537. }
  538. if (_fileFromMediaLibrary)
  539. _fileFromMediaLibrary = nil;
  540. if (_mediaList)
  541. _mediaList = nil;
  542. if (_url)
  543. _url = nil;
  544. _playerIsSetup = NO;
  545. }
  546. - (void)_saveCurrentState
  547. {
  548. if (self.fileFromMediaLibrary) {
  549. @try {
  550. MLFile *item = self.fileFromMediaLibrary;
  551. item.lastPosition = @([_mediaPlayer position]);
  552. item.lastAudioTrack = @(_mediaPlayer.currentAudioTrackIndex);
  553. item.lastSubtitleTrack = @(_mediaPlayer.currentVideoSubTitleIndex);
  554. }
  555. @catch (NSException *exception) {
  556. APLog(@"failed to save current media state - file removed?");
  557. }
  558. } else {
  559. NSArray *files = [MLFile fileForURL:[[_mediaPlayer.media url] absoluteString]];
  560. if (files.count > 0) {
  561. MLFile *fileFromList = files[0];
  562. fileFromList.lastPosition = @([_mediaPlayer position]);
  563. fileFromList.lastAudioTrack = @(_mediaPlayer.currentAudioTrackIndex);
  564. fileFromList.lastSubtitleTrack = @(_mediaPlayer.currentVideoSubTitleIndex);
  565. }
  566. }
  567. }
  568. - (NSString *)_resolveFontName
  569. {
  570. NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
  571. BOOL bold = [[defaults objectForKey:kVLCSettingSubtitlesBoldFont] boolValue];
  572. NSString *font = [defaults objectForKey:kVLCSettingSubtitlesFont];
  573. NSDictionary *fontMap = @{
  574. @"AmericanTypewriter": @"AmericanTypewriter-Bold",
  575. @"ArialMT": @"Arial-BoldMT",
  576. @"ArialHebrew": @"ArialHebrew-Bold",
  577. @"ChalkboardSE-Regular": @"ChalkboardSE-Bold",
  578. @"CourierNewPSMT": @"CourierNewPS-BoldMT",
  579. @"Georgia": @"Georgia-Bold",
  580. @"GillSans": @"GillSans-Bold",
  581. @"GujaratiSangamMN": @"GujaratiSangamMN-Bold",
  582. @"STHeitiSC-Light": @"STHeitiSC-Medium",
  583. @"STHeitiTC-Light": @"STHeitiTC-Medium",
  584. @"HelveticaNeue": @"HelveticaNeue-Bold",
  585. @"HiraKakuProN-W3": @"HiraKakuProN-W6",
  586. @"HiraMinProN-W3": @"HiraMinProN-W6",
  587. @"HoeflerText-Regular": @"HoeflerText-Black",
  588. @"Kailasa": @"Kailasa-Bold",
  589. @"KannadaSangamMN": @"KannadaSangamMN-Bold",
  590. @"MalayalamSangamMN": @"MalayalamSangamMN-Bold",
  591. @"OriyaSangamMN": @"OriyaSangamMN-Bold",
  592. @"SinhalaSangamMN": @"SinhalaSangamMN-Bold",
  593. @"SnellRoundhand": @"SnellRoundhand-Bold",
  594. @"TamilSangamMN": @"TamilSangamMN-Bold",
  595. @"TeluguSangamMN": @"TeluguSangamMN-Bold",
  596. @"TimesNewRomanPSMT": @"TimesNewRomanPS-BoldMT",
  597. @"Zapfino": @"Zapfino"
  598. };
  599. if (!bold) {
  600. return font;
  601. } else {
  602. return fontMap[font];
  603. }
  604. }
  605. #pragma mark - remote events
  606. - (void)viewDidAppear:(BOOL)animated
  607. {
  608. [super viewDidAppear:animated];
  609. [[UIApplication sharedApplication] beginReceivingRemoteControlEvents];
  610. [self becomeFirstResponder];
  611. }
  612. - (void)viewDidDisappear:(BOOL)animated
  613. {
  614. [super viewDidDisappear:animated];
  615. [[UIApplication sharedApplication] endReceivingRemoteControlEvents];
  616. [self resignFirstResponder];
  617. [[NSUserDefaults standardUserDefaults] setBool:_displayRemainingTime forKey:kVLCShowRemainingTime];
  618. }
  619. - (BOOL)canBecomeFirstResponder
  620. {
  621. return YES;
  622. }
  623. - (void)remoteControlReceivedWithEvent:(UIEvent *)event
  624. {
  625. switch (event.subtype) {
  626. case UIEventSubtypeRemoteControlPlay:
  627. [_listPlayer play];
  628. break;
  629. case UIEventSubtypeRemoteControlPause:
  630. [_listPlayer pause];
  631. break;
  632. case UIEventSubtypeRemoteControlTogglePlayPause:
  633. [self playPause];
  634. break;
  635. case UIEventSubtypeRemoteControlNextTrack:
  636. [self forward:nil];
  637. break;
  638. case UIEventSubtypeRemoteControlPreviousTrack:
  639. [self backward:nil];
  640. break;
  641. case UIEventSubtypeRemoteControlStop:
  642. [self closePlayback:nil];
  643. break;
  644. default:
  645. break;
  646. }
  647. }
  648. #pragma mark - controls visibility
  649. - (void)handlePinchGesture:(UIPinchGestureRecognizer *)recognizer
  650. {
  651. if (!_swipeGesturesEnabled)
  652. return;
  653. if (recognizer.velocity < 0.)
  654. [self closePlayback:nil];
  655. }
  656. - (BOOL)gestureRecognizer:(UIGestureRecognizer *)gestureRecognizer shouldReceiveTouch:(UITouch *)touch
  657. {
  658. if (!_swipeGesturesEnabled)
  659. return NO;
  660. if (touch.view != self.view)
  661. return NO;
  662. return YES;
  663. }
  664. - (BOOL)gestureRecognizer:(UIGestureRecognizer *)gestureRecognizer shouldRecognizeSimultaneouslyWithGestureRecognizer:(UIGestureRecognizer *)otherGestureRecognizer
  665. {
  666. if (!_swipeGesturesEnabled)
  667. return NO;
  668. return YES;
  669. }
  670. - (void)setControlsHidden:(BOOL)hidden animated:(BOOL)animated
  671. {
  672. _controlsHidden = hidden;
  673. CGFloat alpha = _controlsHidden? 0.0f: 1.0f;
  674. if (!_controlsHidden) {
  675. _controllerPanel.alpha = 0.0f;
  676. _controllerPanel.hidden = !_videoFiltersHidden;
  677. _controllerPanelLandscape.alpha = 0.0f;
  678. _controllerPanelLandscape.hidden = !_videoFiltersHidden;
  679. _toolbar.alpha = 0.0f;
  680. _toolbar.hidden = NO;
  681. _videoFilterView.alpha = 0.0f;
  682. _videoFilterView.hidden = _videoFiltersHidden;
  683. _playbackSpeedView.alpha = 0.0f;
  684. _playbackSpeedView.hidden = _playbackSpeedViewHidden;
  685. }
  686. void (^animationBlock)() = ^() {
  687. _controllerPanel.alpha = alpha;
  688. _controllerPanelLandscape.alpha = alpha;
  689. _toolbar.alpha = alpha;
  690. _videoFilterView.alpha = alpha;
  691. _playbackSpeedView.alpha = alpha;
  692. };
  693. void (^completionBlock)(BOOL finished) = ^(BOOL finished) {
  694. _controllerPanel.hidden = _videoFiltersHidden ? _controlsHidden : NO;
  695. _controllerPanelLandscape.hidden = _videoFiltersHidden ? _controlsHidden : NO;
  696. _toolbar.hidden = _controlsHidden;
  697. _videoFilterView.hidden = _videoFiltersHidden;
  698. _playbackSpeedView.hidden = _playbackSpeedViewHidden;
  699. };
  700. UIStatusBarAnimation animationType = animated? UIStatusBarAnimationFade: UIStatusBarAnimationNone;
  701. NSTimeInterval animationDuration = animated? 0.3: 0.0;
  702. [[UIApplication sharedApplication] setStatusBarHidden:_viewAppeared ? _controlsHidden : NO withAnimation:animationType];
  703. [UIView animateWithDuration:animationDuration animations:animationBlock completion:completionBlock];
  704. _volumeView.hidden = _volumeViewLandscape.hidden = _controllerPanel.hidden;
  705. }
  706. - (void)toggleControlsVisible
  707. {
  708. if (_controlsHidden && !_videoFiltersHidden)
  709. _videoFiltersHidden = YES;
  710. [self setControlsHidden:!_controlsHidden animated:YES];
  711. }
  712. - (void)_resetIdleTimer
  713. {
  714. if (!_idleTimer)
  715. _idleTimer = [NSTimer scheduledTimerWithTimeInterval:4.
  716. target:self
  717. selector:@selector(idleTimerExceeded)
  718. userInfo:nil
  719. repeats:NO];
  720. else {
  721. if (fabs([_idleTimer.fireDate timeIntervalSinceNow]) < 4.)
  722. [_idleTimer setFireDate:[NSDate dateWithTimeIntervalSinceNow:4.]];
  723. }
  724. }
  725. - (void)idleTimerExceeded
  726. {
  727. _idleTimer = nil;
  728. if (!_controlsHidden)
  729. [self toggleControlsVisible];
  730. if (!_videoFiltersHidden)
  731. _videoFiltersHidden = YES;
  732. if (!_playbackSpeedViewHidden)
  733. _playbackSpeedViewHidden = YES;
  734. if (self.scrubIndicatorView.hidden == NO)
  735. self.scrubIndicatorView.hidden = YES;
  736. }
  737. - (UIResponder *)nextResponder
  738. {
  739. [self _resetIdleTimer];
  740. return [super nextResponder];
  741. }
  742. #pragma mark - controls
  743. - (IBAction)closePlayback:(id)sender
  744. {
  745. [self setControlsHidden:NO animated:NO];
  746. [self.navigationController dismissViewControllerAnimated:YES completion:nil];
  747. }
  748. - (IBAction)positionSliderAction:(UISlider *)sender
  749. {
  750. /* we need to limit the number of events sent by the slider, since otherwise, the user
  751. * wouldn't see the I-frames when seeking on current mobile devices. This isn't a problem
  752. * within the Simulator, but especially on older ARMv7 devices, it's clearly noticeable. */
  753. [self performSelector:@selector(_setPositionForReal) withObject:nil afterDelay:0.3];
  754. VLCTime *newPosition = [VLCTime timeWithInt:(int)(_positionSlider.value * self.fileFromMediaLibrary.duration.intValue)];
  755. [self.timeDisplay setTitle:newPosition.stringValue forState:UIControlStateNormal];
  756. self.timeDisplay.accessibilityLabel = [NSString stringWithFormat:@"%@: %@", NSLocalizedString(@"PLAYBACK_POSITION", @""), newPosition.stringValue];
  757. _positionSet = NO;
  758. [self _resetIdleTimer];
  759. }
  760. - (void)_setPositionForReal
  761. {
  762. if (!_positionSet) {
  763. _mediaPlayer.position = _positionSlider.value;
  764. _positionSet = YES;
  765. }
  766. }
  767. - (IBAction)positionSliderTouchDown:(id)sender
  768. {
  769. [self _updateScrubLabel];
  770. self.scrubIndicatorView.hidden = NO;
  771. _isScrubbing = YES;
  772. }
  773. - (IBAction)positionSliderTouchUp:(id)sender
  774. {
  775. self.scrubIndicatorView.hidden = YES;
  776. _isScrubbing = NO;
  777. }
  778. - (void)_updateScrubLabel
  779. {
  780. float speed = self.positionSlider.scrubbingSpeed;
  781. if (speed == 1.)
  782. self.currentScrubSpeedLabel.text = NSLocalizedString(@"PLAYBACK_SCRUB_HIGH", @"");
  783. else if (speed == .5)
  784. self.currentScrubSpeedLabel.text = NSLocalizedString(@"PLAYBACK_SCRUB_HALF", @"");
  785. else if (speed == .25)
  786. self.currentScrubSpeedLabel.text = NSLocalizedString(@"PLAYBACK_SCRUB_QUARTER", @"");
  787. else
  788. self.currentScrubSpeedLabel.text = NSLocalizedString(@"PLAYBACK_SCRUB_FINE", @"");
  789. [self _resetIdleTimer];
  790. }
  791. - (IBAction)positionSliderDrag:(id)sender
  792. {
  793. [self _updateScrubLabel];
  794. }
  795. - (IBAction)volumeSliderAction:(id)sender
  796. {
  797. [self _resetIdleTimer];
  798. }
  799. - (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context
  800. {
  801. if (!_isScrubbing) {
  802. self.positionSlider.value = [_mediaPlayer position];
  803. }
  804. if (_displayRemainingTime)
  805. [self.timeDisplay setTitle:[[_mediaPlayer remainingTime] stringValue] forState:UIControlStateNormal];
  806. else
  807. [self.timeDisplay setTitle:[[_mediaPlayer time] stringValue] forState:UIControlStateNormal];
  808. }
  809. - (void)mediaPlayerStateChanged:(NSNotification *)aNotification
  810. {
  811. VLCMediaPlayerState currentState = _mediaPlayer.state;
  812. if (currentState == VLCMediaPlayerStateBuffering) {
  813. /* attach delegate */
  814. _mediaPlayer.media.delegate = self;
  815. /* let's update meta data */
  816. [self _updateDisplayedMetadata];
  817. }
  818. if (currentState == VLCMediaPlayerStateError) {
  819. [self.statusLabel showStatusMessage:NSLocalizedString(@"PLAYBACK_FAILED", @"")];
  820. [self performSelector:@selector(closePlayback:) withObject:nil afterDelay:2.];
  821. }
  822. if ((currentState == VLCMediaPlayerStateEnded || currentState == VLCMediaPlayerStateStopped) && _listPlayer.repeatMode == VLCDoNotRepeat) {
  823. if ([_listPlayer.mediaList indexOfMedia:_mediaPlayer.media] == _listPlayer.mediaList.count - 1)
  824. [self performSelector:@selector(closePlayback:) withObject:nil afterDelay:2.];
  825. }
  826. UIImage *playPauseImage = [_mediaPlayer isPlaying]? [UIImage imageNamed:@"pauseIcon"] : [UIImage imageNamed:@"playIcon"];
  827. [_playPauseButton setImage:playPauseImage forState:UIControlStateNormal];
  828. [_playPauseButtonLandscape setImage:playPauseImage forState:UIControlStateNormal];
  829. if ([[_mediaPlayer audioTrackIndexes] count] > 2) {
  830. self.audioSwitcherButton.hidden = NO;
  831. self.audioSwitcherButtonLandscape.hidden = NO;
  832. } else {
  833. self.audioSwitcherButton.hidden = YES;
  834. self.audioSwitcherButtonLandscape.hidden = YES;
  835. }
  836. if ([[_mediaPlayer videoSubTitlesIndexes] count] > 1) {
  837. self.subtitleContainer.hidden = NO;
  838. self.subtitleContainerLandscape.hidden = NO;
  839. } else {
  840. self.subtitleContainer.hidden = YES;
  841. self.subtitleContainerLandscape.hidden = YES;
  842. }
  843. }
  844. - (IBAction)playPause
  845. {
  846. if ([_mediaPlayer isPlaying])
  847. [_listPlayer pause];
  848. else
  849. [_listPlayer play];
  850. }
  851. - (IBAction)forward:(id)sender
  852. {
  853. if (self.mediaList)
  854. [_listPlayer next];
  855. else
  856. [_mediaPlayer mediumJumpForward];
  857. }
  858. - (IBAction)backward:(id)sender
  859. {
  860. if (self.mediaList)
  861. [_listPlayer previous];
  862. else
  863. [_mediaPlayer mediumJumpBackward];
  864. }
  865. - (void)toggleRepeatMode:(id)sender
  866. {
  867. if (_listPlayer.repeatMode == VLCDoNotRepeat) {
  868. _listPlayer.repeatMode = VLCRepeatCurrentItem;
  869. [self.repeatButton setImage:[UIImage imageNamed:@"repeatOne"] forState:UIControlStateNormal];
  870. [self.repeatButtonLandscape setImage:[UIImage imageNamed:@"repeatOne"] forState:UIControlStateNormal];
  871. } else {
  872. _listPlayer.repeatMode = VLCDoNotRepeat;
  873. [self.repeatButton setImage:[UIImage imageNamed:@"repeat"] forState:UIControlStateNormal];
  874. [self.repeatButtonLandscape setImage:[UIImage imageNamed:@"repeat"] forState:UIControlStateNormal];
  875. }
  876. }
  877. - (IBAction)switchAudioTrack:(id)sender
  878. {
  879. _audiotrackActionSheet = [[UIActionSheet alloc] initWithTitle:NSLocalizedString(@"CHOOSE_AUDIO_TRACK", @"audio track selector") delegate:self cancelButtonTitle:nil destructiveButtonTitle:nil otherButtonTitles: nil];
  880. NSArray *audioTracks = [_mediaPlayer audioTrackNames];
  881. NSArray *audioTrackIndexes = [_mediaPlayer audioTrackIndexes];
  882. NSUInteger count = [audioTracks count];
  883. for (NSUInteger i = 0; i < count; i++) {
  884. NSString *indexIndicator = ([audioTrackIndexes[i] intValue] == [_mediaPlayer currentAudioTrackIndex])? @"\u2713": @"";
  885. NSString *buttonTitle = [NSString stringWithFormat:@"%@ %@", indexIndicator, audioTracks[i]];
  886. [_audiotrackActionSheet addButtonWithTitle:buttonTitle];
  887. }
  888. [_audiotrackActionSheet addButtonWithTitle:NSLocalizedString(@"BUTTON_CANCEL", @"cancel button")];
  889. [_audiotrackActionSheet setCancelButtonIndex:[_audiotrackActionSheet numberOfButtons] - 1];
  890. [_audiotrackActionSheet showInView:(UIButton *)sender];
  891. }
  892. - (IBAction)switchSubtitleTrack:(id)sender
  893. {
  894. NSArray *spuTracks = [_mediaPlayer videoSubTitlesNames];
  895. NSArray *spuTrackIndexes = [_mediaPlayer videoSubTitlesIndexes];
  896. NSUInteger count = [spuTracks count];
  897. if (count <= 1)
  898. return;
  899. _subtitleActionSheet = [[UIActionSheet alloc] initWithTitle:NSLocalizedString(@"CHOOSE_SUBTITLE_TRACK", @"subtitle track selector") delegate:self cancelButtonTitle:nil destructiveButtonTitle:nil otherButtonTitles: nil];
  900. for (NSUInteger i = 0; i < count; i++) {
  901. NSString *indexIndicator = ([spuTrackIndexes[i] intValue] == [_mediaPlayer currentVideoSubTitleIndex])? @"\u2713": @"";
  902. NSString *buttonTitle = [NSString stringWithFormat:@"%@ %@", indexIndicator, spuTracks[i]];
  903. [_subtitleActionSheet addButtonWithTitle:buttonTitle];
  904. }
  905. [_subtitleActionSheet addButtonWithTitle:NSLocalizedString(@"BUTTON_CANCEL", @"cancel button")];
  906. [_subtitleActionSheet setCancelButtonIndex:[_subtitleActionSheet numberOfButtons] - 1];
  907. [_subtitleActionSheet showInView:(UIButton *)sender];
  908. }
  909. - (void)actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex
  910. {
  911. if (buttonIndex == [actionSheet cancelButtonIndex])
  912. return;
  913. NSArray *indexArray;
  914. if (actionSheet == _subtitleActionSheet) {
  915. indexArray = _mediaPlayer.videoSubTitlesIndexes;
  916. if (buttonIndex <= indexArray.count) {
  917. _mediaPlayer.currentVideoSubTitleIndex = [indexArray[buttonIndex] intValue];
  918. }
  919. } else if (actionSheet == _audiotrackActionSheet) {
  920. indexArray = _mediaPlayer.audioTrackIndexes;
  921. if (buttonIndex <= indexArray.count) {
  922. _mediaPlayer.currentAudioTrackIndex = [indexArray[buttonIndex] intValue];
  923. }
  924. }
  925. }
  926. - (IBAction)toggleTimeDisplay:(id)sender
  927. {
  928. _displayRemainingTime = !_displayRemainingTime;
  929. [self _resetIdleTimer];
  930. }
  931. #pragma mark - multi-touch gestures
  932. - (void)tapRecognized
  933. {
  934. if ([_mediaPlayer isPlaying]) {
  935. [_listPlayer pause];
  936. [self.statusLabel showStatusMessage:@" ▌▌"];
  937. } else {
  938. [_listPlayer play];
  939. [self.statusLabel showStatusMessage:@" ►"];
  940. }
  941. }
  942. - (NSString*)detectPanTypeForPan:(UIPanGestureRecognizer*)panRecognizer
  943. {
  944. NSString * type;
  945. NSString * deviceType = [[UIDevice currentDevice] model];
  946. type = @"Volume"; // default in case of error
  947. CGPoint location = [panRecognizer locationInView:self.view];
  948. CGFloat position = location.x;
  949. UIInterfaceOrientation orientation = [[UIApplication sharedApplication] statusBarOrientation];
  950. CGRect screenRect = [[UIScreen mainScreen] bounds];
  951. CGFloat screenWidth = .0;
  952. if (orientation == UIDeviceOrientationPortrait)
  953. screenWidth = screenRect.size.width;
  954. else
  955. screenWidth = screenRect.size.height;
  956. if (position < screenWidth / 2)
  957. type = @"Brightness";
  958. if (position > screenWidth / 2)
  959. type = @"Volume";
  960. // only check for seeking gesture if on iPad , will overwrite last statements if true
  961. if ([deviceType isEqualToString:@"iPad"]) {
  962. if (location.y < 110)
  963. type = @"Seek";
  964. }
  965. return type;
  966. }
  967. - (void)panRecognized:(UIPanGestureRecognizer*)panRecognizer
  968. {
  969. CGFloat panDirectionX = [panRecognizer velocityInView:self.view].x;
  970. CGFloat panDirectionY = [panRecognizer velocityInView:self.view].y;
  971. if (panRecognizer.state == UIGestureRecognizerStateBegan) // Only Detect pantype when began to allow more freedom
  972. panType = [self detectPanTypeForPan:panRecognizer];
  973. if ([panType isEqual:@"Seek"]) {
  974. double timeRemainingDouble = (-_mediaPlayer.remainingTime.intValue*0.001);
  975. int timeRemaining = timeRemainingDouble;
  976. if (panDirectionX > 0) {
  977. if (timeRemaining > 2 ) // to not go outside duration , video will stop
  978. [_mediaPlayer jumpForward:1];
  979. } else
  980. [_mediaPlayer jumpBackward:1];
  981. } else if ([panType isEqual:@"Volume"]) {
  982. MPMusicPlayerController *musicPlayer = [MPMusicPlayerController applicationMusicPlayer];
  983. if (panDirectionY > 0)
  984. musicPlayer.volume -= 0.01;
  985. else
  986. musicPlayer.volume += 0.01;
  987. } else if ([panType isEqual:@"Brightness"]) {
  988. CGFloat brightness = [UIScreen mainScreen].brightness;
  989. if (panDirectionY > 0)
  990. brightness = brightness - 0.01;
  991. else
  992. brightness = brightness + 0.01;
  993. [[UIScreen mainScreen] setBrightness:brightness];
  994. self.brightnessSlider.value = brightness * 2.;
  995. NSString *brightnessHUD = [NSString stringWithFormat:@"%@: %@ %%", NSLocalizedString(@"VFILTER_BRIGHTNESS", @""), [[[NSString stringWithFormat:@"%f",(brightness*100)] componentsSeparatedByString:@"."] objectAtIndex:0]];
  996. [self.statusLabel showStatusMessage:brightnessHUD];
  997. }
  998. if (panRecognizer.state == UIGestureRecognizerStateEnded) {
  999. if ([_mediaPlayer isPlaying])
  1000. [_listPlayer play];
  1001. }
  1002. }
  1003. - (void)swipeRecognized:(UISwipeGestureRecognizer*)swipeRecognizer
  1004. {
  1005. NSString * hudString = @" ";
  1006. if (swipeRecognizer.direction == UISwipeGestureRecognizerDirectionRight) {
  1007. double timeRemainingDouble = (-_mediaPlayer.remainingTime.intValue*0.001);
  1008. int timeRemaining = timeRemainingDouble;
  1009. if (FORWARD_SWIPE_DURATION < timeRemaining) {
  1010. [_mediaPlayer jumpForward:FORWARD_SWIPE_DURATION];
  1011. hudString = [NSString stringWithFormat:@"⇒ %is", FORWARD_SWIPE_DURATION];
  1012. } else {
  1013. [_mediaPlayer jumpForward:(timeRemaining - 5)];
  1014. hudString = [NSString stringWithFormat:@"⇒ %is",(timeRemaining - 5)];
  1015. }
  1016. }
  1017. else if (swipeRecognizer.direction == UISwipeGestureRecognizerDirectionLeft) {
  1018. [_mediaPlayer jumpBackward:BACKWARD_SWIPE_DURATION];
  1019. hudString = [NSString stringWithFormat:@"⇐ %is",BACKWARD_SWIPE_DURATION];
  1020. }
  1021. if (swipeRecognizer.state == UIGestureRecognizerStateEnded) {
  1022. if ([_mediaPlayer isPlaying])
  1023. [_listPlayer play];
  1024. [self.statusLabel showStatusMessage:hudString];
  1025. }
  1026. }
  1027. #pragma mark - Video Filter UI
  1028. - (IBAction)videoFilterToggle:(id)sender
  1029. {
  1030. if (!_playbackSpeedViewHidden)
  1031. self.playbackSpeedView.hidden = _playbackSpeedViewHidden = YES;
  1032. if (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPhone) {
  1033. if (!_controlsHidden) {
  1034. self.controllerPanel.hidden = _controlsHidden = YES;
  1035. self.controllerPanelLandscape.hidden = YES;
  1036. }
  1037. }
  1038. self.videoFilterView.hidden = !_videoFiltersHidden;
  1039. _videoFiltersHidden = self.videoFilterView.hidden;
  1040. }
  1041. - (IBAction)videoFilterSliderAction:(id)sender
  1042. {
  1043. if (sender == self.hueSlider)
  1044. _mediaPlayer.hue = (int)self.hueSlider.value;
  1045. else if (sender == self.contrastSlider)
  1046. _mediaPlayer.contrast = self.contrastSlider.value;
  1047. else if (sender == self.brightnessSlider) {
  1048. if ([self hasExternalDisplay])
  1049. _mediaPlayer.brightness = self.brightnessSlider.value;
  1050. else
  1051. [[UIScreen mainScreen] setBrightness:(self.brightnessSlider.value / 2.)];
  1052. } else if (sender == self.saturationSlider)
  1053. _mediaPlayer.saturation = self.saturationSlider.value;
  1054. else if (sender == self.gammaSlider)
  1055. _mediaPlayer.gamma = self.gammaSlider.value;
  1056. else if (sender == self.resetVideoFilterButton) {
  1057. _mediaPlayer.hue = self.hueSlider.value = 0.;
  1058. _mediaPlayer.contrast = self.contrastSlider.value = 1.;
  1059. _mediaPlayer.brightness = self.brightnessSlider.value = 1.;
  1060. [[UIScreen mainScreen] setBrightness:(self.brightnessSlider.value / 2.)];
  1061. _mediaPlayer.saturation = self.saturationSlider.value = 1.;
  1062. _mediaPlayer.gamma = self.gammaSlider.value = 1.;
  1063. } else
  1064. APLog(@"unknown sender for videoFilterSliderAction");
  1065. [self _resetIdleTimer];
  1066. }
  1067. #pragma mark - playback view
  1068. - (IBAction)playbackSpeedSliderAction:(UISlider *)sender
  1069. {
  1070. double speed = pow(2, sender.value / 17.);
  1071. float rate = INPUT_RATE_DEFAULT / speed;
  1072. if (_currentPlaybackRate != rate)
  1073. [_mediaPlayer setRate:INPUT_RATE_DEFAULT / rate];
  1074. _currentPlaybackRate = rate;
  1075. [self _updatePlaybackSpeedIndicator];
  1076. [self _resetIdleTimer];
  1077. }
  1078. - (void)_updatePlaybackSpeedIndicator
  1079. {
  1080. float f_value = self.playbackSpeedSlider.value;
  1081. double speed = pow(2, f_value / 17.);
  1082. self.playbackSpeedIndicator.text = [NSString stringWithFormat:@"%.2fx", speed];
  1083. /* rate changed, so update the exported info */
  1084. [self performSelectorInBackground:@selector(_updateDisplayedMetadata) withObject:nil];
  1085. }
  1086. - (float)_playbackSpeed
  1087. {
  1088. float f_rate = _mediaPlayer.rate;
  1089. double value = 17 * log(f_rate) / log(2.);
  1090. float returnValue = (int) ((value > 0) ? value + .5 : value - .5);
  1091. if (returnValue < -34.)
  1092. returnValue = -34.;
  1093. else if (returnValue > 34.)
  1094. returnValue = 34.;
  1095. _currentPlaybackRate = returnValue;
  1096. return returnValue;
  1097. }
  1098. - (IBAction)videoDimensionAction:(id)sender
  1099. {
  1100. if (sender == self.playbackSpeedButton || sender == self.playbackSpeedButtonLandscape) {
  1101. if (!_videoFiltersHidden)
  1102. self.videoFilterView.hidden = _videoFiltersHidden = YES;
  1103. self.playbackSpeedView.hidden = !_playbackSpeedViewHidden;
  1104. _playbackSpeedViewHidden = self.playbackSpeedView.hidden;
  1105. [self _resetIdleTimer];
  1106. } else if (sender == self.aspectRatioButton) {
  1107. NSUInteger count = [_aspectRatios count];
  1108. if (_currentAspectRatioMask + 1 > count - 1) {
  1109. _mediaPlayer.videoAspectRatio = NULL;
  1110. _mediaPlayer.videoCropGeometry = NULL;
  1111. _currentAspectRatioMask = 0;
  1112. [self.statusLabel showStatusMessage:[NSString stringWithFormat:NSLocalizedString(@"AR_CHANGED", @""), NSLocalizedString(@"DEFAULT", @"")]];
  1113. } else {
  1114. _currentAspectRatioMask++;
  1115. if ([_aspectRatios[_currentAspectRatioMask] isEqualToString:@"FILL_TO_SCREEN"]) {
  1116. UIScreen *screen;
  1117. if (![self hasExternalDisplay])
  1118. screen = [UIScreen mainScreen];
  1119. else
  1120. screen = [UIScreen screens][1];
  1121. float f_ar = screen.bounds.size.width / screen.bounds.size.height;
  1122. if (f_ar == (float)(640./1136.)) // iPhone 5 aka 16:9.01
  1123. _mediaPlayer.videoCropGeometry = "16:9";
  1124. else if (f_ar == (float)(2./3.)) // all other iPhones
  1125. _mediaPlayer.videoCropGeometry = "16:10"; // libvlc doesn't support 2:3 crop
  1126. else if (f_ar == .75) // all iPads
  1127. _mediaPlayer.videoCropGeometry = "4:3";
  1128. else if (f_ar == .5625) // AirPlay
  1129. _mediaPlayer.videoCropGeometry = "16:9";
  1130. else
  1131. APLog(@"unknown screen format %f, can't crop", f_ar);
  1132. [self.statusLabel showStatusMessage:NSLocalizedString(@"FILL_TO_SCREEN", @"")];
  1133. return;
  1134. }
  1135. _mediaPlayer.videoCropGeometry = NULL;
  1136. _mediaPlayer.videoAspectRatio = (char *)[_aspectRatios[_currentAspectRatioMask] UTF8String];
  1137. [self.statusLabel showStatusMessage:[NSString stringWithFormat:NSLocalizedString(@"AR_CHANGED", @""), _aspectRatios[_currentAspectRatioMask]]];
  1138. }
  1139. }
  1140. }
  1141. #pragma mark - background interaction
  1142. - (void)applicationWillResignActive:(NSNotification *)aNotification
  1143. {
  1144. [self _saveCurrentState];
  1145. _mediaPlayer.currentVideoTrackIndex = 0;
  1146. if (![[[NSUserDefaults standardUserDefaults] objectForKey:kVLCSettingContinueAudioInBackgroundKey] boolValue]) {
  1147. if ([_mediaPlayer isPlaying]) {
  1148. [_mediaPlayer pause];
  1149. _shouldResumePlaying = YES;
  1150. }
  1151. }
  1152. }
  1153. - (void)applicationDidEnterBackground:(NSNotification *)notification
  1154. {
  1155. _shouldResumePlaying = NO;
  1156. }
  1157. - (void)applicationDidBecomeActive:(NSNotification *)notification
  1158. {
  1159. _mediaPlayer.currentVideoTrackIndex = 1;
  1160. if (_shouldResumePlaying) {
  1161. _shouldResumePlaying = NO;
  1162. [_listPlayer play];
  1163. }
  1164. }
  1165. - (void)audioSessionRouteChange:(NSNotification *)notification
  1166. {
  1167. NSArray *outputs = [[AVAudioSession sharedInstance] currentRoute].outputs;
  1168. NSString *portName = [[outputs objectAtIndex:0] portName];
  1169. if (![portName isEqualToString:@"Headphones"])
  1170. [_listPlayer pause];
  1171. }
  1172. - (void)mediaDidFinishParsing:(VLCMedia *)aMedia
  1173. {
  1174. [self _updateDisplayedMetadata];
  1175. }
  1176. - (void)mediaMetaDataDidChange:(VLCMedia*)aMedia
  1177. {
  1178. [self _updateDisplayedMetadata];
  1179. }
  1180. - (void)_updateDisplayedMetadata
  1181. {
  1182. MLFile *item;
  1183. NSString *title;
  1184. NSString *artist;
  1185. NSString *albumName;
  1186. NSString *trackNumber;
  1187. if (self.fileFromMediaLibrary)
  1188. item = self.fileFromMediaLibrary;
  1189. else if (self.mediaList) {
  1190. NSArray *matches = [MLFile fileForURL:[_mediaPlayer.media.url absoluteString]];
  1191. if (matches.count > 0)
  1192. item = matches[0];
  1193. }
  1194. if (item) {
  1195. if (item.isAlbumTrack) {
  1196. title = item.albumTrack.title;
  1197. artist = item.albumTrack.artist;
  1198. albumName = item.albumTrack.album.name;
  1199. } else
  1200. title = item.title;
  1201. self.artworkImageView.image = [VLCThumbnailsCache thumbnailForMediaFile:item];
  1202. } else {
  1203. NSDictionary * metaDict = _mediaPlayer.media.metaDictionary;
  1204. if (metaDict) {
  1205. title = metaDict[VLCMetaInformationNowPlaying] ? metaDict[VLCMetaInformationNowPlaying] : metaDict[VLCMetaInformationTitle];
  1206. artist = metaDict[VLCMetaInformationArtist];
  1207. albumName = metaDict[VLCMetaInformationAlbum];
  1208. trackNumber = metaDict[VLCMetaInformationTrackNumber];
  1209. self.artworkImageView.image = [VLCThumbnailsCache thumbnailForMediaItemWithTitle:title Artist:artist andAlbumName:albumName];
  1210. }
  1211. }
  1212. if (!self.artworkImageView.image) {
  1213. self.trackNameLabel.text = title;
  1214. self.artistNameLabel.text = artist;
  1215. self.albumNameLabel.text = albumName;
  1216. } else {
  1217. NSString *trackName = title;
  1218. if (artist)
  1219. trackName = [trackName stringByAppendingFormat:@" — %@", artist];
  1220. if (albumName)
  1221. trackName = [trackName stringByAppendingFormat:@" — %@", albumName];
  1222. self.trackNameLabel.text = trackName;
  1223. }
  1224. if (self.trackNameLabel.text.length < 1)
  1225. self.trackNameLabel.text = [[_mediaPlayer.media url] lastPathComponent];
  1226. /* don't leak sensitive information to the OS, if passcode lock is enabled */
  1227. BOOL passcodeLockEnabled = [[[NSUserDefaults standardUserDefaults] objectForKey:kVLCSettingPasscodeOnKey] boolValue];
  1228. NSMutableDictionary *currentlyPlayingTrackInfo;
  1229. if (passcodeLockEnabled)
  1230. currentlyPlayingTrackInfo = [NSMutableDictionary dictionaryWithObjectsAndKeys:@(_mediaPlayer.media.length.intValue / 1000.), MPMediaItemPropertyPlaybackDuration, @(_mediaPlayer.time.intValue / 1000.), MPNowPlayingInfoPropertyElapsedPlaybackTime, @(_mediaPlayer.rate), MPNowPlayingInfoPropertyPlaybackRate, nil];
  1231. else {
  1232. currentlyPlayingTrackInfo = [NSMutableDictionary dictionaryWithObjectsAndKeys: title, MPMediaItemPropertyTitle, @(_mediaPlayer.media.length.intValue / 1000.), MPMediaItemPropertyPlaybackDuration, @(_mediaPlayer.time.intValue / 1000.), MPNowPlayingInfoPropertyElapsedPlaybackTime, @(_mediaPlayer.rate), MPNowPlayingInfoPropertyPlaybackRate, nil];
  1233. if (artist.length > 0)
  1234. [currentlyPlayingTrackInfo setObject:artist forKey:MPMediaItemPropertyArtist];
  1235. if (albumName.length > 0)
  1236. [currentlyPlayingTrackInfo setObject:albumName forKey:MPMediaItemPropertyAlbumTitle];
  1237. [currentlyPlayingTrackInfo setObject:[NSNumber numberWithInt:[trackNumber intValue]] forKey:MPMediaItemPropertyAlbumTrackNumber];
  1238. if (self.artworkImageView.image) {
  1239. MPMediaItemArtwork *mpartwork = [[MPMediaItemArtwork alloc] initWithImage:self.artworkImageView.image];
  1240. [currentlyPlayingTrackInfo setObject:mpartwork forKey:MPMediaItemPropertyArtwork];
  1241. }
  1242. }
  1243. [MPNowPlayingInfoCenter defaultCenter].nowPlayingInfo = currentlyPlayingTrackInfo;
  1244. }
  1245. #pragma mark - autorotation
  1246. - (BOOL)shouldAutorotate
  1247. {
  1248. UIInterfaceOrientation toInterfaceOrientation = [[UIApplication sharedApplication] statusBarOrientation];
  1249. return UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPad
  1250. || toInterfaceOrientation != UIInterfaceOrientationPortraitUpsideDown;
  1251. }
  1252. - (void)willRotateToInterfaceOrientation:(UIInterfaceOrientation)toInterfaceOrientation duration:(NSTimeInterval)duration
  1253. {
  1254. [super willRotateToInterfaceOrientation:toInterfaceOrientation duration:duration];
  1255. if (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPhone) {
  1256. if (self.artworkImageView.image)
  1257. self.trackNameLabel.hidden = UIInterfaceOrientationIsLandscape(toInterfaceOrientation);
  1258. }
  1259. }
  1260. #pragma mark - AVSession delegate
  1261. - (void)beginInterruption
  1262. {
  1263. if ([[[NSUserDefaults standardUserDefaults] objectForKey:kVLCSettingContinueAudioInBackgroundKey] boolValue])
  1264. _shouldResumePlaying = YES;
  1265. [_mediaPlayer pause];
  1266. }
  1267. - (void)endInterruption
  1268. {
  1269. if (_shouldResumePlaying) {
  1270. [_mediaPlayer play];
  1271. _shouldResumePlaying = NO;
  1272. }
  1273. }
  1274. #pragma mark - External Display
  1275. - (BOOL)hasExternalDisplay
  1276. {
  1277. return ([[UIScreen screens] count] > 1);
  1278. }
  1279. - (void)showOnExternalDisplay
  1280. {
  1281. UIScreen *screen = [UIScreen screens][1];
  1282. screen.overscanCompensation = UIScreenOverscanCompensationInsetApplicationFrame;
  1283. self.externalWindow = [[UIWindow alloc] initWithFrame:screen.bounds];
  1284. UIViewController *controller = [[VLCExternalDisplayController alloc] init];
  1285. self.externalWindow.rootViewController = controller;
  1286. [controller.view addSubview:_movieView];
  1287. controller.view.frame = screen.bounds;
  1288. _movieView.frame = screen.bounds;
  1289. self.playingExternallyView.hidden = NO;
  1290. self.externalWindow.screen = screen;
  1291. self.externalWindow.hidden = NO;
  1292. }
  1293. - (void)hideFromExternalDisplay
  1294. {
  1295. [self.view addSubview:_movieView];
  1296. [self.view sendSubviewToBack:_movieView];
  1297. _movieView.frame = self.view.frame;
  1298. self.playingExternallyView.hidden = YES;
  1299. self.externalWindow.hidden = YES;
  1300. self.externalWindow = nil;
  1301. }
  1302. - (void)handleExternalScreenDidConnect:(NSNotification *)notification
  1303. {
  1304. [self showOnExternalDisplay];
  1305. }
  1306. - (void)handleExternalScreenDidDisconnect:(NSNotification *)notification
  1307. {
  1308. [self hideFromExternalDisplay];
  1309. }
  1310. @end