VLCMovieViewController.m 46 KB

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