VLCPlaybackController.m 40 KB

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