VLCPlaybackService.m 42 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341
  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 *_backgroundDummyPlayer;
  36. VLCMediaPlayer *_mediaPlayer;
  37. VLCMediaListPlayer *_listPlayer;
  38. BOOL _shouldResumePlaying;
  39. BOOL _sessionWillRestart;
  40. NSString *_pathToExternalSubtitlesFile;
  41. int _itemInMediaListToBePlayedFirst;
  42. NSTimer *_sleepTimer;
  43. BOOL _isInFillToScreen;
  44. NSUInteger _previousAspectRatio;
  45. UIView *_videoOutputViewWrapper;
  46. UIView *_actualVideoOutputView;
  47. UIView *_preBackgroundWrapperView;
  48. BOOL _needsMetadataUpdate;
  49. BOOL _mediaWasJustStarted;
  50. BOOL _recheckForExistingThumbnail;
  51. BOOL _externalAudioPlaybackDeviceConnected;
  52. NSLock *_playbackSessionManagementLock;
  53. NSMutableArray *_shuffleStack;
  54. void (^_playbackCompletion)(BOOL success);
  55. VLCDialogProvider *_dialogProvider;
  56. VLCCustomDialogRendererHandler *_customDialogHandler;
  57. VLCPlayerDisplayController *_playerDisplayController;
  58. }
  59. @end
  60. @implementation VLCPlaybackService
  61. #pragma mark instance management
  62. + (VLCPlaybackService *)sharedInstance
  63. {
  64. static VLCPlaybackService *sharedInstance = nil;
  65. static dispatch_once_t pred;
  66. dispatch_once(&pred, ^{
  67. sharedInstance = [VLCPlaybackService new];
  68. });
  69. return sharedInstance;
  70. }
  71. - (void)dealloc
  72. {
  73. _dialogProvider = nil;
  74. }
  75. - (instancetype)init
  76. {
  77. self = [super init];
  78. if (self) {
  79. // listen to audiosessions and appkit callback
  80. _externalAudioPlaybackDeviceConnected = [self isExternalAudioPlaybackDeviceConnected];
  81. NSNotificationCenter *defaultCenter = [NSNotificationCenter defaultCenter];
  82. [defaultCenter addObserver:self selector:@selector(audioSessionRouteChange:)
  83. name:AVAudioSessionRouteChangeNotification object:nil];
  84. [defaultCenter addObserver:self selector:@selector(handleInterruption:)
  85. name:AVAudioSessionInterruptionNotification object:[AVAudioSession sharedInstance]];
  86. // appkit because we neeed to know when we go to background in order to stop the video, so that we don't crash
  87. [defaultCenter addObserver:self selector:@selector(applicationWillResignActive:)
  88. name:UIApplicationWillResignActiveNotification object:nil];
  89. [defaultCenter addObserver:self selector:@selector(applicationDidBecomeActive:)
  90. name:UIApplicationDidBecomeActiveNotification object:nil];
  91. [defaultCenter addObserver:self selector:@selector(applicationDidEnterBackground:)
  92. name:UIApplicationDidEnterBackgroundNotification object:nil];
  93. _metadata = [VLCMetaData new];
  94. _dialogProvider = [[VLCDialogProvider alloc] initWithLibrary:[VLCLibrary sharedLibrary] customUI:YES];
  95. _customDialogHandler = [[VLCCustomDialogRendererHandler alloc]
  96. initWithDialogProvider:_dialogProvider];
  97. _dialogProvider.customRenderer = _customDialogHandler;
  98. _playbackSessionManagementLock = [[NSLock alloc] init];
  99. _shuffleMode = NO;
  100. _shuffleStack = [[NSMutableArray alloc] init];
  101. // Initialize a separate media player in order to play silence so that the application can
  102. // stay alive in background exclusively for Chromecast.
  103. _backgroundDummyPlayer = [[VLCMediaPlayer alloc] initWithOptions:@[@"--demux=rawaud"]];
  104. _backgroundDummyPlayer.media = [[VLCMedia alloc] initWithPath:@"/dev/zero"];
  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:VLCPlaybackServicePlaybackDidStart object:self];
  219. [_playbackSessionManagementLock unlock];
  220. }
  221. - (void)stopPlayback
  222. {
  223. BOOL ret = [_playbackSessionManagementLock tryLock];
  224. _isInFillToScreen = NO; // reset _isInFillToScreen after playback is finished
  225. if (!ret) {
  226. APLog(@"%s: locking failed", __PRETTY_FUNCTION__);
  227. return;
  228. }
  229. if (_mediaPlayer) {
  230. @try {
  231. [_mediaPlayer removeObserver:self forKeyPath:@"time"];
  232. [_mediaPlayer removeObserver:self forKeyPath:@"remainingTime"];
  233. }
  234. @catch (NSException *exception) {
  235. APLog(@"we weren't an observer yet");
  236. }
  237. if (_mediaPlayer.media) {
  238. [_mediaPlayer pause];
  239. #if TARGET_OS_IOS
  240. [_delegate savePlaybackState: self];
  241. #endif
  242. [_mediaPlayer stop];
  243. }
  244. _mediaPlayer = nil;
  245. _listPlayer = nil;
  246. }
  247. if (!_sessionWillRestart) {
  248. _mediaList = nil;
  249. }
  250. _playerIsSetup = NO;
  251. [_shuffleStack removeAllObjects];
  252. if (_playbackCompletion) {
  253. BOOL finishedPlaybackWithError = _mediaPlayer.state == VLCMediaPlayerStateError && !_sessionWillRestart;
  254. _playbackCompletion(!finishedPlaybackWithError);
  255. }
  256. [[self remoteControlService] unsubscribeFromRemoteCommands];
  257. [_playbackSessionManagementLock unlock];
  258. [[NSNotificationCenter defaultCenter] postNotificationName:VLCPlaybackServicePlaybackDidStop object:self];
  259. if (_sessionWillRestart) {
  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:VLCPlaybackServicePlaybackPositionUpdated
  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:VLCPlaybackServicePlaybackDidFail object:self];
  541. });
  542. _sessionWillRestart = NO;
  543. [self stopPlayback];
  544. } break;
  545. case VLCMediaPlayerStateEnded:
  546. case VLCMediaPlayerStateStopped: {
  547. NSInteger nextIndex = [self nextMediaIndex];
  548. if (nextIndex == -1) {
  549. _sessionWillRestart = NO;
  550. [self stopPlayback];
  551. } else {
  552. [_listPlayer playItemAtNumber:@(nextIndex)];
  553. [[NSNotificationCenter defaultCenter]
  554. postNotificationName:VLCPlaybackServicePlaybackMetadataDidChange object:self];
  555. }
  556. } break;
  557. default:
  558. break;
  559. }
  560. if ([self.delegate respondsToSelector:@selector(mediaPlayerStateChanged:isPlaying:currentMediaHasTrackToChooseFrom:currentMediaHasChapters:forPlaybackService:)])
  561. [self.delegate mediaPlayerStateChanged:currentState
  562. isPlaying:_mediaPlayer.isPlaying
  563. currentMediaHasTrackToChooseFrom:self.currentMediaHasTrackToChooseFrom
  564. currentMediaHasChapters:self.currentMediaHasChapters
  565. forPlaybackService:self];
  566. [self setNeedsMetadataUpdate];
  567. }
  568. #pragma mark - playback controls
  569. - (void)playPause
  570. {
  571. [_mediaPlayer isPlaying] ? [self pause] : [self play];
  572. }
  573. - (void)play
  574. {
  575. [_listPlayer play];
  576. [[NSNotificationCenter defaultCenter] postNotificationName:VLCPlaybackServicePlaybackDidResume object:self];
  577. }
  578. - (void)pause
  579. {
  580. [_listPlayer pause];
  581. #if TARGET_OS_IOS
  582. [_delegate savePlaybackState: self];
  583. #endif
  584. [[NSNotificationCenter defaultCenter] postNotificationName:VLCPlaybackServicePlaybackDidPause object:self];
  585. }
  586. - (void)setShuffleMode:(BOOL)shuffleMode
  587. {
  588. _shuffleMode = shuffleMode;
  589. if (_shuffleMode) {
  590. [_shuffleStack removeAllObjects];
  591. }
  592. }
  593. - (NSInteger)nextMediaIndex
  594. {
  595. NSInteger nextIndex = -1;
  596. NSInteger mediaListCount = _mediaList.count;
  597. NSUInteger currentIndex = [_mediaList indexOfMedia:_listPlayer.mediaPlayer.media];
  598. if (self.repeatMode == VLCRepeatCurrentItem) {
  599. return currentIndex;
  600. }
  601. if (_shuffleMode && mediaListCount > 2) {
  602. //Reached end of playlist
  603. if (_shuffleStack.count + 1 == mediaListCount) {
  604. if ([self repeatMode] == VLCDoNotRepeat)
  605. return -1;
  606. [_shuffleStack removeAllObjects];
  607. }
  608. [_shuffleStack addObject:@(currentIndex)];
  609. do {
  610. nextIndex = arc4random_uniform((uint32_t)mediaListCount);
  611. } while (currentIndex == nextIndex || [_shuffleStack containsObject:@(nextIndex)]);
  612. } else {
  613. // Normal playback
  614. if (currentIndex + 1 < mediaListCount) {
  615. nextIndex = currentIndex + 1;
  616. } else if ([self repeatMode] == VLCDoNotRepeat) {
  617. nextIndex = -1;
  618. }
  619. }
  620. return nextIndex;
  621. }
  622. - (void)next
  623. {
  624. if (_mediaList.count == 1) {
  625. NSNumber *skipLength = [[NSUserDefaults standardUserDefaults] valueForKey:kVLCSettingPlaybackForwardSkipLength];
  626. [_mediaPlayer jumpForward:skipLength.intValue];
  627. return;
  628. }
  629. NSInteger nextIndex = [self nextMediaIndex];
  630. if (nextIndex < 0) {
  631. return;
  632. }
  633. [_listPlayer playItemAtNumber:@(nextIndex)];
  634. [[NSNotificationCenter defaultCenter] postNotificationName:VLCPlaybackServicePlaybackMetadataDidChange object:self];
  635. }
  636. - (void)previous
  637. {
  638. if (_mediaList.count > 1) {
  639. [_listPlayer previous];
  640. [[NSNotificationCenter defaultCenter] postNotificationName:VLCPlaybackServicePlaybackMetadataDidChange object:self];
  641. }
  642. else {
  643. NSNumber *skipLength = [[NSUserDefaults standardUserDefaults] valueForKey:kVLCSettingPlaybackBackwardSkipLength];
  644. [_mediaPlayer jumpBackward:skipLength.intValue];
  645. }
  646. }
  647. - (void)jumpForward:(int)interval
  648. {
  649. [_mediaPlayer jumpForward:interval];
  650. }
  651. - (void)jumpBackward:(int)interval
  652. {
  653. [_mediaPlayer jumpBackward:interval];
  654. }
  655. - (UIScreen *)currentScreen
  656. {
  657. return [[UIDevice currentDevice] VLCHasExternalDisplay] ? [UIScreen screens][1] : [UIScreen mainScreen];
  658. }
  659. - (void)switchToFillToScreen
  660. {
  661. UIScreen *screen = [self currentScreen];
  662. CGSize screenSize = screen.bounds.size;
  663. CGSize videoSize = _mediaPlayer.videoSize;
  664. CGFloat ar = videoSize.width / (float)videoSize.height;
  665. CGFloat dar = screenSize.width / (float)screenSize.height;
  666. CGFloat scale;
  667. if (dar >= ar) {
  668. scale = screenSize.width / (float)videoSize.width;
  669. } else {
  670. scale = screenSize.height / (float)videoSize.height;
  671. }
  672. // Multiplied by screen.scale in consideration of pt to px
  673. _mediaPlayer.scaleFactor = scale * screen.scale;
  674. _isInFillToScreen = YES;
  675. }
  676. - (void)switchAspectRatio:(BOOL)toggleFullScreen
  677. {
  678. if (toggleFullScreen) {
  679. // Set previousAspectRatio to current, unless we're in full screen
  680. _previousAspectRatio = _isInFillToScreen ? _previousAspectRatio : _currentAspectRatio;
  681. _currentAspectRatio = _isInFillToScreen ? _previousAspectRatio : VLCAspectRatioFillToScreen;
  682. } else {
  683. // Increment unless hitting last aspectratio
  684. _currentAspectRatio = _currentAspectRatio == VLCAspectRatioSixteenToTen ? VLCAspectRatioDefault : _currentAspectRatio + 1;
  685. }
  686. // If fullScreen is toggled directly and then the aspect ratio changes, fullScreen is not reset
  687. if (_isInFillToScreen) _isInFillToScreen = NO;
  688. switch (_currentAspectRatio) {
  689. case VLCAspectRatioDefault:
  690. _mediaPlayer.scaleFactor = 0;
  691. _mediaPlayer.videoAspectRatio = NULL;
  692. _mediaPlayer.videoCropGeometry = NULL;
  693. break;
  694. case VLCAspectRatioFillToScreen:
  695. // Reset aspect ratio only with aspectRatio button since we want to keep
  696. // the user ratio with double tap.
  697. _mediaPlayer.videoAspectRatio = NULL;
  698. [self switchToFillToScreen];
  699. break;
  700. case VLCAspectRatioFourToThree:
  701. case VLCAspectRatioSixteenToTen:
  702. case VLCAspectRatioSixteenToNine:
  703. _mediaPlayer.scaleFactor = 0;
  704. _mediaPlayer.videoCropGeometry = NULL;
  705. _mediaPlayer.videoAspectRatio = (char *)[[self stringForAspectRatio:_currentAspectRatio] UTF8String];
  706. }
  707. if ([self.delegate respondsToSelector:@selector(showStatusMessage:)]) {
  708. [self.delegate showStatusMessage:[NSString stringWithFormat:NSLocalizedString(@"AR_CHANGED", nil), [self stringForAspectRatio:_currentAspectRatio]]];
  709. }
  710. if ([self.delegate respondsToSelector:@selector(playbackServiceDidSwitchAspectRatio:)]) {
  711. [_delegate playbackServiceDidSwitchAspectRatio:_currentAspectRatio];
  712. }
  713. }
  714. - (NSString *)stringForAspectRatio:(VLCAspectRatio)ratio
  715. {
  716. switch (ratio) {
  717. case VLCAspectRatioFillToScreen:
  718. return NSLocalizedString(@"FILL_TO_SCREEN", nil);
  719. case VLCAspectRatioDefault:
  720. return NSLocalizedString(@"DEFAULT", nil);
  721. case VLCAspectRatioFourToThree:
  722. return @"4:3";
  723. case VLCAspectRatioSixteenToTen:
  724. return @"16:10";
  725. case VLCAspectRatioSixteenToNine:
  726. return @"16:9";
  727. default:
  728. NSAssert(NO, @"this shouldn't happen");
  729. }
  730. }
  731. - (void)setVideoTrackEnabled:(BOOL)enabled
  732. {
  733. if (!enabled)
  734. _mediaPlayer.currentVideoTrackIndex = -1;
  735. else if (_mediaPlayer.currentVideoTrackIndex == -1) {
  736. for (NSNumber *trackId in _mediaPlayer.videoTrackIndexes) {
  737. if ([trackId intValue] != -1) {
  738. _mediaPlayer.currentVideoTrackIndex = [trackId intValue];
  739. break;
  740. }
  741. }
  742. }
  743. }
  744. - (void)setVideoOutputView:(UIView *)videoOutputView
  745. {
  746. if (videoOutputView) {
  747. if ([_actualVideoOutputView superview] != nil)
  748. [_actualVideoOutputView removeFromSuperview];
  749. _actualVideoOutputView.frame = (CGRect){CGPointZero, videoOutputView.frame.size};
  750. [self setVideoTrackEnabled:true];
  751. [videoOutputView addSubview:_actualVideoOutputView];
  752. [_actualVideoOutputView layoutSubviews];
  753. [_actualVideoOutputView updateConstraints];
  754. [_actualVideoOutputView setNeedsLayout];
  755. } else
  756. [_actualVideoOutputView removeFromSuperview];
  757. _videoOutputViewWrapper = videoOutputView;
  758. }
  759. - (UIView *)videoOutputView
  760. {
  761. return _videoOutputViewWrapper;
  762. }
  763. #pragma mark - 360 Support
  764. #if !TARGET_OS_TV
  765. - (BOOL)updateViewpoint:(CGFloat)yaw pitch:(CGFloat)pitch roll:(CGFloat)roll fov:(CGFloat)fov absolute:(BOOL)absolute
  766. {
  767. //adjusting the values
  768. if (fabs(yaw) > 180) {
  769. yaw = yaw > 0 ? yaw - 360 : yaw + 360;
  770. }
  771. if (fabs(roll) > 180) {
  772. roll = roll > 0 ? roll - 360 : roll + 360;
  773. }
  774. if (fabs(pitch) > 90) {
  775. pitch = pitch > 0 ? pitch - 180 : pitch + 180;
  776. }
  777. return [_mediaPlayer updateViewpoint:yaw pitch:pitch roll:roll fov:fov absolute:absolute];
  778. }
  779. - (CGFloat)yaw
  780. {
  781. return _mediaPlayer.yaw;
  782. }
  783. - (CGFloat)pitch
  784. {
  785. return _mediaPlayer.pitch;
  786. }
  787. - (CGFloat)roll
  788. {
  789. return _mediaPlayer.roll;
  790. }
  791. - (CGFloat)fov
  792. {
  793. return _mediaPlayer.fov;
  794. }
  795. - (BOOL)currentMediaIs360Video
  796. {
  797. return [self currentMediaProjection] == VLCMediaProjectionEquiRectangular;
  798. }
  799. - (NSInteger)currentMediaProjection
  800. {
  801. VLCMedia *media = [_mediaPlayer media];
  802. NSInteger currentVideoTrackIndex = [_mediaPlayer currentVideoTrackIndex];
  803. if (media && currentVideoTrackIndex >= 0) {
  804. NSArray *tracksInfo = media.tracksInformation;
  805. for (NSDictionary *track in tracksInfo) {
  806. if ([track[VLCMediaTracksInformationType] isEqualToString:VLCMediaTracksInformationTypeVideo]) {
  807. return [track[VLCMediaTracksInformationVideoProjection] integerValue];
  808. }
  809. }
  810. }
  811. return -1;
  812. }
  813. #endif
  814. #pragma mark - equalizer
  815. - (void)setAmplification:(CGFloat)amplification forBand:(unsigned int)index
  816. {
  817. if (!_mediaPlayer.equalizerEnabled)
  818. [_mediaPlayer setEqualizerEnabled:YES];
  819. [_mediaPlayer setAmplification:amplification forBand:index];
  820. // For some reason we have to apply again preamp to apply change
  821. [_mediaPlayer setPreAmplification:[_mediaPlayer preAmplification]];
  822. }
  823. - (CGFloat)amplificationOfBand:(unsigned int)index
  824. {
  825. return [_mediaPlayer amplificationOfBand:index];
  826. }
  827. - (NSArray *)equalizerProfiles
  828. {
  829. return _mediaPlayer.equalizerProfiles;
  830. }
  831. - (void)resetEqualizerFromProfile:(unsigned int)profile
  832. {
  833. _mediaPlayer.equalizerEnabled = profile != 0;
  834. [[NSUserDefaults standardUserDefaults] setBool:profile == 0 forKey:kVLCSettingEqualizerProfileDisabled];
  835. if (profile != 0) {
  836. [[NSUserDefaults standardUserDefaults] setObject:@(profile - 1) forKey:kVLCSettingEqualizerProfile];
  837. [_mediaPlayer resetEqualizerFromProfile:profile - 1];
  838. }
  839. }
  840. - (void)setPreAmplification:(CGFloat)preAmplification
  841. {
  842. if (!_mediaPlayer.equalizerEnabled)
  843. [_mediaPlayer setEqualizerEnabled:YES];
  844. [_mediaPlayer setPreAmplification:preAmplification];
  845. }
  846. - (CGFloat)preAmplification
  847. {
  848. return [_mediaPlayer preAmplification];
  849. }
  850. #pragma mark - AVAudioSession Notification Observers
  851. - (void)handleInterruption:(NSNotification *)notification
  852. {
  853. NSDictionary *userInfo = notification.userInfo;
  854. if (!userInfo || !userInfo[AVAudioSessionInterruptionTypeKey]) {
  855. return;
  856. }
  857. NSUInteger interruptionType = [userInfo[AVAudioSessionInterruptionTypeKey] unsignedIntegerValue];
  858. if (interruptionType == AVAudioSessionInterruptionTypeBegan) {
  859. [_mediaPlayer pause];
  860. } else if (interruptionType == AVAudioSessionInterruptionTypeEnded
  861. && [userInfo[AVAudioSessionInterruptionOptionKey] unsignedIntegerValue] == AVAudioSessionInterruptionOptionShouldResume) {
  862. [_mediaPlayer play];
  863. }
  864. }
  865. - (BOOL)isExternalAudioPlaybackDeviceConnected
  866. {
  867. /* check what output device is currently connected
  868. * this code assumes that everything which is not a builtin speaker, must be external */
  869. NSArray *outputs = [[AVAudioSession sharedInstance] currentRoute].outputs;
  870. AVAudioSessionPortDescription *outputDescription = outputs.firstObject;
  871. return ![outputDescription.portType isEqualToString:AVAudioSessionPortBuiltInSpeaker];
  872. }
  873. - (void)audioSessionRouteChange:(NSNotification *)notification
  874. {
  875. NSDictionary *userInfo = notification.userInfo;
  876. NSInteger routeChangeReason = [[userInfo valueForKey:AVAudioSessionRouteChangeReasonKey] integerValue];
  877. if (routeChangeReason == AVAudioSessionRouteChangeReasonRouteConfigurationChange)
  878. return;
  879. BOOL externalAudioPlaybackDeviceConnected = [self isExternalAudioPlaybackDeviceConnected];
  880. if (_externalAudioPlaybackDeviceConnected && !externalAudioPlaybackDeviceConnected && [_mediaPlayer isPlaying]) {
  881. APLog(@"Pausing playback as previously connected external audio playback device was removed");
  882. [_mediaPlayer pause];
  883. #if TARGET_OS_IOS
  884. [_delegate savePlaybackState: self];
  885. #endif
  886. [[NSNotificationCenter defaultCenter] postNotificationName:VLCPlaybackServicePlaybackDidPause object:self];
  887. }
  888. _externalAudioPlaybackDeviceConnected = externalAudioPlaybackDeviceConnected;
  889. }
  890. #pragma mark - Managing the media item
  891. - (VLCMedia *)currentlyPlayingMedia
  892. {
  893. return _mediaPlayer.media;
  894. }
  895. #pragma mark - metadata handling
  896. - (void)performNavigationAction:(VLCMediaPlaybackNavigationAction)action
  897. {
  898. [_mediaPlayer performNavigationAction:action];
  899. }
  900. - (void)mediaDidFinishParsing:(VLCMedia *)aMedia
  901. {
  902. [self setNeedsMetadataUpdate];
  903. }
  904. - (void)mediaMetaDataDidChange:(VLCMedia*)aMedia
  905. {
  906. [self setNeedsMetadataUpdate];
  907. }
  908. - (void)setNeedsMetadataUpdate
  909. {
  910. if (_needsMetadataUpdate == NO) {
  911. _needsMetadataUpdate = YES;
  912. dispatch_async(dispatch_get_main_queue(), ^{
  913. #if TARGET_OS_IOS
  914. VLCMLMedia *media = self->_mediaPlayer.media ? [self->_delegate mediaForPlayingMedia:self->_mediaPlayer.media] : nil;
  915. [self->_metadata updateMetadataFromMedia:media mediaPlayer:self->_mediaPlayer];
  916. #else
  917. [self->_metadata updateMetadataFromMediaPlayer:self->_mediaPlayer];
  918. #endif
  919. self->_needsMetadataUpdate = NO;
  920. [self recoverDisplayedMetadata];
  921. });
  922. }
  923. }
  924. #if TARGET_OS_IOS
  925. - (void)_recoverLastPlaybackState
  926. {
  927. VLCMLMedia *media = [_delegate mediaForPlayingMedia:_mediaPlayer.media];
  928. if (!media) return;
  929. CGFloat lastPosition = media.progress;
  930. // .95 prevents the controller from opening and closing immediatly when restoring state
  931. // Additionaly, check if the media is more than 10 sec
  932. if (lastPosition < .95
  933. && media.duration > 10000
  934. && _mediaPlayer.position < lastPosition) {
  935. NSInteger continuePlayback;
  936. if (media.type == VLCMLMediaTypeAudio)
  937. continuePlayback = [[[NSUserDefaults standardUserDefaults] objectForKey:kVLCSettingContinueAudioPlayback] integerValue];
  938. else
  939. continuePlayback = [[[NSUserDefaults standardUserDefaults] objectForKey:kVLCSettingContinuePlayback] integerValue];
  940. if (continuePlayback == 1) {
  941. [self setPlaybackPosition:lastPosition];
  942. } else if (continuePlayback == 0) {
  943. NSArray<VLCAlertButton *> *buttonsAction = @[[[VLCAlertButton alloc] initWithTitle: NSLocalizedString(@"BUTTON_CANCEL", nil)
  944. style: UIAlertActionStyleCancel
  945. action: nil],
  946. [[VLCAlertButton alloc] initWithTitle: NSLocalizedString(@"BUTTON_CONTINUE", nil)
  947. action: ^(UIAlertAction *action) {
  948. [self setPlaybackPosition:lastPosition];
  949. }]
  950. ];
  951. UIViewController *presentingVC = [UIApplication sharedApplication].delegate.window.rootViewController;
  952. presentingVC = presentingVC.presentedViewController ?: presentingVC;
  953. [VLCAlertViewController alertViewManagerWithTitle:NSLocalizedString(@"CONTINUE_PLAYBACK", nil)
  954. errorMessage:[NSString stringWithFormat:NSLocalizedString(@"CONTINUE_PLAYBACK_LONG", nil), media.title]
  955. viewController:presentingVC
  956. buttonsAction:buttonsAction];
  957. }
  958. }
  959. [self restoreAudioAndSubtitleTrack];
  960. }
  961. #endif
  962. - (void)recoverDisplayedMetadata
  963. {
  964. if ([self.delegate respondsToSelector:@selector(displayMetadataForPlaybackService:metadata:)])
  965. [self.delegate displayMetadataForPlaybackService:self metadata:_metadata];
  966. }
  967. - (void)recoverPlaybackState
  968. {
  969. if ([self.delegate respondsToSelector:@selector(mediaPlayerStateChanged:isPlaying:currentMediaHasTrackToChooseFrom:currentMediaHasChapters:forPlaybackService:)])
  970. [self.delegate mediaPlayerStateChanged:_mediaPlayer.state
  971. isPlaying:self.isPlaying
  972. currentMediaHasTrackToChooseFrom:self.currentMediaHasTrackToChooseFrom
  973. currentMediaHasChapters:self.currentMediaHasChapters
  974. forPlaybackService:self];
  975. if ([self.delegate respondsToSelector:@selector(prepareForMediaPlayback:)])
  976. [self.delegate prepareForMediaPlayback:self];
  977. }
  978. - (void)scheduleSleepTimerWithInterval:(NSTimeInterval)timeInterval
  979. {
  980. if (_sleepTimer) {
  981. [_sleepTimer invalidate];
  982. _sleepTimer = nil;
  983. }
  984. _sleepTimer = [NSTimer scheduledTimerWithTimeInterval:timeInterval target:self selector:@selector(stopPlayback) userInfo:nil repeats:NO];
  985. }
  986. - (BOOL)isPlayingOnExternalScreen
  987. {
  988. return (_renderer || [[UIDevice currentDevice] VLCHasExternalDisplay]);
  989. }
  990. #pragma mark - background interaction
  991. - (void)applicationWillResignActive:(NSNotification *)aNotification
  992. {
  993. #if TARGET_OS_IOS
  994. [_delegate savePlaybackState: self];
  995. #endif
  996. if (![self isPlayingOnExternalScreen]
  997. && ![[[NSUserDefaults standardUserDefaults] objectForKey:kVLCSettingContinueAudioInBackgroundKey] boolValue]) {
  998. if ([_mediaPlayer isPlaying]) {
  999. [_mediaPlayer pause];
  1000. _shouldResumePlaying = YES;
  1001. }
  1002. }
  1003. }
  1004. - (void)applicationDidEnterBackground:(NSNotification *)notification
  1005. {
  1006. _preBackgroundWrapperView = _videoOutputViewWrapper;
  1007. if (!_renderer && _mediaPlayer.audioTrackIndexes.count > 0)
  1008. [self setVideoTrackEnabled:false];
  1009. if (_renderer) {
  1010. [_backgroundDummyPlayer play];
  1011. }
  1012. }
  1013. - (void)applicationDidBecomeActive:(NSNotification *)notification
  1014. {
  1015. if (_preBackgroundWrapperView) {
  1016. [self setVideoOutputView:_preBackgroundWrapperView];
  1017. _preBackgroundWrapperView = nil;
  1018. }
  1019. if (_renderer) {
  1020. [_backgroundDummyPlayer stop];
  1021. }
  1022. [self setVideoTrackEnabled:true];
  1023. if (_shouldResumePlaying) {
  1024. _shouldResumePlaying = NO;
  1025. [_listPlayer play];
  1026. }
  1027. }
  1028. #pragma mark - remoteControlDelegate
  1029. - (void)remoteControlServiceHitPause:(VLCRemoteControlService *)rcs
  1030. {
  1031. [_listPlayer pause];
  1032. }
  1033. - (void)remoteControlServiceHitPlay:(VLCRemoteControlService *)rcs
  1034. {
  1035. [_listPlayer play];
  1036. }
  1037. - (void)remoteControlServiceTogglePlayPause:(VLCRemoteControlService *)rcs
  1038. {
  1039. [self playPause];
  1040. }
  1041. - (void)remoteControlServiceHitStop:(VLCRemoteControlService *)rcs
  1042. {
  1043. //TODO handle stop playback entirely
  1044. [_listPlayer stop];
  1045. }
  1046. - (BOOL)remoteControlServiceHitPlayNextIfPossible:(VLCRemoteControlService *)rcs
  1047. {
  1048. //TODO This doesn't handle shuffle or repeat yet
  1049. return [_listPlayer next];
  1050. }
  1051. - (BOOL)remoteControlServiceHitPlayPreviousIfPossible:(VLCRemoteControlService *)rcs
  1052. {
  1053. //TODO This doesn't handle shuffle or repeat yet
  1054. return [_listPlayer previous];
  1055. }
  1056. - (void)remoteControlService:(VLCRemoteControlService *)rcs jumpForwardInSeconds:(NSTimeInterval)seconds
  1057. {
  1058. [_mediaPlayer jumpForward:seconds];
  1059. }
  1060. - (void)remoteControlService:(VLCRemoteControlService *)rcs jumpBackwardInSeconds:(NSTimeInterval)seconds
  1061. {
  1062. [_mediaPlayer jumpBackward:seconds];
  1063. }
  1064. - (NSInteger)remoteControlServiceNumberOfMediaItemsinList:(VLCRemoteControlService *)rcs
  1065. {
  1066. return _mediaList.count;
  1067. }
  1068. - (void)remoteControlService:(VLCRemoteControlService *)rcs setPlaybackRate:(CGFloat)playbackRate
  1069. {
  1070. self.playbackRate = playbackRate;
  1071. }
  1072. - (void)remoteControlService:(VLCRemoteControlService *)rcs setCurrentPlaybackTime:(NSTimeInterval)playbackTime
  1073. {
  1074. float positionDiff = playbackTime - [self.metadata.elapsedPlaybackTime floatValue];
  1075. [_mediaPlayer jumpForward:positionDiff];
  1076. }
  1077. #pragma mark - helpers
  1078. - (NSDictionary *)mediaOptionsDictionary
  1079. {
  1080. NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
  1081. return @{ kVLCSettingNetworkCaching : [defaults objectForKey:kVLCSettingNetworkCaching],
  1082. kVLCSettingStretchAudio : [[defaults objectForKey:kVLCSettingStretchAudio] boolValue] ? kVLCSettingStretchAudioOnValue : kVLCSettingStretchAudioOffValue,
  1083. kVLCSettingTextEncoding : [defaults objectForKey:kVLCSettingTextEncoding],
  1084. kVLCSettingSkipLoopFilter : [defaults objectForKey:kVLCSettingSkipLoopFilter],
  1085. kVLCSettingHardwareDecoding : [defaults objectForKey:kVLCSettingHardwareDecoding],
  1086. kVLCForceSMBV1 : [NSNull null]
  1087. };
  1088. }
  1089. #pragma mark - Renderer
  1090. - (void)setRenderer:(VLCRendererItem * __nullable)renderer
  1091. {
  1092. _renderer = renderer;
  1093. [_mediaPlayer setRendererItem:_renderer];
  1094. }
  1095. #pragma mark - PlayerDisplayController
  1096. - (void)setPlayerDisplayController:(VLCPlayerDisplayController *)playerDisplayController
  1097. {
  1098. _playerDisplayController = playerDisplayController;
  1099. }
  1100. - (void)setPlayerHidden:(BOOL)hidden
  1101. {
  1102. [_playerDisplayController setEditing:hidden];
  1103. [_playerDisplayController dismissPlaybackView];
  1104. }
  1105. @end