VLCMovieViewController.m 46 KB

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