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