VLCPlaybackController.m 42 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338
  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 "UIDevice+VLC.h"
  20. #import <AVFoundation/AVFoundation.h>
  21. #import "VLCPlayerDisplayController.h"
  22. #import "VLCConstants.h"
  23. #import "VLCRemoteControlService.h"
  24. #import "VLCMetadata.h"
  25. NSString *const VLCPlaybackControllerPlaybackDidStart = @"VLCPlaybackControllerPlaybackDidStart";
  26. NSString *const VLCPlaybackControllerPlaybackDidPause = @"VLCPlaybackControllerPlaybackDidPause";
  27. NSString *const VLCPlaybackControllerPlaybackDidResume = @"VLCPlaybackControllerPlaybackDidResume";
  28. NSString *const VLCPlaybackControllerPlaybackDidStop = @"VLCPlaybackControllerPlaybackDidStop";
  29. NSString *const VLCPlaybackControllerPlaybackMetadataDidChange = @"VLCPlaybackControllerPlaybackMetadataDidChange";
  30. NSString *const VLCPlaybackControllerPlaybackDidFail = @"VLCPlaybackControllerPlaybackDidFail";
  31. NSString *const VLCPlaybackControllerPlaybackPositionUpdated = @"VLCPlaybackControllerPlaybackPositionUpdated";
  32. typedef NS_ENUM(NSUInteger, VLCAspectRatio) {
  33. VLCAspectRatioDefault = 0,
  34. VLCAspectRatioFillToScreen,
  35. VLCAspectRatioFourToThree,
  36. VLCAspectRatioSixteenToNine,
  37. VLCAspectRatioSixteenToTen,
  38. };
  39. @interface VLCPlaybackController () <VLCMediaPlayerDelegate, VLCMediaDelegate, VLCRemoteControlServiceDelegate>
  40. {
  41. VLCRemoteControlService *_remoteControlService;
  42. VLCMediaPlayer *_mediaPlayer;
  43. VLCMediaListPlayer *_listPlayer;
  44. BOOL _playerIsSetup;
  45. BOOL _shouldResumePlaying;
  46. BOOL _sessionWillRestart;
  47. NSString *_pathToExternalSubtitlesFile;
  48. int _itemInMediaListToBePlayedFirst;
  49. NSTimer *_sleepTimer;
  50. NSUInteger _currentAspectRatio;
  51. UIView *_videoOutputViewWrapper;
  52. UIView *_actualVideoOutputView;
  53. UIView *_preBackgroundWrapperView;
  54. BOOL _needsMetadataUpdate;
  55. BOOL _mediaWasJustStarted;
  56. BOOL _recheckForExistingThumbnail;
  57. BOOL _headphonesWasPlugged;
  58. NSLock *_playbackSessionManagementLock;
  59. VLCDialogProvider *_dialogProvider;
  60. NSMutableArray *_shuffleStack;
  61. }
  62. @end
  63. @implementation VLCPlaybackController
  64. #pragma mark instance management
  65. + (VLCPlaybackController *)sharedInstance
  66. {
  67. static VLCPlaybackController *sharedInstance = nil;
  68. static dispatch_once_t pred;
  69. dispatch_once(&pred, ^{
  70. sharedInstance = [VLCPlaybackController new];
  71. });
  72. return sharedInstance;
  73. }
  74. - (void)dealloc
  75. {
  76. _dialogProvider = nil;
  77. }
  78. - (instancetype)init
  79. {
  80. self = [super init];
  81. if (self) {
  82. // listen to audiosessions and appkit callback
  83. _headphonesWasPlugged = [self areHeadphonesPlugged];
  84. NSNotificationCenter *defaultCenter = [NSNotificationCenter defaultCenter];
  85. [defaultCenter addObserver:self selector:@selector(audioSessionRouteChange:)
  86. name:AVAudioSessionRouteChangeNotification object:nil];
  87. [defaultCenter addObserver:self selector:@selector(handleInterruption:)
  88. name:AVAudioSessionInterruptionNotification object:[AVAudioSession sharedInstance]];
  89. // appkit because we neeed to know when we go to background in order to stop the video, so that we don't crash
  90. [defaultCenter addObserver:self selector:@selector(applicationWillResignActive:)
  91. name:UIApplicationWillResignActiveNotification object:nil];
  92. [defaultCenter addObserver:self selector:@selector(applicationDidBecomeActive:)
  93. name:UIApplicationDidBecomeActiveNotification object:nil];
  94. [defaultCenter addObserver:self selector:@selector(applicationDidEnterBackground:)
  95. name:UIApplicationDidEnterBackgroundNotification object:nil];
  96. _metadata = [VLCMetaData new];
  97. _dialogProvider = [[VLCDialogProvider alloc] initWithLibrary:[VLCLibrary sharedLibrary] customUI:NO];
  98. _playbackSessionManagementLock = [[NSLock alloc] init];
  99. _shuffleMode = NO;
  100. _shuffleStack = [[NSMutableArray alloc] init];
  101. }
  102. return self;
  103. }
  104. - (VLCRemoteControlService *)remoteControlService
  105. {
  106. if (!_remoteControlService) {
  107. _remoteControlService = [[VLCRemoteControlService alloc] init];
  108. _remoteControlService.remoteControlServiceDelegate = self;
  109. }
  110. return _remoteControlService;
  111. }
  112. #pragma mark - playback management
  113. - (void)openVideoSubTitlesFromFile:(NSString *)pathToFile
  114. {
  115. [_mediaPlayer addPlaybackSlave:[NSURL fileURLWithPath:pathToFile] type:VLCMediaPlaybackSlaveTypeSubtitle enforce:YES];
  116. }
  117. - (void)playMediaList:(VLCMediaList *)mediaList firstIndex:(NSInteger)index subtitlesFilePath:(NSString *)subsFilePath
  118. {
  119. self.mediaList = mediaList;
  120. _itemInMediaListToBePlayedFirst = (int)index;
  121. _pathToExternalSubtitlesFile = subsFilePath;
  122. _sessionWillRestart = _playerIsSetup;
  123. _playerIsSetup ? [self stopPlayback] : [self startPlayback];
  124. }
  125. - (VLCTime *)playedTime
  126. {
  127. return [_mediaPlayer time];
  128. }
  129. - (void)startPlayback
  130. {
  131. if (_playerIsSetup) {
  132. APLog(@"%s: player is already setup, bailing out", __PRETTY_FUNCTION__);
  133. return;
  134. }
  135. BOOL ret = [_playbackSessionManagementLock tryLock];
  136. if (!ret) {
  137. APLog(@"%s: locking failed", __PRETTY_FUNCTION__);
  138. return;
  139. }
  140. NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
  141. if (!self.mediaList) {
  142. APLog(@"%s: no URL and no media list set, stopping playback", __PRETTY_FUNCTION__);
  143. [_playbackSessionManagementLock unlock];
  144. [self stopPlayback];
  145. return;
  146. }
  147. /* video decoding permanently fails if we don't provide a UIView to draw into on init
  148. * hence we provide one which is not attached to any view controller for off-screen drawing
  149. * and disable video decoding once playback started */
  150. _actualVideoOutputView = [[UIView alloc] initWithFrame:[UIScreen mainScreen].bounds];
  151. _actualVideoOutputView.autoresizingMask = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight;
  152. _actualVideoOutputView.autoresizesSubviews = YES;
  153. if (_pathToExternalSubtitlesFile)
  154. _listPlayer = [[VLCMediaListPlayer alloc] initWithOptions:@[[NSString stringWithFormat:@"--%@=%@", kVLCSettingSubtitlesFilePath, _pathToExternalSubtitlesFile]] andDrawable:_actualVideoOutputView];
  155. else
  156. _listPlayer = [[VLCMediaListPlayer alloc] initWithDrawable:_actualVideoOutputView];
  157. /* to enable debug logging for the playback library instance, switch the boolean below
  158. * note that the library instance used for playback may not necessarily match the instance
  159. * used for media discovery or thumbnailing */
  160. _listPlayer.mediaPlayer.libraryInstance.debugLogging = NO;
  161. _mediaPlayer = _listPlayer.mediaPlayer;
  162. [_mediaPlayer setDelegate:self];
  163. if ([[defaults objectForKey:kVLCSettingPlaybackSpeedDefaultValue] floatValue] != 0)
  164. [_mediaPlayer setRate: [[defaults objectForKey:kVLCSettingPlaybackSpeedDefaultValue] floatValue]];
  165. if ([[defaults objectForKey:kVLCSettingDeinterlace] intValue] != 0)
  166. [_mediaPlayer setDeinterlaceFilter:@"blend"];
  167. else
  168. [_mediaPlayer setDeinterlaceFilter:nil];
  169. if (_pathToExternalSubtitlesFile)
  170. [_mediaPlayer addPlaybackSlave:[NSURL fileURLWithPath:_pathToExternalSubtitlesFile] type:VLCMediaPlaybackSlaveTypeSubtitle enforce:YES];
  171. VLCMedia *media = [_mediaList mediaAtIndex:_itemInMediaListToBePlayedFirst];
  172. [media parseWithOptions:VLCMediaParseLocal];
  173. media.delegate = self;
  174. [media addOptions:self.mediaOptionsDictionary];
  175. [_listPlayer setMediaList:self.mediaList];
  176. [_listPlayer setRepeatMode:VLCDoNotRepeat];
  177. [_playbackSessionManagementLock unlock];
  178. [self _playNewMedia];
  179. }
  180. - (void)_playNewMedia
  181. {
  182. BOOL ret = [_playbackSessionManagementLock tryLock];
  183. if (!ret) {
  184. APLog(@"%s: locking failed", __PRETTY_FUNCTION__);
  185. return;
  186. }
  187. // Set last selected equalizer profile
  188. unsigned int profile = (unsigned int)[[[NSUserDefaults standardUserDefaults] objectForKey:kVLCSettingEqualizerProfile] integerValue];
  189. [_mediaPlayer resetEqualizerFromProfile:profile];
  190. [_mediaPlayer setPreAmplification:[_mediaPlayer preAmplification]];
  191. _mediaWasJustStarted = YES;
  192. [_mediaPlayer addObserver:self forKeyPath:@"time" options:0 context:nil];
  193. [_mediaPlayer addObserver:self forKeyPath:@"remainingTime" options:0 context:nil];
  194. [_mediaPlayer setRendererItem:_renderer];
  195. [_listPlayer playItemAtNumber:@(_itemInMediaListToBePlayedFirst)];
  196. if ([self.delegate respondsToSelector:@selector(prepareForMediaPlayback:)])
  197. [self.delegate prepareForMediaPlayback:self];
  198. _currentAspectRatio = VLCAspectRatioDefault;
  199. _mediaPlayer.videoAspectRatio = NULL;
  200. _mediaPlayer.videoCropGeometry = NULL;
  201. [[self remoteControlService] subscribeToRemoteCommands];
  202. _playerIsSetup = YES;
  203. [[NSNotificationCenter defaultCenter] postNotificationName:VLCPlaybackControllerPlaybackDidStart object:self];
  204. [_playbackSessionManagementLock unlock];
  205. }
  206. - (void)stopPlayback
  207. {
  208. BOOL ret = [_playbackSessionManagementLock tryLock];
  209. if (!ret) {
  210. APLog(@"%s: locking failed", __PRETTY_FUNCTION__);
  211. return;
  212. }
  213. if (_mediaPlayer) {
  214. @try {
  215. [_mediaPlayer removeObserver:self forKeyPath:@"time"];
  216. [_mediaPlayer removeObserver:self forKeyPath:@"remainingTime"];
  217. }
  218. @catch (NSException *exception) {
  219. APLog(@"we weren't an observer yet");
  220. }
  221. if (_mediaPlayer.media) {
  222. [_mediaPlayer pause];
  223. #if TARGET_OS_IOS
  224. [self _savePlaybackState];
  225. #endif
  226. [_mediaPlayer stop];
  227. }
  228. _mediaPlayer = nil;
  229. _listPlayer = nil;
  230. }
  231. if (!_sessionWillRestart) {
  232. _mediaList = nil;
  233. if (_pathToExternalSubtitlesFile) {
  234. NSFileManager *fileManager = [NSFileManager defaultManager];
  235. if ([fileManager fileExistsAtPath:_pathToExternalSubtitlesFile])
  236. [fileManager removeItemAtPath:_pathToExternalSubtitlesFile error:nil];
  237. _pathToExternalSubtitlesFile = nil;
  238. }
  239. }
  240. _playerIsSetup = NO;
  241. [_shuffleStack removeAllObjects];
  242. if (@available(iOS 10, *)) {
  243. if (_errorCallback && _mediaPlayer.state == VLCMediaPlayerStateError && !_sessionWillRestart)
  244. [[UIApplication sharedApplication] openURL:_errorCallback options:@{} completionHandler:nil];
  245. else if (_successCallback && !_sessionWillRestart)
  246. [[UIApplication sharedApplication] openURL:_successCallback options:@{} completionHandler:nil];
  247. } else {
  248. #pragma clang diagnostic push
  249. #pragma clang diagnostic ignored "-Wdeprecated-declarations"
  250. /* UIApplication's replacement calls require iOS 10 or later, which we can't enforce as of yet */
  251. if (_errorCallback && _mediaPlayer.state == VLCMediaPlayerStateError && !_sessionWillRestart)
  252. [[UIApplication sharedApplication] openURL:_errorCallback];
  253. else if (_successCallback && !_sessionWillRestart)
  254. [[UIApplication sharedApplication] openURL:_successCallback];
  255. #pragma clang diagnostic pop
  256. }
  257. [[self remoteControlService] unsubscribeFromRemoteCommands];
  258. [_playbackSessionManagementLock unlock];
  259. if (!_sessionWillRestart) {
  260. [[NSNotificationCenter defaultCenter] postNotificationName:VLCPlaybackControllerPlaybackDidStop object:self];
  261. } else {
  262. _sessionWillRestart = NO;
  263. [self startPlayback];
  264. }
  265. }
  266. #if TARGET_OS_IOS
  267. - (void)restoreAudioAndSubtitleTrack
  268. {
  269. MLFile *item = [MLFile fileForURL:_mediaPlayer.media.url].firstObject;
  270. if (item) {
  271. _mediaPlayer.currentAudioTrackIndex = item.lastAudioTrack.intValue;
  272. _mediaPlayer.currentVideoSubTitleIndex = item.lastSubtitleTrack.intValue;
  273. }
  274. }
  275. - (void)_savePlaybackState
  276. {
  277. @try {
  278. [[MLMediaLibrary sharedMediaLibrary] save];
  279. }
  280. @catch (NSException *exception) {
  281. APLog(@"saving playback state failed");
  282. }
  283. NSArray *files = [MLFile fileForURL:_mediaPlayer.media.url];
  284. MLFile *fileItem = files.firstObject;
  285. if (!fileItem) {
  286. APLog(@"couldn't find file, not saving playback progress");
  287. return;
  288. }
  289. @try {
  290. float position = _mediaPlayer.position;
  291. fileItem.lastPosition = @(position);
  292. fileItem.lastAudioTrack = @(_mediaPlayer.currentAudioTrackIndex);
  293. fileItem.lastSubtitleTrack = @(_mediaPlayer.currentVideoSubTitleIndex);
  294. if (position > .95)
  295. return;
  296. if (_mediaPlayer.hasVideoOut) {
  297. NSArray *searchPaths = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES);
  298. NSString *newThumbnailPath = [searchPaths.firstObject stringByAppendingPathComponent:@"VideoSnapshots"];
  299. NSError *error;
  300. [[NSFileManager defaultManager] createDirectoryAtPath:newThumbnailPath withIntermediateDirectories:YES attributes:nil error:&error];
  301. if (error == nil) {
  302. newThumbnailPath = [newThumbnailPath stringByAppendingPathComponent:fileItem.objectID.URIRepresentation.lastPathComponent];
  303. [_mediaPlayer saveVideoSnapshotAt:newThumbnailPath withWidth:0 andHeight:0];
  304. _recheckForExistingThumbnail = YES;
  305. [self performSelector:@selector(_updateStoredThumbnailForFile:) withObject:fileItem afterDelay:.25];
  306. }
  307. }
  308. }
  309. @catch (NSException *exception) {
  310. APLog(@"failed to save current media state - file removed?");
  311. }
  312. }
  313. #endif
  314. #if TARGET_OS_IOS
  315. - (void)_updateStoredThumbnailForFile:(MLFile *)fileItem
  316. {
  317. NSFileManager *fileManager = [NSFileManager defaultManager];
  318. NSArray *searchPaths = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES);
  319. NSString* newThumbnailPath = [searchPaths[0] stringByAppendingPathComponent:@"VideoSnapshots"];
  320. newThumbnailPath = [newThumbnailPath stringByAppendingPathComponent:fileItem.objectID.URIRepresentation.lastPathComponent];
  321. if (![fileManager fileExistsAtPath:newThumbnailPath]) {
  322. if (_recheckForExistingThumbnail) {
  323. [self performSelector:@selector(_updateStoredThumbnailForFile:) withObject:fileItem afterDelay:1.];
  324. _recheckForExistingThumbnail = NO;
  325. } else
  326. return;
  327. }
  328. UIImage *newThumbnail = [UIImage imageWithContentsOfFile:newThumbnailPath];
  329. if (!newThumbnail) {
  330. if (_recheckForExistingThumbnail) {
  331. [self performSelector:@selector(_updateStoredThumbnailForFile:) withObject:fileItem afterDelay:1.];
  332. _recheckForExistingThumbnail = NO;
  333. } else
  334. return;
  335. }
  336. @try {
  337. [fileItem setComputedThumbnailScaledForDevice:newThumbnail];
  338. }
  339. @catch (NSException *exception) {
  340. APLog(@"updating thumbnail failed");
  341. }
  342. [fileManager removeItemAtPath:newThumbnailPath error:nil];
  343. }
  344. #endif
  345. - (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context
  346. {
  347. if (_mediaWasJustStarted) {
  348. _mediaWasJustStarted = NO;
  349. #if TARGET_OS_IOS
  350. if (self.mediaList) {
  351. NSArray *matches = [MLFile fileForURL:_mediaPlayer.media.url];
  352. MLFile *item = matches.firstObject;
  353. [self _recoverLastPlaybackStateOfItem:item];
  354. }
  355. #else
  356. NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
  357. BOOL bValue = [defaults boolForKey:kVLCSettingUseSPDIF];
  358. if (bValue) {
  359. _mediaPlayer.audio.passthrough = bValue;
  360. }
  361. #endif
  362. }
  363. if ([self.delegate respondsToSelector:@selector(playbackPositionUpdated:)])
  364. [self.delegate playbackPositionUpdated:self];
  365. [[NSNotificationCenter defaultCenter] postNotificationName:VLCPlaybackControllerPlaybackPositionUpdated
  366. object:self];
  367. }
  368. - (NSInteger)mediaDuration
  369. {
  370. return _mediaPlayer.media.length.intValue;;
  371. }
  372. - (BOOL)isPlaying
  373. {
  374. return _mediaPlayer.isPlaying;
  375. }
  376. - (BOOL)willPlay
  377. {
  378. return _mediaPlayer.willPlay;
  379. }
  380. - (VLCRepeatMode)repeatMode
  381. {
  382. return _listPlayer.repeatMode;
  383. }
  384. - (void)setRepeatMode:(VLCRepeatMode)repeatMode
  385. {
  386. _listPlayer.repeatMode = repeatMode;
  387. }
  388. - (BOOL)currentMediaHasChapters
  389. {
  390. return [_mediaPlayer numberOfTitles] > 1 || [_mediaPlayer numberOfChaptersForTitle:_mediaPlayer.currentTitleIndex] > 1;
  391. }
  392. - (BOOL)currentMediaHasTrackToChooseFrom
  393. {
  394. return [[_mediaPlayer audioTrackIndexes] count] > 2 || [[_mediaPlayer videoSubTitlesIndexes] count] > 1;
  395. }
  396. - (BOOL) isSeekable
  397. {
  398. return _mediaPlayer.isSeekable;
  399. }
  400. - (NSNumber *)playbackTime
  401. {
  402. return _mediaPlayer.time.value;
  403. }
  404. - (float)playbackRate
  405. {
  406. return _mediaPlayer.rate;
  407. }
  408. - (void)setPlaybackRate:(float)playbackRate
  409. {
  410. [_mediaPlayer setRate:playbackRate];
  411. _metadata.playbackRate = @(_mediaPlayer.rate);
  412. }
  413. - (void)setAudioDelay:(float)audioDelay
  414. {
  415. _mediaPlayer.currentAudioPlaybackDelay = 1000.*audioDelay;
  416. }
  417. - (float)audioDelay
  418. {
  419. return _mediaPlayer.currentAudioPlaybackDelay/1000.;
  420. }
  421. - (float)playbackPosition
  422. {
  423. return [_mediaPlayer position];
  424. }
  425. - (void)setPlaybackPosition:(float)position
  426. {
  427. _mediaPlayer.position = position;
  428. }
  429. - (void)setSubtitleDelay:(float)subtitleDeleay
  430. {
  431. _mediaPlayer.currentVideoSubTitleDelay = 1000.*subtitleDeleay;
  432. }
  433. - (float)subtitleDelay
  434. {
  435. return _mediaPlayer.currentVideoSubTitleDelay/1000.;
  436. }
  437. - (float)hue
  438. {
  439. return _mediaPlayer.hue;
  440. }
  441. - (void)setHue:(float)hue
  442. {
  443. _mediaPlayer.hue = hue;
  444. }
  445. - (float)contrast
  446. {
  447. return _mediaPlayer.contrast;
  448. }
  449. - (void)setContrast:(float)contrast
  450. {
  451. _mediaPlayer.contrast = contrast;
  452. }
  453. - (float)brightness
  454. {
  455. return _mediaPlayer.brightness;
  456. }
  457. - (void)setBrightness:(float)brightness
  458. {
  459. _mediaPlayer.brightness = brightness;
  460. }
  461. - (float)saturation
  462. {
  463. return _mediaPlayer.saturation;
  464. }
  465. - (void)setSaturation:(float)saturation
  466. {
  467. _mediaPlayer.saturation = saturation;
  468. }
  469. - (void)setGamma:(float)gamma
  470. {
  471. _mediaPlayer.gamma = gamma;
  472. }
  473. - (float)gamma
  474. {
  475. return _mediaPlayer.gamma;
  476. }
  477. - (void)resetFilters
  478. {
  479. _mediaPlayer.hue = 0.;
  480. _mediaPlayer.contrast = 1.;
  481. _mediaPlayer.brightness = 1.;
  482. _mediaPlayer.saturation = 1.;
  483. _mediaPlayer.gamma = 1.;
  484. }
  485. - (void)toggleRepeatMode
  486. {
  487. VLCRepeatMode nextRepeatMode = VLCDoNotRepeat;
  488. switch (_listPlayer.repeatMode) {
  489. case VLCDoNotRepeat:
  490. nextRepeatMode = VLCRepeatCurrentItem;
  491. break;
  492. case VLCRepeatCurrentItem:
  493. nextRepeatMode = VLCRepeatAllItems;
  494. break;
  495. default:
  496. nextRepeatMode = VLCDoNotRepeat;
  497. break;
  498. }
  499. _listPlayer.repeatMode = nextRepeatMode;
  500. }
  501. - (NSInteger)indexOfCurrentAudioTrack
  502. {
  503. return [_mediaPlayer.audioTrackIndexes indexOfObject:@(_mediaPlayer.currentAudioTrackIndex)];
  504. }
  505. - (NSInteger)indexOfCurrentSubtitleTrack
  506. {
  507. return [_mediaPlayer.videoSubTitlesIndexes indexOfObject:@(_mediaPlayer.currentVideoSubTitleIndex)];
  508. }
  509. - (NSInteger)indexOfCurrentChapter
  510. {
  511. return _mediaPlayer.currentChapterIndex;
  512. }
  513. - (NSInteger)indexOfCurrentTitle
  514. {
  515. return _mediaPlayer.currentTitleIndex;
  516. }
  517. - (NSInteger)numberOfAudioTracks
  518. {
  519. return _mediaPlayer.audioTrackIndexes.count;
  520. }
  521. - (NSInteger)numberOfVideoSubtitlesIndexes
  522. {
  523. return _mediaPlayer.videoSubTitlesIndexes.count;
  524. }
  525. - (NSInteger)numberOfTitles
  526. {
  527. return [_mediaPlayer numberOfTitles];
  528. }
  529. - (NSInteger)numberOfChaptersForCurrentTitle
  530. {
  531. return [_mediaPlayer numberOfChaptersForTitle:_mediaPlayer.currentTitleIndex];
  532. }
  533. - (NSString *)videoSubtitleNameAtIndex:(NSInteger)index
  534. {
  535. if (index >= 0 && index < _mediaPlayer.videoSubTitlesNames.count)
  536. return _mediaPlayer.videoSubTitlesNames[index];
  537. return nil;
  538. }
  539. - (NSString *)audioTrackNameAtIndex:(NSInteger)index
  540. {
  541. if (index >= 0 && index < _mediaPlayer.audioTrackNames.count)
  542. return _mediaPlayer.audioTrackNames[index];
  543. return nil;
  544. }
  545. - (NSDictionary *)titleDescriptionsDictAtIndex:(NSInteger)index
  546. {
  547. if (index >= 0 && index < _mediaPlayer.titleDescriptions.count)
  548. return _mediaPlayer.titleDescriptions[index];
  549. return nil;
  550. }
  551. - (NSDictionary *)chapterDescriptionsDictAtIndex:(NSInteger)index
  552. {
  553. NSArray *chapterDescriptions = [_mediaPlayer chapterDescriptionsOfTitle:_mediaPlayer.currentTitleIndex];
  554. if (index >= 0 && index < chapterDescriptions.count)
  555. return chapterDescriptions[index];
  556. return nil;
  557. }
  558. - (void)selectAudioTrackAtIndex:(NSInteger)index
  559. {
  560. if (index >= 0 && index < _mediaPlayer.audioTrackIndexes.count) {
  561. //we can cast this cause we won't have more than 2 million audiotracks
  562. _mediaPlayer.currentAudioTrackIndex = [_mediaPlayer.audioTrackIndexes[index] intValue];
  563. }
  564. }
  565. - (void)selectVideoSubtitleAtIndex:(NSInteger)index
  566. {
  567. if (index >= 0 && index < _mediaPlayer.videoSubTitlesIndexes.count) {
  568. _mediaPlayer.currentVideoSubTitleIndex = [_mediaPlayer.videoSubTitlesIndexes[index] intValue];
  569. }
  570. }
  571. - (void)selectTitleAtIndex:(NSInteger)index
  572. {
  573. if (index >= 0 && index < [_mediaPlayer numberOfTitles]) {
  574. //we can cast this cause we won't have more than 2 million titles
  575. _mediaPlayer.currentTitleIndex = (int)index;
  576. }
  577. }
  578. - (void)selectChapterAtIndex:(NSInteger)index
  579. {
  580. if (index >= 0 && index < [self numberOfChaptersForCurrentTitle]) {
  581. //we can cast this cause we won't have more than 2 million chapters
  582. _mediaPlayer.currentChapterIndex = (int)index;
  583. }
  584. }
  585. - (void)shortJumpForward
  586. {
  587. [_mediaPlayer shortJumpForward];
  588. }
  589. - (void)shortJumpBackward
  590. {
  591. [_mediaPlayer shortJumpBackward];
  592. }
  593. - (VLCTime *)remainingTime
  594. {
  595. return [_mediaPlayer remainingTime];
  596. }
  597. - (void)setAudioPassthrough:(BOOL)shouldPass
  598. {
  599. _mediaPlayer.audio.passthrough = shouldPass;
  600. }
  601. - (void)mediaPlayerStateChanged:(NSNotification *)aNotification
  602. {
  603. VLCMediaPlayerState currentState = _mediaPlayer.state;
  604. switch (currentState) {
  605. case VLCMediaPlayerStateBuffering: {
  606. /* attach delegate */
  607. _mediaPlayer.media.delegate = self;
  608. /* on-the-fly values through hidden API */
  609. NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
  610. #pragma clang diagnostic push
  611. #pragma clang diagnostic ignored "-Wundeclared-selector"
  612. [_mediaPlayer performSelector:@selector(setTextRendererFont:) withObject:[defaults objectForKey:kVLCSettingSubtitlesFont]];
  613. [_mediaPlayer performSelector:@selector(setTextRendererFontSize:) withObject:[defaults objectForKey:kVLCSettingSubtitlesFontSize]];
  614. [_mediaPlayer performSelector:@selector(setTextRendererFontColor:) withObject:[defaults objectForKey:kVLCSettingSubtitlesFontColor]];
  615. [_mediaPlayer performSelector:@selector(setTextRendererFontForceBold:) withObject:[defaults objectForKey:kVLCSettingSubtitlesBoldFont]];
  616. #pragma clang diagnostic pop
  617. } break;
  618. case VLCMediaPlayerStateError: {
  619. APLog(@"Playback failed");
  620. dispatch_async(dispatch_get_main_queue(),^{
  621. [[NSNotificationCenter defaultCenter] postNotificationName:VLCPlaybackControllerPlaybackDidFail object:self];
  622. });
  623. _sessionWillRestart = NO;
  624. [self stopPlayback];
  625. } break;
  626. case VLCMediaPlayerStateEnded:
  627. case VLCMediaPlayerStateStopped: {
  628. [_listPlayer.mediaList lock];
  629. NSUInteger listCount = _listPlayer.mediaList.count;
  630. if ([_listPlayer.mediaList indexOfMedia:_mediaPlayer.media] == listCount - 1 && self.repeatMode == VLCDoNotRepeat) {
  631. [_listPlayer.mediaList unlock];
  632. _sessionWillRestart = NO;
  633. [self stopPlayback];
  634. return;
  635. } else if (listCount > 1) {
  636. [_listPlayer.mediaList unlock];
  637. [_listPlayer next];
  638. } else
  639. [_listPlayer.mediaList unlock];
  640. } break;
  641. case VLCMediaPlayerStateESAdded: {
  642. #if TARGET_OS_IOS
  643. [self restoreAudioAndSubtitleTrack];
  644. #endif
  645. } break;
  646. default:
  647. break;
  648. }
  649. if ([self.delegate respondsToSelector:@selector(mediaPlayerStateChanged:isPlaying:currentMediaHasTrackToChooseFrom:currentMediaHasChapters:forPlaybackController:)])
  650. [self.delegate mediaPlayerStateChanged:currentState
  651. isPlaying:_mediaPlayer.isPlaying
  652. currentMediaHasTrackToChooseFrom:self.currentMediaHasTrackToChooseFrom
  653. currentMediaHasChapters:self.currentMediaHasChapters
  654. forPlaybackController:self];
  655. [self setNeedsMetadataUpdate];
  656. }
  657. #pragma mark - playback controls
  658. - (void)playPause
  659. {
  660. [_mediaPlayer isPlaying] ? [self pause] : [self play];
  661. }
  662. - (void)play
  663. {
  664. [_listPlayer play];
  665. [[NSNotificationCenter defaultCenter] postNotificationName:VLCPlaybackControllerPlaybackDidResume object:self];
  666. }
  667. - (void)pause
  668. {
  669. [_listPlayer pause];
  670. #if TARGET_OS_IOS
  671. [self _savePlaybackState];
  672. #endif
  673. [[NSNotificationCenter defaultCenter] postNotificationName:VLCPlaybackControllerPlaybackDidPause object:self];
  674. }
  675. - (void)next
  676. {
  677. NSInteger mediaListCount = _mediaList.count;
  678. #if TARGET_OS_IOS
  679. if (self.repeatMode != VLCRepeatCurrentItem && mediaListCount > 2 && _shuffleMode) {
  680. NSNumber *nextIndex;
  681. NSUInteger currentIndex = [_mediaList indexOfMedia:_listPlayer.mediaPlayer.media];
  682. //Reached end of playlist
  683. if (_shuffleStack.count + 1 == mediaListCount) {
  684. if ([self repeatMode] == VLCDoNotRepeat)
  685. return;
  686. [_shuffleStack removeAllObjects];
  687. }
  688. [_shuffleStack addObject:[NSNumber numberWithUnsignedInteger:currentIndex]];
  689. do {
  690. nextIndex = [NSNumber numberWithUnsignedInt:arc4random_uniform((uint32_t)mediaListCount)];
  691. } while (currentIndex == nextIndex.unsignedIntegerValue || [_shuffleStack containsObject:nextIndex]);
  692. [_listPlayer playItemAtNumber:[NSNumber numberWithUnsignedInteger:nextIndex.unsignedIntegerValue]];
  693. [[NSNotificationCenter defaultCenter] postNotificationName:VLCPlaybackControllerPlaybackMetadataDidChange object:self];
  694. return;
  695. }
  696. #endif
  697. if (mediaListCount > 1) {
  698. [_listPlayer next];
  699. [[NSNotificationCenter defaultCenter] postNotificationName:VLCPlaybackControllerPlaybackMetadataDidChange object:self];
  700. } else {
  701. NSNumber *skipLength = [[NSUserDefaults standardUserDefaults] valueForKey:kVLCSettingPlaybackForwardSkipLength];
  702. [_mediaPlayer jumpForward:skipLength.intValue];
  703. }
  704. }
  705. - (void)previous
  706. {
  707. if (_mediaList.count > 1) {
  708. [_listPlayer previous];
  709. [[NSNotificationCenter defaultCenter] postNotificationName:VLCPlaybackControllerPlaybackMetadataDidChange object:self];
  710. }
  711. else {
  712. NSNumber *skipLength = [[NSUserDefaults standardUserDefaults] valueForKey:kVLCSettingPlaybackBackwardSkipLength];
  713. [_mediaPlayer jumpBackward:skipLength.intValue];
  714. }
  715. }
  716. - (void)jumpForward:(int)interval
  717. {
  718. [_mediaPlayer jumpForward:interval];
  719. }
  720. - (void)jumpBackward:(int)interval
  721. {
  722. [_mediaPlayer jumpBackward:interval];
  723. }
  724. - (NSString *)screenAspectRatio
  725. {
  726. UIScreen *screen = [[UIDevice currentDevice] VLCHasExternalDisplay] ? [UIScreen screens][1] : [UIScreen mainScreen];
  727. return [NSString stringWithFormat:@"%d:%d", (int)screen.bounds.size.width, (int)screen.bounds.size.height];
  728. }
  729. - (void)switchIPhoneXFullScreen
  730. {
  731. BOOL inFullScreen = _mediaPlayer.videoCropGeometry && [[NSString stringWithUTF8String:_mediaPlayer.videoCropGeometry] isEqualToString:[self screenAspectRatio]];
  732. if (inFullScreen) {
  733. const char *previousAspectRatio = _currentAspectRatio == VLCAspectRatioDefault ? NULL : [[self stringForAspectRatio:_currentAspectRatio] UTF8String];
  734. _mediaPlayer.videoAspectRatio = (char *)previousAspectRatio;
  735. }
  736. _mediaPlayer.videoCropGeometry = inFullScreen ? NULL : (char *)[[self screenAspectRatio] UTF8String];
  737. }
  738. - (void)switchAspectRatio
  739. {
  740. _currentAspectRatio = _currentAspectRatio == VLCAspectRatioSixteenToTen ? VLCAspectRatioDefault : _currentAspectRatio + 1;
  741. switch (_currentAspectRatio) {
  742. case VLCAspectRatioDefault:
  743. _mediaPlayer.videoAspectRatio = NULL;
  744. _mediaPlayer.videoCropGeometry = NULL;
  745. break;
  746. case VLCAspectRatioFillToScreen:
  747. _mediaPlayer.videoCropGeometry = (char *)[[self screenAspectRatio] UTF8String];
  748. break;
  749. case VLCAspectRatioFourToThree:
  750. case VLCAspectRatioSixteenToTen:
  751. case VLCAspectRatioSixteenToNine:
  752. _mediaPlayer.videoCropGeometry = NULL;
  753. _mediaPlayer.videoAspectRatio = (char *)[[self stringForAspectRatio:_currentAspectRatio] UTF8String];
  754. }
  755. if ([self.delegate respondsToSelector:@selector(showStatusMessage:forPlaybackController:)]) {
  756. [self.delegate showStatusMessage:[NSString stringWithFormat:NSLocalizedString(@"AR_CHANGED", nil), [self stringForAspectRatio:_currentAspectRatio]] forPlaybackController:self];
  757. }
  758. }
  759. - (NSString *)stringForAspectRatio:(VLCAspectRatio)ratio
  760. {
  761. switch (ratio) {
  762. case VLCAspectRatioFillToScreen:
  763. return NSLocalizedString(@"FILL_TO_SCREEN", nil);
  764. case VLCAspectRatioDefault:
  765. return NSLocalizedString(@"DEFAULT", nil);
  766. case VLCAspectRatioFourToThree:
  767. return @"4:3";
  768. case VLCAspectRatioSixteenToTen:
  769. return @"16:10";
  770. case VLCAspectRatioSixteenToNine:
  771. return @"16:9";
  772. default:
  773. NSAssert(NO, @"this shouldn't happen");
  774. }
  775. }
  776. - (void)setVideoTrackEnabled:(BOOL)enabled
  777. {
  778. if (!enabled)
  779. _mediaPlayer.currentVideoTrackIndex = -1;
  780. else if (_mediaPlayer.currentVideoTrackIndex == -1) {
  781. for (NSNumber *trackId in _mediaPlayer.videoTrackIndexes) {
  782. if ([trackId intValue] != -1) {
  783. _mediaPlayer.currentVideoTrackIndex = [trackId intValue];
  784. break;
  785. }
  786. }
  787. }
  788. }
  789. - (void)setVideoOutputView:(UIView *)videoOutputView
  790. {
  791. if (videoOutputView) {
  792. if ([_actualVideoOutputView superview] != nil)
  793. [_actualVideoOutputView removeFromSuperview];
  794. _actualVideoOutputView.frame = (CGRect){CGPointZero, videoOutputView.frame.size};
  795. [self setVideoTrackEnabled:true];
  796. [videoOutputView addSubview:_actualVideoOutputView];
  797. [_actualVideoOutputView layoutSubviews];
  798. [_actualVideoOutputView updateConstraints];
  799. [_actualVideoOutputView setNeedsLayout];
  800. } else
  801. [_actualVideoOutputView removeFromSuperview];
  802. _videoOutputViewWrapper = videoOutputView;
  803. }
  804. - (UIView *)videoOutputView
  805. {
  806. return _videoOutputViewWrapper;
  807. }
  808. #pragma mark - 360 Support
  809. #if !TARGET_OS_TV
  810. - (BOOL)updateViewpoint:(CGFloat)yaw pitch:(CGFloat)pitch roll:(CGFloat)roll fov:(CGFloat)fov absolute:(BOOL)absolute
  811. {
  812. //adjusting the values
  813. if (fabs(yaw) > 180) {
  814. yaw = yaw > 0 ? yaw - 360 : yaw + 360;
  815. }
  816. if (fabs(roll) > 180) {
  817. roll = roll > 0 ? roll - 360 : roll + 360;
  818. }
  819. if (fabs(pitch) > 90) {
  820. pitch = pitch > 0 ? pitch - 180 : pitch + 180;
  821. }
  822. return [_mediaPlayer updateViewpoint:yaw pitch:pitch roll:roll fov:fov absolute:absolute];
  823. }
  824. - (CGFloat)yaw
  825. {
  826. return _mediaPlayer.yaw;
  827. }
  828. - (CGFloat)pitch
  829. {
  830. return _mediaPlayer.pitch;
  831. }
  832. - (CGFloat)roll
  833. {
  834. return _mediaPlayer.roll;
  835. }
  836. - (CGFloat)fov
  837. {
  838. return _mediaPlayer.fov;
  839. }
  840. - (BOOL)currentMediaIs360Video
  841. {
  842. return [self currentMediaProjection] == VLCMediaProjectionEquiRectangular;
  843. }
  844. - (NSInteger)currentMediaProjection
  845. {
  846. VLCMedia *media = [_mediaPlayer media];
  847. NSInteger currentVideoTrackIndex = [_mediaPlayer currentVideoTrackIndex];
  848. if (media && currentVideoTrackIndex >= 0) {
  849. NSArray *tracksInfo = media.tracksInformation;
  850. for (NSDictionary *track in tracksInfo) {
  851. if ([track[VLCMediaTracksInformationType] isEqualToString:VLCMediaTracksInformationTypeVideo]) {
  852. return [track[VLCMediaTracksInformationVideoProjection] integerValue];
  853. }
  854. }
  855. }
  856. return -1;
  857. }
  858. #endif
  859. #pragma mark - equalizer
  860. - (void)setAmplification:(CGFloat)amplification forBand:(unsigned int)index
  861. {
  862. if (!_mediaPlayer.equalizerEnabled)
  863. [_mediaPlayer setEqualizerEnabled:YES];
  864. [_mediaPlayer setAmplification:amplification forBand:index];
  865. // For some reason we have to apply again preamp to apply change
  866. [_mediaPlayer setPreAmplification:[_mediaPlayer preAmplification]];
  867. }
  868. - (CGFloat)amplificationOfBand:(unsigned int)index
  869. {
  870. return [_mediaPlayer amplificationOfBand:index];
  871. }
  872. - (NSArray *)equalizerProfiles
  873. {
  874. return _mediaPlayer.equalizerProfiles;
  875. }
  876. - (void)resetEqualizerFromProfile:(unsigned int)profile
  877. {
  878. [[NSUserDefaults standardUserDefaults] setObject:@(profile) forKey:kVLCSettingEqualizerProfile];
  879. [_mediaPlayer resetEqualizerFromProfile:profile];
  880. }
  881. - (void)setPreAmplification:(CGFloat)preAmplification
  882. {
  883. if (!_mediaPlayer.equalizerEnabled)
  884. [_mediaPlayer setEqualizerEnabled:YES];
  885. [_mediaPlayer setPreAmplification:preAmplification];
  886. }
  887. - (CGFloat)preAmplification
  888. {
  889. return [_mediaPlayer preAmplification];
  890. }
  891. #pragma mark - AVAudioSession Notification Observers
  892. - (void)handleInterruption:(NSNotification *)notification
  893. {
  894. NSDictionary *userInfo = notification.userInfo;
  895. if (!userInfo || !userInfo[AVAudioSessionInterruptionTypeKey]) {
  896. return;
  897. }
  898. NSUInteger interruptionType = [userInfo[AVAudioSessionInterruptionTypeKey] unsignedIntegerValue];
  899. if (interruptionType == AVAudioSessionInterruptionTypeBegan) {
  900. [_mediaPlayer pause];
  901. } else if (interruptionType == AVAudioSessionInterruptionTypeEnded
  902. && [userInfo[AVAudioSessionInterruptionOptionKey] unsignedIntegerValue] == AVAudioSessionInterruptionOptionShouldResume) {
  903. [_mediaPlayer play];
  904. }
  905. }
  906. - (BOOL)areHeadphonesPlugged
  907. {
  908. NSArray *outputs = [[AVAudioSession sharedInstance] currentRoute].outputs;
  909. NSString *portName = [[outputs firstObject] portName];
  910. return [portName isEqualToString:@"Headphones"];
  911. }
  912. - (void)audioSessionRouteChange:(NSNotification *)notification
  913. {
  914. NSDictionary *userInfo = notification.userInfo;
  915. NSInteger routeChangeReason = [[userInfo valueForKey:AVAudioSessionRouteChangeReasonKey] integerValue];
  916. if (routeChangeReason == AVAudioSessionRouteChangeReasonRouteConfigurationChange)
  917. return;
  918. BOOL headphonesPlugged = [self areHeadphonesPlugged];
  919. if (_headphonesWasPlugged && !headphonesPlugged && [_mediaPlayer isPlaying]) {
  920. [_mediaPlayer pause];
  921. #if TARGET_OS_IOS
  922. [self _savePlaybackState];
  923. #endif
  924. [[NSNotificationCenter defaultCenter] postNotificationName:VLCPlaybackControllerPlaybackDidPause object:self];
  925. }
  926. _headphonesWasPlugged = headphonesPlugged;
  927. }
  928. #pragma mark - Managing the media item
  929. - (VLCMedia *)currentlyPlayingMedia
  930. {
  931. return _mediaPlayer.media;
  932. }
  933. #pragma mark - metadata handling
  934. - (void)performNavigationAction:(VLCMediaPlaybackNavigationAction)action
  935. {
  936. [_mediaPlayer performNavigationAction:action];
  937. }
  938. - (void)mediaDidFinishParsing:(VLCMedia *)aMedia
  939. {
  940. [self setNeedsMetadataUpdate];
  941. }
  942. - (void)mediaMetaDataDidChange:(VLCMedia*)aMedia
  943. {
  944. [self setNeedsMetadataUpdate];
  945. }
  946. - (void)setNeedsMetadataUpdate
  947. {
  948. if (_needsMetadataUpdate == NO) {
  949. _needsMetadataUpdate = YES;
  950. dispatch_async(dispatch_get_main_queue(), ^{
  951. [self->_metadata updateMetadataFromMediaPlayer:self->_mediaPlayer];
  952. self->_needsMetadataUpdate = NO;
  953. if ([self.delegate respondsToSelector:@selector(displayMetadataForPlaybackController:metadata:)])
  954. [self.delegate displayMetadataForPlaybackController:self metadata:self->_metadata];
  955. });
  956. }
  957. }
  958. #if TARGET_OS_IOS
  959. - (void)_recoverLastPlaybackStateOfItem:(MLFile *)item
  960. {
  961. if (item) {
  962. CGFloat lastPosition = .0;
  963. NSInteger duration = 0;
  964. if (item.lastPosition) {
  965. lastPosition = item.lastPosition.floatValue;
  966. }
  967. duration = item.duration.intValue;
  968. if (lastPosition < .95 && _mediaPlayer.position < lastPosition) {
  969. NSInteger continuePlayback;
  970. if ([item isAlbumTrack] || [item isSupportedAudioFile])
  971. continuePlayback = [[[NSUserDefaults standardUserDefaults] objectForKey:kVLCSettingContinueAudioPlayback] integerValue];
  972. else
  973. continuePlayback = [[[NSUserDefaults standardUserDefaults] objectForKey:kVLCSettingContinuePlayback] integerValue];
  974. if (continuePlayback == 1) {
  975. [self setPlaybackPosition:lastPosition];
  976. } else if (continuePlayback == 0) {
  977. VLCAlertView *alert = [[VLCAlertView alloc] initWithTitle:NSLocalizedString(@"CONTINUE_PLAYBACK", nil)
  978. message:[NSString stringWithFormat:NSLocalizedString(@"CONTINUE_PLAYBACK_LONG", nil), item.title]
  979. delegate:self
  980. cancelButtonTitle:NSLocalizedString(@"BUTTON_CANCEL", nil)
  981. otherButtonTitles:NSLocalizedString(@"BUTTON_CONTINUE", nil), nil];
  982. alert.completion = ^(BOOL cancelled, NSInteger buttonIndex) {
  983. if (!cancelled) {
  984. [self setPlaybackPosition:lastPosition];
  985. }
  986. };
  987. [alert show];
  988. }
  989. }
  990. }
  991. }
  992. #endif
  993. - (void)recoverDisplayedMetadata
  994. {
  995. if ([self.delegate respondsToSelector:@selector(displayMetadataForPlaybackController:metadata:)])
  996. [self.delegate displayMetadataForPlaybackController:self metadata:_metadata];
  997. }
  998. - (void)recoverPlaybackState
  999. {
  1000. if ([self.delegate respondsToSelector:@selector(mediaPlayerStateChanged:isPlaying:currentMediaHasTrackToChooseFrom:currentMediaHasChapters:forPlaybackController:)])
  1001. [self.delegate mediaPlayerStateChanged:_mediaPlayer.state
  1002. isPlaying:self.isPlaying
  1003. currentMediaHasTrackToChooseFrom:self.currentMediaHasTrackToChooseFrom
  1004. currentMediaHasChapters:self.currentMediaHasChapters
  1005. forPlaybackController:self];
  1006. if ([self.delegate respondsToSelector:@selector(prepareForMediaPlayback:)])
  1007. [self.delegate prepareForMediaPlayback:self];
  1008. }
  1009. - (void)scheduleSleepTimerWithInterval:(NSTimeInterval)timeInterval
  1010. {
  1011. if (_sleepTimer) {
  1012. [_sleepTimer invalidate];
  1013. _sleepTimer = nil;
  1014. }
  1015. _sleepTimer = [NSTimer scheduledTimerWithTimeInterval:timeInterval target:self selector:@selector(stopPlayback) userInfo:nil repeats:NO];
  1016. }
  1017. #pragma mark - background interaction
  1018. - (void)applicationWillResignActive:(NSNotification *)aNotification
  1019. {
  1020. #if TARGET_OS_IOS
  1021. [self _savePlaybackState];
  1022. #endif
  1023. if (![[[NSUserDefaults standardUserDefaults] objectForKey:kVLCSettingContinueAudioInBackgroundKey] boolValue]) {
  1024. if ([_mediaPlayer isPlaying]) {
  1025. [_mediaPlayer pause];
  1026. _shouldResumePlaying = YES;
  1027. }
  1028. }
  1029. }
  1030. - (void)applicationDidEnterBackground:(NSNotification *)notification
  1031. {
  1032. _preBackgroundWrapperView = _videoOutputViewWrapper;
  1033. if (!_renderer && _mediaPlayer.audioTrackIndexes.count > 0)
  1034. [self setVideoTrackEnabled:false];
  1035. }
  1036. - (void)applicationDidBecomeActive:(NSNotification *)notification
  1037. {
  1038. if (_preBackgroundWrapperView) {
  1039. [self setVideoOutputView:_preBackgroundWrapperView];
  1040. _preBackgroundWrapperView = nil;
  1041. }
  1042. [self setVideoTrackEnabled:true];
  1043. if (_shouldResumePlaying) {
  1044. _shouldResumePlaying = NO;
  1045. [_listPlayer play];
  1046. }
  1047. }
  1048. #pragma mark - remoteControlDelegate
  1049. - (void)remoteControlServiceHitPause:(VLCRemoteControlService *)rcs
  1050. {
  1051. [_listPlayer pause];
  1052. }
  1053. - (void)remoteControlServiceHitPlay:(VLCRemoteControlService *)rcs
  1054. {
  1055. [_listPlayer play];
  1056. }
  1057. - (void)remoteControlServiceTogglePlayPause:(VLCRemoteControlService *)rcs
  1058. {
  1059. [self playPause];
  1060. }
  1061. - (void)remoteControlServiceHitStop:(VLCRemoteControlService *)rcs
  1062. {
  1063. //TODO handle stop playback entirely
  1064. [_listPlayer stop];
  1065. }
  1066. - (BOOL)remoteControlServiceHitPlayNextIfPossible:(VLCRemoteControlService *)rcs
  1067. {
  1068. //TODO This doesn't handle shuffle or repeat yet
  1069. return [_listPlayer next];
  1070. }
  1071. - (BOOL)remoteControlServiceHitPlayPreviousIfPossible:(VLCRemoteControlService *)rcs
  1072. {
  1073. //TODO This doesn't handle shuffle or repeat yet
  1074. return [_listPlayer previous];
  1075. }
  1076. - (void)remoteControlService:(VLCRemoteControlService *)rcs jumpForwardInSeconds:(NSTimeInterval)seconds
  1077. {
  1078. [_mediaPlayer jumpForward:seconds];
  1079. }
  1080. - (void)remoteControlService:(VLCRemoteControlService *)rcs jumpBackwardInSeconds:(NSTimeInterval)seconds
  1081. {
  1082. [_mediaPlayer jumpBackward:seconds];
  1083. }
  1084. - (NSInteger)remoteControlServiceNumberOfMediaItemsinList:(VLCRemoteControlService *)rcs
  1085. {
  1086. return _mediaList.count;
  1087. }
  1088. - (void)remoteControlService:(VLCRemoteControlService *)rcs setPlaybackRate:(CGFloat)playbackRate
  1089. {
  1090. self.playbackRate = playbackRate;
  1091. }
  1092. - (void)remoteControlService:(VLCRemoteControlService *)rcs setCurrentPlaybackTime:(NSTimeInterval)playbackTime
  1093. {
  1094. float positionDiff = playbackTime - [self.metadata.elapsedPlaybackTime floatValue];
  1095. [_mediaPlayer jumpForward:positionDiff];
  1096. }
  1097. #pragma mark - helpers
  1098. - (NSDictionary *)mediaOptionsDictionary
  1099. {
  1100. NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
  1101. return @{ kVLCSettingNetworkCaching : [defaults objectForKey:kVLCSettingNetworkCaching],
  1102. kVLCSettingStretchAudio : [[defaults objectForKey:kVLCSettingStretchAudio] boolValue] ? kVLCSettingStretchAudioOnValue : kVLCSettingStretchAudioOffValue,
  1103. kVLCSettingTextEncoding : [defaults objectForKey:kVLCSettingTextEncoding],
  1104. kVLCSettingSkipLoopFilter : [defaults objectForKey:kVLCSettingSkipLoopFilter],
  1105. kVLCSettingHardwareDecoding : [defaults objectForKey:kVLCSettingHardwareDecoding]};
  1106. }
  1107. #pragma mark - Renderer
  1108. - (void)mediaPlayerSetRenderer:(VLCRendererItem *)renderer
  1109. {
  1110. [_mediaPlayer setRendererItem:renderer];
  1111. }
  1112. @end