VLCPlaybackController.m 40 KB

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