VLCPlaybackController.m 47 KB

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