VLCPlaybackController.m 44 KB

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