VLCPlaybackController.m 50 KB

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