VLCPlaybackController.m 46 KB

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