VLCMovieViewController.m 68 KB

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