VLCMovieViewController.m 68 KB

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