VLCPlaybackController.m 43 KB

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