VLCMovieViewController.m 40 KB

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