VLCPlaybackController.m 47 KB

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