VLCPlaybackController.m 48 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333
  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. for (NSDictionary *track in tracksInfo) {
  661. if ([track[VLCMediaTracksInformationType] isEqualToString:VLCMediaTracksInformationTypeVideo]) {
  662. return [track[VLCMediaTracksInformationVideoProjection] integerValue];
  663. }
  664. }
  665. }
  666. return -1;
  667. }
  668. #pragma mark - equalizer
  669. - (void)setAmplification:(CGFloat)amplification forBand:(unsigned int)index
  670. {
  671. if (!_mediaPlayer.equalizerEnabled)
  672. [_mediaPlayer setEqualizerEnabled:YES];
  673. [_mediaPlayer setAmplification:amplification forBand:index];
  674. // For some reason we have to apply again preamp to apply change
  675. [_mediaPlayer setPreAmplification:[_mediaPlayer preAmplification]];
  676. }
  677. - (CGFloat)amplificationOfBand:(unsigned int)index
  678. {
  679. return [_mediaPlayer amplificationOfBand:index];
  680. }
  681. - (NSArray *)equalizerProfiles
  682. {
  683. return _mediaPlayer.equalizerProfiles;
  684. }
  685. - (void)resetEqualizerFromProfile:(unsigned int)profile
  686. {
  687. [[NSUserDefaults standardUserDefaults] setObject:@(profile) forKey:kVLCSettingEqualizerProfile];
  688. [_mediaPlayer resetEqualizerFromProfile:profile];
  689. }
  690. - (void)setPreAmplification:(CGFloat)preAmplification
  691. {
  692. if (!_mediaPlayer.equalizerEnabled)
  693. [_mediaPlayer setEqualizerEnabled:YES];
  694. [_mediaPlayer setPreAmplification:preAmplification];
  695. }
  696. - (CGFloat)preAmplification
  697. {
  698. return [_mediaPlayer preAmplification];
  699. }
  700. #pragma mark - AVSession delegate
  701. - (void)beginInterruption
  702. {
  703. if ([_mediaPlayer isPlaying]) {
  704. [_mediaPlayer pause];
  705. _shouldResumePlayingAfterInteruption = YES;
  706. }
  707. }
  708. - (void)endInterruption
  709. {
  710. if (_shouldResumePlayingAfterInteruption) {
  711. [_mediaPlayer play];
  712. _shouldResumePlayingAfterInteruption = NO;
  713. }
  714. }
  715. - (BOOL)areHeadphonesPlugged
  716. {
  717. NSArray *outputs = [[AVAudioSession sharedInstance] currentRoute].outputs;
  718. NSString *portName = [[outputs firstObject] portName];
  719. return [portName isEqualToString:@"Headphones"];
  720. }
  721. - (void)audioSessionRouteChange:(NSNotification *)notification
  722. {
  723. NSDictionary *userInfo = notification.userInfo;
  724. NSInteger routeChangeReason = [[userInfo valueForKey:AVAudioSessionRouteChangeReasonKey] integerValue];
  725. if (routeChangeReason == AVAudioSessionRouteChangeReasonRouteConfigurationChange)
  726. return;
  727. BOOL headphonesPlugged = [self areHeadphonesPlugged];
  728. if (_headphonesWasPlugged && !headphonesPlugged && [_mediaPlayer isPlaying]) {
  729. [_mediaPlayer pause];
  730. #if TARGET_OS_IOS
  731. [self _savePlaybackState];
  732. #endif
  733. [[NSNotificationCenter defaultCenter] postNotificationName:VLCPlaybackControllerPlaybackDidPause object:self];
  734. }
  735. _headphonesWasPlugged = headphonesPlugged;
  736. }
  737. #pragma mark - Managing the media item
  738. #if TARGET_OS_IOS
  739. - (MLFile *)currentlyPlayingMediaFile {
  740. if (self.mediaList) {
  741. NSArray *results = [MLFile fileForURL:_mediaPlayer.media.url];
  742. return results.firstObject;
  743. }
  744. return nil;
  745. }
  746. #endif
  747. #pragma mark - metadata handling
  748. - (void)mediaDidFinishParsing:(VLCMedia *)aMedia
  749. {
  750. [self setNeedsMetadataUpdate];
  751. }
  752. - (void)mediaMetaDataDidChange:(VLCMedia*)aMedia
  753. {
  754. [self setNeedsMetadataUpdate];
  755. }
  756. - (void)setNeedsMetadataUpdate
  757. {
  758. if (_needsMetadataUpdate == NO) {
  759. _needsMetadataUpdate = YES;
  760. dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.5 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
  761. [self _updateDisplayedMetadata];
  762. });
  763. }
  764. }
  765. - (void)_updateDisplayedMetadata
  766. {
  767. _needsMetadataUpdate = NO;
  768. NSNumber *trackNumber;
  769. NSString *title;
  770. NSString *artist;
  771. NSString *albumName;
  772. UIImage* artworkImage;
  773. BOOL mediaIsAudioOnly = NO;
  774. #if TARGET_OS_IOS
  775. MLFile *item;
  776. if (self.mediaList) {
  777. NSArray *matches = [MLFile fileForURL:_mediaPlayer.media.url];
  778. item = matches.firstObject;
  779. }
  780. if (item) {
  781. if (item.isAlbumTrack) {
  782. title = item.albumTrack.title;
  783. artist = item.albumTrack.artist;
  784. albumName = item.albumTrack.album.name;
  785. } else
  786. title = item.title;
  787. /* MLKit knows better than us if this thing is audio only or not */
  788. mediaIsAudioOnly = [item isSupportedAudioFile];
  789. } else {
  790. #endif
  791. NSDictionary * metaDict = _mediaPlayer.media.metaDictionary;
  792. if (metaDict) {
  793. title = metaDict[VLCMetaInformationNowPlaying] ? metaDict[VLCMetaInformationNowPlaying] : metaDict[VLCMetaInformationTitle];
  794. artist = metaDict[VLCMetaInformationArtist];
  795. albumName = metaDict[VLCMetaInformationAlbum];
  796. trackNumber = metaDict[VLCMetaInformationTrackNumber];
  797. }
  798. #if TARGET_OS_IOS
  799. }
  800. #endif
  801. if (!mediaIsAudioOnly) {
  802. /* either what we are playing is not a file known to MLKit or
  803. * MLKit fails to acknowledge that it is audio-only.
  804. * Either way, do a more expensive check to see if it is really audio-only */
  805. NSArray *tracks = _mediaPlayer.media.tracksInformation;
  806. NSUInteger trackCount = tracks.count;
  807. mediaIsAudioOnly = YES;
  808. for (NSUInteger x = 0 ; x < trackCount; x++) {
  809. if ([[tracks[x] objectForKey:VLCMediaTracksInformationType] isEqualToString:VLCMediaTracksInformationTypeVideo]) {
  810. mediaIsAudioOnly = NO;
  811. break;
  812. }
  813. }
  814. }
  815. if (mediaIsAudioOnly) {
  816. #if TARGET_OS_IOS
  817. artworkImage = [VLCThumbnailsCache thumbnailForManagedObject:item];
  818. if (artworkImage) {
  819. if (artist)
  820. title = [title stringByAppendingFormat:@" — %@", artist];
  821. if (albumName)
  822. title = [title stringByAppendingFormat:@" — %@", albumName];
  823. }
  824. #endif
  825. if (title.length < 1)
  826. title = [[_mediaPlayer.media url] lastPathComponent];
  827. }
  828. /* populate delegate with metadata info */
  829. if ([self.delegate respondsToSelector:@selector(displayMetadataForPlaybackController:title:artwork:artist:album:audioOnly:)])
  830. [self.delegate displayMetadataForPlaybackController:self
  831. title:title
  832. artwork:artworkImage
  833. artist:artist
  834. album:albumName
  835. audioOnly:mediaIsAudioOnly];
  836. /* populate now playing info center with metadata information */
  837. NSMutableDictionary *currentlyPlayingTrackInfo = [NSMutableDictionary dictionary];
  838. currentlyPlayingTrackInfo[MPMediaItemPropertyPlaybackDuration] = @(_mediaPlayer.media.length.intValue / 1000.);
  839. currentlyPlayingTrackInfo[MPNowPlayingInfoPropertyElapsedPlaybackTime] = @(_mediaPlayer.time.intValue / 1000.);
  840. currentlyPlayingTrackInfo[MPNowPlayingInfoPropertyPlaybackRate] = @(_mediaPlayer.isPlaying ? _mediaPlayer.rate : 0.0);
  841. /* don't leak sensitive information to the OS, if passcode lock is enabled */
  842. #if TARGET_OS_IOS
  843. if (![[VLCKeychainCoordinator defaultCoordinator] passcodeLockEnabled]) {
  844. #endif
  845. if (title)
  846. currentlyPlayingTrackInfo[MPMediaItemPropertyTitle] = title;
  847. if (artist.length > 0)
  848. currentlyPlayingTrackInfo[MPMediaItemPropertyArtist] = artist;
  849. if (albumName.length > 0)
  850. currentlyPlayingTrackInfo[MPMediaItemPropertyAlbumTitle] = albumName;
  851. if ([trackNumber intValue] > 0)
  852. currentlyPlayingTrackInfo[MPMediaItemPropertyAlbumTrackNumber] = trackNumber;
  853. #if TARGET_OS_IOS
  854. /* FIXME: UGLY HACK
  855. * iOS 8.2 and 8.3 include an issue which will lead to a termination of the client app if we set artwork
  856. * when the playback initialized through the watch extension
  857. * radar://pending */
  858. if ([WKInterfaceDevice class] != nil) {
  859. if ([WKInterfaceDevice currentDevice] != nil)
  860. goto setstuff;
  861. }
  862. if (artworkImage) {
  863. MPMediaItemArtwork *mpartwork = [[MPMediaItemArtwork alloc] initWithImage:artworkImage];
  864. currentlyPlayingTrackInfo[MPMediaItemPropertyArtwork] = mpartwork;
  865. }
  866. }
  867. #endif
  868. setstuff:
  869. [MPNowPlayingInfoCenter defaultCenter].nowPlayingInfo = currentlyPlayingTrackInfo;
  870. [[NSNotificationCenter defaultCenter] postNotificationName:VLCPlaybackControllerPlaybackMetadataDidChange object:self];
  871. _title = title;
  872. _artist = artist;
  873. _albumName = albumName;
  874. _artworkImage = artworkImage;
  875. _mediaIsAudioOnly = mediaIsAudioOnly;
  876. }
  877. #if TARGET_OS_IOS
  878. - (void)_recoverLastPlaybackStateOfItem:(MLFile *)item
  879. {
  880. if (item) {
  881. if (_mediaPlayer.numberOfAudioTracks > 2) {
  882. if (item.lastAudioTrack.intValue > 0)
  883. _mediaPlayer.currentAudioTrackIndex = item.lastAudioTrack.intValue;
  884. }
  885. if (_mediaPlayer.numberOfSubtitlesTracks > 2) {
  886. if (item.lastSubtitleTrack.intValue > 0)
  887. _mediaPlayer.currentVideoSubTitleIndex = item.lastSubtitleTrack.intValue;
  888. }
  889. CGFloat lastPosition = .0;
  890. NSInteger duration = 0;
  891. if (item.lastPosition)
  892. lastPosition = item.lastPosition.floatValue;
  893. duration = item.duration.intValue;
  894. if (lastPosition < .95 && _mediaPlayer.position < lastPosition && (duration * lastPosition - duration) < -50000) {
  895. NSInteger continuePlayback;
  896. if ([item isAlbumTrack] || [item isSupportedAudioFile])
  897. continuePlayback = [[[NSUserDefaults standardUserDefaults] objectForKey:kVLCSettingContinueAudioPlayback] integerValue];
  898. else
  899. continuePlayback = [[[NSUserDefaults standardUserDefaults] objectForKey:kVLCSettingContinuePlayback] integerValue];
  900. if (continuePlayback == 1) {
  901. _mediaPlayer.position = lastPosition;
  902. } else if (continuePlayback == 0) {
  903. VLCAlertView *alert = [[VLCAlertView alloc] initWithTitle:NSLocalizedString(@"CONTINUE_PLAYBACK", nil)
  904. message:[NSString stringWithFormat:NSLocalizedString(@"CONTINUE_PLAYBACK_LONG", nil), item.title]
  905. delegate:self
  906. cancelButtonTitle:NSLocalizedString(@"BUTTON_CANCEL", nil)
  907. otherButtonTitles:NSLocalizedString(@"BUTTON_CONTINUE", nil), nil];
  908. alert.completion = ^(BOOL cancelled, NSInteger buttonIndex) {
  909. if (!cancelled) {
  910. _mediaPlayer.position = lastPosition;
  911. }
  912. };
  913. [alert show];
  914. }
  915. }
  916. }
  917. }
  918. #endif
  919. - (void)recoverDisplayedMetadata
  920. {
  921. if ([self.delegate respondsToSelector:@selector(displayMetadataForPlaybackController:title:artwork:artist:album:audioOnly:)])
  922. [self.delegate displayMetadataForPlaybackController:self
  923. title:_title
  924. artwork:_artworkImage
  925. artist:_artist
  926. album:_albumName
  927. audioOnly:_mediaIsAudioOnly];
  928. }
  929. - (void)recoverPlaybackState
  930. {
  931. if ([self.delegate respondsToSelector:@selector(mediaPlayerStateChanged:isPlaying:currentMediaHasTrackToChooseFrom:currentMediaHasChapters:forPlaybackController:)])
  932. [self.delegate mediaPlayerStateChanged:_mediaPlayer.state
  933. isPlaying:self.isPlaying
  934. currentMediaHasTrackToChooseFrom:self.currentMediaHasTrackToChooseFrom
  935. currentMediaHasChapters:self.currentMediaHasChapters
  936. forPlaybackController:self];
  937. if ([self.delegate respondsToSelector:@selector(prepareForMediaPlayback:)])
  938. [self.delegate prepareForMediaPlayback:self];
  939. }
  940. - (void)scheduleSleepTimerWithInterval:(NSTimeInterval)timeInterval
  941. {
  942. if (_sleepTimer) {
  943. [_sleepTimer invalidate];
  944. _sleepTimer = nil;
  945. }
  946. _sleepTimer = [NSTimer scheduledTimerWithTimeInterval:timeInterval target:self selector:@selector(stopPlayback) userInfo:nil repeats:NO];
  947. }
  948. #pragma mark - remote events
  949. static inline NSArray * RemoteCommandCenterCommandsToHandle(MPRemoteCommandCenter *cc)
  950. {
  951. /* commmented out other available commands which we don't support now but may
  952. * support at some point in the future */
  953. return @[cc.pauseCommand, cc.playCommand, cc.stopCommand, cc.togglePlayPauseCommand,
  954. cc.nextTrackCommand, cc.previousTrackCommand,
  955. cc.skipForwardCommand, cc.skipBackwardCommand,
  956. // cc.seekForwardCommand, cc.seekBackwardCommand,
  957. // cc.ratingCommand,
  958. cc.changePlaybackRateCommand,
  959. // cc.likeCommand,cc.dislikeCommand,cc.bookmarkCommand,
  960. ];
  961. }
  962. - (void)subscribeRemoteCommands
  963. {
  964. /* pre iOS 7.1 */
  965. if (![MPRemoteCommandCenter class]) {
  966. [[UIApplication sharedApplication] beginReceivingRemoteControlEvents];
  967. return;
  968. }
  969. /* for iOS 7.1 and above: */
  970. MPRemoteCommandCenter *commandCenter = [MPRemoteCommandCenter sharedCommandCenter];
  971. /*
  972. * since the control center and lockscreen shows only either skipForward/Backward
  973. * or next/previousTrack buttons but prefers skip buttons,
  974. * we only enable skip buttons if we have a no medialist
  975. */
  976. BOOL enableSkip = [VLCPlaybackController sharedInstance].mediaList.count <= 1;
  977. commandCenter.skipForwardCommand.enabled = enableSkip;
  978. commandCenter.skipBackwardCommand.enabled = enableSkip;
  979. NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
  980. NSNumber *forwardSkip = [defaults valueForKey:kVLCSettingPlaybackForwardSkipLength];
  981. commandCenter.skipForwardCommand.preferredIntervals = @[forwardSkip];
  982. NSNumber *backwardSkip = [defaults valueForKey:kVLCSettingPlaybackBackwardSkipLength];
  983. commandCenter.skipBackwardCommand.preferredIntervals = @[backwardSkip];
  984. NSArray *supportedPlaybackRates = @[@(0.5),@(0.75),@(1.0),@(1.25),@(1.5),@(1.75),@(2.0)];
  985. commandCenter.changePlaybackRateCommand.supportedPlaybackRates = supportedPlaybackRates;
  986. NSArray *commandsToSubscribe = RemoteCommandCenterCommandsToHandle(commandCenter);
  987. for (MPRemoteCommand *command in commandsToSubscribe) {
  988. [command addTarget:self action:@selector(remoteCommandEvent:)];
  989. }
  990. }
  991. - (void)unsubscribeFromRemoteCommand
  992. {
  993. /* pre iOS 7.1 */
  994. if (![MPRemoteCommandCenter class]) {
  995. [[UIApplication sharedApplication] endReceivingRemoteControlEvents];
  996. return;
  997. }
  998. /* for iOS 7.1 and above: */
  999. MPRemoteCommandCenter *cc = [MPRemoteCommandCenter sharedCommandCenter];
  1000. NSArray *commmandsToRemoveFrom = RemoteCommandCenterCommandsToHandle(cc);
  1001. for (MPRemoteCommand *command in commmandsToRemoveFrom) {
  1002. [command removeTarget:self];
  1003. }
  1004. }
  1005. - (MPRemoteCommandHandlerStatus )remoteCommandEvent:(MPRemoteCommandEvent *)event
  1006. {
  1007. MPRemoteCommandCenter *cc = [MPRemoteCommandCenter sharedCommandCenter];
  1008. MPRemoteCommandHandlerStatus result = MPRemoteCommandHandlerStatusSuccess;
  1009. if (event.command == cc.pauseCommand) {
  1010. [_listPlayer pause];
  1011. } else if (event.command == cc.playCommand) {
  1012. [_listPlayer play];
  1013. } else if (event.command == cc.stopCommand) {
  1014. [_listPlayer stop];
  1015. } else if (event.command == cc.togglePlayPauseCommand) {
  1016. [self playPause];
  1017. } else if (event.command == cc.nextTrackCommand) {
  1018. result = [_listPlayer next] ? MPRemoteCommandHandlerStatusSuccess : MPRemoteCommandHandlerStatusNoSuchContent;
  1019. } else if (event.command == cc.previousTrackCommand) {
  1020. result = [_listPlayer previous] ? MPRemoteCommandHandlerStatusSuccess : MPRemoteCommandHandlerStatusNoSuchContent;
  1021. } else if (event.command == cc.skipForwardCommand) {
  1022. if ([event isKindOfClass:[MPSkipIntervalCommandEvent class]]) {
  1023. MPSkipIntervalCommandEvent *skipEvent = (MPSkipIntervalCommandEvent *)event;
  1024. [_mediaPlayer jumpForward:skipEvent.interval];
  1025. } else {
  1026. result = MPRemoteCommandHandlerStatusCommandFailed;
  1027. }
  1028. } else if (event.command == cc.skipBackwardCommand) {
  1029. if ([event isKindOfClass:[MPSkipIntervalCommandEvent class]]) {
  1030. MPSkipIntervalCommandEvent *skipEvent = (MPSkipIntervalCommandEvent *)event;
  1031. [_mediaPlayer jumpBackward:skipEvent.interval];
  1032. } else {
  1033. result = MPRemoteCommandHandlerStatusCommandFailed;
  1034. }
  1035. } else if (event.command == cc.changePlaybackRateCommand) {
  1036. if ([event isKindOfClass:[MPChangePlaybackRateCommandEvent class]]) {
  1037. MPChangePlaybackRateCommandEvent *rateEvent = (MPChangePlaybackRateCommandEvent *)event;
  1038. [_mediaPlayer setRate:rateEvent.playbackRate];
  1039. } else {
  1040. result = MPRemoteCommandHandlerStatusCommandFailed;
  1041. }
  1042. /* stubs for when we want to support the other available commands */
  1043. // } else if (event.command == cc.seekForwardCommand) {
  1044. // } else if (event.command == cc.seekBackwardCommand) {
  1045. // } else if (event.command == cc.ratingCommand) {
  1046. // } else if (event.command == cc.likeCommand) {
  1047. // } else if (event.command == cc.dislikeCommand) {
  1048. // } else if (event.command == cc.bookmarkCommand) {
  1049. } else {
  1050. APLog(@"%s Unsupported remote control event: %@",__PRETTY_FUNCTION__,event);
  1051. result = MPRemoteCommandHandlerStatusCommandFailed;
  1052. }
  1053. if (result == MPRemoteCommandHandlerStatusCommandFailed)
  1054. APLog(@"%s Wasn't able to handle remote control event: %@",__PRETTY_FUNCTION__,event);
  1055. return result;
  1056. }
  1057. - (void)remoteControlReceivedWithEvent:(UIEvent *)event
  1058. {
  1059. switch (event.subtype) {
  1060. case UIEventSubtypeRemoteControlPlay:
  1061. [_listPlayer play];
  1062. break;
  1063. case UIEventSubtypeRemoteControlPause:
  1064. [_listPlayer pause];
  1065. break;
  1066. case UIEventSubtypeRemoteControlTogglePlayPause:
  1067. [self playPause];
  1068. break;
  1069. case UIEventSubtypeRemoteControlNextTrack:
  1070. [self forward];
  1071. break;
  1072. case UIEventSubtypeRemoteControlPreviousTrack:
  1073. [self backward];
  1074. break;
  1075. case UIEventSubtypeRemoteControlStop:
  1076. [self stopPlayback];
  1077. break;
  1078. default:
  1079. break;
  1080. }
  1081. }
  1082. #pragma mark - background interaction
  1083. - (void)applicationWillResignActive:(NSNotification *)aNotification
  1084. {
  1085. #if TARGET_OS_IOS
  1086. [self _savePlaybackState];
  1087. #endif
  1088. if (![[[NSUserDefaults standardUserDefaults] objectForKey:kVLCSettingContinueAudioInBackgroundKey] boolValue]) {
  1089. if ([_mediaPlayer isPlaying]) {
  1090. [_mediaPlayer pause];
  1091. _shouldResumePlaying = YES;
  1092. }
  1093. }
  1094. }
  1095. - (void)applicationDidEnterBackground:(NSNotification *)notification
  1096. {
  1097. _preBackgroundWrapperView = _videoOutputViewWrapper;
  1098. [self setVideoOutputView:nil];
  1099. if (_mediaPlayer.audioTrackIndexes.count > 0)
  1100. _mediaPlayer.currentVideoTrackIndex = -1;
  1101. }
  1102. - (void)applicationDidBecomeActive:(NSNotification *)notification
  1103. {
  1104. if (_preBackgroundWrapperView) {
  1105. [self setVideoOutputView:_preBackgroundWrapperView];
  1106. _preBackgroundWrapperView = nil;
  1107. }
  1108. if (_mediaPlayer.numberOfVideoTracks > 0) {
  1109. /* re-enable video decoding */
  1110. _mediaPlayer.currentVideoTrackIndex = 1;
  1111. }
  1112. if (_shouldResumePlaying) {
  1113. _shouldResumePlaying = NO;
  1114. [_listPlayer play];
  1115. }
  1116. }
  1117. #pragma mark - helpers
  1118. - (NSDictionary *)mediaOptionsDictionary
  1119. {
  1120. NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
  1121. return @{ kVLCSettingNetworkCaching : [defaults objectForKey:kVLCSettingNetworkCaching],
  1122. kVLCSettingStretchAudio : [[defaults objectForKey:kVLCSettingStretchAudio] boolValue] ? kVLCSettingStretchAudioOnValue : kVLCSettingStretchAudioOffValue,
  1123. kVLCSettingTextEncoding : [defaults objectForKey:kVLCSettingTextEncoding],
  1124. kVLCSettingSkipLoopFilter : [defaults objectForKey:kVLCSettingSkipLoopFilter],
  1125. kVLCSettingHWDecoding : [defaults objectForKey:kVLCSettingHWDecoding]};
  1126. }
  1127. @end