VLCMovieViewController.m 41 KB

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