VLCPlaybackController.m 43 KB

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