VLCPlaybackController.m 48 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331
  1. /*****************************************************************************
  2. * VLCPlaybackController.m
  3. * VLC for iOS
  4. *****************************************************************************
  5. * Copyright (c) 2013-2015 VideoLAN. All rights reserved.
  6. * $Id$
  7. *
  8. * Authors: Felix Paul Kühne <fkuehne # videolan.org>
  9. * Carola Nitz <caro # videolan.org>
  10. * Gleb Pinigin <gpinigin # gmail.com>
  11. * Pierre Sagaspe <pierre.sagaspe # me.com>
  12. * Tobias Conradi <videolan # tobias-conradi.de>
  13. * Sylver Bruneau <sylver.bruneau # gmail dot com>
  14. * Winston Weinert <winston # ml1 dot net>
  15. *
  16. * Refer to the COPYING file of the official project for license.
  17. *****************************************************************************/
  18. #import "VLCPlaybackController.h"
  19. #import <CommonCrypto/CommonDigest.h>
  20. #import "UIDevice+VLC.h"
  21. #import <AVFoundation/AVFoundation.h>
  22. #import <MediaPlayer/MediaPlayer.h>
  23. #import "VLCPlayerDisplayController.h"
  24. #if TARGET_OS_IOS
  25. #import "VLCKeychainCoordinator.h"
  26. #import "VLCThumbnailsCache.h"
  27. #import "VLCLibraryViewController.h"
  28. #import <WatchKit/WatchKit.h>
  29. #endif
  30. NSString *const VLCPlaybackControllerPlaybackDidStart = @"VLCPlaybackControllerPlaybackDidStart";
  31. NSString *const VLCPlaybackControllerPlaybackDidPause = @"VLCPlaybackControllerPlaybackDidPause";
  32. NSString *const VLCPlaybackControllerPlaybackDidResume = @"VLCPlaybackControllerPlaybackDidResume";
  33. NSString *const VLCPlaybackControllerPlaybackDidStop = @"VLCPlaybackControllerPlaybackDidStop";
  34. NSString *const VLCPlaybackControllerPlaybackMetadataDidChange = @"VLCPlaybackControllerPlaybackMetadataDidChange";
  35. NSString *const VLCPlaybackControllerPlaybackDidFail = @"VLCPlaybackControllerPlaybackDidFail";
  36. NSString *const VLCPlaybackControllerPlaybackPositionUpdated = @"VLCPlaybackControllerPlaybackPositionUpdated";
  37. @interface VLCPlaybackController () <VLCMediaPlayerDelegate,
  38. #if TARGET_OS_IOS
  39. AVAudioSessionDelegate,
  40. #endif
  41. VLCMediaDelegate>
  42. {
  43. BOOL _playerIsSetup;
  44. BOOL _playbackFailed;
  45. BOOL _shouldResumePlaying;
  46. BOOL _shouldResumePlayingAfterInteruption;
  47. NSTimer *_sleepTimer;
  48. NSArray *_aspectRatios;
  49. NSUInteger _currentAspectRatioMask;
  50. float _currentPlaybackRate;
  51. UIView *_videoOutputViewWrapper;
  52. UIView *_actualVideoOutputView;
  53. UIView *_preBackgroundWrapperView;
  54. /* cached stuff for the VC */
  55. NSString *_title;
  56. UIImage *_artworkImage;
  57. NSString *_artist;
  58. NSString *_albumName;
  59. BOOL _mediaIsAudioOnly;
  60. BOOL _needsMetadataUpdate;
  61. BOOL _mediaWasJustStarted;
  62. BOOL _recheckForExistingThumbnail;
  63. BOOL _activeSession;
  64. BOOL _headphonesWasPlugged;
  65. NSLock *_playbackSessionManagementLock;
  66. VLCDialogProvider *_dialogProvider;
  67. }
  68. @end
  69. @implementation VLCPlaybackController
  70. #pragma mark instance management
  71. + (VLCPlaybackController *)sharedInstance
  72. {
  73. static VLCPlaybackController *sharedInstance = nil;
  74. static dispatch_once_t pred;
  75. dispatch_once(&pred, ^{
  76. sharedInstance = [VLCPlaybackController new];
  77. });
  78. return sharedInstance;
  79. }
  80. - (void)dealloc
  81. {
  82. _dialogProvider = nil;
  83. [[NSNotificationCenter defaultCenter] removeObserver:self];
  84. }
  85. - (instancetype)init
  86. {
  87. self = [super init];
  88. if (self) {
  89. _headphonesWasPlugged = [self areHeadphonesPlugged];
  90. NSNotificationCenter *defaultCenter = [NSNotificationCenter defaultCenter];
  91. [defaultCenter addObserver:self selector:@selector(audioSessionRouteChange:)
  92. name:AVAudioSessionRouteChangeNotification object:nil];
  93. [defaultCenter addObserver:self selector:@selector(applicationWillResignActive:)
  94. name:UIApplicationWillResignActiveNotification object:nil];
  95. [defaultCenter addObserver:self selector:@selector(applicationDidBecomeActive:)
  96. name:UIApplicationDidBecomeActiveNotification object:nil];
  97. [defaultCenter addObserver:self selector:@selector(applicationDidEnterBackground:)
  98. name:UIApplicationDidEnterBackgroundNotification object:nil];
  99. _dialogProvider = [[VLCDialogProvider alloc] initWithLibrary:[VLCLibrary sharedLibrary] customUI:NO];
  100. _playbackSessionManagementLock = [[NSLock alloc] init];
  101. }
  102. return self;
  103. }
  104. #pragma mark - playback management
  105. - (BOOL)_isMediaSuitableForDevice:(VLCMedia *)media
  106. {
  107. NSArray *tracksInfo = media.tracksInformation;
  108. double width = 0.0, height = 0.0;
  109. NSDictionary *track;
  110. for (NSUInteger x = 0; x < tracksInfo.count; x++) {
  111. track = tracksInfo[x];
  112. if ([track[VLCMediaTracksInformationType] isEqualToString:VLCMediaTracksInformationTypeVideo]) {
  113. width = [track[VLCMediaTracksInformationVideoWidth] doubleValue];
  114. height = [track[VLCMediaTracksInformationVideoHeight] doubleValue];
  115. }
  116. }
  117. NSUInteger totalNumberOfPixels = width * height;
  118. NSInteger speedCategory = [[UIDevice currentDevice] VLCSpeedCategory];
  119. if (speedCategory == 1) {
  120. // iPhone 3GS, iPhone 4, first gen. iPad, 3rd and 4th generation iPod touch
  121. return (totalNumberOfPixels < 600000); // between 480p and 720p
  122. } else if (speedCategory == 2) {
  123. // iPhone 4S, iPad 2 and 3, iPod 4 and 5
  124. return (totalNumberOfPixels < 922000); // 720p
  125. } else if (speedCategory == 3) {
  126. // iPhone 5, iPad 4
  127. return (totalNumberOfPixels < 2074000); // 1080p
  128. } else if (speedCategory == 4) {
  129. // iPhone 6, 2014 iPads
  130. return (totalNumberOfPixels < 8850000); // 4K
  131. }
  132. return YES;
  133. }
  134. - (void)playMediaList:(VLCMediaList *)mediaList firstIndex:(NSInteger)index
  135. {
  136. self.mediaList = mediaList;
  137. self.itemInMediaListToBePlayedFirst = (int)index;
  138. self.pathToExternalSubtitlesFile = nil;
  139. if (self.activePlaybackSession) {
  140. self.sessionWillRestart = YES;
  141. [self stopPlayback];
  142. } else {
  143. self.sessionWillRestart = NO;
  144. [self startPlayback];
  145. }
  146. }
  147. - (void)playURL:(NSURL *)url successCallback:(NSURL*)successCallback errorCallback:(NSURL *)errorCallback
  148. {
  149. self.url = url;
  150. self.successCallback = successCallback;
  151. self.errorCallback = errorCallback;
  152. if (self.activePlaybackSession) {
  153. self.sessionWillRestart = YES;
  154. [self stopPlayback];
  155. } else {
  156. self.sessionWillRestart = NO;
  157. [self startPlayback];
  158. }
  159. }
  160. - (void)playURL:(NSURL *)url subtitlesFilePath:(NSString *)subsFilePath
  161. {
  162. self.url = url;
  163. self.pathToExternalSubtitlesFile = subsFilePath;
  164. if (self.activePlaybackSession) {
  165. self.sessionWillRestart = YES;
  166. [self stopPlayback];
  167. } else {
  168. self.sessionWillRestart = NO;
  169. [self startPlayback];
  170. }
  171. }
  172. - (void)startPlayback
  173. {
  174. if (_playerIsSetup) {
  175. APLog(@"%s: player is already setup, bailing out", __PRETTY_FUNCTION__);
  176. return;
  177. }
  178. BOOL ret = [_playbackSessionManagementLock tryLock];
  179. if (!ret) {
  180. APLog(@"%s: locking failed", __PRETTY_FUNCTION__);
  181. return;
  182. }
  183. _activeSession = YES;
  184. #if TARGET_OS_IOS
  185. [[AVAudioSession sharedInstance] setDelegate:self];
  186. #endif
  187. NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
  188. _aspectRatios = @[@"DEFAULT", @"FILL_TO_SCREEN", @"4:3", @"16:9", @"16:10", @"2.21:1"];
  189. if (!self.url && !self.mediaList) {
  190. APLog(@"%s: no URL and no media list set, stopping playback", __PRETTY_FUNCTION__);
  191. [_playbackSessionManagementLock unlock];
  192. [self stopPlayback];
  193. return;
  194. }
  195. /* video decoding permanently fails if we don't provide a UIView to draw into on init
  196. * hence we provide one which is not attached to any view controller for off-screen drawing
  197. * and disable video decoding once playback started */
  198. _actualVideoOutputView = [[UIView alloc] initWithFrame:[UIScreen mainScreen].bounds];
  199. _actualVideoOutputView.autoresizingMask = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight;
  200. _actualVideoOutputView.autoresizesSubviews = YES;
  201. if (self.pathToExternalSubtitlesFile)
  202. _listPlayer = [[VLCMediaListPlayer alloc] initWithOptions:@[[NSString stringWithFormat:@"--%@=%@", kVLCSettingSubtitlesFilePath, self.pathToExternalSubtitlesFile]] andDrawable:_actualVideoOutputView];
  203. else
  204. _listPlayer = [[VLCMediaListPlayer alloc] initWithDrawable:_actualVideoOutputView];
  205. /* to enable debug logging for the playback library instance, switch the boolean below
  206. * note that the library instance used for playback may not necessarily match the instance
  207. * used for media discovery or thumbnailing */
  208. _listPlayer.mediaPlayer.libraryInstance.debugLogging = NO;
  209. _mediaPlayer = _listPlayer.mediaPlayer;
  210. [_mediaPlayer setDelegate:self];
  211. if ([[defaults objectForKey:kVLCSettingPlaybackSpeedDefaultValue] floatValue] != 0)
  212. [_mediaPlayer setRate: [[defaults objectForKey:kVLCSettingPlaybackSpeedDefaultValue] floatValue]];
  213. if ([[defaults objectForKey:kVLCSettingDeinterlace] intValue] != 0)
  214. [_mediaPlayer setDeinterlaceFilter:@"blend"];
  215. else
  216. [_mediaPlayer setDeinterlaceFilter:nil];
  217. if (self.pathToExternalSubtitlesFile)
  218. [_mediaPlayer openVideoSubTitlesFromFile:self.pathToExternalSubtitlesFile];
  219. VLCMedia *media;
  220. if (_mediaList) {
  221. media = [_mediaList mediaAtIndex:_itemInMediaListToBePlayedFirst];
  222. [media parseWithOptions:VLCMediaParseLocal];
  223. media.delegate = self;
  224. } else {
  225. media = [VLCMedia mediaWithURL:self.url];
  226. media.delegate = self;
  227. [media parseWithOptions:VLCMediaParseLocal];
  228. [media addOptions:self.mediaOptionsDictionary];
  229. }
  230. if (self.mediaList) {
  231. [_listPlayer setMediaList:self.mediaList];
  232. } else {
  233. [_listPlayer setRootMedia:media];
  234. }
  235. [_listPlayer setRepeatMode:VLCDoNotRepeat];
  236. [_playbackSessionManagementLock unlock];
  237. if (![self _isMediaSuitableForDevice:media]) {
  238. #if TARGET_OS_IOS
  239. VLCAlertView *alert = [[VLCAlertView alloc] initWithTitle:NSLocalizedString(@"DEVICE_TOOSLOW_TITLE", nil)
  240. message:[NSString stringWithFormat:NSLocalizedString(@"DEVICE_TOOSLOW", nil), [[UIDevice currentDevice] model], media.url.lastPathComponent]
  241. delegate:self
  242. cancelButtonTitle:NSLocalizedString(@"BUTTON_CANCEL", nil)
  243. otherButtonTitles:NSLocalizedString(@"BUTTON_OPEN", nil), nil];
  244. [alert show];
  245. #else
  246. UIAlertController *alert = [UIAlertController alertControllerWithTitle:NSLocalizedString(@"DEVICE_TOOSLOW_TITLE", nil)
  247. message:[NSString stringWithFormat:NSLocalizedString(@"DEVICE_TOOSLOW", nil), [[UIDevice currentDevice] model], media.url.lastPathComponent]
  248. preferredStyle:UIAlertControllerStyleAlert];
  249. UIAlertAction *defaultAction = [UIAlertAction actionWithTitle:NSLocalizedString(@"BUTTON_OPEN", nil)
  250. style:UIAlertActionStyleDefault
  251. handler:^(UIAlertAction * action) {
  252. [self _playNewMedia];
  253. }];
  254. UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:NSLocalizedString(@"BUTTON_CANCEL", nil)
  255. style:UIAlertActionStyleDestructive
  256. handler:^(UIAlertAction * action) {
  257. [self stopPlayback];
  258. }];
  259. [alert addAction:defaultAction];
  260. [alert addAction:cancelAction];
  261. [[UIApplication sharedApplication].keyWindow.rootViewController presentViewController:alert animated:YES completion:nil];
  262. #endif
  263. } else
  264. [self _playNewMedia];
  265. }
  266. - (void)_playNewMedia
  267. {
  268. BOOL ret = [_playbackSessionManagementLock tryLock];
  269. if (!ret) {
  270. APLog(@"%s: locking failed", __PRETTY_FUNCTION__);
  271. return;
  272. }
  273. // Set last selected equalizer profile
  274. unsigned int profile = (unsigned int)[[[NSUserDefaults standardUserDefaults] objectForKey:kVLCSettingEqualizerProfile] integerValue];
  275. [_mediaPlayer resetEqualizerFromProfile:profile];
  276. [_mediaPlayer setPreAmplification:[_mediaPlayer preAmplification]];
  277. _mediaWasJustStarted = YES;
  278. [_mediaPlayer addObserver:self forKeyPath:@"time" options:0 context:nil];
  279. [_mediaPlayer addObserver:self forKeyPath:@"remainingTime" options:0 context:nil];
  280. if (self.mediaList)
  281. [_listPlayer playItemAtIndex:self.itemInMediaListToBePlayedFirst];
  282. else
  283. [_listPlayer playMedia:_listPlayer.rootMedia];
  284. if ([self.delegate respondsToSelector:@selector(prepareForMediaPlayback:)])
  285. [self.delegate prepareForMediaPlayback:self];
  286. _currentAspectRatioMask = 0;
  287. _mediaPlayer.videoAspectRatio = NULL;
  288. [self subscribeRemoteCommands];
  289. _playerIsSetup = YES;
  290. [[NSNotificationCenter defaultCenter] postNotificationName:VLCPlaybackControllerPlaybackDidStart object:self];
  291. [_playbackSessionManagementLock unlock];
  292. }
  293. #if TARGET_OS_IOS
  294. - (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
  295. {
  296. if (buttonIndex == 1)
  297. [self _playNewMedia];
  298. else
  299. [self stopPlayback];
  300. }
  301. #endif
  302. - (void)stopPlayback
  303. {
  304. BOOL ret = [_playbackSessionManagementLock tryLock];
  305. if (!ret) {
  306. APLog(@"%s: locking failed", __PRETTY_FUNCTION__);
  307. return;
  308. }
  309. if (_mediaPlayer) {
  310. @try {
  311. [_mediaPlayer removeObserver:self forKeyPath:@"time"];
  312. [_mediaPlayer removeObserver:self forKeyPath:@"remainingTime"];
  313. }
  314. @catch (NSException *exception) {
  315. APLog(@"we weren't an observer yet");
  316. }
  317. if (_mediaPlayer.media) {
  318. [_mediaPlayer pause];
  319. #if TARGET_OS_IOS
  320. [self _savePlaybackState];
  321. #endif
  322. [_mediaPlayer stop];
  323. }
  324. if (_mediaPlayer)
  325. _mediaPlayer = nil;
  326. if (_listPlayer)
  327. _listPlayer = nil;
  328. }
  329. if (!_sessionWillRestart) {
  330. if (_mediaList)
  331. _mediaList = nil;
  332. if (_url)
  333. _url = nil;
  334. if (_pathToExternalSubtitlesFile) {
  335. NSFileManager *fileManager = [NSFileManager defaultManager];
  336. if ([fileManager fileExistsAtPath:_pathToExternalSubtitlesFile])
  337. [fileManager removeItemAtPath:_pathToExternalSubtitlesFile error:nil];
  338. _pathToExternalSubtitlesFile = nil;
  339. }
  340. }
  341. _playerIsSetup = NO;
  342. if (self.errorCallback && _playbackFailed && !_sessionWillRestart)
  343. [[UIApplication sharedApplication] openURL:self.errorCallback];
  344. else if (self.successCallback && !_sessionWillRestart)
  345. [[UIApplication sharedApplication] openURL:self.successCallback];
  346. [MPNowPlayingInfoCenter defaultCenter].nowPlayingInfo = nil;
  347. [self unsubscribeFromRemoteCommand];
  348. _activeSession = NO;
  349. [_playbackSessionManagementLock unlock];
  350. if (_playbackFailed) {
  351. [[NSNotificationCenter defaultCenter] postNotificationName:VLCPlaybackControllerPlaybackDidFail object:self];
  352. } else if (!_sessionWillRestart) {
  353. [[NSNotificationCenter defaultCenter] postNotificationName:VLCPlaybackControllerPlaybackDidStop object:self];
  354. } else {
  355. self.sessionWillRestart = NO;
  356. [self startPlayback];
  357. }
  358. }
  359. #if TARGET_OS_IOS
  360. - (void)_savePlaybackState
  361. {
  362. @try {
  363. [[MLMediaLibrary sharedMediaLibrary] save];
  364. }
  365. @catch (NSException *exception) {
  366. APLog(@"saving playback state failed");
  367. }
  368. MLFile *fileItem;
  369. NSArray *files = [MLFile fileForURL:_mediaPlayer.media.url];
  370. if (files.count > 0)
  371. fileItem = files.firstObject;
  372. if (!fileItem) {
  373. APLog(@"couldn't find file, not saving playback progress");
  374. return;
  375. }
  376. @try {
  377. float position = _mediaPlayer.position;
  378. fileItem.lastPosition = @(position);
  379. fileItem.lastAudioTrack = @(_mediaPlayer.currentAudioTrackIndex);
  380. fileItem.lastSubtitleTrack = @(_mediaPlayer.currentVideoSubTitleIndex);
  381. if (position > .95)
  382. return;
  383. NSArray *searchPaths = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES);
  384. NSString* newThumbnailPath = [searchPaths[0] stringByAppendingPathComponent:@"VideoSnapshots"];
  385. NSFileManager *fileManager = [NSFileManager defaultManager];
  386. if (![fileManager fileExistsAtPath:newThumbnailPath])
  387. [fileManager createDirectoryAtPath:newThumbnailPath withIntermediateDirectories:YES attributes:nil error:nil];
  388. newThumbnailPath = [newThumbnailPath stringByAppendingPathComponent:fileItem.objectID.URIRepresentation.lastPathComponent];
  389. [_mediaPlayer saveVideoSnapshotAt:newThumbnailPath withWidth:0 andHeight:0];
  390. _recheckForExistingThumbnail = YES;
  391. [self performSelector:@selector(_updateStoredThumbnailForFile:) withObject:fileItem afterDelay:.25];
  392. }
  393. @catch (NSException *exception) {
  394. APLog(@"failed to save current media state - file removed?");
  395. }
  396. }
  397. #endif
  398. #if TARGET_OS_IOS
  399. - (void)_updateStoredThumbnailForFile:(MLFile *)fileItem
  400. {
  401. NSFileManager *fileManager = [NSFileManager defaultManager];
  402. NSArray *searchPaths = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES);
  403. NSString* newThumbnailPath = [searchPaths[0] stringByAppendingPathComponent:@"VideoSnapshots"];
  404. newThumbnailPath = [newThumbnailPath stringByAppendingPathComponent:fileItem.objectID.URIRepresentation.lastPathComponent];
  405. if (![fileManager fileExistsAtPath:newThumbnailPath]) {
  406. if (_recheckForExistingThumbnail) {
  407. [self performSelector:@selector(_updateStoredThumbnailForFile:) withObject:fileItem afterDelay:1.];
  408. _recheckForExistingThumbnail = NO;
  409. } else
  410. return;
  411. }
  412. UIImage *newThumbnail = [UIImage imageWithContentsOfFile:newThumbnailPath];
  413. if (!newThumbnail) {
  414. if (_recheckForExistingThumbnail) {
  415. [self performSelector:@selector(_updateStoredThumbnailForFile:) withObject:fileItem afterDelay:1.];
  416. _recheckForExistingThumbnail = NO;
  417. } else
  418. return;
  419. }
  420. @try {
  421. [fileItem setComputedThumbnailScaledForDevice:newThumbnail];
  422. }
  423. @catch (NSException *exception) {
  424. APLog(@"updating thumbnail failed");
  425. }
  426. [fileManager removeItemAtPath:newThumbnailPath error:nil];
  427. }
  428. #endif
  429. - (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context
  430. {
  431. if (_mediaWasJustStarted) {
  432. _mediaWasJustStarted = NO;
  433. #if TARGET_OS_IOS
  434. if (self.mediaList) {
  435. MLFile *item;
  436. NSArray *matches = [MLFile fileForURL:_mediaPlayer.media.url];
  437. item = matches.firstObject;
  438. [self _recoverLastPlaybackStateOfItem:item];
  439. }
  440. #else
  441. NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
  442. BOOL bValue = [defaults boolForKey:kVLCSettingUseSPDIF];
  443. if (bValue) {
  444. [_mediaPlayer performSelector:@selector(setPassthroughAudio:) withObject:@(bValue)];
  445. }
  446. #endif
  447. }
  448. if ([self.delegate respondsToSelector:@selector(playbackPositionUpdated:)])
  449. [self.delegate playbackPositionUpdated:self];
  450. [[NSNotificationCenter defaultCenter] postNotificationName:VLCPlaybackControllerPlaybackPositionUpdated
  451. object:self];
  452. }
  453. - (NSInteger)mediaDuration
  454. {
  455. return _listPlayer.mediaPlayer.media.length.intValue;;
  456. }
  457. - (BOOL)isPlaying
  458. {
  459. return _mediaPlayer.isPlaying;
  460. }
  461. - (VLCRepeatMode)repeatMode
  462. {
  463. return _listPlayer.repeatMode;
  464. }
  465. - (void)setRepeatMode:(VLCRepeatMode)repeatMode
  466. {
  467. _listPlayer.repeatMode = repeatMode;
  468. }
  469. - (BOOL)currentMediaHasChapters
  470. {
  471. return [_mediaPlayer numberOfTitles] > 1 || [_mediaPlayer numberOfChaptersForTitle:_mediaPlayer.currentTitleIndex] > 1;
  472. }
  473. - (BOOL)currentMediaHasTrackToChooseFrom
  474. {
  475. return [[_mediaPlayer audioTrackIndexes] count] > 2 || [[_mediaPlayer videoSubTitlesIndexes] count] > 1;
  476. }
  477. - (BOOL)activePlaybackSession
  478. {
  479. return _activeSession;
  480. }
  481. - (BOOL)audioOnlyPlaybackSession
  482. {
  483. return _mediaIsAudioOnly;
  484. }
  485. - (NSString *)mediaTitle
  486. {
  487. return _title;
  488. }
  489. - (float)playbackRate
  490. {
  491. float f_rate = _mediaPlayer.rate;
  492. _currentPlaybackRate = f_rate;
  493. return f_rate;
  494. }
  495. - (void)setPlaybackRate:(float)playbackRate
  496. {
  497. if (_currentPlaybackRate != playbackRate)
  498. [_mediaPlayer setRate:playbackRate];
  499. _currentPlaybackRate = playbackRate;
  500. }
  501. - (void)setAudioDelay:(float)audioDelay
  502. {
  503. _mediaPlayer.currentAudioPlaybackDelay = 1000000.*audioDelay;
  504. }
  505. - (float)audioDelay
  506. {
  507. return _mediaPlayer.currentAudioPlaybackDelay/1000000.;
  508. }
  509. -(void)setSubtitleDelay:(float)subtitleDeleay
  510. {
  511. _mediaPlayer.currentVideoSubTitleDelay = 1000000.*subtitleDeleay;
  512. }
  513. - (float)subtitleDelay
  514. {
  515. return _mediaPlayer.currentVideoSubTitleDelay/1000000.;
  516. }
  517. - (void)mediaPlayerStateChanged:(NSNotification *)aNotification
  518. {
  519. VLCMediaPlayerState currentState = _mediaPlayer.state;
  520. if (currentState == VLCMediaPlayerStateBuffering) {
  521. /* attach delegate */
  522. _mediaPlayer.media.delegate = self;
  523. /* on-the-fly values through hidden API */
  524. NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
  525. [_mediaPlayer performSelector:@selector(setTextRendererFont:) withObject:[defaults objectForKey:kVLCSettingSubtitlesFont]];
  526. [_mediaPlayer performSelector:@selector(setTextRendererFontSize:) withObject:[defaults objectForKey:kVLCSettingSubtitlesFontSize]];
  527. [_mediaPlayer performSelector:@selector(setTextRendererFontColor:) withObject:[defaults objectForKey:kVLCSettingSubtitlesFontColor]];
  528. [_mediaPlayer performSelector:@selector(setTextRendererFontForceBold:) withObject:[defaults objectForKey:kVLCSettingSubtitlesBoldFont]];
  529. } else if (currentState == VLCMediaPlayerStateError) {
  530. APLog(@"Playback failed");
  531. _playbackFailed = YES;
  532. self.sessionWillRestart = NO;
  533. [self stopPlayback];
  534. } else if (currentState == VLCMediaPlayerStateEnded || currentState == VLCMediaPlayerStateStopped) {
  535. [_listPlayer.mediaList lock];
  536. NSUInteger listCount = _listPlayer.mediaList.count;
  537. if ([_listPlayer.mediaList indexOfMedia:_mediaPlayer.media] == listCount - 1 && self.repeatMode == VLCDoNotRepeat) {
  538. [_listPlayer.mediaList unlock];
  539. self.sessionWillRestart = NO;
  540. [self stopPlayback];
  541. return;
  542. } else if (listCount > 1) {
  543. [_listPlayer.mediaList unlock];
  544. [_listPlayer next];
  545. } else
  546. [_listPlayer.mediaList unlock];
  547. }
  548. if ([self.delegate respondsToSelector:@selector(mediaPlayerStateChanged:isPlaying:currentMediaHasTrackToChooseFrom:currentMediaHasChapters:forPlaybackController:)])
  549. [self.delegate mediaPlayerStateChanged:currentState
  550. isPlaying:_mediaPlayer.isPlaying
  551. currentMediaHasTrackToChooseFrom:self.currentMediaHasTrackToChooseFrom
  552. currentMediaHasChapters:self.currentMediaHasChapters
  553. forPlaybackController:self];
  554. [self setNeedsMetadataUpdate];
  555. }
  556. #pragma mark - playback controls
  557. - (void)playPause
  558. {
  559. if ([_mediaPlayer isPlaying]) {
  560. [_listPlayer pause];
  561. #if TARGET_OS_IOS
  562. [self _savePlaybackState];
  563. #endif
  564. [[NSNotificationCenter defaultCenter] postNotificationName:VLCPlaybackControllerPlaybackDidPause object:self];
  565. } else {
  566. [_listPlayer play];
  567. [[NSNotificationCenter defaultCenter] postNotificationName:VLCPlaybackControllerPlaybackDidResume object:self];
  568. }
  569. }
  570. - (void)forward
  571. {
  572. if (_mediaList.count > 1) {
  573. [_listPlayer next];
  574. [[NSNotificationCenter defaultCenter] postNotificationName:VLCPlaybackControllerPlaybackMetadataDidChange object:self];
  575. } else {
  576. NSNumber *skipLength = [[NSUserDefaults standardUserDefaults] valueForKey:kVLCSettingPlaybackForwardSkipLength];
  577. [_mediaPlayer jumpForward:skipLength.intValue];
  578. }
  579. }
  580. - (void)backward
  581. {
  582. if (_mediaList.count > 1) {
  583. [_listPlayer previous];
  584. [[NSNotificationCenter defaultCenter] postNotificationName:VLCPlaybackControllerPlaybackMetadataDidChange object:self];
  585. }
  586. else {
  587. NSNumber *skipLength = [[NSUserDefaults standardUserDefaults] valueForKey:kVLCSettingPlaybackBackwardSkipLength];
  588. [_mediaPlayer jumpBackward:skipLength.intValue];
  589. }
  590. }
  591. - (void)switchAspectRatio
  592. {
  593. NSUInteger count = [_aspectRatios count];
  594. if (_currentAspectRatioMask + 1 > count - 1) {
  595. _mediaPlayer.videoAspectRatio = NULL;
  596. _mediaPlayer.videoCropGeometry = NULL;
  597. _currentAspectRatioMask = 0;
  598. if ([self.delegate respondsToSelector:@selector(showStatusMessage:forPlaybackController:)])
  599. [self.delegate showStatusMessage:[NSString stringWithFormat:NSLocalizedString(@"AR_CHANGED", nil), NSLocalizedString(@"DEFAULT", nil)] forPlaybackController:self];
  600. } else {
  601. _currentAspectRatioMask++;
  602. if ([_aspectRatios[_currentAspectRatioMask] isEqualToString:@"FILL_TO_SCREEN"]) {
  603. UIScreen *screen;
  604. if (![[UIDevice currentDevice] VLCHasExternalDisplay])
  605. screen = [UIScreen mainScreen];
  606. else
  607. screen = [UIScreen screens][1];
  608. float f_ar = screen.bounds.size.width / screen.bounds.size.height;
  609. if (f_ar == (float)(640./1136.)) // iPhone 5 aka 16:9.01
  610. _mediaPlayer.videoCropGeometry = "16:9";
  611. else if (f_ar == (float)(2./3.)) // all other iPhones
  612. _mediaPlayer.videoCropGeometry = "16:10"; // libvlc doesn't support 2:3 crop
  613. else if (f_ar == (float)(1. + (1./3.))) // all iPads
  614. _mediaPlayer.videoCropGeometry = "4:3";
  615. else if (f_ar == .5625) // AirPlay
  616. _mediaPlayer.videoCropGeometry = "16:9";
  617. else
  618. APLog(@"unknown screen format %f, can't crop", f_ar);
  619. if ([self.delegate respondsToSelector:@selector(showStatusMessage:forPlaybackController:)])
  620. [self.delegate showStatusMessage:NSLocalizedString(@"FILL_TO_SCREEN", nil) forPlaybackController:self];
  621. return;
  622. }
  623. _mediaPlayer.videoCropGeometry = NULL;
  624. _mediaPlayer.videoAspectRatio = (char *)[_aspectRatios[_currentAspectRatioMask] UTF8String];
  625. if ([self.delegate respondsToSelector:@selector(showStatusMessage:forPlaybackController:)])
  626. [self.delegate showStatusMessage:[NSString stringWithFormat:NSLocalizedString(@"AR_CHANGED", nil), _aspectRatios[_currentAspectRatioMask]] forPlaybackController:self];
  627. }
  628. }
  629. - (void)setVideoOutputView:(UIView *)videoOutputView
  630. {
  631. if (videoOutputView) {
  632. if ([_actualVideoOutputView superview] != nil)
  633. [_actualVideoOutputView removeFromSuperview];
  634. _actualVideoOutputView.frame = (CGRect){CGPointZero, videoOutputView.frame.size};
  635. if (_mediaPlayer.currentVideoTrackIndex == -1)
  636. _mediaPlayer.currentVideoTrackIndex = 0;
  637. [videoOutputView addSubview:_actualVideoOutputView];
  638. [_actualVideoOutputView layoutSubviews];
  639. [_actualVideoOutputView updateConstraints];
  640. [_actualVideoOutputView setNeedsLayout];
  641. } else
  642. [_actualVideoOutputView removeFromSuperview];
  643. _videoOutputViewWrapper = videoOutputView;
  644. }
  645. - (UIView *)videoOutputView
  646. {
  647. return _videoOutputViewWrapper;
  648. }
  649. #pragma mark - 360 Support
  650. - (BOOL)updateViewpoint:(CGFloat)yaw pitch:(CGFloat)pitch roll:(CGFloat)roll fov:(CGFloat)fov absolute:(BOOL)absolute
  651. {
  652. return [_mediaPlayer updateViewpoint:yaw pitch:pitch roll:roll fov:fov absolute:absolute];
  653. }
  654. - (NSInteger)currentMediaProjection
  655. {
  656. VLCMedia *media = [_mediaPlayer media];
  657. NSInteger currentVideoTrackIndex = [_mediaPlayer currentVideoTrackIndex];
  658. if (media && currentVideoTrackIndex >= 0) {
  659. NSArray *tracksInfo = media.tracksInformation;
  660. NSDictionary *track = tracksInfo[currentVideoTrackIndex];
  661. if ([track[VLCMediaTracksInformationType] isEqualToString:VLCMediaTracksInformationTypeVideo]) {
  662. return [track[VLCMediaTracksInformationVideoProjection] integerValue];
  663. }
  664. }
  665. return -1;
  666. }
  667. #pragma mark - equalizer
  668. - (void)setAmplification:(CGFloat)amplification forBand:(unsigned int)index
  669. {
  670. if (!_mediaPlayer.equalizerEnabled)
  671. [_mediaPlayer setEqualizerEnabled:YES];
  672. [_mediaPlayer setAmplification:amplification forBand:index];
  673. // For some reason we have to apply again preamp to apply change
  674. [_mediaPlayer setPreAmplification:[_mediaPlayer preAmplification]];
  675. }
  676. - (CGFloat)amplificationOfBand:(unsigned int)index
  677. {
  678. return [_mediaPlayer amplificationOfBand:index];
  679. }
  680. - (NSArray *)equalizerProfiles
  681. {
  682. return _mediaPlayer.equalizerProfiles;
  683. }
  684. - (void)resetEqualizerFromProfile:(unsigned int)profile
  685. {
  686. [[NSUserDefaults standardUserDefaults] setObject:@(profile) forKey:kVLCSettingEqualizerProfile];
  687. [_mediaPlayer resetEqualizerFromProfile:profile];
  688. }
  689. - (void)setPreAmplification:(CGFloat)preAmplification
  690. {
  691. if (!_mediaPlayer.equalizerEnabled)
  692. [_mediaPlayer setEqualizerEnabled:YES];
  693. [_mediaPlayer setPreAmplification:preAmplification];
  694. }
  695. - (CGFloat)preAmplification
  696. {
  697. return [_mediaPlayer preAmplification];
  698. }
  699. #pragma mark - AVSession delegate
  700. - (void)beginInterruption
  701. {
  702. if ([_mediaPlayer isPlaying]) {
  703. [_mediaPlayer pause];
  704. _shouldResumePlayingAfterInteruption = YES;
  705. }
  706. }
  707. - (void)endInterruption
  708. {
  709. if (_shouldResumePlayingAfterInteruption) {
  710. [_mediaPlayer play];
  711. _shouldResumePlayingAfterInteruption = NO;
  712. }
  713. }
  714. - (BOOL)areHeadphonesPlugged
  715. {
  716. NSArray *outputs = [[AVAudioSession sharedInstance] currentRoute].outputs;
  717. NSString *portName = [[outputs firstObject] portName];
  718. return [portName isEqualToString:@"Headphones"];
  719. }
  720. - (void)audioSessionRouteChange:(NSNotification *)notification
  721. {
  722. NSDictionary *userInfo = notification.userInfo;
  723. NSInteger routeChangeReason = [[userInfo valueForKey:AVAudioSessionRouteChangeReasonKey] integerValue];
  724. if (routeChangeReason == AVAudioSessionRouteChangeReasonRouteConfigurationChange)
  725. return;
  726. BOOL headphonesPlugged = [self areHeadphonesPlugged];
  727. if (_headphonesWasPlugged && !headphonesPlugged && [_mediaPlayer isPlaying]) {
  728. [_mediaPlayer pause];
  729. #if TARGET_OS_IOS
  730. [self _savePlaybackState];
  731. #endif
  732. [[NSNotificationCenter defaultCenter] postNotificationName:VLCPlaybackControllerPlaybackDidPause object:self];
  733. }
  734. _headphonesWasPlugged = headphonesPlugged;
  735. }
  736. #pragma mark - Managing the media item
  737. #if TARGET_OS_IOS
  738. - (MLFile *)currentlyPlayingMediaFile {
  739. if (self.mediaList) {
  740. NSArray *results = [MLFile fileForURL:_mediaPlayer.media.url];
  741. return results.firstObject;
  742. }
  743. return nil;
  744. }
  745. #endif
  746. #pragma mark - metadata handling
  747. - (void)mediaDidFinishParsing:(VLCMedia *)aMedia
  748. {
  749. [self setNeedsMetadataUpdate];
  750. }
  751. - (void)mediaMetaDataDidChange:(VLCMedia*)aMedia
  752. {
  753. [self setNeedsMetadataUpdate];
  754. }
  755. - (void)setNeedsMetadataUpdate
  756. {
  757. if (_needsMetadataUpdate == NO) {
  758. _needsMetadataUpdate = YES;
  759. dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.5 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
  760. [self _updateDisplayedMetadata];
  761. });
  762. }
  763. }
  764. - (void)_updateDisplayedMetadata
  765. {
  766. _needsMetadataUpdate = NO;
  767. NSNumber *trackNumber;
  768. NSString *title;
  769. NSString *artist;
  770. NSString *albumName;
  771. UIImage* artworkImage;
  772. BOOL mediaIsAudioOnly = NO;
  773. #if TARGET_OS_IOS
  774. MLFile *item;
  775. if (self.mediaList) {
  776. NSArray *matches = [MLFile fileForURL:_mediaPlayer.media.url];
  777. item = matches.firstObject;
  778. }
  779. if (item) {
  780. if (item.isAlbumTrack) {
  781. title = item.albumTrack.title;
  782. artist = item.albumTrack.artist;
  783. albumName = item.albumTrack.album.name;
  784. } else
  785. title = item.title;
  786. /* MLKit knows better than us if this thing is audio only or not */
  787. mediaIsAudioOnly = [item isSupportedAudioFile];
  788. } else {
  789. #endif
  790. NSDictionary * metaDict = _mediaPlayer.media.metaDictionary;
  791. if (metaDict) {
  792. title = metaDict[VLCMetaInformationNowPlaying] ? metaDict[VLCMetaInformationNowPlaying] : metaDict[VLCMetaInformationTitle];
  793. artist = metaDict[VLCMetaInformationArtist];
  794. albumName = metaDict[VLCMetaInformationAlbum];
  795. trackNumber = metaDict[VLCMetaInformationTrackNumber];
  796. }
  797. #if TARGET_OS_IOS
  798. }
  799. #endif
  800. if (!mediaIsAudioOnly) {
  801. /* either what we are playing is not a file known to MLKit or
  802. * MLKit fails to acknowledge that it is audio-only.
  803. * Either way, do a more expensive check to see if it is really audio-only */
  804. NSArray *tracks = _mediaPlayer.media.tracksInformation;
  805. NSUInteger trackCount = tracks.count;
  806. mediaIsAudioOnly = YES;
  807. for (NSUInteger x = 0 ; x < trackCount; x++) {
  808. if ([[tracks[x] objectForKey:VLCMediaTracksInformationType] isEqualToString:VLCMediaTracksInformationTypeVideo]) {
  809. mediaIsAudioOnly = NO;
  810. break;
  811. }
  812. }
  813. }
  814. if (mediaIsAudioOnly) {
  815. #if TARGET_OS_IOS
  816. artworkImage = [VLCThumbnailsCache thumbnailForManagedObject:item];
  817. if (artworkImage) {
  818. if (artist)
  819. title = [title stringByAppendingFormat:@" — %@", artist];
  820. if (albumName)
  821. title = [title stringByAppendingFormat:@" — %@", albumName];
  822. }
  823. #endif
  824. if (title.length < 1)
  825. title = [[_mediaPlayer.media url] lastPathComponent];
  826. }
  827. /* populate delegate with metadata info */
  828. if ([self.delegate respondsToSelector:@selector(displayMetadataForPlaybackController:title:artwork:artist:album:audioOnly:)])
  829. [self.delegate displayMetadataForPlaybackController:self
  830. title:title
  831. artwork:artworkImage
  832. artist:artist
  833. album:albumName
  834. audioOnly:mediaIsAudioOnly];
  835. /* populate now playing info center with metadata information */
  836. NSMutableDictionary *currentlyPlayingTrackInfo = [NSMutableDictionary dictionary];
  837. currentlyPlayingTrackInfo[MPMediaItemPropertyPlaybackDuration] = @(_mediaPlayer.media.length.intValue / 1000.);
  838. currentlyPlayingTrackInfo[MPNowPlayingInfoPropertyElapsedPlaybackTime] = @(_mediaPlayer.time.intValue / 1000.);
  839. currentlyPlayingTrackInfo[MPNowPlayingInfoPropertyPlaybackRate] = @(_mediaPlayer.isPlaying ? _mediaPlayer.rate : 0.0);
  840. /* don't leak sensitive information to the OS, if passcode lock is enabled */
  841. #if TARGET_OS_IOS
  842. if (![[VLCKeychainCoordinator defaultCoordinator] passcodeLockEnabled]) {
  843. #endif
  844. if (title)
  845. currentlyPlayingTrackInfo[MPMediaItemPropertyTitle] = title;
  846. if (artist.length > 0)
  847. currentlyPlayingTrackInfo[MPMediaItemPropertyArtist] = artist;
  848. if (albumName.length > 0)
  849. currentlyPlayingTrackInfo[MPMediaItemPropertyAlbumTitle] = albumName;
  850. if ([trackNumber intValue] > 0)
  851. currentlyPlayingTrackInfo[MPMediaItemPropertyAlbumTrackNumber] = trackNumber;
  852. #if TARGET_OS_IOS
  853. /* FIXME: UGLY HACK
  854. * iOS 8.2 and 8.3 include an issue which will lead to a termination of the client app if we set artwork
  855. * when the playback initialized through the watch extension
  856. * radar://pending */
  857. if ([WKInterfaceDevice class] != nil) {
  858. if ([WKInterfaceDevice currentDevice] != nil)
  859. goto setstuff;
  860. }
  861. if (artworkImage) {
  862. MPMediaItemArtwork *mpartwork = [[MPMediaItemArtwork alloc] initWithImage:artworkImage];
  863. currentlyPlayingTrackInfo[MPMediaItemPropertyArtwork] = mpartwork;
  864. }
  865. }
  866. #endif
  867. setstuff:
  868. [MPNowPlayingInfoCenter defaultCenter].nowPlayingInfo = currentlyPlayingTrackInfo;
  869. [[NSNotificationCenter defaultCenter] postNotificationName:VLCPlaybackControllerPlaybackMetadataDidChange object:self];
  870. _title = title;
  871. _artist = artist;
  872. _albumName = albumName;
  873. _artworkImage = artworkImage;
  874. _mediaIsAudioOnly = mediaIsAudioOnly;
  875. }
  876. #if TARGET_OS_IOS
  877. - (void)_recoverLastPlaybackStateOfItem:(MLFile *)item
  878. {
  879. if (item) {
  880. if (_mediaPlayer.numberOfAudioTracks > 2) {
  881. if (item.lastAudioTrack.intValue > 0)
  882. _mediaPlayer.currentAudioTrackIndex = item.lastAudioTrack.intValue;
  883. }
  884. if (_mediaPlayer.numberOfSubtitlesTracks > 2) {
  885. if (item.lastSubtitleTrack.intValue > 0)
  886. _mediaPlayer.currentVideoSubTitleIndex = item.lastSubtitleTrack.intValue;
  887. }
  888. CGFloat lastPosition = .0;
  889. NSInteger duration = 0;
  890. if (item.lastPosition)
  891. lastPosition = item.lastPosition.floatValue;
  892. duration = item.duration.intValue;
  893. if (lastPosition < .95 && _mediaPlayer.position < lastPosition && (duration * lastPosition - duration) < -50000) {
  894. NSInteger continuePlayback;
  895. if ([item isAlbumTrack] || [item isSupportedAudioFile])
  896. continuePlayback = [[[NSUserDefaults standardUserDefaults] objectForKey:kVLCSettingContinueAudioPlayback] integerValue];
  897. else
  898. continuePlayback = [[[NSUserDefaults standardUserDefaults] objectForKey:kVLCSettingContinuePlayback] integerValue];
  899. if (continuePlayback == 1) {
  900. _mediaPlayer.position = lastPosition;
  901. } else if (continuePlayback == 0) {
  902. VLCAlertView *alert = [[VLCAlertView alloc] initWithTitle:NSLocalizedString(@"CONTINUE_PLAYBACK", nil)
  903. message:[NSString stringWithFormat:NSLocalizedString(@"CONTINUE_PLAYBACK_LONG", nil), item.title]
  904. delegate:self
  905. cancelButtonTitle:NSLocalizedString(@"BUTTON_CANCEL", nil)
  906. otherButtonTitles:NSLocalizedString(@"BUTTON_CONTINUE", nil), nil];
  907. alert.completion = ^(BOOL cancelled, NSInteger buttonIndex) {
  908. if (!cancelled) {
  909. _mediaPlayer.position = lastPosition;
  910. }
  911. };
  912. [alert show];
  913. }
  914. }
  915. }
  916. }
  917. #endif
  918. - (void)recoverDisplayedMetadata
  919. {
  920. if ([self.delegate respondsToSelector:@selector(displayMetadataForPlaybackController:title:artwork:artist:album:audioOnly:)])
  921. [self.delegate displayMetadataForPlaybackController:self
  922. title:_title
  923. artwork:_artworkImage
  924. artist:_artist
  925. album:_albumName
  926. audioOnly:_mediaIsAudioOnly];
  927. }
  928. - (void)recoverPlaybackState
  929. {
  930. if ([self.delegate respondsToSelector:@selector(mediaPlayerStateChanged:isPlaying:currentMediaHasTrackToChooseFrom:currentMediaHasChapters:forPlaybackController:)])
  931. [self.delegate mediaPlayerStateChanged:_mediaPlayer.state
  932. isPlaying:self.isPlaying
  933. currentMediaHasTrackToChooseFrom:self.currentMediaHasTrackToChooseFrom
  934. currentMediaHasChapters:self.currentMediaHasChapters
  935. forPlaybackController:self];
  936. if ([self.delegate respondsToSelector:@selector(prepareForMediaPlayback:)])
  937. [self.delegate prepareForMediaPlayback:self];
  938. }
  939. - (void)scheduleSleepTimerWithInterval:(NSTimeInterval)timeInterval
  940. {
  941. if (_sleepTimer) {
  942. [_sleepTimer invalidate];
  943. _sleepTimer = nil;
  944. }
  945. _sleepTimer = [NSTimer scheduledTimerWithTimeInterval:timeInterval target:self selector:@selector(stopPlayback) userInfo:nil repeats:NO];
  946. }
  947. #pragma mark - remote events
  948. static inline NSArray * RemoteCommandCenterCommandsToHandle(MPRemoteCommandCenter *cc)
  949. {
  950. /* commmented out other available commands which we don't support now but may
  951. * support at some point in the future */
  952. return @[cc.pauseCommand, cc.playCommand, cc.stopCommand, cc.togglePlayPauseCommand,
  953. cc.nextTrackCommand, cc.previousTrackCommand,
  954. cc.skipForwardCommand, cc.skipBackwardCommand,
  955. // cc.seekForwardCommand, cc.seekBackwardCommand,
  956. // cc.ratingCommand,
  957. cc.changePlaybackRateCommand,
  958. // cc.likeCommand,cc.dislikeCommand,cc.bookmarkCommand,
  959. ];
  960. }
  961. - (void)subscribeRemoteCommands
  962. {
  963. /* pre iOS 7.1 */
  964. if (![MPRemoteCommandCenter class]) {
  965. [[UIApplication sharedApplication] beginReceivingRemoteControlEvents];
  966. return;
  967. }
  968. /* for iOS 7.1 and above: */
  969. MPRemoteCommandCenter *commandCenter = [MPRemoteCommandCenter sharedCommandCenter];
  970. /*
  971. * since the control center and lockscreen shows only either skipForward/Backward
  972. * or next/previousTrack buttons but prefers skip buttons,
  973. * we only enable skip buttons if we have a no medialist
  974. */
  975. BOOL enableSkip = [VLCPlaybackController sharedInstance].mediaList.count <= 1;
  976. commandCenter.skipForwardCommand.enabled = enableSkip;
  977. commandCenter.skipBackwardCommand.enabled = enableSkip;
  978. NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
  979. NSNumber *forwardSkip = [defaults valueForKey:kVLCSettingPlaybackForwardSkipLength];
  980. commandCenter.skipForwardCommand.preferredIntervals = @[forwardSkip];
  981. NSNumber *backwardSkip = [defaults valueForKey:kVLCSettingPlaybackBackwardSkipLength];
  982. commandCenter.skipBackwardCommand.preferredIntervals = @[backwardSkip];
  983. NSArray *supportedPlaybackRates = @[@(0.5),@(0.75),@(1.0),@(1.25),@(1.5),@(1.75),@(2.0)];
  984. commandCenter.changePlaybackRateCommand.supportedPlaybackRates = supportedPlaybackRates;
  985. NSArray *commandsToSubscribe = RemoteCommandCenterCommandsToHandle(commandCenter);
  986. for (MPRemoteCommand *command in commandsToSubscribe) {
  987. [command addTarget:self action:@selector(remoteCommandEvent:)];
  988. }
  989. }
  990. - (void)unsubscribeFromRemoteCommand
  991. {
  992. /* pre iOS 7.1 */
  993. if (![MPRemoteCommandCenter class]) {
  994. [[UIApplication sharedApplication] endReceivingRemoteControlEvents];
  995. return;
  996. }
  997. /* for iOS 7.1 and above: */
  998. MPRemoteCommandCenter *cc = [MPRemoteCommandCenter sharedCommandCenter];
  999. NSArray *commmandsToRemoveFrom = RemoteCommandCenterCommandsToHandle(cc);
  1000. for (MPRemoteCommand *command in commmandsToRemoveFrom) {
  1001. [command removeTarget:self];
  1002. }
  1003. }
  1004. - (MPRemoteCommandHandlerStatus )remoteCommandEvent:(MPRemoteCommandEvent *)event
  1005. {
  1006. MPRemoteCommandCenter *cc = [MPRemoteCommandCenter sharedCommandCenter];
  1007. MPRemoteCommandHandlerStatus result = MPRemoteCommandHandlerStatusSuccess;
  1008. if (event.command == cc.pauseCommand) {
  1009. [_listPlayer pause];
  1010. } else if (event.command == cc.playCommand) {
  1011. [_listPlayer play];
  1012. } else if (event.command == cc.stopCommand) {
  1013. [_listPlayer stop];
  1014. } else if (event.command == cc.togglePlayPauseCommand) {
  1015. [self playPause];
  1016. } else if (event.command == cc.nextTrackCommand) {
  1017. result = [_listPlayer next] ? MPRemoteCommandHandlerStatusSuccess : MPRemoteCommandHandlerStatusNoSuchContent;
  1018. } else if (event.command == cc.previousTrackCommand) {
  1019. result = [_listPlayer previous] ? MPRemoteCommandHandlerStatusSuccess : MPRemoteCommandHandlerStatusNoSuchContent;
  1020. } else if (event.command == cc.skipForwardCommand) {
  1021. if ([event isKindOfClass:[MPSkipIntervalCommandEvent class]]) {
  1022. MPSkipIntervalCommandEvent *skipEvent = (MPSkipIntervalCommandEvent *)event;
  1023. [_mediaPlayer jumpForward:skipEvent.interval];
  1024. } else {
  1025. result = MPRemoteCommandHandlerStatusCommandFailed;
  1026. }
  1027. } else if (event.command == cc.skipBackwardCommand) {
  1028. if ([event isKindOfClass:[MPSkipIntervalCommandEvent class]]) {
  1029. MPSkipIntervalCommandEvent *skipEvent = (MPSkipIntervalCommandEvent *)event;
  1030. [_mediaPlayer jumpBackward:skipEvent.interval];
  1031. } else {
  1032. result = MPRemoteCommandHandlerStatusCommandFailed;
  1033. }
  1034. } else if (event.command == cc.changePlaybackRateCommand) {
  1035. if ([event isKindOfClass:[MPChangePlaybackRateCommandEvent class]]) {
  1036. MPChangePlaybackRateCommandEvent *rateEvent = (MPChangePlaybackRateCommandEvent *)event;
  1037. [_mediaPlayer setRate:rateEvent.playbackRate];
  1038. } else {
  1039. result = MPRemoteCommandHandlerStatusCommandFailed;
  1040. }
  1041. /* stubs for when we want to support the other available commands */
  1042. // } else if (event.command == cc.seekForwardCommand) {
  1043. // } else if (event.command == cc.seekBackwardCommand) {
  1044. // } else if (event.command == cc.ratingCommand) {
  1045. // } else if (event.command == cc.likeCommand) {
  1046. // } else if (event.command == cc.dislikeCommand) {
  1047. // } else if (event.command == cc.bookmarkCommand) {
  1048. } else {
  1049. APLog(@"%s Unsupported remote control event: %@",__PRETTY_FUNCTION__,event);
  1050. result = MPRemoteCommandHandlerStatusCommandFailed;
  1051. }
  1052. if (result == MPRemoteCommandHandlerStatusCommandFailed)
  1053. APLog(@"%s Wasn't able to handle remote control event: %@",__PRETTY_FUNCTION__,event);
  1054. return result;
  1055. }
  1056. - (void)remoteControlReceivedWithEvent:(UIEvent *)event
  1057. {
  1058. switch (event.subtype) {
  1059. case UIEventSubtypeRemoteControlPlay:
  1060. [_listPlayer play];
  1061. break;
  1062. case UIEventSubtypeRemoteControlPause:
  1063. [_listPlayer pause];
  1064. break;
  1065. case UIEventSubtypeRemoteControlTogglePlayPause:
  1066. [self playPause];
  1067. break;
  1068. case UIEventSubtypeRemoteControlNextTrack:
  1069. [self forward];
  1070. break;
  1071. case UIEventSubtypeRemoteControlPreviousTrack:
  1072. [self backward];
  1073. break;
  1074. case UIEventSubtypeRemoteControlStop:
  1075. [self stopPlayback];
  1076. break;
  1077. default:
  1078. break;
  1079. }
  1080. }
  1081. #pragma mark - background interaction
  1082. - (void)applicationWillResignActive:(NSNotification *)aNotification
  1083. {
  1084. #if TARGET_OS_IOS
  1085. [self _savePlaybackState];
  1086. #endif
  1087. if (![[[NSUserDefaults standardUserDefaults] objectForKey:kVLCSettingContinueAudioInBackgroundKey] boolValue]) {
  1088. if ([_mediaPlayer isPlaying]) {
  1089. [_mediaPlayer pause];
  1090. _shouldResumePlaying = YES;
  1091. }
  1092. }
  1093. }
  1094. - (void)applicationDidEnterBackground:(NSNotification *)notification
  1095. {
  1096. _preBackgroundWrapperView = _videoOutputViewWrapper;
  1097. [self setVideoOutputView:nil];
  1098. if (_mediaPlayer.audioTrackIndexes.count > 0)
  1099. _mediaPlayer.currentVideoTrackIndex = -1;
  1100. }
  1101. - (void)applicationDidBecomeActive:(NSNotification *)notification
  1102. {
  1103. if (_preBackgroundWrapperView) {
  1104. [self setVideoOutputView:_preBackgroundWrapperView];
  1105. _preBackgroundWrapperView = nil;
  1106. }
  1107. if (_mediaPlayer.numberOfVideoTracks > 0) {
  1108. /* re-enable video decoding */
  1109. _mediaPlayer.currentVideoTrackIndex = 1;
  1110. }
  1111. if (_shouldResumePlaying) {
  1112. _shouldResumePlaying = NO;
  1113. [_listPlayer play];
  1114. }
  1115. }
  1116. #pragma mark - helpers
  1117. - (NSDictionary *)mediaOptionsDictionary
  1118. {
  1119. NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
  1120. return @{ kVLCSettingNetworkCaching : [defaults objectForKey:kVLCSettingNetworkCaching],
  1121. kVLCSettingStretchAudio : [[defaults objectForKey:kVLCSettingStretchAudio] boolValue] ? kVLCSettingStretchAudioOnValue : kVLCSettingStretchAudioOffValue,
  1122. kVLCSettingTextEncoding : [defaults objectForKey:kVLCSettingTextEncoding],
  1123. kVLCSettingSkipLoopFilter : [defaults objectForKey:kVLCSettingSkipLoopFilter] };
  1124. }
  1125. @end