VLCPlaybackController.m 43 KB

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