VLCPlaybackController.m 47 KB

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