VLCPlaybackController.m 48 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285
  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. [_mediaPlayer performSelector:@selector(setTextRendererFont:) withObject:[self _resolveFontName]];
  489. [_mediaPlayer performSelector:@selector(setTextRendererFontSize:) withObject:[[NSUserDefaults standardUserDefaults] objectForKey:kVLCSettingSubtitlesFontSize]];
  490. [_mediaPlayer performSelector:@selector(setTextRendererFontColor:) withObject:[[NSUserDefaults standardUserDefaults] objectForKey:kVLCSettingSubtitlesFontColor]];
  491. } else if (currentState == VLCMediaPlayerStateError) {
  492. APLog(@"Playback failed");
  493. _playbackFailed = YES;
  494. self.sessionWillRestart = NO;
  495. [self stopPlayback];
  496. } else if ((currentState == VLCMediaPlayerStateEnded || currentState == VLCMediaPlayerStateStopped) && _listPlayer.repeatMode == VLCDoNotRepeat) {
  497. [_listPlayer.mediaList lock];
  498. NSUInteger listCount = _listPlayer.mediaList.count;
  499. if ([_listPlayer.mediaList indexOfMedia:_mediaPlayer.media] == listCount - 1) {
  500. [_listPlayer.mediaList unlock];
  501. self.sessionWillRestart = NO;
  502. [self stopPlayback];
  503. return;
  504. } else if (listCount > 1) {
  505. [_listPlayer.mediaList unlock];
  506. [_listPlayer next];
  507. }
  508. }
  509. if ([self.delegate respondsToSelector:@selector(mediaPlayerStateChanged:isPlaying:currentMediaHasTrackToChooseFrom:currentMediaHasChapters:forPlaybackController:)])
  510. [self.delegate mediaPlayerStateChanged:currentState
  511. isPlaying:_mediaPlayer.isPlaying
  512. currentMediaHasTrackToChooseFrom:self.currentMediaHasTrackToChooseFrom
  513. currentMediaHasChapters:self.currentMediaHasChapters
  514. forPlaybackController:self];
  515. [self setNeedsMetadataUpdate];
  516. }
  517. #pragma mark - playback controls
  518. - (void)playPause
  519. {
  520. if ([_mediaPlayer isPlaying]) {
  521. [_listPlayer pause];
  522. #if TARGET_OS_IOS
  523. [self _savePlaybackState];
  524. #endif
  525. [[NSNotificationCenter defaultCenter] postNotificationName:VLCPlaybackControllerPlaybackDidPause object:self];
  526. } else {
  527. [_listPlayer play];
  528. [[NSNotificationCenter defaultCenter] postNotificationName:VLCPlaybackControllerPlaybackDidResume object:self];
  529. }
  530. }
  531. - (void)forward
  532. {
  533. if (_mediaList.count > 1) {
  534. [_listPlayer next];
  535. [[NSNotificationCenter defaultCenter] postNotificationName:VLCPlaybackControllerPlaybackMetadataDidChange object:self];
  536. } else {
  537. NSNumber *skipLength = [[NSUserDefaults standardUserDefaults] valueForKey:kVLCSettingPlaybackForwardSkipLength];
  538. [_mediaPlayer jumpForward:skipLength.intValue];
  539. }
  540. }
  541. - (void)backward
  542. {
  543. if (_mediaList.count > 1) {
  544. [_listPlayer previous];
  545. [[NSNotificationCenter defaultCenter] postNotificationName:VLCPlaybackControllerPlaybackMetadataDidChange object:self];
  546. }
  547. else {
  548. NSNumber *skipLength = [[NSUserDefaults standardUserDefaults] valueForKey:kVLCSettingPlaybackBackwardSkipLength];
  549. [_mediaPlayer jumpBackward:skipLength.intValue];
  550. }
  551. }
  552. - (void)switchAspectRatio
  553. {
  554. NSUInteger count = [_aspectRatios count];
  555. if (_currentAspectRatioMask + 1 > count - 1) {
  556. _mediaPlayer.videoAspectRatio = NULL;
  557. _mediaPlayer.videoCropGeometry = NULL;
  558. _currentAspectRatioMask = 0;
  559. if ([self.delegate respondsToSelector:@selector(showStatusMessage:forPlaybackController:)])
  560. [self.delegate showStatusMessage:[NSString stringWithFormat:NSLocalizedString(@"AR_CHANGED", nil), NSLocalizedString(@"DEFAULT", nil)] forPlaybackController:self];
  561. } else {
  562. _currentAspectRatioMask++;
  563. if ([_aspectRatios[_currentAspectRatioMask] isEqualToString:@"FILL_TO_SCREEN"]) {
  564. UIScreen *screen;
  565. if (![[UIDevice currentDevice] hasExternalDisplay])
  566. screen = [UIScreen mainScreen];
  567. else
  568. screen = [UIScreen screens][1];
  569. float f_ar = screen.bounds.size.width / screen.bounds.size.height;
  570. if (f_ar == (float)(640./1136.)) // iPhone 5 aka 16:9.01
  571. _mediaPlayer.videoCropGeometry = "16:9";
  572. else if (f_ar == (float)(2./3.)) // all other iPhones
  573. _mediaPlayer.videoCropGeometry = "16:10"; // libvlc doesn't support 2:3 crop
  574. else if (f_ar == (float)(1. + (1./3.))) // all iPads
  575. _mediaPlayer.videoCropGeometry = "4:3";
  576. else if (f_ar == .5625) // AirPlay
  577. _mediaPlayer.videoCropGeometry = "16:9";
  578. else
  579. APLog(@"unknown screen format %f, can't crop", f_ar);
  580. if ([self.delegate respondsToSelector:@selector(showStatusMessage:forPlaybackController:)])
  581. [self.delegate showStatusMessage:NSLocalizedString(@"FILL_TO_SCREEN", nil) forPlaybackController:self];
  582. return;
  583. }
  584. _mediaPlayer.videoCropGeometry = NULL;
  585. _mediaPlayer.videoAspectRatio = (char *)[_aspectRatios[_currentAspectRatioMask] UTF8String];
  586. if ([self.delegate respondsToSelector:@selector(showStatusMessage:forPlaybackController:)])
  587. [self.delegate showStatusMessage:[NSString stringWithFormat:NSLocalizedString(@"AR_CHANGED", nil), _aspectRatios[_currentAspectRatioMask]] forPlaybackController:self];
  588. }
  589. }
  590. - (void)setVideoOutputView:(UIView *)videoOutputView
  591. {
  592. if (videoOutputView) {
  593. if ([_actualVideoOutputView superview] != nil)
  594. [_actualVideoOutputView removeFromSuperview];
  595. _actualVideoOutputView.frame = (CGRect){CGPointZero, videoOutputView.frame.size};
  596. if (_mediaPlayer.currentVideoTrackIndex == -1)
  597. _mediaPlayer.currentVideoTrackIndex = 0;
  598. [videoOutputView addSubview:_actualVideoOutputView];
  599. [_actualVideoOutputView layoutSubviews];
  600. [_actualVideoOutputView updateConstraints];
  601. [_actualVideoOutputView setNeedsLayout];
  602. } else
  603. [_actualVideoOutputView removeFromSuperview];
  604. _videoOutputViewWrapper = videoOutputView;
  605. }
  606. - (UIView *)videoOutputView
  607. {
  608. return _videoOutputViewWrapper;
  609. }
  610. #pragma mark - equalizer
  611. - (void)setAmplification:(CGFloat)amplification forBand:(unsigned int)index
  612. {
  613. if (!_mediaPlayer.equalizerEnabled)
  614. [_mediaPlayer setEqualizerEnabled:YES];
  615. [_mediaPlayer setAmplification:amplification forBand:index];
  616. // For some reason we have to apply again preamp to apply change
  617. [_mediaPlayer setPreAmplification:[_mediaPlayer preAmplification]];
  618. }
  619. - (CGFloat)amplificationOfBand:(unsigned int)index
  620. {
  621. return [_mediaPlayer amplificationOfBand:index];
  622. }
  623. - (NSArray *)equalizerProfiles
  624. {
  625. return _mediaPlayer.equalizerProfiles;
  626. }
  627. - (void)resetEqualizerFromProfile:(unsigned int)profile
  628. {
  629. [[NSUserDefaults standardUserDefaults] setObject:@(profile) forKey:kVLCSettingEqualizerProfile];
  630. [_mediaPlayer resetEqualizerFromProfile:profile];
  631. }
  632. - (void)setPreAmplification:(CGFloat)preAmplification
  633. {
  634. if (!_mediaPlayer.equalizerEnabled)
  635. [_mediaPlayer setEqualizerEnabled:YES];
  636. [_mediaPlayer setPreAmplification:preAmplification];
  637. }
  638. - (CGFloat)preAmplification
  639. {
  640. return [_mediaPlayer preAmplification];
  641. }
  642. #pragma mark - AVSession delegate
  643. - (void)beginInterruption
  644. {
  645. if ([_mediaPlayer isPlaying]) {
  646. [_mediaPlayer pause];
  647. _shouldResumePlayingAfterInteruption = YES;
  648. }
  649. }
  650. - (void)endInterruption
  651. {
  652. if (_shouldResumePlayingAfterInteruption) {
  653. [_mediaPlayer play];
  654. _shouldResumePlayingAfterInteruption = NO;
  655. }
  656. }
  657. - (void)audioSessionRouteChange:(NSNotification *)notification
  658. {
  659. NSArray *outputs = [[AVAudioSession sharedInstance] currentRoute].outputs;
  660. NSString *portName = [[outputs firstObject] portName];
  661. if (![portName isEqualToString:@"Headphones"] && [_mediaPlayer isPlaying]) {
  662. [_mediaPlayer pause];
  663. #if TARGET_OS_IOS
  664. [self _savePlaybackState];
  665. #endif
  666. [[NSNotificationCenter defaultCenter] postNotificationName:VLCPlaybackControllerPlaybackDidPause object:self];
  667. }
  668. }
  669. #pragma mark - Managing the media item
  670. #if TARGET_OS_IOS
  671. - (MLFile *)currentlyPlayingMediaFile {
  672. if (self.mediaList) {
  673. NSArray *results = [MLFile fileForURL:_mediaPlayer.media.url];
  674. return results.firstObject;
  675. }
  676. return nil;
  677. }
  678. #endif
  679. #pragma mark - metadata handling
  680. - (void)mediaDidFinishParsing:(VLCMedia *)aMedia
  681. {
  682. [self setNeedsMetadataUpdate];
  683. }
  684. - (void)mediaMetaDataDidChange:(VLCMedia*)aMedia
  685. {
  686. [self setNeedsMetadataUpdate];
  687. }
  688. - (void)setNeedsMetadataUpdate
  689. {
  690. if (_needsMetadataUpdate == NO) {
  691. _needsMetadataUpdate = YES;
  692. dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.5 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
  693. [self _updateDisplayedMetadata];
  694. });
  695. }
  696. }
  697. - (void)_updateDisplayedMetadata
  698. {
  699. _needsMetadataUpdate = NO;
  700. NSNumber *trackNumber;
  701. NSString *title;
  702. NSString *artist;
  703. NSString *albumName;
  704. UIImage* artworkImage;
  705. BOOL mediaIsAudioOnly = NO;
  706. #if TARGET_OS_IOS
  707. MLFile *item;
  708. if (self.mediaList) {
  709. NSArray *matches = [MLFile fileForURL:_mediaPlayer.media.url];
  710. item = matches.firstObject;
  711. }
  712. if (item) {
  713. if (item.isAlbumTrack) {
  714. title = item.albumTrack.title;
  715. artist = item.albumTrack.artist;
  716. albumName = item.albumTrack.album.name;
  717. } else
  718. title = item.title;
  719. /* MLKit knows better than us if this thing is audio only or not */
  720. mediaIsAudioOnly = [item isSupportedAudioFile];
  721. } else {
  722. #endif
  723. NSDictionary * metaDict = _mediaPlayer.media.metaDictionary;
  724. if (metaDict) {
  725. title = metaDict[VLCMetaInformationNowPlaying] ? metaDict[VLCMetaInformationNowPlaying] : metaDict[VLCMetaInformationTitle];
  726. artist = metaDict[VLCMetaInformationArtist];
  727. albumName = metaDict[VLCMetaInformationAlbum];
  728. trackNumber = metaDict[VLCMetaInformationTrackNumber];
  729. }
  730. #if TARGET_OS_IOS
  731. }
  732. #endif
  733. if (!mediaIsAudioOnly) {
  734. /* either what we are playing is not a file known to MLKit or
  735. * MLKit fails to acknowledge that it is audio-only.
  736. * Either way, do a more expensive check to see if it is really audio-only */
  737. NSArray *tracks = _mediaPlayer.media.tracksInformation;
  738. NSUInteger trackCount = tracks.count;
  739. mediaIsAudioOnly = YES;
  740. for (NSUInteger x = 0 ; x < trackCount; x++) {
  741. if ([[tracks[x] objectForKey:VLCMediaTracksInformationType] isEqualToString:VLCMediaTracksInformationTypeVideo]) {
  742. mediaIsAudioOnly = NO;
  743. break;
  744. }
  745. }
  746. }
  747. if (mediaIsAudioOnly) {
  748. #if TARGET_OS_IOS
  749. artworkImage = [VLCThumbnailsCache thumbnailForManagedObject:item];
  750. if (artworkImage) {
  751. if (artist)
  752. title = [title stringByAppendingFormat:@" — %@", artist];
  753. if (albumName)
  754. title = [title stringByAppendingFormat:@" — %@", albumName];
  755. }
  756. #endif
  757. if (title.length < 1)
  758. title = [[_mediaPlayer.media url] lastPathComponent];
  759. }
  760. /* populate delegate with metadata info */
  761. if ([self.delegate respondsToSelector:@selector(displayMetadataForPlaybackController:title:artwork:artist:album:audioOnly:)])
  762. [self.delegate displayMetadataForPlaybackController:self
  763. title:title
  764. artwork:artworkImage
  765. artist:artist
  766. album:albumName
  767. audioOnly:mediaIsAudioOnly];
  768. /* populate now playing info center with metadata information */
  769. NSMutableDictionary *currentlyPlayingTrackInfo = [NSMutableDictionary dictionary];
  770. currentlyPlayingTrackInfo[MPMediaItemPropertyPlaybackDuration] = @(_mediaPlayer.media.length.intValue / 1000.);
  771. currentlyPlayingTrackInfo[MPNowPlayingInfoPropertyElapsedPlaybackTime] = @(_mediaPlayer.time.intValue / 1000.);
  772. currentlyPlayingTrackInfo[MPNowPlayingInfoPropertyPlaybackRate] = @(_mediaPlayer.isPlaying ? _mediaPlayer.rate : 0.0);
  773. /* don't leak sensitive information to the OS, if passcode lock is enabled */
  774. #if TARGET_OS_IOS
  775. if (![[VLCKeychainCoordinator defaultCoordinator] passcodeLockEnabled]) {
  776. #endif
  777. if (title)
  778. currentlyPlayingTrackInfo[MPMediaItemPropertyTitle] = title;
  779. if (artist.length > 0)
  780. currentlyPlayingTrackInfo[MPMediaItemPropertyArtist] = artist;
  781. if (albumName.length > 0)
  782. currentlyPlayingTrackInfo[MPMediaItemPropertyAlbumTitle] = albumName;
  783. if ([trackNumber intValue] > 0)
  784. currentlyPlayingTrackInfo[MPMediaItemPropertyAlbumTrackNumber] = trackNumber;
  785. #if TARGET_OS_IOS
  786. /* FIXME: UGLY HACK
  787. * iOS 8.2 and 8.3 include an issue which will lead to a termination of the client app if we set artwork
  788. * when the playback initialized through the watch extension
  789. * radar://pending */
  790. if ([WKInterfaceDevice class] != nil) {
  791. if ([WKInterfaceDevice currentDevice] != nil)
  792. goto setstuff;
  793. }
  794. if (artworkImage) {
  795. MPMediaItemArtwork *mpartwork = [[MPMediaItemArtwork alloc] initWithImage:artworkImage];
  796. currentlyPlayingTrackInfo[MPMediaItemPropertyArtwork] = mpartwork;
  797. }
  798. }
  799. #endif
  800. setstuff:
  801. [MPNowPlayingInfoCenter defaultCenter].nowPlayingInfo = currentlyPlayingTrackInfo;
  802. [[NSNotificationCenter defaultCenter] postNotificationName:VLCPlaybackControllerPlaybackMetadataDidChange object:self];
  803. _title = title;
  804. _artist = artist;
  805. _albumName = albumName;
  806. _artworkImage = artworkImage;
  807. _mediaIsAudioOnly = mediaIsAudioOnly;
  808. }
  809. #if TARGET_OS_IOS
  810. - (void)_recoverLastPlaybackStateOfItem:(MLFile *)item
  811. {
  812. if (item) {
  813. if (_mediaPlayer.numberOfAudioTracks > 2) {
  814. if (item.lastAudioTrack.intValue > 0)
  815. _mediaPlayer.currentAudioTrackIndex = item.lastAudioTrack.intValue;
  816. }
  817. if (_mediaPlayer.numberOfSubtitlesTracks > 2) {
  818. if (item.lastSubtitleTrack.intValue > 0)
  819. _mediaPlayer.currentVideoSubTitleIndex = item.lastSubtitleTrack.intValue;
  820. }
  821. CGFloat lastPosition = .0;
  822. NSInteger duration = 0;
  823. if (item.lastPosition)
  824. lastPosition = item.lastPosition.floatValue;
  825. duration = item.duration.intValue;
  826. if (lastPosition < .95 && _mediaPlayer.position < lastPosition && (duration * lastPosition - duration) < -50000) {
  827. NSInteger continuePlayback;
  828. if (!_mediaPlayer.hasVideoOut)
  829. continuePlayback = [[[NSUserDefaults standardUserDefaults] objectForKey:kVLCSettingContinueAudioPlayback] integerValue];
  830. else
  831. continuePlayback = [[[NSUserDefaults standardUserDefaults] objectForKey:kVLCSettingContinuePlayback] integerValue];
  832. if (continuePlayback == 1) {
  833. _mediaPlayer.position = lastPosition;
  834. } else if (continuePlayback == 0) {
  835. VLCAlertView *alert = [[VLCAlertView alloc] initWithTitle:NSLocalizedString(@"CONTINUE_PLAYBACK", nil)
  836. message:[NSString stringWithFormat:NSLocalizedString(@"CONTINUE_PLAYBACK_LONG", nil), item.title]
  837. delegate:self
  838. cancelButtonTitle:NSLocalizedString(@"BUTTON_CANCEL", nil)
  839. otherButtonTitles:NSLocalizedString(@"BUTTON_CONTINUE", nil), nil];
  840. alert.completion = ^(BOOL cancelled, NSInteger buttonIndex) {
  841. if (!cancelled) {
  842. _mediaPlayer.position = lastPosition;
  843. }
  844. };
  845. [alert show];
  846. }
  847. }
  848. }
  849. }
  850. #endif
  851. - (void)recoverDisplayedMetadata
  852. {
  853. if ([self.delegate respondsToSelector:@selector(displayMetadataForPlaybackController:title:artwork:artist:album:audioOnly:)])
  854. [self.delegate displayMetadataForPlaybackController:self
  855. title:_title
  856. artwork:_artworkImage
  857. artist:_artist
  858. album:_albumName
  859. audioOnly:_mediaIsAudioOnly];
  860. }
  861. - (void)recoverPlaybackState
  862. {
  863. if ([self.delegate respondsToSelector:@selector(mediaPlayerStateChanged:isPlaying:currentMediaHasTrackToChooseFrom:currentMediaHasChapters:forPlaybackController:)])
  864. [self.delegate mediaPlayerStateChanged:_mediaPlayer.state
  865. isPlaying:self.isPlaying
  866. currentMediaHasTrackToChooseFrom:self.currentMediaHasTrackToChooseFrom
  867. currentMediaHasChapters:self.currentMediaHasChapters
  868. forPlaybackController:self];
  869. if ([self.delegate respondsToSelector:@selector(prepareForMediaPlayback:)])
  870. [self.delegate prepareForMediaPlayback:self];
  871. }
  872. - (void)scheduleSleepTimerWithInterval:(NSTimeInterval)timeInterval
  873. {
  874. if (_sleepTimer) {
  875. [_sleepTimer invalidate];
  876. _sleepTimer = nil;
  877. }
  878. _sleepTimer = [NSTimer scheduledTimerWithTimeInterval:timeInterval target:self selector:@selector(stopPlayback) userInfo:nil repeats:NO];
  879. }
  880. #pragma mark - remote events
  881. static inline NSArray * RemoteCommandCenterCommandsToHandle(MPRemoteCommandCenter *cc)
  882. {
  883. /* commmented out other available commands which we don't support now but may
  884. * support at some point in the future */
  885. return @[cc.pauseCommand, cc.playCommand, cc.stopCommand, cc.togglePlayPauseCommand,
  886. cc.nextTrackCommand, cc.previousTrackCommand,
  887. cc.skipForwardCommand, cc.skipBackwardCommand,
  888. // cc.seekForwardCommand, cc.seekBackwardCommand,
  889. // cc.ratingCommand,
  890. cc.changePlaybackRateCommand,
  891. // cc.likeCommand,cc.dislikeCommand,cc.bookmarkCommand,
  892. ];
  893. }
  894. - (void)subscribeRemoteCommands
  895. {
  896. /* pre iOS 7.1 */
  897. if (![MPRemoteCommandCenter class]) {
  898. [[UIApplication sharedApplication] beginReceivingRemoteControlEvents];
  899. return;
  900. }
  901. /* for iOS 7.1 and above: */
  902. MPRemoteCommandCenter *commandCenter = [MPRemoteCommandCenter sharedCommandCenter];
  903. /*
  904. * since the control center and lockscreen shows only either skipForward/Backward
  905. * or next/previousTrack buttons but prefers skip buttons,
  906. * we only enable skip buttons if we have a no medialist
  907. */
  908. BOOL enableSkip = [VLCPlaybackController sharedInstance].mediaList.count <= 1;
  909. commandCenter.skipForwardCommand.enabled = enableSkip;
  910. commandCenter.skipBackwardCommand.enabled = enableSkip;
  911. NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
  912. NSNumber *forwardSkip = [defaults valueForKey:kVLCSettingPlaybackForwardSkipLength];
  913. commandCenter.skipForwardCommand.preferredIntervals = @[forwardSkip];
  914. NSNumber *backwardSkip = [defaults valueForKey:kVLCSettingPlaybackBackwardSkipLength];
  915. commandCenter.skipBackwardCommand.preferredIntervals = @[backwardSkip];
  916. NSArray *supportedPlaybackRates = @[@(0.5),@(0.75),@(1.0),@(1.25),@(1.5),@(1.75),@(2.0)];
  917. commandCenter.changePlaybackRateCommand.supportedPlaybackRates = supportedPlaybackRates;
  918. NSArray *commandsToSubscribe = RemoteCommandCenterCommandsToHandle(commandCenter);
  919. for (MPRemoteCommand *command in commandsToSubscribe) {
  920. [command addTarget:self action:@selector(remoteCommandEvent:)];
  921. }
  922. }
  923. - (void)unsubscribeFromRemoteCommand
  924. {
  925. /* pre iOS 7.1 */
  926. if (![MPRemoteCommandCenter class]) {
  927. [[UIApplication sharedApplication] endReceivingRemoteControlEvents];
  928. return;
  929. }
  930. /* for iOS 7.1 and above: */
  931. MPRemoteCommandCenter *cc = [MPRemoteCommandCenter sharedCommandCenter];
  932. NSArray *commmandsToRemoveFrom = RemoteCommandCenterCommandsToHandle(cc);
  933. for (MPRemoteCommand *command in commmandsToRemoveFrom) {
  934. [command removeTarget:self];
  935. }
  936. }
  937. - (MPRemoteCommandHandlerStatus )remoteCommandEvent:(MPRemoteCommandEvent *)event
  938. {
  939. MPRemoteCommandCenter *cc = [MPRemoteCommandCenter sharedCommandCenter];
  940. MPRemoteCommandHandlerStatus result = MPRemoteCommandHandlerStatusSuccess;
  941. if (event.command == cc.pauseCommand) {
  942. [_listPlayer pause];
  943. } else if (event.command == cc.playCommand) {
  944. [_listPlayer play];
  945. } else if (event.command == cc.stopCommand) {
  946. [_listPlayer stop];
  947. } else if (event.command == cc.togglePlayPauseCommand) {
  948. [self playPause];
  949. } else if (event.command == cc.nextTrackCommand) {
  950. result = [_listPlayer next] ? MPRemoteCommandHandlerStatusSuccess : MPRemoteCommandHandlerStatusNoSuchContent;
  951. } else if (event.command == cc.previousTrackCommand) {
  952. result = [_listPlayer previous] ? MPRemoteCommandHandlerStatusSuccess : MPRemoteCommandHandlerStatusNoSuchContent;
  953. } else if (event.command == cc.skipForwardCommand) {
  954. if ([event isKindOfClass:[MPSkipIntervalCommandEvent class]]) {
  955. MPSkipIntervalCommandEvent *skipEvent = (MPSkipIntervalCommandEvent *)event;
  956. [_mediaPlayer jumpForward:skipEvent.interval];
  957. } else {
  958. result = MPRemoteCommandHandlerStatusCommandFailed;
  959. }
  960. } else if (event.command == cc.skipBackwardCommand) {
  961. if ([event isKindOfClass:[MPSkipIntervalCommandEvent class]]) {
  962. MPSkipIntervalCommandEvent *skipEvent = (MPSkipIntervalCommandEvent *)event;
  963. [_mediaPlayer jumpBackward:skipEvent.interval];
  964. } else {
  965. result = MPRemoteCommandHandlerStatusCommandFailed;
  966. }
  967. } else if (event.command == cc.changePlaybackRateCommand) {
  968. if ([event isKindOfClass:[MPChangePlaybackRateCommandEvent class]]) {
  969. MPChangePlaybackRateCommandEvent *rateEvent = (MPChangePlaybackRateCommandEvent *)event;
  970. [_mediaPlayer setRate:rateEvent.playbackRate];
  971. } else {
  972. result = MPRemoteCommandHandlerStatusCommandFailed;
  973. }
  974. /* stubs for when we want to support the other available commands */
  975. // } else if (event.command == cc.seekForwardCommand) {
  976. // } else if (event.command == cc.seekBackwardCommand) {
  977. // } else if (event.command == cc.ratingCommand) {
  978. // } else if (event.command == cc.likeCommand) {
  979. // } else if (event.command == cc.dislikeCommand) {
  980. // } else if (event.command == cc.bookmarkCommand) {
  981. } else {
  982. APLog(@"%s Unsupported remote control event: %@",__PRETTY_FUNCTION__,event);
  983. result = MPRemoteCommandHandlerStatusCommandFailed;
  984. }
  985. if (result == MPRemoteCommandHandlerStatusCommandFailed)
  986. APLog(@"%s Wasn't able to handle remote control event: %@",__PRETTY_FUNCTION__,event);
  987. return result;
  988. }
  989. - (void)remoteControlReceivedWithEvent:(UIEvent *)event
  990. {
  991. switch (event.subtype) {
  992. case UIEventSubtypeRemoteControlPlay:
  993. [_listPlayer play];
  994. break;
  995. case UIEventSubtypeRemoteControlPause:
  996. [_listPlayer pause];
  997. break;
  998. case UIEventSubtypeRemoteControlTogglePlayPause:
  999. [self playPause];
  1000. break;
  1001. case UIEventSubtypeRemoteControlNextTrack:
  1002. [self forward];
  1003. break;
  1004. case UIEventSubtypeRemoteControlPreviousTrack:
  1005. [self backward];
  1006. break;
  1007. case UIEventSubtypeRemoteControlStop:
  1008. [self stopPlayback];
  1009. break;
  1010. default:
  1011. break;
  1012. }
  1013. }
  1014. #pragma mark - background interaction
  1015. - (void)applicationWillResignActive:(NSNotification *)aNotification
  1016. {
  1017. #if TARGET_OS_IOS
  1018. [self _savePlaybackState];
  1019. #endif
  1020. if (![[[NSUserDefaults standardUserDefaults] objectForKey:kVLCSettingContinueAudioInBackgroundKey] boolValue]) {
  1021. if ([_mediaPlayer isPlaying]) {
  1022. [_mediaPlayer pause];
  1023. _shouldResumePlaying = YES;
  1024. }
  1025. }
  1026. }
  1027. - (void)applicationDidEnterBackground:(NSNotification *)notification
  1028. {
  1029. _preBackgroundWrapperView = _videoOutputViewWrapper;
  1030. [self setVideoOutputView:nil];
  1031. if (_mediaPlayer.audioTrackIndexes.count > 0)
  1032. _mediaPlayer.currentVideoTrackIndex = -1;
  1033. }
  1034. - (void)applicationDidBecomeActive:(NSNotification *)notification
  1035. {
  1036. if (_preBackgroundWrapperView) {
  1037. [self setVideoOutputView:_preBackgroundWrapperView];
  1038. _preBackgroundWrapperView = nil;
  1039. }
  1040. if (_mediaPlayer.numberOfVideoTracks > 0) {
  1041. /* re-enable video decoding */
  1042. _mediaPlayer.currentVideoTrackIndex = 1;
  1043. }
  1044. if (_shouldResumePlaying) {
  1045. _shouldResumePlaying = NO;
  1046. [_listPlayer play];
  1047. }
  1048. }
  1049. #pragma mark - helpers
  1050. - (NSString *)_resolveFontName
  1051. {
  1052. NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
  1053. BOOL bold = [[defaults objectForKey:kVLCSettingSubtitlesBoldFont] boolValue];
  1054. NSString *font = [defaults objectForKey:kVLCSettingSubtitlesFont];
  1055. NSDictionary *fontMap = @{
  1056. @"AmericanTypewriter": @"AmericanTypewriter-Bold",
  1057. @"ArialMT": @"Arial-BoldMT",
  1058. @"ArialHebrew": @"ArialHebrew-Bold",
  1059. @"ChalkboardSE-Regular": @"ChalkboardSE-Bold",
  1060. @"CourierNewPSMT": @"CourierNewPS-BoldMT",
  1061. @"Georgia": @"Georgia-Bold",
  1062. @"GillSans": @"GillSans-Bold",
  1063. @"GujaratiSangamMN": @"GujaratiSangamMN-Bold",
  1064. @"STHeitiSC-Light": @"STHeitiSC-Medium",
  1065. @"STHeitiTC-Light": @"STHeitiTC-Medium",
  1066. @"HelveticaNeue": @"HelveticaNeue-Bold",
  1067. @"HiraKakuProN-W3": @"HiraKakuProN-W6",
  1068. @"HiraMinProN-W3": @"HiraMinProN-W6",
  1069. @"HoeflerText-Regular": @"HoeflerText-Black",
  1070. @"Kailasa": @"Kailasa-Bold",
  1071. @"KannadaSangamMN": @"KannadaSangamMN-Bold",
  1072. @"MalayalamSangamMN": @"MalayalamSangamMN-Bold",
  1073. @"OriyaSangamMN": @"OriyaSangamMN-Bold",
  1074. @"SinhalaSangamMN": @"SinhalaSangamMN-Bold",
  1075. @"SnellRoundhand": @"SnellRoundhand-Bold",
  1076. @"TamilSangamMN": @"TamilSangamMN-Bold",
  1077. @"TeluguSangamMN": @"TeluguSangamMN-Bold",
  1078. @"TimesNewRomanPSMT": @"TimesNewRomanPS-BoldMT",
  1079. @"Zapfino": @"Zapfino"
  1080. };
  1081. if (!bold) {
  1082. return font;
  1083. } else {
  1084. return fontMap[font];
  1085. }
  1086. }
  1087. - (NSDictionary *)mediaOptionsDictionary
  1088. {
  1089. NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
  1090. return @{ kVLCSettingNetworkCaching : [defaults objectForKey:kVLCSettingNetworkCaching],
  1091. kVLCSettingStretchAudio : [[defaults objectForKey:kVLCSettingStretchAudio] boolValue] ? kVLCSettingStretchAudioOnValue : kVLCSettingStretchAudioOffValue,
  1092. kVLCSettingTextEncoding : [defaults objectForKey:kVLCSettingTextEncoding],
  1093. kVLCSettingSkipLoopFilter : [defaults objectForKey:kVLCSettingSkipLoopFilter] };
  1094. }
  1095. @end