VLCPlaybackController.m 50 KB

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