VLCMovieViewController.m 68 KB

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