VLCPlaybackController.m 43 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358
  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)switchIPhoneXFullScreen
  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. if ([self.delegate respondsToSelector:@selector(displayMetadataForPlaybackController:metadata:)])
  964. [self.delegate displayMetadataForPlaybackController:self metadata:self->_metadata];
  965. });
  966. }
  967. }
  968. #if TARGET_OS_IOS
  969. - (void)_recoverLastPlaybackStateOfItem:(MLFile *)item
  970. {
  971. if (item) {
  972. CGFloat lastPosition = .0;
  973. NSInteger duration = 0;
  974. if (item.lastPosition) {
  975. lastPosition = item.lastPosition.floatValue;
  976. }
  977. duration = item.duration.intValue;
  978. if (lastPosition < .95 && _mediaPlayer.position < lastPosition) {
  979. NSInteger continuePlayback;
  980. if ([item isAlbumTrack] || [item isSupportedAudioFile])
  981. continuePlayback = [[[NSUserDefaults standardUserDefaults] objectForKey:kVLCSettingContinueAudioPlayback] integerValue];
  982. else
  983. continuePlayback = [[[NSUserDefaults standardUserDefaults] objectForKey:kVLCSettingContinuePlayback] integerValue];
  984. if (continuePlayback == 1) {
  985. [self setPlaybackPosition:lastPosition];
  986. } else if (continuePlayback == 0) {
  987. NSArray<VLCAlertButton *> *buttonsAction = @[[[VLCAlertButton alloc] initWithTitle: NSLocalizedString(@"BUTTON_CANCEL", nil)
  988. style: UIAlertActionStyleCancel
  989. action: nil],
  990. [[VLCAlertButton alloc] initWithTitle: NSLocalizedString(@"BUTTON_CONTINUE", nil)
  991. action: ^(UIAlertAction *action) {
  992. [self setPlaybackPosition:lastPosition];
  993. }]
  994. ];
  995. UIViewController *presentingVC = [UIApplication sharedApplication].delegate.window.rootViewController;
  996. presentingVC = presentingVC.presentedViewController ?: presentingVC;
  997. [VLCAlertViewController alertViewManagerWithTitle:NSLocalizedString(@"CONTINUE_PLAYBACK", nil)
  998. errorMessage:[NSString stringWithFormat:NSLocalizedString(@"CONTINUE_PLAYBACK_LONG", nil), item.title]
  999. viewController:presentingVC
  1000. buttonsAction:buttonsAction];
  1001. }
  1002. }
  1003. }
  1004. }
  1005. #endif
  1006. - (void)recoverDisplayedMetadata
  1007. {
  1008. if ([self.delegate respondsToSelector:@selector(displayMetadataForPlaybackController:metadata:)])
  1009. [self.delegate displayMetadataForPlaybackController:self metadata:_metadata];
  1010. }
  1011. - (void)recoverPlaybackState
  1012. {
  1013. if ([self.delegate respondsToSelector:@selector(mediaPlayerStateChanged:isPlaying:currentMediaHasTrackToChooseFrom:currentMediaHasChapters:forPlaybackController:)])
  1014. [self.delegate mediaPlayerStateChanged:_mediaPlayer.state
  1015. isPlaying:self.isPlaying
  1016. currentMediaHasTrackToChooseFrom:self.currentMediaHasTrackToChooseFrom
  1017. currentMediaHasChapters:self.currentMediaHasChapters
  1018. forPlaybackController:self];
  1019. if ([self.delegate respondsToSelector:@selector(prepareForMediaPlayback:)])
  1020. [self.delegate prepareForMediaPlayback:self];
  1021. }
  1022. - (void)scheduleSleepTimerWithInterval:(NSTimeInterval)timeInterval
  1023. {
  1024. if (_sleepTimer) {
  1025. [_sleepTimer invalidate];
  1026. _sleepTimer = nil;
  1027. }
  1028. _sleepTimer = [NSTimer scheduledTimerWithTimeInterval:timeInterval target:self selector:@selector(stopPlayback) userInfo:nil repeats:NO];
  1029. }
  1030. #pragma mark - background interaction
  1031. - (void)applicationWillResignActive:(NSNotification *)aNotification
  1032. {
  1033. #if TARGET_OS_IOS
  1034. [self _savePlaybackState];
  1035. #endif
  1036. if (![[[NSUserDefaults standardUserDefaults] objectForKey:kVLCSettingContinueAudioInBackgroundKey] boolValue]) {
  1037. if ([_mediaPlayer isPlaying]) {
  1038. [_mediaPlayer pause];
  1039. _shouldResumePlaying = YES;
  1040. }
  1041. }
  1042. }
  1043. - (void)applicationDidEnterBackground:(NSNotification *)notification
  1044. {
  1045. _preBackgroundWrapperView = _videoOutputViewWrapper;
  1046. if (!_renderer && _mediaPlayer.audioTrackIndexes.count > 0)
  1047. [self setVideoTrackEnabled:false];
  1048. }
  1049. - (void)applicationDidBecomeActive:(NSNotification *)notification
  1050. {
  1051. if (_preBackgroundWrapperView) {
  1052. [self setVideoOutputView:_preBackgroundWrapperView];
  1053. _preBackgroundWrapperView = nil;
  1054. }
  1055. [self setVideoTrackEnabled:true];
  1056. if (_shouldResumePlaying) {
  1057. _shouldResumePlaying = NO;
  1058. [_listPlayer play];
  1059. }
  1060. }
  1061. #pragma mark - remoteControlDelegate
  1062. - (void)remoteControlServiceHitPause:(VLCRemoteControlService *)rcs
  1063. {
  1064. [_listPlayer pause];
  1065. }
  1066. - (void)remoteControlServiceHitPlay:(VLCRemoteControlService *)rcs
  1067. {
  1068. [_listPlayer play];
  1069. }
  1070. - (void)remoteControlServiceTogglePlayPause:(VLCRemoteControlService *)rcs
  1071. {
  1072. [self playPause];
  1073. }
  1074. - (void)remoteControlServiceHitStop:(VLCRemoteControlService *)rcs
  1075. {
  1076. //TODO handle stop playback entirely
  1077. [_listPlayer stop];
  1078. }
  1079. - (BOOL)remoteControlServiceHitPlayNextIfPossible:(VLCRemoteControlService *)rcs
  1080. {
  1081. //TODO This doesn't handle shuffle or repeat yet
  1082. return [_listPlayer next];
  1083. }
  1084. - (BOOL)remoteControlServiceHitPlayPreviousIfPossible:(VLCRemoteControlService *)rcs
  1085. {
  1086. //TODO This doesn't handle shuffle or repeat yet
  1087. return [_listPlayer previous];
  1088. }
  1089. - (void)remoteControlService:(VLCRemoteControlService *)rcs jumpForwardInSeconds:(NSTimeInterval)seconds
  1090. {
  1091. [_mediaPlayer jumpForward:seconds];
  1092. }
  1093. - (void)remoteControlService:(VLCRemoteControlService *)rcs jumpBackwardInSeconds:(NSTimeInterval)seconds
  1094. {
  1095. [_mediaPlayer jumpBackward:seconds];
  1096. }
  1097. - (NSInteger)remoteControlServiceNumberOfMediaItemsinList:(VLCRemoteControlService *)rcs
  1098. {
  1099. return _mediaList.count;
  1100. }
  1101. - (void)remoteControlService:(VLCRemoteControlService *)rcs setPlaybackRate:(CGFloat)playbackRate
  1102. {
  1103. self.playbackRate = playbackRate;
  1104. }
  1105. - (void)remoteControlService:(VLCRemoteControlService *)rcs setCurrentPlaybackTime:(NSTimeInterval)playbackTime
  1106. {
  1107. float positionDiff = playbackTime - [self.metadata.elapsedPlaybackTime floatValue];
  1108. [_mediaPlayer jumpForward:positionDiff];
  1109. }
  1110. #pragma mark - helpers
  1111. - (NSDictionary *)mediaOptionsDictionary
  1112. {
  1113. NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
  1114. return @{ kVLCSettingNetworkCaching : [defaults objectForKey:kVLCSettingNetworkCaching],
  1115. kVLCSettingStretchAudio : [[defaults objectForKey:kVLCSettingStretchAudio] boolValue] ? kVLCSettingStretchAudioOnValue : kVLCSettingStretchAudioOffValue,
  1116. kVLCSettingTextEncoding : [defaults objectForKey:kVLCSettingTextEncoding],
  1117. kVLCSettingSkipLoopFilter : [defaults objectForKey:kVLCSettingSkipLoopFilter],
  1118. kVLCSettingHardwareDecoding : [defaults objectForKey:kVLCSettingHardwareDecoding]};
  1119. }
  1120. #pragma mark - Renderer
  1121. - (void)setRenderer:(VLCRendererItem * __nullable)renderer
  1122. {
  1123. _renderer = renderer;
  1124. [_mediaPlayer setRendererItem:_renderer];
  1125. }
  1126. @end