VLCMovieViewController.m 42 KB

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