VLCMovieViewController.m 48 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288
  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. if (![self _isMediaSuitableForDevice]) {
  344. 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];
  345. [alert show];
  346. } else
  347. [self _playNewMedia];
  348. if (![self hasExternalDisplay])
  349. self.brightnessSlider.value = [UIScreen mainScreen].brightness * 2.;
  350. }
  351. - (BOOL)_isMediaSuitableForDevice
  352. {
  353. if (!self.mediaItem)
  354. return YES;
  355. NSUInteger totalNumberOfPixels = [[[self.mediaItem videoTrack] valueForKey:@"width"] doubleValue] * [[[self.mediaItem videoTrack] valueForKey:@"height"] doubleValue];
  356. NSInteger speedCategory = [[UIDevice currentDevice] speedCategory];
  357. if (speedCategory == 1) {
  358. // iPhone 3GS, iPhone 4, first gen. iPad, 3rd and 4th generation iPod touch
  359. return (totalNumberOfPixels < 600000); // between 480p and 720p
  360. } else if (speedCategory == 2) {
  361. // iPhone 4S, iPad 2 and 3, iPod 4 and 5
  362. return (totalNumberOfPixels < 922000); // 720p
  363. } else if (speedCategory == 3) {
  364. // iPhone 5, iPad 4
  365. return (totalNumberOfPixels < 2074000); // 1080p
  366. }
  367. return YES;
  368. }
  369. - (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
  370. {
  371. if (buttonIndex == 1)
  372. [self _playNewMedia];
  373. else {
  374. [self _stopPlayback];
  375. [self closePlayback:nil];
  376. }
  377. }
  378. - (void)_playNewMedia
  379. {
  380. NSNumber *playbackPositionInTime = @(0);
  381. CGFloat lastPosition = .0;
  382. NSInteger duration = self.mediaItem.duration.intValue;
  383. if (self.mediaItem.lastPosition)
  384. lastPosition = self.mediaItem.lastPosition.floatValue;
  385. if (lastPosition < .95) {
  386. if (duration != 0)
  387. playbackPositionInTime = @(lastPosition * (duration / 1000.));
  388. }
  389. if (playbackPositionInTime.intValue > 0) {
  390. [_mediaPlayer.media addOptions:@{@"start-time": playbackPositionInTime}];
  391. APLog(@"set starttime to %i", playbackPositionInTime.intValue);
  392. }
  393. [_mediaPlayer addObserver:self forKeyPath:@"time" options:0 context:nil];
  394. [_mediaPlayer addObserver:self forKeyPath:@"remainingTime" options:0 context:nil];
  395. [_listPlayer playMedia:_listPlayer.rootMedia];
  396. if (self.mediaItem) {
  397. if (self.mediaItem.lastAudioTrack.intValue > 0)
  398. _mediaPlayer.currentAudioTrackIndex = self.mediaItem.lastAudioTrack.intValue;
  399. if (self.mediaItem.lastSubtitleTrack.intValue > 0)
  400. _mediaPlayer.currentVideoSubTitleIndex = self.mediaItem.lastSubtitleTrack.intValue;
  401. }
  402. self.playbackSpeedSlider.value = [self _playbackSpeed];
  403. [self _updatePlaybackSpeedIndicator];
  404. [self performSelectorInBackground:@selector(_updateExportedPlaybackInformation) withObject:nil];
  405. _currentAspectRatioMask = 0;
  406. _mediaPlayer.videoAspectRatio = NULL;
  407. /* some demuxers don't respect :start-time, so re-try here */
  408. if (lastPosition < .95 && _mediaPlayer.position < lastPosition)
  409. _mediaPlayer.position = lastPosition;
  410. [self _resetIdleTimer];
  411. _playerIsSetup = YES;
  412. }
  413. - (void)viewWillDisappear:(BOOL)animated
  414. {
  415. [self _stopPlayback];
  416. _viewAppeared = NO;
  417. if (_idleTimer) {
  418. [_idleTimer invalidate];
  419. _idleTimer = nil;
  420. }
  421. [self.navigationController setNavigationBarHidden:NO animated:YES];
  422. if (!SYSTEM_RUNS_IOS7_OR_LATER)
  423. [UIApplication sharedApplication].statusBarStyle = UIStatusBarStyleBlackOpaque;
  424. [[UIApplication sharedApplication] setStatusBarHidden:NO withAnimation:UIStatusBarAnimationFade];
  425. [super viewWillDisappear:animated];
  426. // hide filter UI for next run
  427. if (!_videoFiltersHidden)
  428. _videoFiltersHidden = YES;
  429. if (!_playbackSpeedViewHidden)
  430. _playbackSpeedViewHidden = YES;
  431. }
  432. - (void)_stopPlayback
  433. {
  434. if (_mediaPlayer) {
  435. @try {
  436. [_mediaPlayer removeObserver:self forKeyPath:@"time"];
  437. [_mediaPlayer removeObserver:self forKeyPath:@"remainingTime"];
  438. }
  439. @catch (NSException *exception) {
  440. APLog(@"we weren't an observer yet");
  441. }
  442. if (_mediaPlayer.media) {
  443. [_mediaPlayer pause];
  444. [self _saveCurrentState];
  445. [_mediaPlayer stop];
  446. }
  447. if (_mediaPlayer)
  448. _mediaPlayer = nil;
  449. if (_listPlayer)
  450. _listPlayer = nil;
  451. }
  452. if (_mediaItem)
  453. _mediaItem = nil;
  454. _playerIsSetup = NO;
  455. }
  456. - (void)_saveCurrentState
  457. {
  458. if (self.mediaItem) {
  459. @try {
  460. MLFile *item = self.mediaItem;
  461. item.lastPosition = @([_mediaPlayer position]);
  462. item.lastAudioTrack = @(_mediaPlayer.currentAudioTrackIndex);
  463. item.lastSubtitleTrack = @(_mediaPlayer.currentVideoSubTitleIndex);
  464. }
  465. @catch (NSException *exception) {
  466. APLog(@"failed to save current media state - file removed?");
  467. }
  468. }
  469. }
  470. #pragma mark - remote events
  471. - (void)viewDidAppear:(BOOL)animated
  472. {
  473. [super viewDidAppear:animated];
  474. [[UIApplication sharedApplication] beginReceivingRemoteControlEvents];
  475. [self becomeFirstResponder];
  476. }
  477. - (void)viewDidDisappear:(BOOL)animated
  478. {
  479. [super viewDidDisappear:animated];
  480. [[UIApplication sharedApplication] endReceivingRemoteControlEvents];
  481. [self resignFirstResponder];
  482. [[NSUserDefaults standardUserDefaults] setBool:_displayRemainingTime forKey:kVLCShowRemainingTime];
  483. }
  484. - (BOOL)canBecomeFirstResponder
  485. {
  486. return YES;
  487. }
  488. - (void)remoteControlReceivedWithEvent:(UIEvent *)event
  489. {
  490. switch (event.subtype) {
  491. case UIEventSubtypeRemoteControlPlay:
  492. [_listPlayer play];
  493. break;
  494. case UIEventSubtypeRemoteControlPause:
  495. [_listPlayer pause];
  496. break;
  497. case UIEventSubtypeRemoteControlTogglePlayPause:
  498. [self playPause];
  499. break;
  500. default:
  501. break;
  502. }
  503. }
  504. #pragma mark - controls visibility
  505. - (void)handlePinchGesture:(UIPinchGestureRecognizer *)recognizer
  506. {
  507. if (recognizer.velocity < 0.)
  508. [self closePlayback:nil];
  509. }
  510. - (BOOL)gestureRecognizer:(UIGestureRecognizer *)gestureRecognizer shouldReceiveTouch:(UITouch *)touch
  511. {
  512. if (touch.view != self.view)
  513. return NO;
  514. return YES;
  515. }
  516. - (BOOL)gestureRecognizer:(UIGestureRecognizer *)gestureRecognizer shouldRecognizeSimultaneouslyWithGestureRecognizer:(UIGestureRecognizer *)otherGestureRecognizer
  517. {
  518. return YES;
  519. }
  520. - (void)setControlsHidden:(BOOL)hidden animated:(BOOL)animated
  521. {
  522. _controlsHidden = hidden;
  523. CGFloat alpha = _controlsHidden? 0.0f: 1.0f;
  524. if (!_controlsHidden) {
  525. _controllerPanel.alpha = 0.0f;
  526. _controllerPanel.hidden = !_videoFiltersHidden;
  527. _toolbar.alpha = 0.0f;
  528. _toolbar.hidden = NO;
  529. _videoFilterView.alpha = 0.0f;
  530. _videoFilterView.hidden = _videoFiltersHidden;
  531. _playbackSpeedView.alpha = 0.0f;
  532. _playbackSpeedView.hidden = _playbackSpeedViewHidden;
  533. }
  534. void (^animationBlock)() = ^() {
  535. _controllerPanel.alpha = alpha;
  536. _toolbar.alpha = alpha;
  537. _videoFilterView.alpha = alpha;
  538. _playbackSpeedView.alpha = alpha;
  539. };
  540. void (^completionBlock)(BOOL finished) = ^(BOOL finished) {
  541. if (_videoFiltersHidden)
  542. _controllerPanel.hidden = _controlsHidden;
  543. else
  544. _controllerPanel.hidden = NO;
  545. _toolbar.hidden = _controlsHidden;
  546. _videoFilterView.hidden = _videoFiltersHidden;
  547. _playbackSpeedView.hidden = _playbackSpeedViewHidden;
  548. };
  549. UIStatusBarAnimation animationType = animated? UIStatusBarAnimationFade: UIStatusBarAnimationNone;
  550. NSTimeInterval animationDuration = animated? 0.3: 0.0;
  551. [[UIApplication sharedApplication] setStatusBarHidden:_viewAppeared ? _controlsHidden : NO withAnimation:animationType];
  552. [UIView animateWithDuration:animationDuration animations:animationBlock completion:completionBlock];
  553. _volumeView.hidden = _controllerPanel.hidden;
  554. }
  555. - (void)toggleControlsVisible
  556. {
  557. if (_controlsHidden && !_videoFiltersHidden)
  558. _videoFiltersHidden = YES;
  559. [self setControlsHidden:!_controlsHidden animated:YES];
  560. }
  561. - (void)_resetIdleTimer
  562. {
  563. if (!_idleTimer)
  564. _idleTimer = [NSTimer scheduledTimerWithTimeInterval:4.
  565. target:self
  566. selector:@selector(idleTimerExceeded)
  567. userInfo:nil
  568. repeats:NO];
  569. else {
  570. if (fabs([_idleTimer.fireDate timeIntervalSinceNow]) < 4.)
  571. [_idleTimer setFireDate:[NSDate dateWithTimeIntervalSinceNow:4.]];
  572. }
  573. }
  574. - (void)idleTimerExceeded
  575. {
  576. _idleTimer = nil;
  577. if (!_controlsHidden)
  578. [self toggleControlsVisible];
  579. if (!_videoFiltersHidden)
  580. _videoFiltersHidden = YES;
  581. if (!_playbackSpeedViewHidden)
  582. _playbackSpeedViewHidden = YES;
  583. if (self.scrubIndicatorView.hidden == NO)
  584. self.scrubIndicatorView.hidden = YES;
  585. }
  586. - (UIResponder *)nextResponder
  587. {
  588. [self _resetIdleTimer];
  589. return [super nextResponder];
  590. }
  591. #pragma mark - controls
  592. - (IBAction)closePlayback:(id)sender
  593. {
  594. [self setControlsHidden:NO animated:NO];
  595. [self.navigationController dismissViewControllerAnimated:YES completion:nil];
  596. }
  597. - (IBAction)positionSliderAction:(UISlider *)sender
  598. {
  599. /* we need to limit the number of events sent by the slider, since otherwise, the user
  600. * wouldn't see the I-frames when seeking on current mobile devices. This isn't a problem
  601. * within the Simulator, but especially on older ARMv7 devices, it's clearly noticeable. */
  602. [self performSelector:@selector(_setPositionForReal) withObject:nil afterDelay:0.3];
  603. VLCTime *newPosition = [VLCTime timeWithInt:(int)(_positionSlider.value * self.mediaItem.duration.intValue)];
  604. [self.timeDisplay setTitle:newPosition.stringValue forState:UIControlStateNormal];
  605. self.timeDisplay.accessibilityLabel = [NSString stringWithFormat:@"%@: %@", NSLocalizedString(@"PLAYBACK_POSITION", @""), newPosition.stringValue];
  606. _positionSet = NO;
  607. [self _resetIdleTimer];
  608. }
  609. - (void)_setPositionForReal
  610. {
  611. if (!_positionSet) {
  612. _mediaPlayer.position = _positionSlider.value;
  613. _positionSet = YES;
  614. }
  615. }
  616. - (IBAction)positionSliderTouchDown:(id)sender
  617. {
  618. [self _updateScrubLabel];
  619. self.scrubIndicatorView.hidden = NO;
  620. _isScrubbing = YES;
  621. }
  622. - (IBAction)positionSliderTouchUp:(id)sender
  623. {
  624. self.scrubIndicatorView.hidden = YES;
  625. _isScrubbing = NO;
  626. }
  627. - (void)_updateScrubLabel
  628. {
  629. float speed = self.positionSlider.scrubbingSpeed;
  630. if (speed == 1.)
  631. self.currentScrubSpeedLabel.text = NSLocalizedString(@"PLAYBACK_SCRUB_HIGH", @"");
  632. else if (speed == .5)
  633. self.currentScrubSpeedLabel.text = NSLocalizedString(@"PLAYBACK_SCRUB_HALF", @"");
  634. else if (speed == .25)
  635. self.currentScrubSpeedLabel.text = NSLocalizedString(@"PLAYBACK_SCRUB_QUARTER", @"");
  636. else
  637. self.currentScrubSpeedLabel.text = NSLocalizedString(@"PLAYBACK_SCRUB_FINE", @"");
  638. [self _resetIdleTimer];
  639. }
  640. - (IBAction)positionSliderDrag:(id)sender
  641. {
  642. [self _updateScrubLabel];
  643. }
  644. - (IBAction)volumeSliderAction:(id)sender
  645. {
  646. [self _resetIdleTimer];
  647. }
  648. - (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context
  649. {
  650. if (!_isScrubbing) {
  651. self.positionSlider.value = [_mediaPlayer position];
  652. }
  653. if (_displayRemainingTime)
  654. [self.timeDisplay setTitle:[[_mediaPlayer remainingTime] stringValue] forState:UIControlStateNormal];
  655. else
  656. [self.timeDisplay setTitle:[[_mediaPlayer time] stringValue] forState:UIControlStateNormal];
  657. }
  658. - (void)mediaPlayerStateChanged:(NSNotification *)aNotification
  659. {
  660. VLCMediaPlayerState currentState = _mediaPlayer.state;
  661. if (currentState == VLCMediaPlayerStateError) {
  662. [self.statusLabel showStatusMessage:NSLocalizedString(@"PLAYBACK_FAILED", @"")];
  663. [self performSelector:@selector(closePlayback:) withObject:nil afterDelay:2.];
  664. }
  665. if ((currentState == VLCMediaPlayerStateEnded || currentState == VLCMediaPlayerStateStopped) && _listPlayer.repeatMode == VLCDoNotRepeat)
  666. [self performSelector:@selector(closePlayback:) withObject:nil afterDelay:2.];
  667. UIImage *playPauseImage = [_mediaPlayer isPlaying]? [UIImage imageNamed:@"pauseIcon"] : [UIImage imageNamed:@"playIcon"];
  668. [_playPauseButton setImage:playPauseImage forState:UIControlStateNormal];
  669. if ([[_mediaPlayer audioTrackIndexes] count] > 2)
  670. self.audioSwitcherButton.hidden = NO;
  671. else
  672. self.audioSwitcherButton.hidden = YES;
  673. if ([[_mediaPlayer videoSubTitlesIndexes] count] > 1)
  674. self.subtitleContainer.hidden = NO;
  675. else
  676. self.subtitleContainer.hidden = YES;
  677. }
  678. - (IBAction)playPause
  679. {
  680. if ([_mediaPlayer isPlaying])
  681. [_listPlayer pause];
  682. else
  683. [_listPlayer play];
  684. }
  685. - (IBAction)forward:(id)sender
  686. {
  687. [_mediaPlayer mediumJumpForward];
  688. }
  689. - (IBAction)backward:(id)sender
  690. {
  691. [_mediaPlayer mediumJumpBackward];
  692. }
  693. - (void)toggleRepeatMode:(id)sender
  694. {
  695. if (_listPlayer.repeatMode == VLCDoNotRepeat)
  696. _listPlayer.repeatMode = VLCRepeatCurrentItem;
  697. else
  698. _listPlayer.repeatMode = VLCDoNotRepeat;
  699. }
  700. - (IBAction)switchAudioTrack:(id)sender
  701. {
  702. _audiotrackActionSheet = [[UIActionSheet alloc] initWithTitle:NSLocalizedString(@"CHOOSE_AUDIO_TRACK", @"audio track selector") delegate:self cancelButtonTitle:nil destructiveButtonTitle:nil otherButtonTitles: nil];
  703. NSArray *audioTracks = [_mediaPlayer audioTrackNames];
  704. NSArray *audioTrackIndexes = [_mediaPlayer audioTrackIndexes];
  705. NSUInteger count = [audioTracks count];
  706. for (NSUInteger i = 0; i < count; i++) {
  707. NSString *indexIndicator = ([audioTrackIndexes[i] intValue] == [_mediaPlayer currentAudioTrackIndex])? @"\u2713": @"";
  708. NSString *buttonTitle = [NSString stringWithFormat:@"%@ %@", indexIndicator, audioTracks[i]];
  709. [_audiotrackActionSheet addButtonWithTitle:buttonTitle];
  710. }
  711. [_audiotrackActionSheet addButtonWithTitle:NSLocalizedString(@"BUTTON_CANCEL", @"cancel button")];
  712. [_audiotrackActionSheet setCancelButtonIndex:[_audiotrackActionSheet numberOfButtons] - 1];
  713. [_audiotrackActionSheet showInView:self.audioSwitcherButton];
  714. }
  715. - (IBAction)switchSubtitleTrack:(id)sender
  716. {
  717. NSArray *spuTracks = [_mediaPlayer videoSubTitlesNames];
  718. NSArray *spuTrackIndexes = [_mediaPlayer videoSubTitlesIndexes];
  719. NSUInteger count = [spuTracks count];
  720. if (count <= 1)
  721. return;
  722. _subtitleActionSheet = [[UIActionSheet alloc] initWithTitle:NSLocalizedString(@"CHOOSE_SUBTITLE_TRACK", @"subtitle track selector") delegate:self cancelButtonTitle:nil destructiveButtonTitle:nil otherButtonTitles: nil];
  723. for (NSUInteger i = 0; i < count; i++) {
  724. NSString *indexIndicator = ([spuTrackIndexes[i] intValue] == [_mediaPlayer currentVideoSubTitleIndex])? @"\u2713": @"";
  725. NSString *buttonTitle = [NSString stringWithFormat:@"%@ %@", indexIndicator, spuTracks[i]];
  726. [_subtitleActionSheet addButtonWithTitle:buttonTitle];
  727. }
  728. [_subtitleActionSheet addButtonWithTitle:NSLocalizedString(@"BUTTON_CANCEL", @"cancel button")];
  729. [_subtitleActionSheet setCancelButtonIndex:[_subtitleActionSheet numberOfButtons] - 1];
  730. [_subtitleActionSheet showInView: self.subtitleSwitcherButton];
  731. }
  732. - (void)actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex {
  733. if (buttonIndex == [actionSheet cancelButtonIndex])
  734. return;
  735. NSArray *indexArray;
  736. if (actionSheet == _subtitleActionSheet) {
  737. indexArray = _mediaPlayer.videoSubTitlesIndexes;
  738. if (buttonIndex <= indexArray.count) {
  739. _mediaPlayer.currentVideoSubTitleIndex = [indexArray[buttonIndex] intValue];
  740. }
  741. } else if (actionSheet == _audiotrackActionSheet) {
  742. indexArray = _mediaPlayer.audioTrackIndexes;
  743. if (buttonIndex <= indexArray.count) {
  744. _mediaPlayer.currentAudioTrackIndex = [indexArray[buttonIndex] intValue];
  745. }
  746. }
  747. }
  748. - (IBAction)toggleTimeDisplay:(id)sender
  749. {
  750. _displayRemainingTime = !_displayRemainingTime;
  751. [self _resetIdleTimer];
  752. }
  753. #pragma mark - multi-touch gestures
  754. - (void)tapRecognized
  755. {
  756. if ([_mediaPlayer isPlaying]) {
  757. [_listPlayer pause];
  758. [self.statusLabel showStatusMessage:@" ▌▌"];
  759. } else {
  760. [_listPlayer play];
  761. [self.statusLabel showStatusMessage:@" ►"];
  762. }
  763. }
  764. - (NSString*)detectPanTypeForPan:(UIPanGestureRecognizer*)panRecognizer
  765. {
  766. NSString * type;
  767. NSString * deviceType = [[UIDevice currentDevice] model];
  768. type = @"Volume"; // default in case of error
  769. CGPoint location = [panRecognizer locationInView:self.view];
  770. CGFloat position = location.x;
  771. UIInterfaceOrientation orientation = [[UIApplication sharedApplication] statusBarOrientation];
  772. CGRect screenRect = [[UIScreen mainScreen] bounds];
  773. CGFloat screenWidth = .0;
  774. if (orientation == UIDeviceOrientationPortrait)
  775. screenWidth = screenRect.size.width;
  776. else
  777. screenWidth = screenRect.size.height;
  778. if (position < screenWidth / 2)
  779. type = @"Brightness";
  780. if (position > screenWidth / 2)
  781. type = @"Volume";
  782. // only check for seeking gesture if on iPad , will overwrite last statements if true
  783. if ([deviceType isEqualToString:@"iPad"]) {
  784. if (location.y < 110)
  785. type = @"Seek";
  786. }
  787. return type;
  788. }
  789. - (void)panRecognized:(UIPanGestureRecognizer*)panRecognizer
  790. {
  791. CGFloat panDirectionX = [panRecognizer velocityInView:self.view].x;
  792. CGFloat panDirectionY = [panRecognizer velocityInView:self.view].y;
  793. if (panRecognizer.state == UIGestureRecognizerStateBegan) // Only Detect pantype when began to allow more freedom
  794. panType = [self detectPanTypeForPan:panRecognizer];
  795. if ([panType isEqual:@"Seek"]) {
  796. double timeRemainingDouble = (-_mediaPlayer.remainingTime.intValue*0.001);
  797. int timeRemaining = timeRemainingDouble;
  798. if (panDirectionX > 0) {
  799. if (timeRemaining > 2 ) // to not go outside duration , video will stop
  800. [_mediaPlayer jumpForward:1];
  801. } else
  802. [_mediaPlayer jumpBackward:1];
  803. } else if ([panType isEqual:@"Volume"]) {
  804. MPMusicPlayerController *musicPlayer = [MPMusicPlayerController applicationMusicPlayer];
  805. if (panDirectionY > 0)
  806. musicPlayer.volume -= 0.01;
  807. else
  808. musicPlayer.volume += 0.01;
  809. } else if ([panType isEqual:@"Brightness"]) {
  810. CGFloat brightness = [UIScreen mainScreen].brightness;
  811. if (panDirectionY > 0)
  812. [[UIScreen mainScreen] setBrightness:(brightness - 0.01)];
  813. else
  814. [[UIScreen mainScreen] setBrightness:(brightness + 0.01)];
  815. NSString *brightnessHUD = [NSString stringWithFormat:@"%@: %@ %%", NSLocalizedString(@"VFILTER_BRIGHTNESS", @""), [[[NSString stringWithFormat:@"%f",(brightness*100)] componentsSeparatedByString:@"."] objectAtIndex:0]];
  816. [self.statusLabel showStatusMessage:brightnessHUD];
  817. }
  818. if (panRecognizer.state == UIGestureRecognizerStateEnded) {
  819. if ([_mediaPlayer isPlaying])
  820. [_listPlayer play];
  821. }
  822. }
  823. - (void)swipeRecognized:(UISwipeGestureRecognizer*)swipeRecognizer
  824. {
  825. NSString * hudString = @" ";
  826. if (swipeRecognizer.direction == UISwipeGestureRecognizerDirectionRight) {
  827. double timeRemainingDouble = (-_mediaPlayer.remainingTime.intValue*0.001);
  828. int timeRemaining = timeRemainingDouble;
  829. if (FORWARD_SWIPE_DURATION < timeRemaining) {
  830. [_mediaPlayer jumpForward:FORWARD_SWIPE_DURATION];
  831. hudString = [NSString stringWithFormat:@"⇒ %is", FORWARD_SWIPE_DURATION];
  832. } else {
  833. [_mediaPlayer jumpForward:(timeRemaining - 5)];
  834. hudString = [NSString stringWithFormat:@"⇒ %is",(timeRemaining - 5)];
  835. }
  836. }
  837. else if (swipeRecognizer.direction == UISwipeGestureRecognizerDirectionLeft) {
  838. [_mediaPlayer jumpBackward:BACKWARD_SWIPE_DURATION];
  839. hudString = [NSString stringWithFormat:@"⇐ %is",BACKWARD_SWIPE_DURATION];
  840. }
  841. if (swipeRecognizer.state == UIGestureRecognizerStateEnded) {
  842. if ([_mediaPlayer isPlaying])
  843. [_listPlayer play];
  844. [self.statusLabel showStatusMessage:hudString];
  845. }
  846. }
  847. #pragma mark - Video Filter UI
  848. - (IBAction)videoFilterToggle:(id)sender
  849. {
  850. if (!_playbackSpeedViewHidden)
  851. self.playbackSpeedView.hidden = _playbackSpeedViewHidden = YES;
  852. if (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPhone) {
  853. if (!_controlsHidden)
  854. self.controllerPanel.hidden = _controlsHidden = YES;
  855. }
  856. self.videoFilterView.hidden = !_videoFiltersHidden;
  857. _videoFiltersHidden = self.videoFilterView.hidden;
  858. }
  859. - (IBAction)videoFilterSliderAction:(id)sender
  860. {
  861. if (sender == self.hueSlider)
  862. _mediaPlayer.hue = (int)self.hueSlider.value;
  863. else if (sender == self.contrastSlider)
  864. _mediaPlayer.contrast = self.contrastSlider.value;
  865. else if (sender == self.brightnessSlider) {
  866. if ([self hasExternalDisplay])
  867. _mediaPlayer.brightness = self.brightnessSlider.value;
  868. else
  869. [[UIScreen mainScreen] setBrightness:(self.brightnessSlider.value / 2.)];
  870. } else if (sender == self.saturationSlider)
  871. _mediaPlayer.saturation = self.saturationSlider.value;
  872. else if (sender == self.gammaSlider)
  873. _mediaPlayer.gamma = self.gammaSlider.value;
  874. else if (sender == self.resetVideoFilterButton) {
  875. _mediaPlayer.hue = self.hueSlider.value = 0.;
  876. _mediaPlayer.contrast = self.contrastSlider.value = 1.;
  877. _mediaPlayer.brightness = self.brightnessSlider.value = 1.;
  878. [[UIScreen mainScreen] setBrightness:(self.brightnessSlider.value / 2.)];
  879. _mediaPlayer.saturation = self.saturationSlider.value = 1.;
  880. _mediaPlayer.gamma = self.gammaSlider.value = 1.;
  881. } else
  882. APLog(@"unknown sender for videoFilterSliderAction");
  883. [self _resetIdleTimer];
  884. }
  885. #pragma mark - playback view
  886. - (IBAction)playbackSpeedSliderAction:(UISlider *)sender
  887. {
  888. double speed = pow(2, sender.value / 17.);
  889. float rate = INPUT_RATE_DEFAULT / speed;
  890. if (_currentPlaybackRate != rate)
  891. [_mediaPlayer setRate:INPUT_RATE_DEFAULT / rate];
  892. _currentPlaybackRate = rate;
  893. [self _updatePlaybackSpeedIndicator];
  894. [self _resetIdleTimer];
  895. }
  896. - (void)_updatePlaybackSpeedIndicator
  897. {
  898. float f_value = self.playbackSpeedSlider.value;
  899. double speed = pow(2, f_value / 17.);
  900. self.playbackSpeedIndicator.text = [NSString stringWithFormat:@"%.2fx", speed];
  901. /* rate changed, so update the exported info */
  902. [self performSelectorInBackground:@selector(_updateExportedPlaybackInformation) withObject:nil];
  903. }
  904. - (float)_playbackSpeed
  905. {
  906. float f_rate = _mediaPlayer.rate;
  907. double value = 17 * log(f_rate) / log(2.);
  908. float returnValue = (int) ((value > 0) ? value + .5 : value - .5);
  909. if (returnValue < -34.)
  910. returnValue = -34.;
  911. else if (returnValue > 34.)
  912. returnValue = 34.;
  913. _currentPlaybackRate = returnValue;
  914. return returnValue;
  915. }
  916. - (IBAction)videoDimensionAction:(id)sender
  917. {
  918. if (sender == self.playbackSpeedButton) {
  919. if (!_videoFiltersHidden)
  920. self.videoFilterView.hidden = _videoFiltersHidden = YES;
  921. self.playbackSpeedView.hidden = !_playbackSpeedViewHidden;
  922. _playbackSpeedViewHidden = self.playbackSpeedView.hidden;
  923. [self _resetIdleTimer];
  924. } else if (sender == self.aspectRatioButton) {
  925. NSUInteger count = [_aspectRatios count];
  926. if (_currentAspectRatioMask + 1 > count - 1) {
  927. _mediaPlayer.videoAspectRatio = NULL;
  928. _mediaPlayer.videoCropGeometry = NULL;
  929. _currentAspectRatioMask = 0;
  930. [self.statusLabel showStatusMessage:[NSString stringWithFormat:NSLocalizedString(@"AR_CHANGED", @""), NSLocalizedString(@"DEFAULT", @"")]];
  931. } else {
  932. _currentAspectRatioMask++;
  933. if ([_aspectRatios[_currentAspectRatioMask] isEqualToString:@"FILL_TO_SCREEN"]) {
  934. UIScreen *screen;
  935. if (![self hasExternalDisplay])
  936. screen = [UIScreen mainScreen];
  937. else
  938. screen = [UIScreen screens][1];
  939. float f_ar = screen.bounds.size.width / screen.bounds.size.height;
  940. if (f_ar == (float)(640./1136.)) // iPhone 5 aka 16:9.01
  941. _mediaPlayer.videoCropGeometry = "16:9";
  942. else if (f_ar == (float)(2./3.)) // all other iPhones
  943. _mediaPlayer.videoCropGeometry = "16:10"; // libvlc doesn't support 2:3 crop
  944. else if (f_ar == .75) // all iPads
  945. _mediaPlayer.videoCropGeometry = "4:3";
  946. else if (f_ar == .5625) // AirPlay
  947. _mediaPlayer.videoCropGeometry = "16:9";
  948. else
  949. APLog(@"unknown screen format %f, can't crop", f_ar);
  950. [self.statusLabel showStatusMessage:NSLocalizedString(@"FILL_TO_SCREEN", @"")];
  951. return;
  952. }
  953. _mediaPlayer.videoCropGeometry = NULL;
  954. _mediaPlayer.videoAspectRatio = (char *)[_aspectRatios[_currentAspectRatioMask] UTF8String];
  955. [self.statusLabel showStatusMessage:[NSString stringWithFormat:NSLocalizedString(@"AR_CHANGED", @""), _aspectRatios[_currentAspectRatioMask]]];
  956. }
  957. }
  958. }
  959. #pragma mark - background interaction
  960. - (void)applicationWillResignActive:(NSNotification *)aNotification
  961. {
  962. [self _saveCurrentState];
  963. _mediaPlayer.currentVideoTrackIndex = 0;
  964. if (![[[NSUserDefaults standardUserDefaults] objectForKey:kVLCSettingContinueAudioInBackgroundKey] boolValue]) {
  965. if ([_mediaPlayer isPlaying]) {
  966. [_mediaPlayer pause];
  967. _shouldResumePlaying = YES;
  968. }
  969. }
  970. }
  971. - (void)applicationDidEnterBackground:(NSNotification *)notification
  972. {
  973. _shouldResumePlaying = NO;
  974. }
  975. - (void)applicationDidBecomeActive:(NSNotification *)notification
  976. {
  977. _mediaPlayer.currentVideoTrackIndex = 1;
  978. if (_shouldResumePlaying) {
  979. _shouldResumePlaying = NO;
  980. [_listPlayer play];
  981. }
  982. }
  983. - (void)_updateExportedPlaybackInformation
  984. {
  985. if (!_mediaItem) {
  986. [MPNowPlayingInfoCenter defaultCenter].nowPlayingInfo = nil;
  987. return;
  988. }
  989. MLFile * currentFile = _mediaItem;
  990. /* don't leak sensitive information to the OS, if passcode lock is enabled */
  991. BOOL passcodeLockEnabled = [[[NSUserDefaults standardUserDefaults] objectForKey:kVLCSettingPasscodeOnKey] boolValue];
  992. /* we omit artwork for now since we had to read it from storage as we can't access
  993. * the artwork cache at the moment - FIXME? */
  994. NSMutableDictionary *currentlyPlayingTrackInfo;
  995. if (passcodeLockEnabled)
  996. currentlyPlayingTrackInfo = [NSMutableDictionary dictionaryWithObjectsAndKeys:@(currentFile.duration.intValue / 1000.), MPMediaItemPropertyPlaybackDuration, @(_mediaPlayer.time.intValue / 1000.), MPNowPlayingInfoPropertyElapsedPlaybackTime, @(_mediaPlayer.rate), MPNowPlayingInfoPropertyPlaybackRate, nil];
  997. else
  998. currentlyPlayingTrackInfo = [NSMutableDictionary dictionaryWithObjectsAndKeys: currentFile.title, MPMediaItemPropertyTitle, @(currentFile.duration.intValue / 1000.), MPMediaItemPropertyPlaybackDuration, @(_mediaPlayer.time.intValue / 1000.), MPNowPlayingInfoPropertyElapsedPlaybackTime, @(_mediaPlayer.rate), MPNowPlayingInfoPropertyPlaybackRate, nil];
  999. if ([currentFile isAlbumTrack] && !passcodeLockEnabled) {
  1000. MLAlbumTrack *track = currentFile.albumTrack;
  1001. if (track.artist.length > 0)
  1002. [currentlyPlayingTrackInfo setObject:track.artist forKey:MPMediaItemPropertyArtist];
  1003. if (track.title.length > 0)
  1004. [currentlyPlayingTrackInfo setObject:track.title forKey:MPMediaItemPropertyTitle];
  1005. if (track.album.name.length > 0)
  1006. [currentlyPlayingTrackInfo setObject:track.album.name forKey:MPMediaItemPropertyAlbumTitle];
  1007. [currentlyPlayingTrackInfo setObject:[NSNumber numberWithInt:[track.trackNumber intValue]] forKey:MPMediaItemPropertyAlbumTrackNumber];
  1008. }
  1009. [MPNowPlayingInfoCenter defaultCenter].nowPlayingInfo = currentlyPlayingTrackInfo;
  1010. }
  1011. #pragma mark - autorotation
  1012. - (BOOL)shouldAutorotate
  1013. {
  1014. UIInterfaceOrientation toInterfaceOrientation = [[UIApplication sharedApplication] statusBarOrientation];
  1015. return UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPad
  1016. || toInterfaceOrientation != UIInterfaceOrientationPortraitUpsideDown;
  1017. }
  1018. #pragma mark - AVSession delegate
  1019. - (void)beginInterruption
  1020. {
  1021. if ([[[NSUserDefaults standardUserDefaults] objectForKey:kVLCSettingContinueAudioInBackgroundKey] boolValue])
  1022. _shouldResumePlaying = YES;
  1023. [_mediaPlayer pause];
  1024. }
  1025. - (void)endInterruption
  1026. {
  1027. if (_shouldResumePlaying) {
  1028. [_listPlayer play];
  1029. _shouldResumePlaying = NO;
  1030. }
  1031. }
  1032. #pragma mark - External Display
  1033. - (BOOL)hasExternalDisplay
  1034. {
  1035. return ([[UIScreen screens] count] > 1);
  1036. }
  1037. - (void)showOnExternalDisplay
  1038. {
  1039. UIScreen *screen = [UIScreen screens][1];
  1040. screen.overscanCompensation = UIScreenOverscanCompensationInsetApplicationFrame;
  1041. self.externalWindow = [[UIWindow alloc] initWithFrame:screen.bounds];
  1042. UIViewController *controller = [[VLCExternalDisplayController alloc] init];
  1043. self.externalWindow.rootViewController = controller;
  1044. [controller.view addSubview:_movieView];
  1045. controller.view.frame = screen.bounds;
  1046. _movieView.frame = screen.bounds;
  1047. self.playingExternallyView.hidden = NO;
  1048. self.externalWindow.screen = screen;
  1049. self.externalWindow.hidden = NO;
  1050. }
  1051. - (void)hideFromExternalDisplay
  1052. {
  1053. [self.view addSubview:_movieView];
  1054. [self.view sendSubviewToBack:_movieView];
  1055. _movieView.frame = self.view.frame;
  1056. self.playingExternallyView.hidden = YES;
  1057. self.externalWindow.hidden = YES;
  1058. self.externalWindow = nil;
  1059. }
  1060. - (void)handleExternalScreenDidConnect:(NSNotification *)notification
  1061. {
  1062. [self showOnExternalDisplay];
  1063. }
  1064. - (void)handleExternalScreenDidDisconnect:(NSNotification *)notification
  1065. {
  1066. [self hideFromExternalDisplay];
  1067. }
  1068. @end