VLCPlaybackController.m 46 KB

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