VLCPlaybackController.m 49 KB

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