VLCMovieViewController.m 39 KB

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