VLCPlaybackController.m 47 KB

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