VLCPlaybackService.m 41 KB

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