VLCPlaybackController.m 44 KB

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