VLCPlaybackController.m 46 KB

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