VLCPlaybackController.m 50 KB

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