VLCPlaybackController.m 47 KB

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