VLCPlaybackController.m 50 KB

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