VLCPlaybackController.m 46 KB

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