VLCPlaybackController.m 47 KB

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