VLCPlaybackController.m 46 KB

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