VLCPlaybackController.m 47 KB

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