VLCMovieViewController.m 46 KB

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