VLCMovieViewController.m 48 KB

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