VLCPlaybackController.m 43 KB

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