VLCPlaybackController.m 41 KB

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