VLCPlaybackController.m 47 KB

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