VLCPlaybackController.m 44 KB

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