VLCMovieViewController.m 47 KB

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