VLCPlaybackService.m 43 KB

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