VLCMovieViewController.m 40 KB

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