VLCPlaybackController.m 40 KB

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