VLCPlaybackController.m 42 KB

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