VLCPlaybackController.m 47 KB

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