VLCPlaybackService.m 41 KB

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