VLCMovieViewController.m 61 KB

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