VLCMovieViewController.m 60 KB

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