VLCPlaybackController.m 42 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329
  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. NSString *const VLCPlaybackControllerPlaybackDidStart = @"VLCPlaybackControllerPlaybackDidStart";
  26. NSString *const VLCPlaybackControllerPlaybackDidPause = @"VLCPlaybackControllerPlaybackDidPause";
  27. NSString *const VLCPlaybackControllerPlaybackDidResume = @"VLCPlaybackControllerPlaybackDidResume";
  28. NSString *const VLCPlaybackControllerPlaybackDidStop = @"VLCPlaybackControllerPlaybackDidStop";
  29. NSString *const VLCPlaybackControllerPlaybackMetadataDidChange = @"VLCPlaybackControllerPlaybackMetadataDidChange";
  30. NSString *const VLCPlaybackControllerPlaybackDidFail = @"VLCPlaybackControllerPlaybackDidFail";
  31. NSString *const VLCPlaybackControllerPlaybackPositionUpdated = @"VLCPlaybackControllerPlaybackPositionUpdated";
  32. typedef NS_ENUM(NSUInteger, VLCAspectRatio) {
  33. VLCAspectRatioDefault = 0,
  34. VLCAspectRatioFillToScreen,
  35. VLCAspectRatioFourToThree,
  36. VLCAspectRatioSixteenToNine,
  37. VLCAspectRatioSixteenToTen,
  38. };
  39. @interface VLCPlaybackController () <VLCMediaPlayerDelegate, VLCMediaDelegate, VLCRemoteControlServiceDelegate>
  40. {
  41. VLCRemoteControlService *_remoteControlService;
  42. VLCMediaPlayer *_mediaPlayer;
  43. VLCMediaListPlayer *_listPlayer;
  44. BOOL _playerIsSetup;
  45. BOOL _shouldResumePlaying;
  46. BOOL _sessionWillRestart;
  47. NSString *_pathToExternalSubtitlesFile;
  48. int _itemInMediaListToBePlayedFirst;
  49. NSTimer *_sleepTimer;
  50. NSUInteger _currentAspectRatio;
  51. UIView *_videoOutputViewWrapper;
  52. UIView *_actualVideoOutputView;
  53. UIView *_preBackgroundWrapperView;
  54. BOOL _needsMetadataUpdate;
  55. BOOL _mediaWasJustStarted;
  56. BOOL _recheckForExistingThumbnail;
  57. BOOL _headphonesWasPlugged;
  58. NSLock *_playbackSessionManagementLock;
  59. VLCDialogProvider *_dialogProvider;
  60. NSMutableArray *_shuffleStack;
  61. }
  62. @end
  63. @implementation VLCPlaybackController
  64. #pragma mark instance management
  65. + (VLCPlaybackController *)sharedInstance
  66. {
  67. static VLCPlaybackController *sharedInstance = nil;
  68. static dispatch_once_t pred;
  69. dispatch_once(&pred, ^{
  70. sharedInstance = [VLCPlaybackController new];
  71. });
  72. return sharedInstance;
  73. }
  74. - (void)dealloc
  75. {
  76. _dialogProvider = nil;
  77. }
  78. - (instancetype)init
  79. {
  80. self = [super init];
  81. if (self) {
  82. // listen to audiosessions and appkit callback
  83. _headphonesWasPlugged = [self areHeadphonesPlugged];
  84. NSNotificationCenter *defaultCenter = [NSNotificationCenter defaultCenter];
  85. [defaultCenter addObserver:self selector:@selector(audioSessionRouteChange:)
  86. name:AVAudioSessionRouteChangeNotification object:nil];
  87. [defaultCenter addObserver:self selector:@selector(handleInterruption:)
  88. name:AVAudioSessionInterruptionNotification object:[AVAudioSession sharedInstance]];
  89. // appkit because we neeed to know when we go to background in order to stop the video, so that we don't crash
  90. [defaultCenter addObserver:self selector:@selector(applicationWillResignActive:)
  91. name:UIApplicationWillResignActiveNotification object:nil];
  92. [defaultCenter addObserver:self selector:@selector(applicationDidBecomeActive:)
  93. name:UIApplicationDidBecomeActiveNotification object:nil];
  94. [defaultCenter addObserver:self selector:@selector(applicationDidEnterBackground:)
  95. name:UIApplicationDidEnterBackgroundNotification object:nil];
  96. _metadata = [VLCMetaData new];
  97. _dialogProvider = [[VLCDialogProvider alloc] initWithLibrary:[VLCLibrary sharedLibrary] customUI:NO];
  98. _playbackSessionManagementLock = [[NSLock alloc] init];
  99. _shuffleMode = NO;
  100. _shuffleStack = [[NSMutableArray alloc] init];
  101. }
  102. return self;
  103. }
  104. - (VLCRemoteControlService *)remoteControlService
  105. {
  106. if (!_remoteControlService) {
  107. _remoteControlService = [[VLCRemoteControlService alloc] init];
  108. _remoteControlService.remoteControlServiceDelegate = self;
  109. }
  110. return _remoteControlService;
  111. }
  112. #pragma mark - playback management
  113. - (void)openVideoSubTitlesFromFile:(NSString *)pathToFile
  114. {
  115. [_mediaPlayer addPlaybackSlave:[NSURL fileURLWithPath:pathToFile] type:VLCMediaPlaybackSlaveTypeSubtitle enforce:YES];
  116. }
  117. - (void)playMediaList:(VLCMediaList *)mediaList firstIndex:(NSInteger)index subtitlesFilePath:(NSString *)subsFilePath
  118. {
  119. self.mediaList = mediaList;
  120. _itemInMediaListToBePlayedFirst = (int)index;
  121. _pathToExternalSubtitlesFile = subsFilePath;
  122. _sessionWillRestart = _playerIsSetup;
  123. _playerIsSetup ? [self stopPlayback] : [self startPlayback];
  124. }
  125. - (VLCTime *)playedTime
  126. {
  127. return [_mediaPlayer time];
  128. }
  129. - (void)startPlayback
  130. {
  131. if (_playerIsSetup) {
  132. APLog(@"%s: player is already setup, bailing out", __PRETTY_FUNCTION__);
  133. return;
  134. }
  135. BOOL ret = [_playbackSessionManagementLock tryLock];
  136. if (!ret) {
  137. APLog(@"%s: locking failed", __PRETTY_FUNCTION__);
  138. return;
  139. }
  140. NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
  141. if (!self.mediaList) {
  142. APLog(@"%s: no URL and no media list set, stopping playback", __PRETTY_FUNCTION__);
  143. [_playbackSessionManagementLock unlock];
  144. [self stopPlayback];
  145. return;
  146. }
  147. /* video decoding permanently fails if we don't provide a UIView to draw into on init
  148. * hence we provide one which is not attached to any view controller for off-screen drawing
  149. * and disable video decoding once playback started */
  150. _actualVideoOutputView = [[UIView alloc] initWithFrame:[UIScreen mainScreen].bounds];
  151. _actualVideoOutputView.autoresizingMask = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight;
  152. _actualVideoOutputView.autoresizesSubviews = YES;
  153. if (_pathToExternalSubtitlesFile)
  154. _listPlayer = [[VLCMediaListPlayer alloc] initWithOptions:@[[NSString stringWithFormat:@"--%@=%@", kVLCSettingSubtitlesFilePath, _pathToExternalSubtitlesFile]] andDrawable:_actualVideoOutputView];
  155. else
  156. _listPlayer = [[VLCMediaListPlayer alloc] initWithDrawable:_actualVideoOutputView];
  157. /* to enable debug logging for the playback library instance, switch the boolean below
  158. * note that the library instance used for playback may not necessarily match the instance
  159. * used for media discovery or thumbnailing */
  160. _listPlayer.mediaPlayer.libraryInstance.debugLogging = NO;
  161. _mediaPlayer = _listPlayer.mediaPlayer;
  162. [_mediaPlayer setDelegate:self];
  163. if ([[defaults objectForKey:kVLCSettingPlaybackSpeedDefaultValue] floatValue] != 0)
  164. [_mediaPlayer setRate: [[defaults objectForKey:kVLCSettingPlaybackSpeedDefaultValue] floatValue]];
  165. if ([[defaults objectForKey:kVLCSettingDeinterlace] intValue] != 0)
  166. [_mediaPlayer setDeinterlaceFilter:@"blend"];
  167. else
  168. [_mediaPlayer setDeinterlaceFilter:nil];
  169. if (_pathToExternalSubtitlesFile)
  170. [_mediaPlayer addPlaybackSlave:[NSURL fileURLWithPath:_pathToExternalSubtitlesFile] type:VLCMediaPlaybackSlaveTypeSubtitle enforce:YES];
  171. VLCMedia *media = [_mediaList mediaAtIndex:_itemInMediaListToBePlayedFirst];
  172. [media parseWithOptions:VLCMediaParseLocal];
  173. media.delegate = self;
  174. [media addOptions:self.mediaOptionsDictionary];
  175. [_listPlayer setMediaList:self.mediaList];
  176. [_listPlayer setRepeatMode:VLCDoNotRepeat];
  177. [_playbackSessionManagementLock unlock];
  178. [self _playNewMedia];
  179. }
  180. - (void)_playNewMedia
  181. {
  182. BOOL ret = [_playbackSessionManagementLock tryLock];
  183. if (!ret) {
  184. APLog(@"%s: locking failed", __PRETTY_FUNCTION__);
  185. return;
  186. }
  187. // Set last selected equalizer profile
  188. unsigned int profile = (unsigned int)[[[NSUserDefaults standardUserDefaults] objectForKey:kVLCSettingEqualizerProfile] integerValue];
  189. [_mediaPlayer resetEqualizerFromProfile:profile];
  190. [_mediaPlayer setPreAmplification:[_mediaPlayer preAmplification]];
  191. _mediaWasJustStarted = YES;
  192. [_mediaPlayer addObserver:self forKeyPath:@"time" options:0 context:nil];
  193. [_mediaPlayer addObserver:self forKeyPath:@"remainingTime" options:0 context:nil];
  194. [_listPlayer playItemAtNumber:@(_itemInMediaListToBePlayedFirst)];
  195. if ([self.delegate respondsToSelector:@selector(prepareForMediaPlayback:)])
  196. [self.delegate prepareForMediaPlayback:self];
  197. _currentAspectRatio = VLCAspectRatioDefault;
  198. _mediaPlayer.videoAspectRatio = NULL;
  199. _mediaPlayer.videoCropGeometry = NULL;
  200. [[self remoteControlService] subscribeToRemoteCommands];
  201. _playerIsSetup = YES;
  202. [[NSNotificationCenter defaultCenter] postNotificationName:VLCPlaybackControllerPlaybackDidStart object:self];
  203. [_playbackSessionManagementLock unlock];
  204. }
  205. - (void)stopPlayback
  206. {
  207. BOOL ret = [_playbackSessionManagementLock tryLock];
  208. if (!ret) {
  209. APLog(@"%s: locking failed", __PRETTY_FUNCTION__);
  210. return;
  211. }
  212. if (_mediaPlayer) {
  213. @try {
  214. [_mediaPlayer removeObserver:self forKeyPath:@"time"];
  215. [_mediaPlayer removeObserver:self forKeyPath:@"remainingTime"];
  216. }
  217. @catch (NSException *exception) {
  218. APLog(@"we weren't an observer yet");
  219. }
  220. if (_mediaPlayer.media) {
  221. [_mediaPlayer pause];
  222. #if TARGET_OS_IOS
  223. [self _savePlaybackState];
  224. #endif
  225. [_mediaPlayer stop];
  226. }
  227. _mediaPlayer = nil;
  228. _listPlayer = nil;
  229. }
  230. if (!_sessionWillRestart) {
  231. _mediaList = nil;
  232. if (_pathToExternalSubtitlesFile) {
  233. NSFileManager *fileManager = [NSFileManager defaultManager];
  234. if ([fileManager fileExistsAtPath:_pathToExternalSubtitlesFile])
  235. [fileManager removeItemAtPath:_pathToExternalSubtitlesFile error:nil];
  236. _pathToExternalSubtitlesFile = nil;
  237. }
  238. }
  239. _playerIsSetup = NO;
  240. [_shuffleStack removeAllObjects];
  241. if (@available(iOS 10, *)) {
  242. if (_errorCallback && _mediaPlayer.state == VLCMediaPlayerStateError && !_sessionWillRestart)
  243. [[UIApplication sharedApplication] openURL:_errorCallback options:@{} completionHandler:nil];
  244. else if (_successCallback && !_sessionWillRestart)
  245. [[UIApplication sharedApplication] openURL:_successCallback options:@{} completionHandler:nil];
  246. } else {
  247. #pragma clang diagnostic push
  248. #pragma clang diagnostic ignored "-Wdeprecated-declarations"
  249. /* UIApplication's replacement calls require iOS 10 or later, which we can't enforce as of yet */
  250. if (_errorCallback && _mediaPlayer.state == VLCMediaPlayerStateError && !_sessionWillRestart)
  251. [[UIApplication sharedApplication] openURL:_errorCallback];
  252. else if (_successCallback && !_sessionWillRestart)
  253. [[UIApplication sharedApplication] openURL:_successCallback];
  254. #pragma clang diagnostic pop
  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. VLCRepeatMode nextRepeatMode = VLCDoNotRepeat;
  487. switch (_listPlayer.repeatMode) {
  488. case VLCDoNotRepeat:
  489. nextRepeatMode = VLCRepeatCurrentItem;
  490. break;
  491. case VLCRepeatCurrentItem:
  492. nextRepeatMode = VLCRepeatAllItems;
  493. break;
  494. default:
  495. nextRepeatMode = VLCDoNotRepeat;
  496. break;
  497. }
  498. _listPlayer.repeatMode = nextRepeatMode;
  499. }
  500. - (NSInteger)indexOfCurrentAudioTrack
  501. {
  502. return [_mediaPlayer.audioTrackIndexes indexOfObject:@(_mediaPlayer.currentAudioTrackIndex)];
  503. }
  504. - (NSInteger)indexOfCurrentSubtitleTrack
  505. {
  506. return [_mediaPlayer.videoSubTitlesIndexes indexOfObject:@(_mediaPlayer.currentVideoSubTitleIndex)];
  507. }
  508. - (NSInteger)indexOfCurrentChapter
  509. {
  510. return _mediaPlayer.currentChapterIndex;
  511. }
  512. - (NSInteger)indexOfCurrentTitle
  513. {
  514. return _mediaPlayer.currentTitleIndex;
  515. }
  516. - (NSInteger)numberOfAudioTracks
  517. {
  518. return _mediaPlayer.audioTrackIndexes.count;
  519. }
  520. - (NSInteger)numberOfVideoSubtitlesIndexes
  521. {
  522. return _mediaPlayer.videoSubTitlesIndexes.count;
  523. }
  524. - (NSInteger)numberOfTitles
  525. {
  526. return [_mediaPlayer numberOfTitles];
  527. }
  528. - (NSInteger)numberOfChaptersForCurrentTitle
  529. {
  530. return [_mediaPlayer numberOfChaptersForTitle:_mediaPlayer.currentTitleIndex];
  531. }
  532. - (NSString *)videoSubtitleNameAtIndex:(NSInteger)index
  533. {
  534. if (index >= 0 && index < _mediaPlayer.videoSubTitlesNames.count)
  535. return _mediaPlayer.videoSubTitlesNames[index];
  536. return nil;
  537. }
  538. - (NSString *)audioTrackNameAtIndex:(NSInteger)index
  539. {
  540. if (index >= 0 && index < _mediaPlayer.audioTrackNames.count)
  541. return _mediaPlayer.audioTrackNames[index];
  542. return nil;
  543. }
  544. - (NSDictionary *)titleDescriptionsDictAtIndex:(NSInteger)index
  545. {
  546. if (index >= 0 && index < _mediaPlayer.titleDescriptions.count)
  547. return _mediaPlayer.titleDescriptions[index];
  548. return nil;
  549. }
  550. - (NSDictionary *)chapterDescriptionsDictAtIndex:(NSInteger)index
  551. {
  552. NSArray *chapterDescriptions = [_mediaPlayer chapterDescriptionsOfTitle:_mediaPlayer.currentTitleIndex];
  553. if (index >= 0 && index < chapterDescriptions.count)
  554. return chapterDescriptions[index];
  555. return nil;
  556. }
  557. - (void)selectAudioTrackAtIndex:(NSInteger)index
  558. {
  559. if (index >= 0 && index < _mediaPlayer.audioTrackIndexes.count) {
  560. //we can cast this cause we won't have more than 2 million audiotracks
  561. _mediaPlayer.currentAudioTrackIndex = [_mediaPlayer.audioTrackIndexes[index] intValue];
  562. }
  563. }
  564. - (void)selectVideoSubtitleAtIndex:(NSInteger)index
  565. {
  566. if (index >= 0 && index < _mediaPlayer.videoSubTitlesIndexes.count) {
  567. _mediaPlayer.currentVideoSubTitleIndex = [_mediaPlayer.videoSubTitlesIndexes[index] intValue];
  568. }
  569. }
  570. - (void)selectTitleAtIndex:(NSInteger)index
  571. {
  572. if (index >= 0 && index < [_mediaPlayer numberOfTitles]) {
  573. //we can cast this cause we won't have more than 2 million titles
  574. _mediaPlayer.currentTitleIndex = (int)index;
  575. }
  576. }
  577. - (void)selectChapterAtIndex:(NSInteger)index
  578. {
  579. if (index >= 0 && index < [self numberOfChaptersForCurrentTitle]) {
  580. //we can cast this cause we won't have more than 2 million chapters
  581. _mediaPlayer.currentChapterIndex = (int)index;
  582. }
  583. }
  584. - (void)shortJumpForward
  585. {
  586. [_mediaPlayer shortJumpForward];
  587. }
  588. - (void)shortJumpBackward
  589. {
  590. [_mediaPlayer shortJumpBackward];
  591. }
  592. - (VLCTime *)remainingTime
  593. {
  594. return [_mediaPlayer remainingTime];
  595. }
  596. - (void)setAudioPassthrough:(BOOL)shouldPass
  597. {
  598. _mediaPlayer.audio.passthrough = shouldPass;
  599. }
  600. - (void)mediaPlayerStateChanged:(NSNotification *)aNotification
  601. {
  602. VLCMediaPlayerState currentState = _mediaPlayer.state;
  603. switch (currentState) {
  604. case VLCMediaPlayerStateBuffering: {
  605. /* attach delegate */
  606. _mediaPlayer.media.delegate = self;
  607. /* on-the-fly values through hidden API */
  608. NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
  609. #pragma clang diagnostic push
  610. #pragma clang diagnostic ignored "-Wundeclared-selector"
  611. [_mediaPlayer performSelector:@selector(setTextRendererFont:) withObject:[defaults objectForKey:kVLCSettingSubtitlesFont]];
  612. [_mediaPlayer performSelector:@selector(setTextRendererFontSize:) withObject:[defaults objectForKey:kVLCSettingSubtitlesFontSize]];
  613. [_mediaPlayer performSelector:@selector(setTextRendererFontColor:) withObject:[defaults objectForKey:kVLCSettingSubtitlesFontColor]];
  614. [_mediaPlayer performSelector:@selector(setTextRendererFontForceBold:) withObject:[defaults objectForKey:kVLCSettingSubtitlesBoldFont]];
  615. #pragma clang diagnostic pop
  616. } break;
  617. case VLCMediaPlayerStateError: {
  618. APLog(@"Playback failed");
  619. dispatch_async(dispatch_get_main_queue(),^{
  620. [[NSNotificationCenter defaultCenter] postNotificationName:VLCPlaybackControllerPlaybackDidFail object:self];
  621. });
  622. _sessionWillRestart = NO;
  623. [self stopPlayback];
  624. } break;
  625. case VLCMediaPlayerStateEnded:
  626. case VLCMediaPlayerStateStopped: {
  627. [_listPlayer.mediaList lock];
  628. NSUInteger listCount = _listPlayer.mediaList.count;
  629. if ([_listPlayer.mediaList indexOfMedia:_mediaPlayer.media] == listCount - 1 && self.repeatMode == VLCDoNotRepeat) {
  630. [_listPlayer.mediaList unlock];
  631. _sessionWillRestart = NO;
  632. [self stopPlayback];
  633. return;
  634. } else if (listCount > 1) {
  635. [_listPlayer.mediaList unlock];
  636. [_listPlayer next];
  637. } else
  638. [_listPlayer.mediaList unlock];
  639. } break;
  640. case VLCMediaPlayerStateESAdded: {
  641. #if TARGET_OS_IOS
  642. [self restoreAudioAndSubtitleTrack];
  643. #endif
  644. } break;
  645. default:
  646. break;
  647. }
  648. if ([self.delegate respondsToSelector:@selector(mediaPlayerStateChanged:isPlaying:currentMediaHasTrackToChooseFrom:currentMediaHasChapters:forPlaybackController:)])
  649. [self.delegate mediaPlayerStateChanged:currentState
  650. isPlaying:_mediaPlayer.isPlaying
  651. currentMediaHasTrackToChooseFrom:self.currentMediaHasTrackToChooseFrom
  652. currentMediaHasChapters:self.currentMediaHasChapters
  653. forPlaybackController:self];
  654. [self setNeedsMetadataUpdate];
  655. }
  656. #pragma mark - playback controls
  657. - (void)playPause
  658. {
  659. [_mediaPlayer isPlaying] ? [self pause] : [self play];
  660. }
  661. - (void)play
  662. {
  663. [_listPlayer play];
  664. [[NSNotificationCenter defaultCenter] postNotificationName:VLCPlaybackControllerPlaybackDidResume object:self];
  665. }
  666. - (void)pause
  667. {
  668. [_listPlayer pause];
  669. #if TARGET_OS_IOS
  670. [self _savePlaybackState];
  671. #endif
  672. [[NSNotificationCenter defaultCenter] postNotificationName:VLCPlaybackControllerPlaybackDidPause object:self];
  673. }
  674. - (void)next
  675. {
  676. NSInteger mediaListCount = _mediaList.count;
  677. #if TARGET_OS_IOS
  678. if (self.repeatMode != VLCRepeatCurrentItem && mediaListCount > 2 && _shuffleMode) {
  679. NSNumber *nextIndex;
  680. NSUInteger currentIndex = [_mediaList indexOfMedia:_listPlayer.mediaPlayer.media];
  681. //Reached end of playlist
  682. if (_shuffleStack.count + 1 == mediaListCount) {
  683. if ([self repeatMode] == VLCDoNotRepeat)
  684. return;
  685. [_shuffleStack removeAllObjects];
  686. }
  687. [_shuffleStack addObject:[NSNumber numberWithUnsignedInteger:currentIndex]];
  688. do {
  689. nextIndex = [NSNumber numberWithUnsignedInt:arc4random_uniform((uint32_t)mediaListCount)];
  690. } while (currentIndex == nextIndex.unsignedIntegerValue || [_shuffleStack containsObject:nextIndex]);
  691. [_listPlayer playItemAtNumber:[NSNumber numberWithUnsignedInteger:nextIndex.unsignedIntegerValue]];
  692. [[NSNotificationCenter defaultCenter] postNotificationName:VLCPlaybackControllerPlaybackMetadataDidChange object:self];
  693. return;
  694. }
  695. #endif
  696. if (mediaListCount > 1) {
  697. [_listPlayer next];
  698. [[NSNotificationCenter defaultCenter] postNotificationName:VLCPlaybackControllerPlaybackMetadataDidChange object:self];
  699. } else {
  700. NSNumber *skipLength = [[NSUserDefaults standardUserDefaults] valueForKey:kVLCSettingPlaybackForwardSkipLength];
  701. [_mediaPlayer jumpForward:skipLength.intValue];
  702. }
  703. }
  704. - (void)previous
  705. {
  706. if (_mediaList.count > 1) {
  707. [_listPlayer previous];
  708. [[NSNotificationCenter defaultCenter] postNotificationName:VLCPlaybackControllerPlaybackMetadataDidChange object:self];
  709. }
  710. else {
  711. NSNumber *skipLength = [[NSUserDefaults standardUserDefaults] valueForKey:kVLCSettingPlaybackBackwardSkipLength];
  712. [_mediaPlayer jumpBackward:skipLength.intValue];
  713. }
  714. }
  715. - (void)jumpForward:(int)interval
  716. {
  717. [_mediaPlayer jumpForward:interval];
  718. }
  719. - (void)jumpBackward:(int)interval
  720. {
  721. [_mediaPlayer jumpBackward:interval];
  722. }
  723. - (NSString *)screenAspectRatio
  724. {
  725. UIScreen *screen = [[UIDevice currentDevice] VLCHasExternalDisplay] ? [UIScreen screens][1] : [UIScreen mainScreen];
  726. return [NSString stringWithFormat:@"%d:%d", (int)screen.bounds.size.width, (int)screen.bounds.size.height];
  727. }
  728. - (void)switchIPhoneXFullScreen
  729. {
  730. BOOL inFullScreen = _mediaPlayer.videoCropGeometry && [[NSString stringWithUTF8String:_mediaPlayer.videoCropGeometry] isEqualToString:[self screenAspectRatio]];
  731. if (inFullScreen) {
  732. const char *previousAspectRatio = _currentAspectRatio == VLCAspectRatioDefault ? NULL : [[self stringForAspectRatio:_currentAspectRatio] UTF8String];
  733. _mediaPlayer.videoAspectRatio = (char *)previousAspectRatio;
  734. }
  735. _mediaPlayer.videoCropGeometry = inFullScreen ? NULL : (char *)[[self screenAspectRatio] UTF8String];
  736. }
  737. - (void)switchAspectRatio
  738. {
  739. _currentAspectRatio = _currentAspectRatio == VLCAspectRatioSixteenToTen ? VLCAspectRatioDefault : _currentAspectRatio + 1;
  740. switch (_currentAspectRatio) {
  741. case VLCAspectRatioDefault:
  742. _mediaPlayer.videoAspectRatio = NULL;
  743. _mediaPlayer.videoCropGeometry = NULL;
  744. break;
  745. case VLCAspectRatioFillToScreen:
  746. _mediaPlayer.videoCropGeometry = (char *)[[self screenAspectRatio] UTF8String];
  747. break;
  748. case VLCAspectRatioFourToThree:
  749. case VLCAspectRatioSixteenToTen:
  750. case VLCAspectRatioSixteenToNine:
  751. _mediaPlayer.videoCropGeometry = NULL;
  752. _mediaPlayer.videoAspectRatio = (char *)[[self stringForAspectRatio:_currentAspectRatio] UTF8String];
  753. }
  754. if ([self.delegate respondsToSelector:@selector(showStatusMessage:forPlaybackController:)]) {
  755. [self.delegate showStatusMessage:[NSString stringWithFormat:NSLocalizedString(@"AR_CHANGED", nil), [self stringForAspectRatio:_currentAspectRatio]] forPlaybackController:self];
  756. }
  757. }
  758. - (NSString *)stringForAspectRatio:(VLCAspectRatio)ratio
  759. {
  760. switch (ratio) {
  761. case VLCAspectRatioFillToScreen:
  762. return NSLocalizedString(@"FILL_TO_SCREEN", nil);
  763. case VLCAspectRatioDefault:
  764. return NSLocalizedString(@"DEFAULT", nil);
  765. case VLCAspectRatioFourToThree:
  766. return @"4:3";
  767. case VLCAspectRatioSixteenToTen:
  768. return @"16:10";
  769. case VLCAspectRatioSixteenToNine:
  770. return @"16:9";
  771. default:
  772. NSAssert(NO, @"this shouldn't happen");
  773. }
  774. }
  775. - (void)setVideoTrackEnabled:(BOOL)enabled
  776. {
  777. if (!enabled)
  778. _mediaPlayer.currentVideoTrackIndex = -1;
  779. else if (_mediaPlayer.currentVideoTrackIndex == -1) {
  780. for (NSNumber *trackId in _mediaPlayer.videoTrackIndexes) {
  781. if ([trackId intValue] != -1) {
  782. _mediaPlayer.currentVideoTrackIndex = [trackId intValue];
  783. break;
  784. }
  785. }
  786. }
  787. }
  788. - (void)setVideoOutputView:(UIView *)videoOutputView
  789. {
  790. if (videoOutputView) {
  791. if ([_actualVideoOutputView superview] != nil)
  792. [_actualVideoOutputView removeFromSuperview];
  793. _actualVideoOutputView.frame = (CGRect){CGPointZero, videoOutputView.frame.size};
  794. [self setVideoTrackEnabled:true];
  795. [videoOutputView addSubview:_actualVideoOutputView];
  796. [_actualVideoOutputView layoutSubviews];
  797. [_actualVideoOutputView updateConstraints];
  798. [_actualVideoOutputView setNeedsLayout];
  799. } else
  800. [_actualVideoOutputView removeFromSuperview];
  801. _videoOutputViewWrapper = videoOutputView;
  802. }
  803. - (UIView *)videoOutputView
  804. {
  805. return _videoOutputViewWrapper;
  806. }
  807. #pragma mark - 360 Support
  808. #if !TARGET_OS_TV
  809. - (BOOL)updateViewpoint:(CGFloat)yaw pitch:(CGFloat)pitch roll:(CGFloat)roll fov:(CGFloat)fov absolute:(BOOL)absolute
  810. {
  811. //adjusting the values
  812. if (fabs(yaw) > 180) {
  813. yaw = yaw > 0 ? yaw - 360 : yaw + 360;
  814. }
  815. if (fabs(roll) > 180) {
  816. roll = roll > 0 ? roll - 360 : roll + 360;
  817. }
  818. if (fabs(pitch) > 90) {
  819. pitch = pitch > 0 ? pitch - 180 : pitch + 180;
  820. }
  821. return [_mediaPlayer updateViewpoint:yaw pitch:pitch roll:roll fov:fov absolute:absolute];
  822. }
  823. - (CGFloat)yaw
  824. {
  825. return _mediaPlayer.yaw;
  826. }
  827. - (CGFloat)pitch
  828. {
  829. return _mediaPlayer.pitch;
  830. }
  831. - (CGFloat)roll
  832. {
  833. return _mediaPlayer.roll;
  834. }
  835. - (CGFloat)fov
  836. {
  837. return _mediaPlayer.fov;
  838. }
  839. - (BOOL)currentMediaIs360Video
  840. {
  841. return [self currentMediaProjection] == VLCMediaProjectionEquiRectangular;
  842. }
  843. - (NSInteger)currentMediaProjection
  844. {
  845. VLCMedia *media = [_mediaPlayer media];
  846. NSInteger currentVideoTrackIndex = [_mediaPlayer currentVideoTrackIndex];
  847. if (media && currentVideoTrackIndex >= 0) {
  848. NSArray *tracksInfo = media.tracksInformation;
  849. for (NSDictionary *track in tracksInfo) {
  850. if ([track[VLCMediaTracksInformationType] isEqualToString:VLCMediaTracksInformationTypeVideo]) {
  851. return [track[VLCMediaTracksInformationVideoProjection] integerValue];
  852. }
  853. }
  854. }
  855. return -1;
  856. }
  857. #endif
  858. #pragma mark - equalizer
  859. - (void)setAmplification:(CGFloat)amplification forBand:(unsigned int)index
  860. {
  861. if (!_mediaPlayer.equalizerEnabled)
  862. [_mediaPlayer setEqualizerEnabled:YES];
  863. [_mediaPlayer setAmplification:amplification forBand:index];
  864. // For some reason we have to apply again preamp to apply change
  865. [_mediaPlayer setPreAmplification:[_mediaPlayer preAmplification]];
  866. }
  867. - (CGFloat)amplificationOfBand:(unsigned int)index
  868. {
  869. return [_mediaPlayer amplificationOfBand:index];
  870. }
  871. - (NSArray *)equalizerProfiles
  872. {
  873. return _mediaPlayer.equalizerProfiles;
  874. }
  875. - (void)resetEqualizerFromProfile:(unsigned int)profile
  876. {
  877. [[NSUserDefaults standardUserDefaults] setObject:@(profile) forKey:kVLCSettingEqualizerProfile];
  878. [_mediaPlayer resetEqualizerFromProfile:profile];
  879. }
  880. - (void)setPreAmplification:(CGFloat)preAmplification
  881. {
  882. if (!_mediaPlayer.equalizerEnabled)
  883. [_mediaPlayer setEqualizerEnabled:YES];
  884. [_mediaPlayer setPreAmplification:preAmplification];
  885. }
  886. - (CGFloat)preAmplification
  887. {
  888. return [_mediaPlayer preAmplification];
  889. }
  890. #pragma mark - AVAudioSession Notification Observers
  891. - (void)handleInterruption:(NSNotification *)notification
  892. {
  893. NSDictionary *userInfo = notification.userInfo;
  894. if (!userInfo || !userInfo[AVAudioSessionInterruptionTypeKey]) {
  895. return;
  896. }
  897. NSUInteger interruptionType = [userInfo[AVAudioSessionInterruptionTypeKey] unsignedIntegerValue];
  898. if (interruptionType == AVAudioSessionInterruptionTypeBegan) {
  899. [_mediaPlayer pause];
  900. } else if (interruptionType == AVAudioSessionInterruptionTypeEnded
  901. && [userInfo[AVAudioSessionInterruptionOptionKey] unsignedIntegerValue] == AVAudioSessionInterruptionOptionShouldResume) {
  902. [_mediaPlayer play];
  903. }
  904. }
  905. - (BOOL)areHeadphonesPlugged
  906. {
  907. NSArray *outputs = [[AVAudioSession sharedInstance] currentRoute].outputs;
  908. NSString *portName = [[outputs firstObject] portName];
  909. return [portName isEqualToString:@"Headphones"];
  910. }
  911. - (void)audioSessionRouteChange:(NSNotification *)notification
  912. {
  913. NSDictionary *userInfo = notification.userInfo;
  914. NSInteger routeChangeReason = [[userInfo valueForKey:AVAudioSessionRouteChangeReasonKey] integerValue];
  915. if (routeChangeReason == AVAudioSessionRouteChangeReasonRouteConfigurationChange)
  916. return;
  917. BOOL headphonesPlugged = [self areHeadphonesPlugged];
  918. if (_headphonesWasPlugged && !headphonesPlugged && [_mediaPlayer isPlaying]) {
  919. [_mediaPlayer pause];
  920. #if TARGET_OS_IOS
  921. [self _savePlaybackState];
  922. #endif
  923. [[NSNotificationCenter defaultCenter] postNotificationName:VLCPlaybackControllerPlaybackDidPause object:self];
  924. }
  925. _headphonesWasPlugged = headphonesPlugged;
  926. }
  927. #pragma mark - Managing the media item
  928. - (VLCMedia *)currentlyPlayingMedia
  929. {
  930. return _mediaPlayer.media;
  931. }
  932. #pragma mark - metadata handling
  933. - (void)performNavigationAction:(VLCMediaPlaybackNavigationAction)action
  934. {
  935. [_mediaPlayer performNavigationAction:action];
  936. }
  937. - (void)mediaDidFinishParsing:(VLCMedia *)aMedia
  938. {
  939. [self setNeedsMetadataUpdate];
  940. }
  941. - (void)mediaMetaDataDidChange:(VLCMedia*)aMedia
  942. {
  943. [self setNeedsMetadataUpdate];
  944. }
  945. - (void)setNeedsMetadataUpdate
  946. {
  947. if (_needsMetadataUpdate == NO) {
  948. _needsMetadataUpdate = YES;
  949. dispatch_async(dispatch_get_main_queue(), ^{
  950. [_metadata updateMetadataFromMediaPlayer:_mediaPlayer];
  951. _needsMetadataUpdate = NO;
  952. if ([self.delegate respondsToSelector:@selector(displayMetadataForPlaybackController:metadata:)])
  953. [self.delegate displayMetadataForPlaybackController:self metadata:_metadata];
  954. });
  955. }
  956. }
  957. #if TARGET_OS_IOS
  958. - (void)_recoverLastPlaybackStateOfItem:(MLFile *)item
  959. {
  960. if (item) {
  961. CGFloat lastPosition = .0;
  962. NSInteger duration = 0;
  963. if (item.lastPosition) {
  964. lastPosition = item.lastPosition.floatValue;
  965. }
  966. duration = item.duration.intValue;
  967. if (lastPosition < .95 && _mediaPlayer.position < lastPosition) {
  968. NSInteger continuePlayback;
  969. if ([item isAlbumTrack] || [item isSupportedAudioFile])
  970. continuePlayback = [[[NSUserDefaults standardUserDefaults] objectForKey:kVLCSettingContinueAudioPlayback] integerValue];
  971. else
  972. continuePlayback = [[[NSUserDefaults standardUserDefaults] objectForKey:kVLCSettingContinuePlayback] integerValue];
  973. if (continuePlayback == 1) {
  974. [self setPlaybackPosition:lastPosition];
  975. } else if (continuePlayback == 0) {
  976. VLCAlertView *alert = [[VLCAlertView alloc] initWithTitle:NSLocalizedString(@"CONTINUE_PLAYBACK", nil)
  977. message:[NSString stringWithFormat:NSLocalizedString(@"CONTINUE_PLAYBACK_LONG", nil), item.title]
  978. delegate:self
  979. cancelButtonTitle:NSLocalizedString(@"BUTTON_CANCEL", nil)
  980. otherButtonTitles:NSLocalizedString(@"BUTTON_CONTINUE", nil), nil];
  981. alert.completion = ^(BOOL cancelled, NSInteger buttonIndex) {
  982. if (!cancelled) {
  983. [self setPlaybackPosition:lastPosition];
  984. }
  985. };
  986. [alert show];
  987. }
  988. }
  989. }
  990. }
  991. #endif
  992. - (void)recoverDisplayedMetadata
  993. {
  994. if ([self.delegate respondsToSelector:@selector(displayMetadataForPlaybackController:metadata:)])
  995. [self.delegate displayMetadataForPlaybackController:self metadata:_metadata];
  996. }
  997. - (void)recoverPlaybackState
  998. {
  999. if ([self.delegate respondsToSelector:@selector(mediaPlayerStateChanged:isPlaying:currentMediaHasTrackToChooseFrom:currentMediaHasChapters:forPlaybackController:)])
  1000. [self.delegate mediaPlayerStateChanged:_mediaPlayer.state
  1001. isPlaying:self.isPlaying
  1002. currentMediaHasTrackToChooseFrom:self.currentMediaHasTrackToChooseFrom
  1003. currentMediaHasChapters:self.currentMediaHasChapters
  1004. forPlaybackController:self];
  1005. if ([self.delegate respondsToSelector:@selector(prepareForMediaPlayback:)])
  1006. [self.delegate prepareForMediaPlayback:self];
  1007. }
  1008. - (void)scheduleSleepTimerWithInterval:(NSTimeInterval)timeInterval
  1009. {
  1010. if (_sleepTimer) {
  1011. [_sleepTimer invalidate];
  1012. _sleepTimer = nil;
  1013. }
  1014. _sleepTimer = [NSTimer scheduledTimerWithTimeInterval:timeInterval target:self selector:@selector(stopPlayback) userInfo:nil repeats:NO];
  1015. }
  1016. #pragma mark - background interaction
  1017. - (void)applicationWillResignActive:(NSNotification *)aNotification
  1018. {
  1019. #if TARGET_OS_IOS
  1020. [self _savePlaybackState];
  1021. #endif
  1022. if (![[[NSUserDefaults standardUserDefaults] objectForKey:kVLCSettingContinueAudioInBackgroundKey] boolValue]) {
  1023. if ([_mediaPlayer isPlaying]) {
  1024. [_mediaPlayer pause];
  1025. _shouldResumePlaying = YES;
  1026. }
  1027. }
  1028. }
  1029. - (void)applicationDidEnterBackground:(NSNotification *)notification
  1030. {
  1031. _preBackgroundWrapperView = _videoOutputViewWrapper;
  1032. if (_mediaPlayer.audioTrackIndexes.count > 0)
  1033. [self setVideoTrackEnabled:false];
  1034. }
  1035. - (void)applicationDidBecomeActive:(NSNotification *)notification
  1036. {
  1037. if (_preBackgroundWrapperView) {
  1038. [self setVideoOutputView:_preBackgroundWrapperView];
  1039. _preBackgroundWrapperView = nil;
  1040. }
  1041. [self setVideoTrackEnabled:true];
  1042. if (_shouldResumePlaying) {
  1043. _shouldResumePlaying = NO;
  1044. [_listPlayer play];
  1045. }
  1046. }
  1047. #pragma mark - remoteControlDelegate
  1048. - (void)remoteControlServiceHitPause:(VLCRemoteControlService *)rcs
  1049. {
  1050. [_listPlayer pause];
  1051. }
  1052. - (void)remoteControlServiceHitPlay:(VLCRemoteControlService *)rcs
  1053. {
  1054. [_listPlayer play];
  1055. }
  1056. - (void)remoteControlServiceTogglePlayPause:(VLCRemoteControlService *)rcs
  1057. {
  1058. [self playPause];
  1059. }
  1060. - (void)remoteControlServiceHitStop:(VLCRemoteControlService *)rcs
  1061. {
  1062. //TODO handle stop playback entirely
  1063. [_listPlayer stop];
  1064. }
  1065. - (BOOL)remoteControlServiceHitPlayNextIfPossible:(VLCRemoteControlService *)rcs
  1066. {
  1067. //TODO This doesn't handle shuffle or repeat yet
  1068. return [_listPlayer next];
  1069. }
  1070. - (BOOL)remoteControlServiceHitPlayPreviousIfPossible:(VLCRemoteControlService *)rcs
  1071. {
  1072. //TODO This doesn't handle shuffle or repeat yet
  1073. return [_listPlayer previous];
  1074. }
  1075. - (void)remoteControlService:(VLCRemoteControlService *)rcs jumpForwardInSeconds:(NSTimeInterval)seconds
  1076. {
  1077. [_mediaPlayer jumpForward:seconds];
  1078. }
  1079. - (void)remoteControlService:(VLCRemoteControlService *)rcs jumpBackwardInSeconds:(NSTimeInterval)seconds
  1080. {
  1081. [_mediaPlayer jumpBackward:seconds];
  1082. }
  1083. - (NSInteger)remoteControlServiceNumberOfMediaItemsinList:(VLCRemoteControlService *)rcs
  1084. {
  1085. return _mediaList.count;
  1086. }
  1087. - (void)remoteControlService:(VLCRemoteControlService *)rcs setPlaybackRate:(CGFloat)playbackRate
  1088. {
  1089. self.playbackRate = playbackRate;
  1090. }
  1091. - (void)remoteControlService:(VLCRemoteControlService *)rcs setCurrentPlaybackTime:(NSTimeInterval)playbackTime
  1092. {
  1093. float positionDiff = playbackTime - [self.metadata.elapsedPlaybackTime floatValue];
  1094. [_mediaPlayer jumpForward:positionDiff];
  1095. }
  1096. #pragma mark - helpers
  1097. - (NSDictionary *)mediaOptionsDictionary
  1098. {
  1099. NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
  1100. return @{ kVLCSettingNetworkCaching : [defaults objectForKey:kVLCSettingNetworkCaching],
  1101. kVLCSettingStretchAudio : [[defaults objectForKey:kVLCSettingStretchAudio] boolValue] ? kVLCSettingStretchAudioOnValue : kVLCSettingStretchAudioOffValue,
  1102. kVLCSettingTextEncoding : [defaults objectForKey:kVLCSettingTextEncoding],
  1103. kVLCSettingSkipLoopFilter : [defaults objectForKey:kVLCSettingSkipLoopFilter],
  1104. kVLCSettingHardwareDecoding : [defaults objectForKey:kVLCSettingHardwareDecoding]};
  1105. }
  1106. @end