VLCPlaybackController.m 40 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,
  40. #if TARGET_OS_IOS
  41. AVAudioSessionDelegate,
  42. #endif
  43. VLCMediaDelegate, VLCRemoteControlServiceDelegate>
  44. {
  45. VLCRemoteControlService *_remoteControlService;
  46. VLCMediaPlayer *_mediaPlayer;
  47. VLCMediaListPlayer *_listPlayer;
  48. BOOL _playerIsSetup;
  49. BOOL _shouldResumePlaying;
  50. BOOL _sessionWillRestart;
  51. BOOL _shouldResumePlayingAfterInteruption;
  52. NSString *_pathToExternalSubtitlesFile;
  53. int _itemInMediaListToBePlayedFirst;
  54. NSTimer *_sleepTimer;
  55. NSUInteger _currentAspectRatio;
  56. UIView *_videoOutputViewWrapper;
  57. UIView *_actualVideoOutputView;
  58. UIView *_preBackgroundWrapperView;
  59. BOOL _needsMetadataUpdate;
  60. BOOL _mediaWasJustStarted;
  61. BOOL _recheckForExistingThumbnail;
  62. BOOL _headphonesWasPlugged;
  63. NSLock *_playbackSessionManagementLock;
  64. VLCDialogProvider *_dialogProvider;
  65. NSMutableArray *_shuffleStack;
  66. }
  67. @end
  68. @implementation VLCPlaybackController
  69. #pragma mark instance management
  70. + (VLCPlaybackController *)sharedInstance
  71. {
  72. static VLCPlaybackController *sharedInstance = nil;
  73. static dispatch_once_t pred;
  74. dispatch_once(&pred, ^{
  75. sharedInstance = [VLCPlaybackController new];
  76. });
  77. return sharedInstance;
  78. }
  79. - (void)dealloc
  80. {
  81. _dialogProvider = nil;
  82. [[NSNotificationCenter defaultCenter] removeObserver:self];
  83. }
  84. - (instancetype)init
  85. {
  86. self = [super init];
  87. if (self) {
  88. // listen to audiosessions and appkit callback
  89. _headphonesWasPlugged = [self areHeadphonesPlugged];
  90. NSNotificationCenter *defaultCenter = [NSNotificationCenter defaultCenter];
  91. [defaultCenter addObserver:self selector:@selector(audioSessionRouteChange:)
  92. name:AVAudioSessionRouteChangeNotification object:nil];
  93. // appkit because we neeed to know when we go to background in order to stop the video, so that we don't crash
  94. [defaultCenter addObserver:self selector:@selector(applicationWillResignActive:)
  95. name:UIApplicationWillResignActiveNotification object:nil];
  96. [defaultCenter addObserver:self selector:@selector(applicationDidBecomeActive:)
  97. name:UIApplicationDidBecomeActiveNotification object:nil];
  98. [defaultCenter addObserver:self selector:@selector(applicationDidEnterBackground:)
  99. name:UIApplicationDidEnterBackgroundNotification object:nil];
  100. _metadata = [VLCMetaData new];
  101. _dialogProvider = [[VLCDialogProvider alloc] initWithLibrary:[VLCLibrary sharedLibrary] customUI:NO];
  102. _playbackSessionManagementLock = [[NSLock alloc] init];
  103. _shuffleMode = NO;
  104. _shuffleStack = [[NSMutableArray alloc] init];
  105. }
  106. return self;
  107. }
  108. - (VLCRemoteControlService *)remoteControlService
  109. {
  110. if (!_remoteControlService) {
  111. _remoteControlService = [[VLCRemoteControlService alloc] init];
  112. _remoteControlService.remoteControlServiceDelegate = self;
  113. }
  114. return _remoteControlService;
  115. }
  116. #pragma mark - playback management
  117. - (void)openVideoSubTitlesFromFile:(NSString *)pathToFile
  118. {
  119. [_mediaPlayer openVideoSubTitlesFromFile:pathToFile];
  120. }
  121. - (void)playMediaList:(VLCMediaList *)mediaList firstIndex:(NSInteger)index subtitlesFilePath:(NSString *)subsFilePath
  122. {
  123. self.mediaList = mediaList;
  124. _itemInMediaListToBePlayedFirst = (int)index;
  125. _pathToExternalSubtitlesFile = subsFilePath;
  126. _sessionWillRestart = _playerIsSetup;
  127. _playerIsSetup ? [self stopPlayback] : [self startPlayback];
  128. }
  129. - (VLCTime *)playedTime
  130. {
  131. return [_mediaPlayer time];
  132. }
  133. - (void)startPlayback
  134. {
  135. if (_playerIsSetup) {
  136. APLog(@"%s: player is already setup, bailing out", __PRETTY_FUNCTION__);
  137. return;
  138. }
  139. BOOL ret = [_playbackSessionManagementLock tryLock];
  140. if (!ret) {
  141. APLog(@"%s: locking failed", __PRETTY_FUNCTION__);
  142. return;
  143. }
  144. #if TARGET_OS_IOS
  145. [[AVAudioSession sharedInstance] setDelegate:self];
  146. #endif
  147. NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
  148. if (!self.mediaList) {
  149. APLog(@"%s: no URL and no media list set, stopping playback", __PRETTY_FUNCTION__);
  150. [_playbackSessionManagementLock unlock];
  151. [self stopPlayback];
  152. return;
  153. }
  154. /* video decoding permanently fails if we don't provide a UIView to draw into on init
  155. * hence we provide one which is not attached to any view controller for off-screen drawing
  156. * and disable video decoding once playback started */
  157. _actualVideoOutputView = [[UIView alloc] initWithFrame:[UIScreen mainScreen].bounds];
  158. _actualVideoOutputView.autoresizingMask = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight;
  159. _actualVideoOutputView.autoresizesSubviews = YES;
  160. if (_pathToExternalSubtitlesFile)
  161. _listPlayer = [[VLCMediaListPlayer alloc] initWithOptions:@[[NSString stringWithFormat:@"--%@=%@", kVLCSettingSubtitlesFilePath, _pathToExternalSubtitlesFile]] andDrawable:_actualVideoOutputView];
  162. else
  163. _listPlayer = [[VLCMediaListPlayer alloc] initWithDrawable:_actualVideoOutputView];
  164. /* to enable debug logging for the playback library instance, switch the boolean below
  165. * note that the library instance used for playback may not necessarily match the instance
  166. * used for media discovery or thumbnailing */
  167. _listPlayer.mediaPlayer.libraryInstance.debugLogging = NO;
  168. _mediaPlayer = _listPlayer.mediaPlayer;
  169. [_mediaPlayer setDelegate:self];
  170. if ([[defaults objectForKey:kVLCSettingPlaybackSpeedDefaultValue] floatValue] != 0)
  171. [_mediaPlayer setRate: [[defaults objectForKey:kVLCSettingPlaybackSpeedDefaultValue] floatValue]];
  172. if ([[defaults objectForKey:kVLCSettingDeinterlace] intValue] != 0)
  173. [_mediaPlayer setDeinterlaceFilter:@"blend"];
  174. else
  175. [_mediaPlayer setDeinterlaceFilter:nil];
  176. if (_pathToExternalSubtitlesFile)
  177. [_mediaPlayer addPlaybackSlave:[NSURL fileURLWithPath:_pathToExternalSubtitlesFile] type:VLCMediaPlaybackSlaveTypeSubtitle enforce:YES];
  178. VLCMedia *media = [_mediaList mediaAtIndex:_itemInMediaListToBePlayedFirst];
  179. [media parseWithOptions:VLCMediaParseLocal];
  180. media.delegate = self;
  181. [media addOptions:self.mediaOptionsDictionary];
  182. [_listPlayer setMediaList:self.mediaList];
  183. [_listPlayer setRepeatMode:VLCDoNotRepeat];
  184. [_playbackSessionManagementLock unlock];
  185. [self _playNewMedia];
  186. }
  187. - (void)_playNewMedia
  188. {
  189. BOOL ret = [_playbackSessionManagementLock tryLock];
  190. if (!ret) {
  191. APLog(@"%s: locking failed", __PRETTY_FUNCTION__);
  192. return;
  193. }
  194. // Set last selected equalizer profile
  195. unsigned int profile = (unsigned int)[[[NSUserDefaults standardUserDefaults] objectForKey:kVLCSettingEqualizerProfile] integerValue];
  196. [_mediaPlayer resetEqualizerFromProfile:profile];
  197. [_mediaPlayer setPreAmplification:[_mediaPlayer preAmplification]];
  198. _mediaWasJustStarted = YES;
  199. [_mediaPlayer addObserver:self forKeyPath:@"time" options:0 context:nil];
  200. [_mediaPlayer addObserver:self forKeyPath:@"remainingTime" options:0 context:nil];
  201. [_listPlayer playItemAtNumber:@(_itemInMediaListToBePlayedFirst)];
  202. if ([self.delegate respondsToSelector:@selector(prepareForMediaPlayback:)])
  203. [self.delegate prepareForMediaPlayback:self];
  204. _currentAspectRatio = VLCAspectRatioDefault;
  205. _mediaPlayer.videoAspectRatio = NULL;
  206. _mediaPlayer.scaleFactor = 0;
  207. [[self remoteControlService] subscribeToRemoteCommands];
  208. _playerIsSetup = YES;
  209. [[NSNotificationCenter defaultCenter] postNotificationName:VLCPlaybackControllerPlaybackDidStart object:self];
  210. [_playbackSessionManagementLock unlock];
  211. }
  212. - (void)stopPlayback
  213. {
  214. BOOL ret = [_playbackSessionManagementLock tryLock];
  215. if (!ret) {
  216. APLog(@"%s: locking failed", __PRETTY_FUNCTION__);
  217. return;
  218. }
  219. if (_mediaPlayer) {
  220. @try {
  221. [_mediaPlayer removeObserver:self forKeyPath:@"time"];
  222. [_mediaPlayer removeObserver:self forKeyPath:@"remainingTime"];
  223. }
  224. @catch (NSException *exception) {
  225. APLog(@"we weren't an observer yet");
  226. }
  227. if (_mediaPlayer.media) {
  228. [_mediaPlayer pause];
  229. #if TARGET_OS_IOS
  230. [self _savePlaybackState];
  231. #endif
  232. [_mediaPlayer stop];
  233. }
  234. _mediaPlayer = nil;
  235. _listPlayer = nil;
  236. }
  237. if (!_sessionWillRestart) {
  238. _mediaList = nil;
  239. if (_pathToExternalSubtitlesFile) {
  240. NSFileManager *fileManager = [NSFileManager defaultManager];
  241. if ([fileManager fileExistsAtPath:_pathToExternalSubtitlesFile])
  242. [fileManager removeItemAtPath:_pathToExternalSubtitlesFile error:nil];
  243. _pathToExternalSubtitlesFile = nil;
  244. }
  245. }
  246. _playerIsSetup = NO;
  247. [_shuffleStack removeAllObjects];
  248. if (_errorCallback && _mediaPlayer.state == VLCMediaPlayerStateError && !_sessionWillRestart)
  249. [[UIApplication sharedApplication] openURL:_errorCallback];
  250. else if (_successCallback && !_sessionWillRestart)
  251. [[UIApplication sharedApplication] openURL:_successCallback];
  252. [[self remoteControlService] unsubscribeFromRemoteCommands];
  253. [_playbackSessionManagementLock unlock];
  254. if (!_sessionWillRestart) {
  255. [[NSNotificationCenter defaultCenter] postNotificationName:VLCPlaybackControllerPlaybackDidStop object:self];
  256. } else {
  257. _sessionWillRestart = NO;
  258. [self startPlayback];
  259. }
  260. }
  261. #if TARGET_OS_IOS
  262. - (void)_savePlaybackState
  263. {
  264. @try {
  265. [[MLMediaLibrary sharedMediaLibrary] save];
  266. }
  267. @catch (NSException *exception) {
  268. APLog(@"saving playback state failed");
  269. }
  270. NSArray *files = [MLFile fileForURL:_mediaPlayer.media.url];
  271. MLFile *fileItem = files.firstObject;
  272. if (!fileItem) {
  273. APLog(@"couldn't find file, not saving playback progress");
  274. return;
  275. }
  276. @try {
  277. float position = _mediaPlayer.position;
  278. fileItem.lastPosition = @(position);
  279. fileItem.lastAudioTrack = @(_mediaPlayer.currentAudioTrackIndex);
  280. fileItem.lastSubtitleTrack = @(_mediaPlayer.currentVideoSubTitleIndex);
  281. if (position > .95)
  282. return;
  283. if (_mediaPlayer.hasVideoOut) {
  284. NSArray *searchPaths = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES);
  285. NSString *newThumbnailPath = [searchPaths.firstObject stringByAppendingPathComponent:@"VideoSnapshots"];
  286. NSError *error;
  287. [[NSFileManager defaultManager] createDirectoryAtPath:newThumbnailPath withIntermediateDirectories:YES attributes:nil error:&error];
  288. if (error == nil) {
  289. newThumbnailPath = [newThumbnailPath stringByAppendingPathComponent:fileItem.objectID.URIRepresentation.lastPathComponent];
  290. [_mediaPlayer saveVideoSnapshotAt:newThumbnailPath withWidth:0 andHeight:0];
  291. _recheckForExistingThumbnail = YES;
  292. [self performSelector:@selector(_updateStoredThumbnailForFile:) withObject:fileItem afterDelay:.25];
  293. }
  294. }
  295. }
  296. @catch (NSException *exception) {
  297. APLog(@"failed to save current media state - file removed?");
  298. }
  299. }
  300. #endif
  301. #if TARGET_OS_IOS
  302. - (void)_updateStoredThumbnailForFile:(MLFile *)fileItem
  303. {
  304. NSFileManager *fileManager = [NSFileManager defaultManager];
  305. NSArray *searchPaths = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES);
  306. NSString* newThumbnailPath = [searchPaths[0] stringByAppendingPathComponent:@"VideoSnapshots"];
  307. newThumbnailPath = [newThumbnailPath stringByAppendingPathComponent:fileItem.objectID.URIRepresentation.lastPathComponent];
  308. if (![fileManager fileExistsAtPath:newThumbnailPath]) {
  309. if (_recheckForExistingThumbnail) {
  310. [self performSelector:@selector(_updateStoredThumbnailForFile:) withObject:fileItem afterDelay:1.];
  311. _recheckForExistingThumbnail = NO;
  312. } else
  313. return;
  314. }
  315. UIImage *newThumbnail = [UIImage imageWithContentsOfFile:newThumbnailPath];
  316. if (!newThumbnail) {
  317. if (_recheckForExistingThumbnail) {
  318. [self performSelector:@selector(_updateStoredThumbnailForFile:) withObject:fileItem afterDelay:1.];
  319. _recheckForExistingThumbnail = NO;
  320. } else
  321. return;
  322. }
  323. @try {
  324. [fileItem setComputedThumbnailScaledForDevice:newThumbnail];
  325. }
  326. @catch (NSException *exception) {
  327. APLog(@"updating thumbnail failed");
  328. }
  329. [fileManager removeItemAtPath:newThumbnailPath error:nil];
  330. }
  331. #endif
  332. - (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context
  333. {
  334. if (_mediaWasJustStarted) {
  335. _mediaWasJustStarted = NO;
  336. #if TARGET_OS_IOS
  337. if (self.mediaList) {
  338. NSArray *matches = [MLFile fileForURL:_mediaPlayer.media.url];
  339. MLFile *item = matches.firstObject;
  340. [self _recoverLastPlaybackStateOfItem:item];
  341. }
  342. #else
  343. NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
  344. BOOL bValue = [defaults boolForKey:kVLCSettingUseSPDIF];
  345. if (bValue) {
  346. _mediaPlayer.audio.passthrough = bValue;
  347. }
  348. #endif
  349. }
  350. if ([self.delegate respondsToSelector:@selector(playbackPositionUpdated:)])
  351. [self.delegate playbackPositionUpdated:self];
  352. [[NSNotificationCenter defaultCenter] postNotificationName:VLCPlaybackControllerPlaybackPositionUpdated
  353. object:self];
  354. }
  355. - (NSInteger)mediaDuration
  356. {
  357. return _mediaPlayer.media.length.intValue;;
  358. }
  359. - (BOOL)isPlaying
  360. {
  361. return _mediaPlayer.isPlaying;
  362. }
  363. - (BOOL)willPlay
  364. {
  365. return _mediaPlayer.willPlay;
  366. }
  367. - (VLCRepeatMode)repeatMode
  368. {
  369. return _listPlayer.repeatMode;
  370. }
  371. - (void)setRepeatMode:(VLCRepeatMode)repeatMode
  372. {
  373. _listPlayer.repeatMode = repeatMode;
  374. }
  375. - (BOOL)currentMediaHasChapters
  376. {
  377. return [_mediaPlayer numberOfTitles] > 1 || [_mediaPlayer numberOfChaptersForTitle:_mediaPlayer.currentTitleIndex] > 1;
  378. }
  379. - (BOOL)currentMediaHasTrackToChooseFrom
  380. {
  381. return [[_mediaPlayer audioTrackIndexes] count] > 2 || [[_mediaPlayer videoSubTitlesIndexes] count] > 1;
  382. }
  383. - (BOOL) isSeekable
  384. {
  385. return _mediaPlayer.isSeekable;
  386. }
  387. - (NSNumber *)playbackTime
  388. {
  389. return _mediaPlayer.time.value;
  390. }
  391. - (float)playbackRate
  392. {
  393. return _mediaPlayer.rate;
  394. }
  395. - (void)setPlaybackRate:(float)playbackRate
  396. {
  397. [_mediaPlayer setRate:playbackRate];
  398. _metadata.playbackRate = @(_mediaPlayer.rate);
  399. }
  400. - (void)setAudioDelay:(float)audioDelay
  401. {
  402. _mediaPlayer.currentAudioPlaybackDelay = 1000000.*audioDelay;
  403. }
  404. - (float)audioDelay
  405. {
  406. return _mediaPlayer.currentAudioPlaybackDelay/1000000.;
  407. }
  408. - (float)playbackPosition
  409. {
  410. return [_mediaPlayer position];
  411. }
  412. - (void)setPlaybackPosition:(float)position
  413. {
  414. _mediaPlayer.position = position;
  415. }
  416. - (void)setSubtitleDelay:(float)subtitleDeleay
  417. {
  418. _mediaPlayer.currentVideoSubTitleDelay = 1000000.*subtitleDeleay;
  419. }
  420. - (float)subtitleDelay
  421. {
  422. return _mediaPlayer.currentVideoSubTitleDelay/1000000.;
  423. }
  424. - (float)hue
  425. {
  426. return _mediaPlayer.hue;
  427. }
  428. - (void)setHue:(float)hue
  429. {
  430. _mediaPlayer.hue = hue;
  431. }
  432. - (float)contrast
  433. {
  434. return _mediaPlayer.contrast;
  435. }
  436. - (void)setConstrast:(float)contrast
  437. {
  438. _mediaPlayer.hue = contrast;
  439. }
  440. - (float)brightness
  441. {
  442. return _mediaPlayer.brightness;
  443. }
  444. #if TARGET_OS_IOS
  445. - (void)setBrightness:(float)brightness
  446. {
  447. if (![[UIDevice currentDevice] VLCHasExternalDisplay])
  448. _mediaPlayer.brightness = brightness;
  449. else
  450. [[UIScreen mainScreen] setBrightness:(brightness / 2.)];
  451. }
  452. #else
  453. - (void)setBrightness:(float)brightness
  454. {
  455. _mediaPlayer.brightness = brightness;
  456. }
  457. #endif
  458. - (float)saturation
  459. {
  460. return _mediaPlayer.saturation;
  461. }
  462. - (void)setSaturation:(float)saturation
  463. {
  464. _mediaPlayer.saturation = saturation;
  465. }
  466. - (void)setGamma:(float)gamma
  467. {
  468. _mediaPlayer.gamma = gamma;
  469. }
  470. - (float)gamma
  471. {
  472. return _mediaPlayer.gamma;
  473. }
  474. - (void)resetFilters
  475. {
  476. _mediaPlayer.hue = 0.;
  477. _mediaPlayer.contrast = 1.;
  478. _mediaPlayer.brightness = 1.;
  479. [self setBrightness:(1/2.)];
  480. _mediaPlayer.saturation = 1.;
  481. _mediaPlayer.gamma = 1.;
  482. }
  483. - (void)toggleRepeatMode
  484. {
  485. VLCRepeatMode nextRepeatMode = VLCDoNotRepeat;
  486. switch (_listPlayer.repeatMode) {
  487. case VLCDoNotRepeat:
  488. nextRepeatMode = VLCRepeatCurrentItem;
  489. break;
  490. case VLCRepeatCurrentItem:
  491. nextRepeatMode = VLCRepeatAllItems;
  492. break;
  493. default:
  494. nextRepeatMode = VLCDoNotRepeat;
  495. break;
  496. }
  497. _listPlayer.repeatMode = nextRepeatMode;
  498. }
  499. - (NSInteger)indexOfCurrentAudioTrack
  500. {
  501. return [_mediaPlayer.audioTrackIndexes indexOfObject:@(_mediaPlayer.currentAudioTrackIndex)];
  502. }
  503. - (NSInteger)indexOfCurrentSubtitleTrack
  504. {
  505. return [_mediaPlayer.videoSubTitlesIndexes indexOfObject:@(_mediaPlayer.currentVideoSubTitleIndex)];
  506. }
  507. - (NSInteger)indexOfCurrentChapter
  508. {
  509. return _mediaPlayer.currentChapterIndex;
  510. }
  511. - (NSInteger)indexOfCurrentTitle
  512. {
  513. return _mediaPlayer.currentTitleIndex;
  514. }
  515. - (NSInteger)numberOfAudioTracks
  516. {
  517. return _mediaPlayer.audioTrackIndexes.count;
  518. }
  519. - (NSInteger)numberOfVideoSubtitlesIndexes
  520. {
  521. return _mediaPlayer.videoSubTitlesIndexes.count;
  522. }
  523. - (NSInteger)numberOfTitles
  524. {
  525. return [_mediaPlayer numberOfTitles];
  526. }
  527. - (NSInteger)numberOfChaptersForCurrentTitle
  528. {
  529. return [_mediaPlayer numberOfChaptersForTitle:_mediaPlayer.currentTitleIndex];
  530. }
  531. - (NSString *)videoSubtitleNameAtIndex:(NSInteger)index
  532. {
  533. if (index >= 0 && index < _mediaPlayer.videoSubTitlesNames.count)
  534. return _mediaPlayer.videoSubTitlesNames[index];
  535. return nil;
  536. }
  537. - (NSString *)audioTrackNameAtIndex:(NSInteger)index
  538. {
  539. if (index >= 0 && index < _mediaPlayer.audioTrackNames.count)
  540. return _mediaPlayer.audioTrackNames[index];
  541. return nil;
  542. }
  543. - (NSDictionary *)titleDescriptionsDictAtIndex:(NSInteger)index
  544. {
  545. if (index >= 0 && index < _mediaPlayer.titleDescriptions.count)
  546. return _mediaPlayer.titleDescriptions[index];
  547. return nil;
  548. }
  549. - (NSDictionary *)chapterDescriptionsDictAtIndex:(NSInteger)index
  550. {
  551. NSArray *chapterDescriptions = [_mediaPlayer chapterDescriptionsOfTitle:_mediaPlayer.currentTitleIndex];
  552. if (index >= 0 && index < chapterDescriptions.count)
  553. return chapterDescriptions[index];
  554. return nil;
  555. }
  556. - (void)selectAudioTrackAtIndex:(NSInteger)index
  557. {
  558. if (index >= 0 && index < _mediaPlayer.audioTrackIndexes.count) {
  559. //we can cast this cause we won't have more than 2 million audiotracks
  560. _mediaPlayer.currentAudioTrackIndex = [_mediaPlayer.audioTrackIndexes[index] intValue];
  561. }
  562. }
  563. - (void)selectVideoSubtitleAtIndex:(NSInteger)index
  564. {
  565. if (index >= 0 && index < _mediaPlayer.videoSubTitlesIndexes.count) {
  566. _mediaPlayer.currentVideoSubTitleIndex = [_mediaPlayer.videoSubTitlesIndexes[index] intValue];
  567. }
  568. }
  569. - (void)selectTitleAtIndex:(NSInteger)index
  570. {
  571. if (index >= 0 && index < [_mediaPlayer numberOfTitles]) {
  572. //we can cast this cause we won't have more than 2 million titles
  573. _mediaPlayer.currentTitleIndex = (int)index;
  574. }
  575. }
  576. - (void)selectChapterAtIndex:(NSInteger)index
  577. {
  578. if (index >= 0 && index < [self numberOfChaptersForCurrentTitle]) {
  579. //we can cast this cause we won't have more than 2 million chapters
  580. _mediaPlayer.currentChapterIndex = (int)index;
  581. }
  582. }
  583. - (void)shortJumpForward
  584. {
  585. [_mediaPlayer shortJumpForward];
  586. }
  587. - (void)shortJumpBackward
  588. {
  589. [_mediaPlayer shortJumpBackward];
  590. }
  591. - (VLCTime *)remainingTime
  592. {
  593. return [_mediaPlayer remainingTime];
  594. }
  595. - (void)setAudioPassthrough:(BOOL)shouldPass
  596. {
  597. _mediaPlayer.audio.passthrough = shouldPass;
  598. }
  599. - (void)mediaPlayerStateChanged:(NSNotification *)aNotification
  600. {
  601. VLCMediaPlayerState currentState = _mediaPlayer.state;
  602. if (currentState == VLCMediaPlayerStateBuffering) {
  603. /* attach delegate */
  604. _mediaPlayer.media.delegate = self;
  605. /* on-the-fly values through hidden API */
  606. NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
  607. [_mediaPlayer performSelector:@selector(setTextRendererFont:) withObject:[defaults objectForKey:kVLCSettingSubtitlesFont]];
  608. [_mediaPlayer performSelector:@selector(setTextRendererFontSize:) withObject:[defaults objectForKey:kVLCSettingSubtitlesFontSize]];
  609. [_mediaPlayer performSelector:@selector(setTextRendererFontColor:) withObject:[defaults objectForKey:kVLCSettingSubtitlesFontColor]];
  610. [_mediaPlayer performSelector:@selector(setTextRendererFontForceBold:) withObject:[defaults objectForKey:kVLCSettingSubtitlesBoldFont]];
  611. } else if (currentState == VLCMediaPlayerStateError) {
  612. APLog(@"Playback failed");
  613. dispatch_async(dispatch_get_main_queue(),^{
  614. [[NSNotificationCenter defaultCenter] postNotificationName:VLCPlaybackControllerPlaybackDidFail object:self];
  615. });
  616. _sessionWillRestart = NO;
  617. [self stopPlayback];
  618. } else if (currentState == VLCMediaPlayerStateEnded || currentState == VLCMediaPlayerStateStopped) {
  619. [_listPlayer.mediaList lock];
  620. NSUInteger listCount = _listPlayer.mediaList.count;
  621. if ([_listPlayer.mediaList indexOfMedia:_mediaPlayer.media] == listCount - 1 && self.repeatMode == VLCDoNotRepeat) {
  622. [_listPlayer.mediaList unlock];
  623. _sessionWillRestart = NO;
  624. [self stopPlayback];
  625. return;
  626. } else if (listCount > 1) {
  627. [_listPlayer.mediaList unlock];
  628. [_listPlayer next];
  629. } else
  630. [_listPlayer.mediaList unlock];
  631. }
  632. if ([self.delegate respondsToSelector:@selector(mediaPlayerStateChanged:isPlaying:currentMediaHasTrackToChooseFrom:currentMediaHasChapters:forPlaybackController:)])
  633. [self.delegate mediaPlayerStateChanged:currentState
  634. isPlaying:_mediaPlayer.isPlaying
  635. currentMediaHasTrackToChooseFrom:self.currentMediaHasTrackToChooseFrom
  636. currentMediaHasChapters:self.currentMediaHasChapters
  637. forPlaybackController:self];
  638. [self setNeedsMetadataUpdate];
  639. }
  640. #pragma mark - playback controls
  641. - (void)playPause
  642. {
  643. [_mediaPlayer isPlaying] ? [self pause] : [self play];
  644. }
  645. - (void)play
  646. {
  647. [_listPlayer play];
  648. [[NSNotificationCenter defaultCenter] postNotificationName:VLCPlaybackControllerPlaybackDidResume object:self];
  649. }
  650. - (void)pause
  651. {
  652. [_listPlayer pause];
  653. #if TARGET_OS_IOS
  654. [self _savePlaybackState];
  655. #endif
  656. [[NSNotificationCenter defaultCenter] postNotificationName:VLCPlaybackControllerPlaybackDidPause object:self];
  657. }
  658. - (void)next
  659. {
  660. NSInteger mediaListCount = _mediaList.count;
  661. #if TARGET_OS_IOS
  662. if (self.repeatMode != VLCRepeatCurrentItem && mediaListCount > 2 && _shuffleMode) {
  663. NSNumber *nextIndex;
  664. NSUInteger currentIndex = [_mediaList indexOfMedia:_listPlayer.mediaPlayer.media];
  665. //Reached end of playlist
  666. if (_shuffleStack.count + 1 == mediaListCount) {
  667. if ([self repeatMode] == VLCDoNotRepeat)
  668. return;
  669. [_shuffleStack removeAllObjects];
  670. }
  671. [_shuffleStack addObject:[NSNumber numberWithUnsignedInteger:currentIndex]];
  672. do {
  673. nextIndex = [NSNumber numberWithUnsignedInt:arc4random_uniform((uint32_t)mediaListCount)];
  674. } while (currentIndex == nextIndex.unsignedIntegerValue || [_shuffleStack containsObject:nextIndex]);
  675. [_listPlayer playItemAtNumber:[NSNumber numberWithUnsignedInteger:nextIndex.unsignedIntegerValue]];
  676. [[NSNotificationCenter defaultCenter] postNotificationName:VLCPlaybackControllerPlaybackMetadataDidChange object:self];
  677. return;
  678. }
  679. #endif
  680. if (mediaListCount > 1) {
  681. [_listPlayer next];
  682. [[NSNotificationCenter defaultCenter] postNotificationName:VLCPlaybackControllerPlaybackMetadataDidChange object:self];
  683. } else {
  684. NSNumber *skipLength = [[NSUserDefaults standardUserDefaults] valueForKey:kVLCSettingPlaybackForwardSkipLength];
  685. [_mediaPlayer jumpForward:skipLength.intValue];
  686. }
  687. }
  688. - (void)previous
  689. {
  690. if (_mediaList.count > 1) {
  691. [_listPlayer previous];
  692. [[NSNotificationCenter defaultCenter] postNotificationName:VLCPlaybackControllerPlaybackMetadataDidChange object:self];
  693. }
  694. else {
  695. NSNumber *skipLength = [[NSUserDefaults standardUserDefaults] valueForKey:kVLCSettingPlaybackBackwardSkipLength];
  696. [_mediaPlayer jumpBackward:skipLength.intValue];
  697. }
  698. }
  699. - (void)jumpForward:(int)interval
  700. {
  701. [_mediaPlayer jumpForward:interval];
  702. }
  703. - (void)jumpBackward:(int)interval
  704. {
  705. [_mediaPlayer jumpBackward:interval];
  706. }
  707. - (void)switchAspectRatio
  708. {
  709. if (_currentAspectRatio == VLCAspectRatioSixteenToTen) {
  710. _mediaPlayer.videoAspectRatio = NULL;
  711. _mediaPlayer.scaleFactor = 0;
  712. _currentAspectRatio = VLCAspectRatioDefault;
  713. } else {
  714. _currentAspectRatio++;
  715. if (_currentAspectRatio == VLCAspectRatioFillToScreen) {
  716. UIScreen *screen;
  717. if (![[UIDevice currentDevice] VLCHasExternalDisplay])
  718. screen = [UIScreen mainScreen];
  719. else
  720. screen = [UIScreen screens][1];
  721. float f_ar = screen.bounds.size.width / screen.bounds.size.height;
  722. if (f_ar == (float)(4.0/3.0) ||
  723. f_ar == (float)(1366./1024.)) {
  724. // all iPads
  725. _mediaPlayer.videoCropGeometry = "4:3";
  726. } else if (f_ar == (float)(2./3.) || f_ar == (float)(480./320.)) {
  727. // all other iPhones
  728. _mediaPlayer.videoCropGeometry = "16:10"; // libvlc doesn't support 2:3 crop
  729. } else if (f_ar == .5625) {
  730. // AirPlay
  731. _mediaPlayer.videoCropGeometry = "16:9";
  732. } else if (f_ar == (float)(640./1136.) ||
  733. f_ar == (float)(568./320.) ||
  734. f_ar == (float)(667./375.) ||
  735. f_ar == (float)(736./414.)) {
  736. // iPhone 5 and 6 and 6+
  737. _mediaPlayer.videoCropGeometry = "16:9";
  738. } else
  739. APLog(@"unknown screen format %f, can't crop", f_ar);
  740. } else {
  741. _mediaPlayer.videoAspectRatio = (char *)[[self stringForAspectRatio:_currentAspectRatio] UTF8String];
  742. _mediaPlayer.videoCropGeometry = NULL;
  743. }
  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 - AVSession delegate
  852. - (void)beginInterruption
  853. {
  854. if ([_mediaPlayer isPlaying]) {
  855. [_mediaPlayer pause];
  856. _shouldResumePlayingAfterInteruption = YES;
  857. }
  858. }
  859. - (void)endInterruption
  860. {
  861. if (_shouldResumePlayingAfterInteruption) {
  862. [_mediaPlayer play];
  863. _shouldResumePlayingAfterInteruption = NO;
  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. if (_mediaPlayer.numberOfAudioTracks > 2) {
  923. if (item.lastAudioTrack.intValue > 0)
  924. _mediaPlayer.currentAudioTrackIndex = item.lastAudioTrack.intValue;
  925. }
  926. if (_mediaPlayer.numberOfSubtitlesTracks > 2) {
  927. if (item.lastSubtitleTrack.intValue > 0)
  928. _mediaPlayer.currentVideoSubTitleIndex = item.lastSubtitleTrack.intValue;
  929. }
  930. CGFloat lastPosition = .0;
  931. NSInteger duration = 0;
  932. if (item.lastPosition)
  933. lastPosition = item.lastPosition.floatValue;
  934. duration = item.duration.intValue;
  935. if (lastPosition < .95 && _mediaPlayer.position < lastPosition && (duration * lastPosition - duration) < -50000) {
  936. NSInteger continuePlayback;
  937. if ([item isAlbumTrack] || [item isSupportedAudioFile])
  938. continuePlayback = [[[NSUserDefaults standardUserDefaults] objectForKey:kVLCSettingContinueAudioPlayback] integerValue];
  939. else
  940. continuePlayback = [[[NSUserDefaults standardUserDefaults] objectForKey:kVLCSettingContinuePlayback] integerValue];
  941. if (continuePlayback == 1) {
  942. _mediaPlayer.position = lastPosition;
  943. } else if (continuePlayback == 0) {
  944. VLCAlertView *alert = [[VLCAlertView alloc] initWithTitle:NSLocalizedString(@"CONTINUE_PLAYBACK", nil)
  945. message:[NSString stringWithFormat:NSLocalizedString(@"CONTINUE_PLAYBACK_LONG", nil), item.title]
  946. delegate:self
  947. cancelButtonTitle:NSLocalizedString(@"BUTTON_CANCEL", nil)
  948. otherButtonTitles:NSLocalizedString(@"BUTTON_CONTINUE", nil), nil];
  949. alert.completion = ^(BOOL cancelled, NSInteger buttonIndex) {
  950. if (!cancelled) {
  951. _mediaPlayer.position = lastPosition;
  952. }
  953. };
  954. [alert show];
  955. }
  956. }
  957. }
  958. }
  959. #endif
  960. - (void)recoverDisplayedMetadata
  961. {
  962. if ([self.delegate respondsToSelector:@selector(displayMetadataForPlaybackController:metadata:)])
  963. [self.delegate displayMetadataForPlaybackController:self metadata:_metadata];
  964. }
  965. - (void)recoverPlaybackState
  966. {
  967. if ([self.delegate respondsToSelector:@selector(mediaPlayerStateChanged:isPlaying:currentMediaHasTrackToChooseFrom:currentMediaHasChapters:forPlaybackController:)])
  968. [self.delegate mediaPlayerStateChanged:_mediaPlayer.state
  969. isPlaying:self.isPlaying
  970. currentMediaHasTrackToChooseFrom:self.currentMediaHasTrackToChooseFrom
  971. currentMediaHasChapters:self.currentMediaHasChapters
  972. forPlaybackController:self];
  973. if ([self.delegate respondsToSelector:@selector(prepareForMediaPlayback:)])
  974. [self.delegate prepareForMediaPlayback:self];
  975. }
  976. - (void)scheduleSleepTimerWithInterval:(NSTimeInterval)timeInterval
  977. {
  978. if (_sleepTimer) {
  979. [_sleepTimer invalidate];
  980. _sleepTimer = nil;
  981. }
  982. _sleepTimer = [NSTimer scheduledTimerWithTimeInterval:timeInterval target:self selector:@selector(stopPlayback) userInfo:nil repeats:NO];
  983. }
  984. #pragma mark - background interaction
  985. - (void)applicationWillResignActive:(NSNotification *)aNotification
  986. {
  987. #if TARGET_OS_IOS
  988. [self _savePlaybackState];
  989. #endif
  990. if (![[[NSUserDefaults standardUserDefaults] objectForKey:kVLCSettingContinueAudioInBackgroundKey] boolValue]) {
  991. if ([_mediaPlayer isPlaying]) {
  992. [_mediaPlayer pause];
  993. _shouldResumePlaying = YES;
  994. }
  995. }
  996. }
  997. - (void)applicationDidEnterBackground:(NSNotification *)notification
  998. {
  999. _preBackgroundWrapperView = _videoOutputViewWrapper;
  1000. if (_mediaPlayer.audioTrackIndexes.count > 0)
  1001. [self setVideoTrackEnabled:false];
  1002. }
  1003. - (void)applicationDidBecomeActive:(NSNotification *)notification
  1004. {
  1005. if (_preBackgroundWrapperView) {
  1006. [self setVideoOutputView:_preBackgroundWrapperView];
  1007. _preBackgroundWrapperView = nil;
  1008. }
  1009. [self setVideoTrackEnabled:true];
  1010. if (_shouldResumePlaying) {
  1011. _shouldResumePlaying = NO;
  1012. [_listPlayer play];
  1013. }
  1014. }
  1015. #pragma mark - remoteControlDelegate
  1016. - (void)remoteControlServiceHitPause:(VLCRemoteControlService *)rcs
  1017. {
  1018. [_listPlayer pause];
  1019. }
  1020. - (void)remoteControlServiceHitPlay:(VLCRemoteControlService *)rcs
  1021. {
  1022. [_listPlayer play];
  1023. }
  1024. - (void)remoteControlServiceTogglePlayPause:(VLCRemoteControlService *)rcs
  1025. {
  1026. [self playPause];
  1027. }
  1028. - (void)remoteControlServiceHitStop:(VLCRemoteControlService *)rcs
  1029. {
  1030. //TODO handle stop playback entirely
  1031. [_listPlayer stop];
  1032. }
  1033. - (BOOL)remoteControlServiceHitPlayNextIfPossible:(VLCRemoteControlService *)rcs
  1034. {
  1035. //TODO This doesn't handle shuffle or repeat yet
  1036. return [_listPlayer next];
  1037. }
  1038. - (BOOL)remoteControlServiceHitPlayPreviousIfPossible:(VLCRemoteControlService *)rcs
  1039. {
  1040. //TODO This doesn't handle shuffle or repeat yet
  1041. return [_listPlayer previous];
  1042. }
  1043. - (void)remoteControlService:(VLCRemoteControlService *)rcs jumpForwardInSeconds:(NSTimeInterval)seconds
  1044. {
  1045. [_mediaPlayer jumpForward:seconds];
  1046. }
  1047. - (void)remoteControlService:(VLCRemoteControlService *)rcs jumpBackwardInSeconds:(NSTimeInterval)seconds
  1048. {
  1049. [_mediaPlayer jumpBackward:seconds];
  1050. }
  1051. - (NSInteger)remoteControlServiceNumberOfMediaItemsinList:(VLCRemoteControlService *)rcs
  1052. {
  1053. return _mediaList.count;
  1054. }
  1055. - (void)remoteControlService:(VLCRemoteControlService *)rcs setPlaybackRate:(CGFloat)playbackRate
  1056. {
  1057. self.playbackRate = playbackRate;
  1058. }
  1059. #pragma mark - helpers
  1060. - (NSDictionary *)mediaOptionsDictionary
  1061. {
  1062. NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
  1063. return @{ kVLCSettingNetworkCaching : [defaults objectForKey:kVLCSettingNetworkCaching],
  1064. kVLCSettingStretchAudio : [[defaults objectForKey:kVLCSettingStretchAudio] boolValue] ? kVLCSettingStretchAudioOnValue : kVLCSettingStretchAudioOffValue,
  1065. kVLCSettingTextEncoding : [defaults objectForKey:kVLCSettingTextEncoding],
  1066. kVLCSettingSkipLoopFilter : [defaults objectForKey:kVLCSettingSkipLoopFilter],
  1067. kVLCSettingHardwareDecoding : [defaults objectForKey:kVLCSettingHardwareDecoding]};
  1068. }
  1069. @end