VLCPlaybackController.m 44 KB

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