VLCMovieViewController.m 49 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292
  1. /*****************************************************************************
  2. * VLCMovieViewController.m
  3. * VLC for iOS
  4. *****************************************************************************
  5. * Copyright (c) 2013 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 "OBSlider.h"
  24. #import "VLCStatusLabel.h"
  25. #define INPUT_RATE_DEFAULT 1000.
  26. #define FORWARD_SWIPE_DURATION 30
  27. #define BACKWARD_SWIPE_DURATION 10
  28. @interface VLCMovieViewController () <UIGestureRecognizerDelegate, AVAudioSessionDelegate>
  29. {
  30. VLCMediaListPlayer *_listPlayer;
  31. VLCMediaPlayer *_mediaPlayer;
  32. BOOL _controlsHidden;
  33. BOOL _videoFiltersHidden;
  34. BOOL _playbackSpeedViewHidden;
  35. UIActionSheet *_subtitleActionSheet;
  36. UIActionSheet *_audiotrackActionSheet;
  37. float _currentPlaybackRate;
  38. NSArray *_aspectRatios;
  39. NSUInteger _currentAspectRatioMask;
  40. NSTimer *_idleTimer;
  41. BOOL _shouldResumePlaying;
  42. BOOL _viewAppeared;
  43. BOOL _displayRemainingTime;
  44. BOOL _positionSet;
  45. BOOL _playerIsSetup;
  46. BOOL _isScrubbing;
  47. BOOL _swipeGesturesEnabled;
  48. NSString * panType;
  49. UIPanGestureRecognizer *_panRecognizer;
  50. UISwipeGestureRecognizer *_swipeRecognizerLeft;
  51. UISwipeGestureRecognizer *_swipeRecognizerRight;
  52. UITapGestureRecognizer *_tapRecognizer;
  53. }
  54. @property (nonatomic, strong) UIPopoverController *masterPopoverController;
  55. @property (nonatomic, strong) UIWindow *externalWindow;
  56. @end
  57. @implementation VLCMovieViewController
  58. + (void)initialize
  59. {
  60. NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
  61. NSDictionary *appDefaults = @{kVLCShowRemainingTime : @(YES)};
  62. [defaults registerDefaults:appDefaults];
  63. }
  64. - (void)dealloc
  65. {
  66. if (_tapRecognizer)
  67. [self.view removeGestureRecognizer:_tapRecognizer];
  68. if (_swipeRecognizerLeft)
  69. [self.view removeGestureRecognizer:_swipeRecognizerLeft];
  70. if (_swipeRecognizerRight)
  71. [self.view removeGestureRecognizer:_swipeRecognizerRight];
  72. if (_panRecognizer)
  73. [self.view removeGestureRecognizer:_panRecognizer];
  74. [[NSNotificationCenter defaultCenter] removeObserver:self];
  75. }
  76. #pragma mark - Managing the media item
  77. - (void)setMediaItem:(id)newMediaItem
  78. {
  79. if (_mediaItem != newMediaItem) {
  80. [self _stopPlayback];
  81. _mediaItem = newMediaItem;
  82. if (_viewAppeared)
  83. [self _startPlayback];
  84. }
  85. if (self.masterPopoverController != nil)
  86. [self.masterPopoverController dismissPopoverAnimated:YES];
  87. }
  88. - (void)setUrl:(NSURL *)url
  89. {
  90. [self _stopPlayback];
  91. _url = url;
  92. _playerIsSetup = NO;
  93. if (_viewAppeared)
  94. [self _startPlayback];
  95. }
  96. - (void)viewDidLoad
  97. {
  98. [super viewDidLoad];
  99. self.wantsFullScreenLayout = YES;
  100. self.videoFilterView.hidden = YES;
  101. _videoFiltersHidden = YES;
  102. _hueLabel.text = NSLocalizedString(@"VFILTER_HUE", @"");
  103. _hueSlider.accessibilityLabel = _hueLabel.text;
  104. _hueSlider.isAccessibilityElement = YES;
  105. _contrastLabel.text = NSLocalizedString(@"VFILTER_CONTRAST", @"");
  106. _contrastSlider.accessibilityLabel = _contrastLabel.text;
  107. _contrastSlider.isAccessibilityElement = YES;
  108. _brightnessLabel.text = NSLocalizedString(@"VFILTER_BRIGHTNESS", @"");
  109. _brightnessSlider.accessibilityLabel = _brightnessLabel.text;
  110. _brightnessSlider.isAccessibilityElement = YES;
  111. _saturationLabel.text = NSLocalizedString(@"VFILTER_SATURATION", @"");
  112. _saturationSlider.accessibilityLabel = _saturationLabel.text;
  113. _saturationSlider.isAccessibilityElement = YES;
  114. _gammaLabel.text = NSLocalizedString(@"VFILTER_GAMMA", @"");
  115. _gammaSlider.accessibilityLabel = _gammaLabel.text;
  116. _gammaSlider.isAccessibilityElement = YES;
  117. _playbackSpeedLabel.text = NSLocalizedString(@"PLAYBACK_SPEED", @"");
  118. _playbackSpeedSlider.accessibilityLabel = _playbackSpeedLabel.text;
  119. _playbackSpeedSlider.isAccessibilityElement = YES;
  120. _positionSlider.accessibilityLabel = NSLocalizedString(@"PLAYBACK_POSITION", @"");
  121. _positionSlider.isAccessibilityElement = YES;
  122. _timeDisplay.isAccessibilityElement = YES;
  123. _audioSwitcherButton.accessibilityLabel = NSLocalizedString(@"CHOOSE_AUDIO_TRACK", @"");
  124. _audioSwitcherButton.isAccessibilityElement = YES;
  125. _subtitleSwitcherButton.accessibilityLabel = NSLocalizedString(@"CHOOSE_SUBTITLE_TRACK", @"");
  126. _subtitleSwitcherButton.isAccessibilityElement = YES;
  127. _playbackSpeedButton.accessibilityLabel = _playbackSpeedLabel.text;
  128. _playbackSpeedButton.isAccessibilityElement = YES;
  129. _videoFilterButton.accessibilityLabel = NSLocalizedString(@"VIDEO_FILTER", @"");
  130. _videoFilterButton.isAccessibilityElement = YES;
  131. _resetVideoFilterButton.accessibilityLabel = NSLocalizedString(@"VIDEO_FILTER_RESET_BUTTON", @"");
  132. _resetVideoFilterButton.isAccessibilityElement = YES;
  133. _aspectRatioButton.accessibilityLabel = NSLocalizedString(@"VIDEO_ASPECT_RATIO_BUTTON", @"");
  134. _aspectRatioButton.isAccessibilityElement = YES;
  135. _playPauseButton.accessibilityLabel = NSLocalizedString(@"PLAY_PAUSE_BUTTON", @"");
  136. _playPauseButton.isAccessibilityElement = YES;
  137. _bwdButton.accessibilityLabel = NSLocalizedString(@"BWD_BUTTON", @"");
  138. _bwdButton.isAccessibilityElement = YES;
  139. _fwdButton.accessibilityLabel = NSLocalizedString(@"FWD_BUTTON", @"");
  140. _fwdButton.isAccessibilityElement = YES;
  141. _scrubHelpLabel.text = NSLocalizedString(@"PLAYBACK_SCRUB_HELP", @"");
  142. self.playbackSpeedView.hidden = YES;
  143. _playbackSpeedViewHidden = YES;
  144. NSNotificationCenter *center = [NSNotificationCenter defaultCenter];
  145. [center addObserver:self selector:@selector(handleExternalScreenDidConnect:)
  146. name:UIScreenDidConnectNotification object:nil];
  147. [center addObserver:self selector:@selector(handleExternalScreenDidDisconnect:)
  148. name:UIScreenDidDisconnectNotification object:nil];
  149. [center addObserver:self selector:@selector(applicationWillResignActive:)
  150. name:UIApplicationWillResignActiveNotification object:nil];
  151. [center addObserver:self selector:@selector(applicationDidBecomeActive:)
  152. name:UIApplicationDidBecomeActiveNotification object:nil];
  153. [center addObserver:self selector:@selector(applicationDidEnterBackground:)
  154. name:UIApplicationDidEnterBackgroundNotification object:nil];
  155. _playingExternallyTitle.text = NSLocalizedString(@"PLAYING_EXTERNALLY_TITLE", @"");
  156. _playingExternallyDescription.text = NSLocalizedString(@"PLAYING_EXTERNALLY_DESC", @"");
  157. if ([self hasExternalDisplay])
  158. [self showOnExternalDisplay];
  159. self.trackNameLabel.text = self.artistNameLabel.text = self.albumNameLabel.text = @"";
  160. _movieView.userInteractionEnabled = NO;
  161. UITapGestureRecognizer *tapOnVideoRecognizer = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(toggleControlsVisible)];
  162. tapOnVideoRecognizer.delegate = self;
  163. [self.view addGestureRecognizer:tapOnVideoRecognizer];
  164. _displayRemainingTime = [[[NSUserDefaults standardUserDefaults] objectForKey:kVLCShowRemainingTime] boolValue];
  165. UIPinchGestureRecognizer *pinchRecognizer = [[UIPinchGestureRecognizer alloc] initWithTarget:self action:@selector(handlePinchGesture:)];
  166. pinchRecognizer.delegate = self;
  167. [self.view addGestureRecognizer:pinchRecognizer];
  168. _swipeGesturesEnabled = YES;
  169. if (_swipeGesturesEnabled) {
  170. _tapRecognizer = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tapRecognized)];
  171. [_tapRecognizer setNumberOfTouchesRequired:2];
  172. _panRecognizer = [[UIPanGestureRecognizer alloc] initWithTarget:self action:@selector(panRecognized:)];
  173. [_panRecognizer setMinimumNumberOfTouches:1];
  174. [_panRecognizer setMaximumNumberOfTouches:1];
  175. _swipeRecognizerLeft = [[UISwipeGestureRecognizer alloc] initWithTarget:self action:@selector(swipeRecognized:)];
  176. _swipeRecognizerLeft.direction = UISwipeGestureRecognizerDirectionLeft;
  177. _swipeRecognizerRight = [[UISwipeGestureRecognizer alloc] initWithTarget:self action:@selector(swipeRecognized:)];
  178. _swipeRecognizerRight.direction = UISwipeGestureRecognizerDirectionRight;
  179. [self.view addGestureRecognizer:_swipeRecognizerLeft];
  180. [self.view addGestureRecognizer:_swipeRecognizerRight];
  181. [self.view addGestureRecognizer:_panRecognizer];
  182. [self.view addGestureRecognizer:_tapRecognizer];
  183. [_panRecognizer requireGestureRecognizerToFail:_swipeRecognizerLeft];
  184. [_panRecognizer requireGestureRecognizerToFail:_swipeRecognizerRight];
  185. _panRecognizer.delegate = self;
  186. _swipeRecognizerRight.delegate = self;
  187. _swipeRecognizerLeft.delegate = self;
  188. _tapRecognizer.delegate = self;
  189. }
  190. _aspectRatios = @[@"DEFAULT", @"FILL_TO_SCREEN", @"4:3", @"16:9", @"16:10", @"2.21:1"];
  191. [self.aspectRatioButton setImage:[UIImage imageNamed:@"ratioIcon"] forState:UIControlStateNormal];
  192. if (SYSTEM_RUNS_IOS7_OR_LATER) {
  193. self.backButton.tintColor = [UIColor colorWithRed:(190.0f/255.0f) green:(190.0f/255.0f) blue:(190.0f/255.0f) alpha:1.];
  194. self.toolbar.tintColor = [UIColor whiteColor];
  195. self.toolbar.barTintColor = [UIColor colorWithWhite:0.f alpha:1.f];
  196. CGRect rect = self.resetVideoFilterButton.frame;
  197. rect.origin.y = rect.origin.y + 5.;
  198. self.resetVideoFilterButton.frame = rect;
  199. rect = self.toolbar.frame;
  200. rect.size.height = rect.size.height + rect.origin.y;
  201. rect.origin.y = 0;
  202. self.toolbar.frame = rect;
  203. rect = self.aspectRatioButton.frame;
  204. rect.size.width -= 19.;
  205. rect.origin.x += 19.;
  206. self.aspectRatioButton.frame = rect;
  207. rect = self.timeDisplay.frame;
  208. rect.origin.x += 19.;
  209. self.timeDisplay.frame = rect;
  210. rect = self.positionSlider.frame;
  211. rect.size.width += 19.;
  212. self.positionSlider.frame = rect;
  213. } else {
  214. CGRect rect = self.positionSlider.frame;
  215. rect.origin.y = rect.origin.y + 3.;
  216. self.positionSlider.frame = rect;
  217. [self.aspectRatioButton setBackgroundImage:[UIImage imageNamed:@"ratioButton"] forState:UIControlStateNormal];
  218. [self.aspectRatioButton setBackgroundImage:[UIImage imageNamed:@"ratioButtonHighlight"] forState:UIControlStateHighlighted];
  219. [self.toolbar setBackgroundImage:[UIImage imageNamed:@"seekbarBg"] forBarMetrics:UIBarMetricsDefault];
  220. [self.backButton setBackgroundImage:[UIImage imageNamed:@"playbackDoneButton"] forState:UIControlStateNormal barMetrics:UIBarMetricsDefault];
  221. [self.backButton setBackgroundImage:[UIImage imageNamed:@"playbackDoneButtonHighlight"] forState:UIControlStateHighlighted barMetrics:UIBarMetricsDefault];
  222. }
  223. /* FIXME: there is a saner iOS 6+ API for this! */
  224. /* this looks a bit weird, but we need to support iOS 5 and should show the same appearance */
  225. UISlider *volumeSlider = nil;
  226. for (id aView in self.volumeView.subviews){
  227. if ([[[aView class] description] isEqualToString:@"MPVolumeSlider"]){
  228. volumeSlider = (UISlider *)aView;
  229. break;
  230. }
  231. }
  232. if (!SYSTEM_RUNS_IOS7_OR_LATER) {
  233. [volumeSlider setMinimumTrackImage:[[UIImage imageNamed:@"sliderminiValue"]resizableImageWithCapInsets:UIEdgeInsetsMake(0, 4, 0, 0)] forState:UIControlStateNormal];
  234. [volumeSlider setMaximumTrackImage:[[UIImage imageNamed:@"slidermaxValue"] resizableImageWithCapInsets:UIEdgeInsetsMake(0, 0, 0, 4)] forState:UIControlStateNormal];
  235. [volumeSlider setThumbImage:[UIImage imageNamed:@"volumeballslider"] forState:UIControlStateNormal];
  236. }
  237. [volumeSlider addTarget:self
  238. action:@selector(volumeSliderAction:)
  239. forControlEvents:UIControlEventValueChanged];
  240. [[AVAudioSession sharedInstance] setDelegate:self];
  241. if (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPad)
  242. self.positionSlider.scrubbingSpeedChangePositions = @[@(0.), @(100.), @(200.), @(300)];
  243. _playerIsSetup = NO;
  244. [self.movieView setAccessibilityLabel:NSLocalizedString(@"VO_VIDEOPLAYER_TITLE", @"")];
  245. [self.movieView setAccessibilityHint:NSLocalizedString(@"VO_VIDEOPLAYER_DOUBLETAP", @"")];
  246. }
  247. - (BOOL)_blobCheck
  248. {
  249. NSArray *searchPaths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
  250. NSString *directoryPath = searchPaths[0];
  251. if (![[NSFileManager defaultManager] fileExistsAtPath:[directoryPath stringByAppendingPathComponent:@"blob.bin"]])
  252. return NO;
  253. NSData *data = [NSData dataWithContentsOfFile:[directoryPath stringByAppendingPathComponent:@"blob.bin"]];
  254. uint8_t digest[CC_SHA1_DIGEST_LENGTH];
  255. CC_SHA1(data.bytes, data.length, digest);
  256. NSMutableString *hash = [NSMutableString stringWithCapacity:CC_SHA1_DIGEST_LENGTH * 2];
  257. for (unsigned int u = 0; u < CC_SHA1_DIGEST_LENGTH; u++)
  258. [hash appendFormat:@"%02x", digest[u]];
  259. if ([hash isEqualToString:kBlobHash])
  260. return YES;
  261. else
  262. return NO;
  263. }
  264. - (void)viewWillAppear:(BOOL)animated
  265. {
  266. [super viewWillAppear:animated];
  267. [self.navigationController setNavigationBarHidden:YES animated:YES];
  268. if (!SYSTEM_RUNS_IOS7_OR_LATER) {
  269. if (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPhone)
  270. [UIApplication sharedApplication].statusBarStyle = UIStatusBarStyleBlackTranslucent;
  271. }
  272. [self _startPlayback];
  273. [self setControlsHidden:NO animated:YES];
  274. _viewAppeared = YES;
  275. }
  276. - (void)_startPlayback
  277. {
  278. if (_playerIsSetup)
  279. return;
  280. NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
  281. if (!self.mediaItem && !self.url) {
  282. [self _stopPlayback];
  283. return;
  284. }
  285. _listPlayer = [[VLCMediaListPlayer alloc] initWithOptions:@[[NSString stringWithFormat:@"--%@=%@", kVLCSettingSubtitlesFont, [defaults objectForKey:kVLCSettingSubtitlesFont]], [NSString stringWithFormat:@"--%@=%@", kVLCSettingSubtitlesFontColor, [defaults objectForKey:kVLCSettingSubtitlesFontColor]], [NSString stringWithFormat:@"--%@=%@", kVLCSettingSubtitlesFontSize, [defaults objectForKey:kVLCSettingSubtitlesFontSize]], [NSString stringWithFormat:@"--%@=%@", kVLCSettingDeinterlace, [defaults objectForKey:kVLCSettingDeinterlace]]]];
  286. _mediaPlayer = _listPlayer.mediaPlayer;
  287. [_mediaPlayer setDelegate:self];
  288. [_mediaPlayer setDrawable:self.movieView];
  289. self.trackNameLabel.text = self.artistNameLabel.text = self.albumNameLabel.text = @"";
  290. VLCMedia *media;
  291. if (self.mediaItem) {
  292. self.title = [self.mediaItem title];
  293. MLFile *item = self.mediaItem;
  294. media = [VLCMedia mediaWithURL:[NSURL URLWithString:item.url]];
  295. item.unread = @(NO);
  296. if (item.isAlbumTrack) {
  297. self.trackNameLabel.text = item.albumTrack.title;
  298. self.artistNameLabel.text = item.albumTrack.artist;
  299. self.albumNameLabel.text = item.albumTrack.album.name;
  300. }
  301. } else {
  302. media = [VLCMedia mediaWithURL:self.url];
  303. self.title = NSLocalizedString(@"NETWORK_TITLE",nil);
  304. }
  305. [media addOptions:
  306. @{kVLCSettingStretchAudio :
  307. [[defaults objectForKey:kVLCSettingStretchAudio] boolValue] ? kVLCSettingStretchAudioOnValue : kVLCSettingStretchAudioOffValue, kVLCSettingTextEncoding : [defaults objectForKey:kVLCSettingTextEncoding], kVLCSettingSkipLoopFilter : [defaults objectForKey:kVLCSettingSkipLoopFilter]}];
  308. [NSTimeZone resetSystemTimeZone];
  309. NSString *tzName = [[NSTimeZone systemTimeZone] name];
  310. 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"];
  311. if ([tzNames containsObject:tzName] || [[tzName stringByDeletingLastPathComponent] isEqualToString:@"US"]) {
  312. NSArray *tracksInfo = media.tracksInformation;
  313. for (NSUInteger x = 0; x < tracksInfo.count; x++) {
  314. if ([[tracksInfo[x] objectForKey:VLCMediaTracksInformationType] isEqualToString:VLCMediaTracksInformationTypeAudio])
  315. {
  316. NSInteger fourcc = [[tracksInfo[x] objectForKey:VLCMediaTracksInformationCodec] integerValue];
  317. switch (fourcc) {
  318. case 540161377:
  319. case 1647457633:
  320. case 858612577:
  321. case 862151027:
  322. case 862151013:
  323. case 1684566644:
  324. case 2126701:
  325. {
  326. if (![self _blobCheck]) {
  327. [media addOptions:@{@"no-audio" : [NSNull null]}];
  328. APLog(@"audio playback disabled because an unsupported codec was found");
  329. }
  330. break;
  331. }
  332. default:
  333. break;
  334. }
  335. }
  336. }
  337. }
  338. [_listPlayer setRootMedia:media];
  339. [_listPlayer setRepeatMode:VLCDoNotRepeat];
  340. self.positionSlider.value = 0.;
  341. [self.timeDisplay setTitle:@"" forState:UIControlStateNormal];
  342. self.timeDisplay.accessibilityLabel = @"";
  343. [self.repeatButton setImage:[UIImage imageNamed:@"repeat"] forState:UIControlStateNormal];
  344. if (![self _isMediaSuitableForDevice]) {
  345. UIAlertView * alert = [[UIAlertView alloc] initWithTitle:NSLocalizedString(@"DEVICE_TOOSLOW_TITLE", @"") message:[NSString stringWithFormat:NSLocalizedString(@"DEVICE_TOOSLOW", @""), [[UIDevice currentDevice] model], self.mediaItem.title] delegate:self cancelButtonTitle:NSLocalizedString(@"BUTTON_CANCEL", @"") otherButtonTitles:NSLocalizedString(@"BUTTON_OPEN", @""), nil];
  346. [alert show];
  347. } else
  348. [self _playNewMedia];
  349. if (![self hasExternalDisplay])
  350. self.brightnessSlider.value = [UIScreen mainScreen].brightness * 2.;
  351. }
  352. - (BOOL)_isMediaSuitableForDevice
  353. {
  354. if (!self.mediaItem)
  355. return YES;
  356. NSUInteger totalNumberOfPixels = [[[self.mediaItem videoTrack] valueForKey:@"width"] doubleValue] * [[[self.mediaItem videoTrack] valueForKey:@"height"] doubleValue];
  357. NSInteger speedCategory = [[UIDevice currentDevice] speedCategory];
  358. if (speedCategory == 1) {
  359. // iPhone 3GS, iPhone 4, first gen. iPad, 3rd and 4th generation iPod touch
  360. return (totalNumberOfPixels < 600000); // between 480p and 720p
  361. } else if (speedCategory == 2) {
  362. // iPhone 4S, iPad 2 and 3, iPod 4 and 5
  363. return (totalNumberOfPixels < 922000); // 720p
  364. } else if (speedCategory == 3) {
  365. // iPhone 5, iPad 4
  366. return (totalNumberOfPixels < 2074000); // 1080p
  367. }
  368. return YES;
  369. }
  370. - (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
  371. {
  372. if (buttonIndex == 1)
  373. [self _playNewMedia];
  374. else {
  375. [self _stopPlayback];
  376. [self closePlayback:nil];
  377. }
  378. }
  379. - (void)_playNewMedia
  380. {
  381. NSNumber *playbackPositionInTime = @(0);
  382. CGFloat lastPosition = .0;
  383. NSInteger duration = self.mediaItem.duration.intValue;
  384. if (self.mediaItem.lastPosition)
  385. lastPosition = self.mediaItem.lastPosition.floatValue;
  386. if (lastPosition < .95) {
  387. if (duration != 0)
  388. playbackPositionInTime = @(lastPosition * (duration / 1000.));
  389. }
  390. if (playbackPositionInTime.intValue > 0) {
  391. [_mediaPlayer.media addOptions:@{@"start-time": playbackPositionInTime}];
  392. APLog(@"set starttime to %i", playbackPositionInTime.intValue);
  393. }
  394. [_mediaPlayer addObserver:self forKeyPath:@"time" options:0 context:nil];
  395. [_mediaPlayer addObserver:self forKeyPath:@"remainingTime" options:0 context:nil];
  396. [_listPlayer playMedia:_listPlayer.rootMedia];
  397. if (self.mediaItem) {
  398. if (self.mediaItem.lastAudioTrack.intValue > 0)
  399. _mediaPlayer.currentAudioTrackIndex = self.mediaItem.lastAudioTrack.intValue;
  400. if (self.mediaItem.lastSubtitleTrack.intValue > 0)
  401. _mediaPlayer.currentVideoSubTitleIndex = self.mediaItem.lastSubtitleTrack.intValue;
  402. }
  403. self.playbackSpeedSlider.value = [self _playbackSpeed];
  404. [self _updatePlaybackSpeedIndicator];
  405. [self performSelectorInBackground:@selector(_updateExportedPlaybackInformation) withObject:nil];
  406. _currentAspectRatioMask = 0;
  407. _mediaPlayer.videoAspectRatio = NULL;
  408. /* some demuxers don't respect :start-time, so re-try here */
  409. if (lastPosition < .95 && _mediaPlayer.position < lastPosition)
  410. _mediaPlayer.position = lastPosition;
  411. [self _resetIdleTimer];
  412. _playerIsSetup = YES;
  413. }
  414. - (void)viewWillDisappear:(BOOL)animated
  415. {
  416. [self _stopPlayback];
  417. _viewAppeared = NO;
  418. if (_idleTimer) {
  419. [_idleTimer invalidate];
  420. _idleTimer = nil;
  421. }
  422. [self.navigationController setNavigationBarHidden:NO animated:YES];
  423. if (!SYSTEM_RUNS_IOS7_OR_LATER)
  424. [UIApplication sharedApplication].statusBarStyle = UIStatusBarStyleBlackOpaque;
  425. [[UIApplication sharedApplication] setStatusBarHidden:NO withAnimation:UIStatusBarAnimationFade];
  426. [super viewWillDisappear:animated];
  427. // hide filter UI for next run
  428. if (!_videoFiltersHidden)
  429. _videoFiltersHidden = YES;
  430. if (!_playbackSpeedViewHidden)
  431. _playbackSpeedViewHidden = YES;
  432. }
  433. - (void)_stopPlayback
  434. {
  435. if (_mediaPlayer) {
  436. @try {
  437. [_mediaPlayer removeObserver:self forKeyPath:@"time"];
  438. [_mediaPlayer removeObserver:self forKeyPath:@"remainingTime"];
  439. }
  440. @catch (NSException *exception) {
  441. APLog(@"we weren't an observer yet");
  442. }
  443. if (_mediaPlayer.media) {
  444. [_mediaPlayer pause];
  445. [self _saveCurrentState];
  446. [_mediaPlayer stop];
  447. }
  448. if (_mediaPlayer)
  449. _mediaPlayer = nil;
  450. if (_listPlayer)
  451. _listPlayer = nil;
  452. }
  453. if (_mediaItem)
  454. _mediaItem = nil;
  455. _playerIsSetup = NO;
  456. }
  457. - (void)_saveCurrentState
  458. {
  459. if (self.mediaItem) {
  460. @try {
  461. MLFile *item = self.mediaItem;
  462. item.lastPosition = @([_mediaPlayer position]);
  463. item.lastAudioTrack = @(_mediaPlayer.currentAudioTrackIndex);
  464. item.lastSubtitleTrack = @(_mediaPlayer.currentVideoSubTitleIndex);
  465. }
  466. @catch (NSException *exception) {
  467. APLog(@"failed to save current media state - file removed?");
  468. }
  469. }
  470. }
  471. #pragma mark - remote events
  472. - (void)viewDidAppear:(BOOL)animated
  473. {
  474. [super viewDidAppear:animated];
  475. [[UIApplication sharedApplication] beginReceivingRemoteControlEvents];
  476. [self becomeFirstResponder];
  477. }
  478. - (void)viewDidDisappear:(BOOL)animated
  479. {
  480. [super viewDidDisappear:animated];
  481. [[UIApplication sharedApplication] endReceivingRemoteControlEvents];
  482. [self resignFirstResponder];
  483. [[NSUserDefaults standardUserDefaults] setBool:_displayRemainingTime forKey:kVLCShowRemainingTime];
  484. }
  485. - (BOOL)canBecomeFirstResponder
  486. {
  487. return YES;
  488. }
  489. - (void)remoteControlReceivedWithEvent:(UIEvent *)event
  490. {
  491. switch (event.subtype) {
  492. case UIEventSubtypeRemoteControlPlay:
  493. [_listPlayer play];
  494. break;
  495. case UIEventSubtypeRemoteControlPause:
  496. [_listPlayer pause];
  497. break;
  498. case UIEventSubtypeRemoteControlTogglePlayPause:
  499. [self playPause];
  500. break;
  501. default:
  502. break;
  503. }
  504. }
  505. #pragma mark - controls visibility
  506. - (void)handlePinchGesture:(UIPinchGestureRecognizer *)recognizer
  507. {
  508. if (recognizer.velocity < 0.)
  509. [self closePlayback:nil];
  510. }
  511. - (BOOL)gestureRecognizer:(UIGestureRecognizer *)gestureRecognizer shouldReceiveTouch:(UITouch *)touch
  512. {
  513. if (touch.view != self.view)
  514. return NO;
  515. return YES;
  516. }
  517. - (BOOL)gestureRecognizer:(UIGestureRecognizer *)gestureRecognizer shouldRecognizeSimultaneouslyWithGestureRecognizer:(UIGestureRecognizer *)otherGestureRecognizer
  518. {
  519. return YES;
  520. }
  521. - (void)setControlsHidden:(BOOL)hidden animated:(BOOL)animated
  522. {
  523. _controlsHidden = hidden;
  524. CGFloat alpha = _controlsHidden? 0.0f: 1.0f;
  525. if (!_controlsHidden) {
  526. _controllerPanel.alpha = 0.0f;
  527. _controllerPanel.hidden = !_videoFiltersHidden;
  528. _toolbar.alpha = 0.0f;
  529. _toolbar.hidden = NO;
  530. _videoFilterView.alpha = 0.0f;
  531. _videoFilterView.hidden = _videoFiltersHidden;
  532. _playbackSpeedView.alpha = 0.0f;
  533. _playbackSpeedView.hidden = _playbackSpeedViewHidden;
  534. }
  535. void (^animationBlock)() = ^() {
  536. _controllerPanel.alpha = alpha;
  537. _toolbar.alpha = alpha;
  538. _videoFilterView.alpha = alpha;
  539. _playbackSpeedView.alpha = alpha;
  540. };
  541. void (^completionBlock)(BOOL finished) = ^(BOOL finished) {
  542. if (_videoFiltersHidden)
  543. _controllerPanel.hidden = _controlsHidden;
  544. else
  545. _controllerPanel.hidden = NO;
  546. _toolbar.hidden = _controlsHidden;
  547. _videoFilterView.hidden = _videoFiltersHidden;
  548. _playbackSpeedView.hidden = _playbackSpeedViewHidden;
  549. };
  550. UIStatusBarAnimation animationType = animated? UIStatusBarAnimationFade: UIStatusBarAnimationNone;
  551. NSTimeInterval animationDuration = animated? 0.3: 0.0;
  552. [[UIApplication sharedApplication] setStatusBarHidden:_viewAppeared ? _controlsHidden : NO withAnimation:animationType];
  553. [UIView animateWithDuration:animationDuration animations:animationBlock completion:completionBlock];
  554. _volumeView.hidden = _controllerPanel.hidden;
  555. }
  556. - (void)toggleControlsVisible
  557. {
  558. if (_controlsHidden && !_videoFiltersHidden)
  559. _videoFiltersHidden = YES;
  560. [self setControlsHidden:!_controlsHidden animated:YES];
  561. }
  562. - (void)_resetIdleTimer
  563. {
  564. if (!_idleTimer)
  565. _idleTimer = [NSTimer scheduledTimerWithTimeInterval:4.
  566. target:self
  567. selector:@selector(idleTimerExceeded)
  568. userInfo:nil
  569. repeats:NO];
  570. else {
  571. if (fabs([_idleTimer.fireDate timeIntervalSinceNow]) < 4.)
  572. [_idleTimer setFireDate:[NSDate dateWithTimeIntervalSinceNow:4.]];
  573. }
  574. }
  575. - (void)idleTimerExceeded
  576. {
  577. _idleTimer = nil;
  578. if (!_controlsHidden)
  579. [self toggleControlsVisible];
  580. if (!_videoFiltersHidden)
  581. _videoFiltersHidden = YES;
  582. if (!_playbackSpeedViewHidden)
  583. _playbackSpeedViewHidden = YES;
  584. if (self.scrubIndicatorView.hidden == NO)
  585. self.scrubIndicatorView.hidden = YES;
  586. }
  587. - (UIResponder *)nextResponder
  588. {
  589. [self _resetIdleTimer];
  590. return [super nextResponder];
  591. }
  592. #pragma mark - controls
  593. - (IBAction)closePlayback:(id)sender
  594. {
  595. [self setControlsHidden:NO animated:NO];
  596. [self.navigationController dismissViewControllerAnimated:YES completion:nil];
  597. }
  598. - (IBAction)positionSliderAction:(UISlider *)sender
  599. {
  600. /* we need to limit the number of events sent by the slider, since otherwise, the user
  601. * wouldn't see the I-frames when seeking on current mobile devices. This isn't a problem
  602. * within the Simulator, but especially on older ARMv7 devices, it's clearly noticeable. */
  603. [self performSelector:@selector(_setPositionForReal) withObject:nil afterDelay:0.3];
  604. VLCTime *newPosition = [VLCTime timeWithInt:(int)(_positionSlider.value * self.mediaItem.duration.intValue)];
  605. [self.timeDisplay setTitle:newPosition.stringValue forState:UIControlStateNormal];
  606. self.timeDisplay.accessibilityLabel = [NSString stringWithFormat:@"%@: %@", NSLocalizedString(@"PLAYBACK_POSITION", @""), newPosition.stringValue];
  607. _positionSet = NO;
  608. [self _resetIdleTimer];
  609. }
  610. - (void)_setPositionForReal
  611. {
  612. if (!_positionSet) {
  613. _mediaPlayer.position = _positionSlider.value;
  614. _positionSet = YES;
  615. }
  616. }
  617. - (IBAction)positionSliderTouchDown:(id)sender
  618. {
  619. [self _updateScrubLabel];
  620. self.scrubIndicatorView.hidden = NO;
  621. _isScrubbing = YES;
  622. }
  623. - (IBAction)positionSliderTouchUp:(id)sender
  624. {
  625. self.scrubIndicatorView.hidden = YES;
  626. _isScrubbing = NO;
  627. }
  628. - (void)_updateScrubLabel
  629. {
  630. float speed = self.positionSlider.scrubbingSpeed;
  631. if (speed == 1.)
  632. self.currentScrubSpeedLabel.text = NSLocalizedString(@"PLAYBACK_SCRUB_HIGH", @"");
  633. else if (speed == .5)
  634. self.currentScrubSpeedLabel.text = NSLocalizedString(@"PLAYBACK_SCRUB_HALF", @"");
  635. else if (speed == .25)
  636. self.currentScrubSpeedLabel.text = NSLocalizedString(@"PLAYBACK_SCRUB_QUARTER", @"");
  637. else
  638. self.currentScrubSpeedLabel.text = NSLocalizedString(@"PLAYBACK_SCRUB_FINE", @"");
  639. [self _resetIdleTimer];
  640. }
  641. - (IBAction)positionSliderDrag:(id)sender
  642. {
  643. [self _updateScrubLabel];
  644. }
  645. - (IBAction)volumeSliderAction:(id)sender
  646. {
  647. [self _resetIdleTimer];
  648. }
  649. - (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context
  650. {
  651. if (!_isScrubbing) {
  652. self.positionSlider.value = [_mediaPlayer position];
  653. }
  654. if (_displayRemainingTime)
  655. [self.timeDisplay setTitle:[[_mediaPlayer remainingTime] stringValue] forState:UIControlStateNormal];
  656. else
  657. [self.timeDisplay setTitle:[[_mediaPlayer time] stringValue] forState:UIControlStateNormal];
  658. }
  659. - (void)mediaPlayerStateChanged:(NSNotification *)aNotification
  660. {
  661. VLCMediaPlayerState currentState = _mediaPlayer.state;
  662. if (currentState == VLCMediaPlayerStateError) {
  663. [self.statusLabel showStatusMessage:NSLocalizedString(@"PLAYBACK_FAILED", @"")];
  664. [self performSelector:@selector(closePlayback:) withObject:nil afterDelay:2.];
  665. }
  666. if ((currentState == VLCMediaPlayerStateEnded || currentState == VLCMediaPlayerStateStopped) && _listPlayer.repeatMode == VLCDoNotRepeat)
  667. [self performSelector:@selector(closePlayback:) withObject:nil afterDelay:2.];
  668. UIImage *playPauseImage = [_mediaPlayer isPlaying]? [UIImage imageNamed:@"pauseIcon"] : [UIImage imageNamed:@"playIcon"];
  669. [_playPauseButton setImage:playPauseImage forState:UIControlStateNormal];
  670. if ([[_mediaPlayer audioTrackIndexes] count] > 2)
  671. self.audioSwitcherButton.hidden = NO;
  672. else
  673. self.audioSwitcherButton.hidden = YES;
  674. if ([[_mediaPlayer videoSubTitlesIndexes] count] > 1)
  675. self.subtitleContainer.hidden = NO;
  676. else
  677. self.subtitleContainer.hidden = YES;
  678. }
  679. - (IBAction)playPause
  680. {
  681. if ([_mediaPlayer isPlaying])
  682. [_listPlayer pause];
  683. else
  684. [_listPlayer play];
  685. }
  686. - (IBAction)forward:(id)sender
  687. {
  688. [_mediaPlayer mediumJumpForward];
  689. }
  690. - (IBAction)backward:(id)sender
  691. {
  692. [_mediaPlayer mediumJumpBackward];
  693. }
  694. - (void)toggleRepeatMode:(id)sender
  695. {
  696. if (_listPlayer.repeatMode == VLCDoNotRepeat) {
  697. _listPlayer.repeatMode = VLCRepeatCurrentItem;
  698. [self.repeatButton setImage:[UIImage imageNamed:@"repeatOne"] forState:UIControlStateNormal];
  699. } else {
  700. _listPlayer.repeatMode = VLCDoNotRepeat;
  701. [self.repeatButton setImage:[UIImage imageNamed:@"repeat"] forState:UIControlStateNormal];
  702. }
  703. }
  704. - (IBAction)switchAudioTrack:(id)sender
  705. {
  706. _audiotrackActionSheet = [[UIActionSheet alloc] initWithTitle:NSLocalizedString(@"CHOOSE_AUDIO_TRACK", @"audio track selector") delegate:self cancelButtonTitle:nil destructiveButtonTitle:nil otherButtonTitles: nil];
  707. NSArray *audioTracks = [_mediaPlayer audioTrackNames];
  708. NSArray *audioTrackIndexes = [_mediaPlayer audioTrackIndexes];
  709. NSUInteger count = [audioTracks count];
  710. for (NSUInteger i = 0; i < count; i++) {
  711. NSString *indexIndicator = ([audioTrackIndexes[i] intValue] == [_mediaPlayer currentAudioTrackIndex])? @"\u2713": @"";
  712. NSString *buttonTitle = [NSString stringWithFormat:@"%@ %@", indexIndicator, audioTracks[i]];
  713. [_audiotrackActionSheet addButtonWithTitle:buttonTitle];
  714. }
  715. [_audiotrackActionSheet addButtonWithTitle:NSLocalizedString(@"BUTTON_CANCEL", @"cancel button")];
  716. [_audiotrackActionSheet setCancelButtonIndex:[_audiotrackActionSheet numberOfButtons] - 1];
  717. [_audiotrackActionSheet showInView:self.audioSwitcherButton];
  718. }
  719. - (IBAction)switchSubtitleTrack:(id)sender
  720. {
  721. NSArray *spuTracks = [_mediaPlayer videoSubTitlesNames];
  722. NSArray *spuTrackIndexes = [_mediaPlayer videoSubTitlesIndexes];
  723. NSUInteger count = [spuTracks count];
  724. if (count <= 1)
  725. return;
  726. _subtitleActionSheet = [[UIActionSheet alloc] initWithTitle:NSLocalizedString(@"CHOOSE_SUBTITLE_TRACK", @"subtitle track selector") delegate:self cancelButtonTitle:nil destructiveButtonTitle:nil otherButtonTitles: nil];
  727. for (NSUInteger i = 0; i < count; i++) {
  728. NSString *indexIndicator = ([spuTrackIndexes[i] intValue] == [_mediaPlayer currentVideoSubTitleIndex])? @"\u2713": @"";
  729. NSString *buttonTitle = [NSString stringWithFormat:@"%@ %@", indexIndicator, spuTracks[i]];
  730. [_subtitleActionSheet addButtonWithTitle:buttonTitle];
  731. }
  732. [_subtitleActionSheet addButtonWithTitle:NSLocalizedString(@"BUTTON_CANCEL", @"cancel button")];
  733. [_subtitleActionSheet setCancelButtonIndex:[_subtitleActionSheet numberOfButtons] - 1];
  734. [_subtitleActionSheet showInView: self.subtitleSwitcherButton];
  735. }
  736. - (void)actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex {
  737. if (buttonIndex == [actionSheet cancelButtonIndex])
  738. return;
  739. NSArray *indexArray;
  740. if (actionSheet == _subtitleActionSheet) {
  741. indexArray = _mediaPlayer.videoSubTitlesIndexes;
  742. if (buttonIndex <= indexArray.count) {
  743. _mediaPlayer.currentVideoSubTitleIndex = [indexArray[buttonIndex] intValue];
  744. }
  745. } else if (actionSheet == _audiotrackActionSheet) {
  746. indexArray = _mediaPlayer.audioTrackIndexes;
  747. if (buttonIndex <= indexArray.count) {
  748. _mediaPlayer.currentAudioTrackIndex = [indexArray[buttonIndex] intValue];
  749. }
  750. }
  751. }
  752. - (IBAction)toggleTimeDisplay:(id)sender
  753. {
  754. _displayRemainingTime = !_displayRemainingTime;
  755. [self _resetIdleTimer];
  756. }
  757. #pragma mark - multi-touch gestures
  758. - (void)tapRecognized
  759. {
  760. if ([_mediaPlayer isPlaying]) {
  761. [_listPlayer pause];
  762. [self.statusLabel showStatusMessage:@" ▌▌"];
  763. } else {
  764. [_listPlayer play];
  765. [self.statusLabel showStatusMessage:@" ►"];
  766. }
  767. }
  768. - (NSString*)detectPanTypeForPan:(UIPanGestureRecognizer*)panRecognizer
  769. {
  770. NSString * type;
  771. NSString * deviceType = [[UIDevice currentDevice] model];
  772. type = @"Volume"; // default in case of error
  773. CGPoint location = [panRecognizer locationInView:self.view];
  774. CGFloat position = location.x;
  775. UIInterfaceOrientation orientation = [[UIApplication sharedApplication] statusBarOrientation];
  776. CGRect screenRect = [[UIScreen mainScreen] bounds];
  777. CGFloat screenWidth = .0;
  778. if (orientation == UIDeviceOrientationPortrait)
  779. screenWidth = screenRect.size.width;
  780. else
  781. screenWidth = screenRect.size.height;
  782. if (position < screenWidth / 2)
  783. type = @"Brightness";
  784. if (position > screenWidth / 2)
  785. type = @"Volume";
  786. // only check for seeking gesture if on iPad , will overwrite last statements if true
  787. if ([deviceType isEqualToString:@"iPad"]) {
  788. if (location.y < 110)
  789. type = @"Seek";
  790. }
  791. return type;
  792. }
  793. - (void)panRecognized:(UIPanGestureRecognizer*)panRecognizer
  794. {
  795. CGFloat panDirectionX = [panRecognizer velocityInView:self.view].x;
  796. CGFloat panDirectionY = [panRecognizer velocityInView:self.view].y;
  797. if (panRecognizer.state == UIGestureRecognizerStateBegan) // Only Detect pantype when began to allow more freedom
  798. panType = [self detectPanTypeForPan:panRecognizer];
  799. if ([panType isEqual:@"Seek"]) {
  800. double timeRemainingDouble = (-_mediaPlayer.remainingTime.intValue*0.001);
  801. int timeRemaining = timeRemainingDouble;
  802. if (panDirectionX > 0) {
  803. if (timeRemaining > 2 ) // to not go outside duration , video will stop
  804. [_mediaPlayer jumpForward:1];
  805. } else
  806. [_mediaPlayer jumpBackward:1];
  807. } else if ([panType isEqual:@"Volume"]) {
  808. MPMusicPlayerController *musicPlayer = [MPMusicPlayerController applicationMusicPlayer];
  809. if (panDirectionY > 0)
  810. musicPlayer.volume -= 0.01;
  811. else
  812. musicPlayer.volume += 0.01;
  813. } else if ([panType isEqual:@"Brightness"]) {
  814. CGFloat brightness = [UIScreen mainScreen].brightness;
  815. if (panDirectionY > 0)
  816. [[UIScreen mainScreen] setBrightness:(brightness - 0.01)];
  817. else
  818. [[UIScreen mainScreen] setBrightness:(brightness + 0.01)];
  819. NSString *brightnessHUD = [NSString stringWithFormat:@"%@: %@ %%", NSLocalizedString(@"VFILTER_BRIGHTNESS", @""), [[[NSString stringWithFormat:@"%f",(brightness*100)] componentsSeparatedByString:@"."] objectAtIndex:0]];
  820. [self.statusLabel showStatusMessage:brightnessHUD];
  821. }
  822. if (panRecognizer.state == UIGestureRecognizerStateEnded) {
  823. if ([_mediaPlayer isPlaying])
  824. [_listPlayer play];
  825. }
  826. }
  827. - (void)swipeRecognized:(UISwipeGestureRecognizer*)swipeRecognizer
  828. {
  829. NSString * hudString = @" ";
  830. if (swipeRecognizer.direction == UISwipeGestureRecognizerDirectionRight) {
  831. double timeRemainingDouble = (-_mediaPlayer.remainingTime.intValue*0.001);
  832. int timeRemaining = timeRemainingDouble;
  833. if (FORWARD_SWIPE_DURATION < timeRemaining) {
  834. [_mediaPlayer jumpForward:FORWARD_SWIPE_DURATION];
  835. hudString = [NSString stringWithFormat:@"⇒ %is", FORWARD_SWIPE_DURATION];
  836. } else {
  837. [_mediaPlayer jumpForward:(timeRemaining - 5)];
  838. hudString = [NSString stringWithFormat:@"⇒ %is",(timeRemaining - 5)];
  839. }
  840. }
  841. else if (swipeRecognizer.direction == UISwipeGestureRecognizerDirectionLeft) {
  842. [_mediaPlayer jumpBackward:BACKWARD_SWIPE_DURATION];
  843. hudString = [NSString stringWithFormat:@"⇐ %is",BACKWARD_SWIPE_DURATION];
  844. }
  845. if (swipeRecognizer.state == UIGestureRecognizerStateEnded) {
  846. if ([_mediaPlayer isPlaying])
  847. [_listPlayer play];
  848. [self.statusLabel showStatusMessage:hudString];
  849. }
  850. }
  851. #pragma mark - Video Filter UI
  852. - (IBAction)videoFilterToggle:(id)sender
  853. {
  854. if (!_playbackSpeedViewHidden)
  855. self.playbackSpeedView.hidden = _playbackSpeedViewHidden = YES;
  856. if (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPhone) {
  857. if (!_controlsHidden)
  858. self.controllerPanel.hidden = _controlsHidden = YES;
  859. }
  860. self.videoFilterView.hidden = !_videoFiltersHidden;
  861. _videoFiltersHidden = self.videoFilterView.hidden;
  862. }
  863. - (IBAction)videoFilterSliderAction:(id)sender
  864. {
  865. if (sender == self.hueSlider)
  866. _mediaPlayer.hue = (int)self.hueSlider.value;
  867. else if (sender == self.contrastSlider)
  868. _mediaPlayer.contrast = self.contrastSlider.value;
  869. else if (sender == self.brightnessSlider) {
  870. if ([self hasExternalDisplay])
  871. _mediaPlayer.brightness = self.brightnessSlider.value;
  872. else
  873. [[UIScreen mainScreen] setBrightness:(self.brightnessSlider.value / 2.)];
  874. } else if (sender == self.saturationSlider)
  875. _mediaPlayer.saturation = self.saturationSlider.value;
  876. else if (sender == self.gammaSlider)
  877. _mediaPlayer.gamma = self.gammaSlider.value;
  878. else if (sender == self.resetVideoFilterButton) {
  879. _mediaPlayer.hue = self.hueSlider.value = 0.;
  880. _mediaPlayer.contrast = self.contrastSlider.value = 1.;
  881. _mediaPlayer.brightness = self.brightnessSlider.value = 1.;
  882. [[UIScreen mainScreen] setBrightness:(self.brightnessSlider.value / 2.)];
  883. _mediaPlayer.saturation = self.saturationSlider.value = 1.;
  884. _mediaPlayer.gamma = self.gammaSlider.value = 1.;
  885. } else
  886. APLog(@"unknown sender for videoFilterSliderAction");
  887. [self _resetIdleTimer];
  888. }
  889. #pragma mark - playback view
  890. - (IBAction)playbackSpeedSliderAction:(UISlider *)sender
  891. {
  892. double speed = pow(2, sender.value / 17.);
  893. float rate = INPUT_RATE_DEFAULT / speed;
  894. if (_currentPlaybackRate != rate)
  895. [_mediaPlayer setRate:INPUT_RATE_DEFAULT / rate];
  896. _currentPlaybackRate = rate;
  897. [self _updatePlaybackSpeedIndicator];
  898. [self _resetIdleTimer];
  899. }
  900. - (void)_updatePlaybackSpeedIndicator
  901. {
  902. float f_value = self.playbackSpeedSlider.value;
  903. double speed = pow(2, f_value / 17.);
  904. self.playbackSpeedIndicator.text = [NSString stringWithFormat:@"%.2fx", speed];
  905. /* rate changed, so update the exported info */
  906. [self performSelectorInBackground:@selector(_updateExportedPlaybackInformation) withObject:nil];
  907. }
  908. - (float)_playbackSpeed
  909. {
  910. float f_rate = _mediaPlayer.rate;
  911. double value = 17 * log(f_rate) / log(2.);
  912. float returnValue = (int) ((value > 0) ? value + .5 : value - .5);
  913. if (returnValue < -34.)
  914. returnValue = -34.;
  915. else if (returnValue > 34.)
  916. returnValue = 34.;
  917. _currentPlaybackRate = returnValue;
  918. return returnValue;
  919. }
  920. - (IBAction)videoDimensionAction:(id)sender
  921. {
  922. if (sender == self.playbackSpeedButton) {
  923. if (!_videoFiltersHidden)
  924. self.videoFilterView.hidden = _videoFiltersHidden = YES;
  925. self.playbackSpeedView.hidden = !_playbackSpeedViewHidden;
  926. _playbackSpeedViewHidden = self.playbackSpeedView.hidden;
  927. [self _resetIdleTimer];
  928. } else if (sender == self.aspectRatioButton) {
  929. NSUInteger count = [_aspectRatios count];
  930. if (_currentAspectRatioMask + 1 > count - 1) {
  931. _mediaPlayer.videoAspectRatio = NULL;
  932. _mediaPlayer.videoCropGeometry = NULL;
  933. _currentAspectRatioMask = 0;
  934. [self.statusLabel showStatusMessage:[NSString stringWithFormat:NSLocalizedString(@"AR_CHANGED", @""), NSLocalizedString(@"DEFAULT", @"")]];
  935. } else {
  936. _currentAspectRatioMask++;
  937. if ([_aspectRatios[_currentAspectRatioMask] isEqualToString:@"FILL_TO_SCREEN"]) {
  938. UIScreen *screen;
  939. if (![self hasExternalDisplay])
  940. screen = [UIScreen mainScreen];
  941. else
  942. screen = [UIScreen screens][1];
  943. float f_ar = screen.bounds.size.width / screen.bounds.size.height;
  944. if (f_ar == (float)(640./1136.)) // iPhone 5 aka 16:9.01
  945. _mediaPlayer.videoCropGeometry = "16:9";
  946. else if (f_ar == (float)(2./3.)) // all other iPhones
  947. _mediaPlayer.videoCropGeometry = "16:10"; // libvlc doesn't support 2:3 crop
  948. else if (f_ar == .75) // all iPads
  949. _mediaPlayer.videoCropGeometry = "4:3";
  950. else if (f_ar == .5625) // AirPlay
  951. _mediaPlayer.videoCropGeometry = "16:9";
  952. else
  953. APLog(@"unknown screen format %f, can't crop", f_ar);
  954. [self.statusLabel showStatusMessage:NSLocalizedString(@"FILL_TO_SCREEN", @"")];
  955. return;
  956. }
  957. _mediaPlayer.videoCropGeometry = NULL;
  958. _mediaPlayer.videoAspectRatio = (char *)[_aspectRatios[_currentAspectRatioMask] UTF8String];
  959. [self.statusLabel showStatusMessage:[NSString stringWithFormat:NSLocalizedString(@"AR_CHANGED", @""), _aspectRatios[_currentAspectRatioMask]]];
  960. }
  961. }
  962. }
  963. #pragma mark - background interaction
  964. - (void)applicationWillResignActive:(NSNotification *)aNotification
  965. {
  966. [self _saveCurrentState];
  967. _mediaPlayer.currentVideoTrackIndex = 0;
  968. if (![[[NSUserDefaults standardUserDefaults] objectForKey:kVLCSettingContinueAudioInBackgroundKey] boolValue]) {
  969. if ([_mediaPlayer isPlaying]) {
  970. [_mediaPlayer pause];
  971. _shouldResumePlaying = YES;
  972. }
  973. }
  974. }
  975. - (void)applicationDidEnterBackground:(NSNotification *)notification
  976. {
  977. _shouldResumePlaying = NO;
  978. }
  979. - (void)applicationDidBecomeActive:(NSNotification *)notification
  980. {
  981. _mediaPlayer.currentVideoTrackIndex = 1;
  982. if (_shouldResumePlaying) {
  983. _shouldResumePlaying = NO;
  984. [_listPlayer play];
  985. }
  986. }
  987. - (void)_updateExportedPlaybackInformation
  988. {
  989. if (!_mediaItem) {
  990. [MPNowPlayingInfoCenter defaultCenter].nowPlayingInfo = nil;
  991. return;
  992. }
  993. MLFile * currentFile = _mediaItem;
  994. /* don't leak sensitive information to the OS, if passcode lock is enabled */
  995. BOOL passcodeLockEnabled = [[[NSUserDefaults standardUserDefaults] objectForKey:kVLCSettingPasscodeOnKey] boolValue];
  996. /* we omit artwork for now since we had to read it from storage as we can't access
  997. * the artwork cache at the moment - FIXME? */
  998. NSMutableDictionary *currentlyPlayingTrackInfo;
  999. if (passcodeLockEnabled)
  1000. currentlyPlayingTrackInfo = [NSMutableDictionary dictionaryWithObjectsAndKeys:@(currentFile.duration.intValue / 1000.), MPMediaItemPropertyPlaybackDuration, @(_mediaPlayer.time.intValue / 1000.), MPNowPlayingInfoPropertyElapsedPlaybackTime, @(_mediaPlayer.rate), MPNowPlayingInfoPropertyPlaybackRate, nil];
  1001. else
  1002. currentlyPlayingTrackInfo = [NSMutableDictionary dictionaryWithObjectsAndKeys: currentFile.title, MPMediaItemPropertyTitle, @(currentFile.duration.intValue / 1000.), MPMediaItemPropertyPlaybackDuration, @(_mediaPlayer.time.intValue / 1000.), MPNowPlayingInfoPropertyElapsedPlaybackTime, @(_mediaPlayer.rate), MPNowPlayingInfoPropertyPlaybackRate, nil];
  1003. if ([currentFile isAlbumTrack] && !passcodeLockEnabled) {
  1004. MLAlbumTrack *track = currentFile.albumTrack;
  1005. if (track.artist.length > 0)
  1006. [currentlyPlayingTrackInfo setObject:track.artist forKey:MPMediaItemPropertyArtist];
  1007. if (track.title.length > 0)
  1008. [currentlyPlayingTrackInfo setObject:track.title forKey:MPMediaItemPropertyTitle];
  1009. if (track.album.name.length > 0)
  1010. [currentlyPlayingTrackInfo setObject:track.album.name forKey:MPMediaItemPropertyAlbumTitle];
  1011. [currentlyPlayingTrackInfo setObject:[NSNumber numberWithInt:[track.trackNumber intValue]] forKey:MPMediaItemPropertyAlbumTrackNumber];
  1012. }
  1013. [MPNowPlayingInfoCenter defaultCenter].nowPlayingInfo = currentlyPlayingTrackInfo;
  1014. }
  1015. #pragma mark - autorotation
  1016. - (BOOL)shouldAutorotate
  1017. {
  1018. UIInterfaceOrientation toInterfaceOrientation = [[UIApplication sharedApplication] statusBarOrientation];
  1019. return UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPad
  1020. || toInterfaceOrientation != UIInterfaceOrientationPortraitUpsideDown;
  1021. }
  1022. #pragma mark - AVSession delegate
  1023. - (void)beginInterruption
  1024. {
  1025. if ([[[NSUserDefaults standardUserDefaults] objectForKey:kVLCSettingContinueAudioInBackgroundKey] boolValue])
  1026. _shouldResumePlaying = YES;
  1027. [_mediaPlayer pause];
  1028. }
  1029. - (void)endInterruption
  1030. {
  1031. if (_shouldResumePlaying) {
  1032. [_listPlayer play];
  1033. _shouldResumePlaying = NO;
  1034. }
  1035. }
  1036. #pragma mark - External Display
  1037. - (BOOL)hasExternalDisplay
  1038. {
  1039. return ([[UIScreen screens] count] > 1);
  1040. }
  1041. - (void)showOnExternalDisplay
  1042. {
  1043. UIScreen *screen = [UIScreen screens][1];
  1044. screen.overscanCompensation = UIScreenOverscanCompensationInsetApplicationFrame;
  1045. self.externalWindow = [[UIWindow alloc] initWithFrame:screen.bounds];
  1046. UIViewController *controller = [[VLCExternalDisplayController alloc] init];
  1047. self.externalWindow.rootViewController = controller;
  1048. [controller.view addSubview:_movieView];
  1049. controller.view.frame = screen.bounds;
  1050. _movieView.frame = screen.bounds;
  1051. self.playingExternallyView.hidden = NO;
  1052. self.externalWindow.screen = screen;
  1053. self.externalWindow.hidden = NO;
  1054. }
  1055. - (void)hideFromExternalDisplay
  1056. {
  1057. [self.view addSubview:_movieView];
  1058. [self.view sendSubviewToBack:_movieView];
  1059. _movieView.frame = self.view.frame;
  1060. self.playingExternallyView.hidden = YES;
  1061. self.externalWindow.hidden = YES;
  1062. self.externalWindow = nil;
  1063. }
  1064. - (void)handleExternalScreenDidConnect:(NSNotification *)notification
  1065. {
  1066. [self showOnExternalDisplay];
  1067. }
  1068. - (void)handleExternalScreenDidDisconnect:(NSNotification *)notification
  1069. {
  1070. [self hideFromExternalDisplay];
  1071. }
  1072. @end