VLCPlaybackController.m 46 KB

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