VLCPlaybackController.m 40 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258
  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. NSString *aspectRatio = [NSString stringWithFormat:@"%d:%d", (int)screen.bounds.size.width, (int)screen.bounds.size.height];
  722. _mediaPlayer.videoCropGeometry = (char *)[aspectRatio UTF8String];
  723. } else {
  724. _mediaPlayer.videoAspectRatio = (char *)[[self stringForAspectRatio:_currentAspectRatio] UTF8String];
  725. _mediaPlayer.videoCropGeometry = NULL;
  726. }
  727. }
  728. if ([self.delegate respondsToSelector:@selector(showStatusMessage:forPlaybackController:)]) {
  729. [self.delegate showStatusMessage:[NSString stringWithFormat:NSLocalizedString(@"AR_CHANGED", nil), [self stringForAspectRatio:_currentAspectRatio]] forPlaybackController:self];
  730. }
  731. }
  732. - (NSString *)stringForAspectRatio:(VLCAspectRatio)ratio
  733. {
  734. switch (ratio) {
  735. case VLCAspectRatioFillToScreen:
  736. return NSLocalizedString(@"FILL_TO_SCREEN", nil);
  737. case VLCAspectRatioDefault:
  738. return NSLocalizedString(@"DEFAULT", nil);
  739. case VLCAspectRatioFourToThree:
  740. return @"4:3";
  741. case VLCAspectRatioSixteenToTen:
  742. return @"16:10";
  743. case VLCAspectRatioSixteenToNine:
  744. return @"16:9";
  745. default:
  746. NSAssert(NO, @"this shouldn't happen");
  747. }
  748. }
  749. - (void)setVideoTrackEnabled:(BOOL)enabled
  750. {
  751. if (!enabled)
  752. _mediaPlayer.currentVideoTrackIndex = -1;
  753. else if (_mediaPlayer.currentVideoTrackIndex == -1) {
  754. for (NSNumber *trackId in _mediaPlayer.videoTrackIndexes) {
  755. if ([trackId intValue] != -1) {
  756. _mediaPlayer.currentVideoTrackIndex = [trackId intValue];
  757. break;
  758. }
  759. }
  760. }
  761. }
  762. - (void)setVideoOutputView:(UIView *)videoOutputView
  763. {
  764. if (videoOutputView) {
  765. if ([_actualVideoOutputView superview] != nil)
  766. [_actualVideoOutputView removeFromSuperview];
  767. _actualVideoOutputView.frame = (CGRect){CGPointZero, videoOutputView.frame.size};
  768. [self setVideoTrackEnabled:true];
  769. [videoOutputView addSubview:_actualVideoOutputView];
  770. [_actualVideoOutputView layoutSubviews];
  771. [_actualVideoOutputView updateConstraints];
  772. [_actualVideoOutputView setNeedsLayout];
  773. } else
  774. [_actualVideoOutputView removeFromSuperview];
  775. _videoOutputViewWrapper = videoOutputView;
  776. }
  777. - (UIView *)videoOutputView
  778. {
  779. return _videoOutputViewWrapper;
  780. }
  781. #pragma mark - 360 Support
  782. #if !TARGET_OS_TV
  783. - (BOOL)updateViewpoint:(CGFloat)yaw pitch:(CGFloat)pitch roll:(CGFloat)roll fov:(CGFloat)fov absolute:(BOOL)absolute
  784. {
  785. return [_mediaPlayer updateViewpoint:yaw pitch:pitch roll:roll fov:fov absolute:absolute];
  786. }
  787. - (NSInteger)currentMediaProjection
  788. {
  789. VLCMedia *media = [_mediaPlayer media];
  790. NSInteger currentVideoTrackIndex = [_mediaPlayer currentVideoTrackIndex];
  791. if (media && currentVideoTrackIndex >= 0) {
  792. NSArray *tracksInfo = media.tracksInformation;
  793. for (NSDictionary *track in tracksInfo) {
  794. if ([track[VLCMediaTracksInformationType] isEqualToString:VLCMediaTracksInformationTypeVideo]) {
  795. return [track[VLCMediaTracksInformationVideoProjection] integerValue];
  796. }
  797. }
  798. }
  799. return -1;
  800. }
  801. #endif
  802. #pragma mark - equalizer
  803. - (void)setAmplification:(CGFloat)amplification forBand:(unsigned int)index
  804. {
  805. if (!_mediaPlayer.equalizerEnabled)
  806. [_mediaPlayer setEqualizerEnabled:YES];
  807. [_mediaPlayer setAmplification:amplification forBand:index];
  808. // For some reason we have to apply again preamp to apply change
  809. [_mediaPlayer setPreAmplification:[_mediaPlayer preAmplification]];
  810. }
  811. - (CGFloat)amplificationOfBand:(unsigned int)index
  812. {
  813. return [_mediaPlayer amplificationOfBand:index];
  814. }
  815. - (NSArray *)equalizerProfiles
  816. {
  817. return _mediaPlayer.equalizerProfiles;
  818. }
  819. - (void)resetEqualizerFromProfile:(unsigned int)profile
  820. {
  821. [[NSUserDefaults standardUserDefaults] setObject:@(profile) forKey:kVLCSettingEqualizerProfile];
  822. [_mediaPlayer resetEqualizerFromProfile:profile];
  823. }
  824. - (void)setPreAmplification:(CGFloat)preAmplification
  825. {
  826. if (!_mediaPlayer.equalizerEnabled)
  827. [_mediaPlayer setEqualizerEnabled:YES];
  828. [_mediaPlayer setPreAmplification:preAmplification];
  829. }
  830. - (CGFloat)preAmplification
  831. {
  832. return [_mediaPlayer preAmplification];
  833. }
  834. #pragma mark - AVSession delegate
  835. - (void)beginInterruption
  836. {
  837. if ([_mediaPlayer isPlaying]) {
  838. [_mediaPlayer pause];
  839. _shouldResumePlayingAfterInteruption = YES;
  840. }
  841. }
  842. - (void)endInterruption
  843. {
  844. if (_shouldResumePlayingAfterInteruption) {
  845. [_mediaPlayer play];
  846. _shouldResumePlayingAfterInteruption = NO;
  847. }
  848. }
  849. - (BOOL)areHeadphonesPlugged
  850. {
  851. NSArray *outputs = [[AVAudioSession sharedInstance] currentRoute].outputs;
  852. NSString *portName = [[outputs firstObject] portName];
  853. return [portName isEqualToString:@"Headphones"];
  854. }
  855. - (void)audioSessionRouteChange:(NSNotification *)notification
  856. {
  857. NSDictionary *userInfo = notification.userInfo;
  858. NSInteger routeChangeReason = [[userInfo valueForKey:AVAudioSessionRouteChangeReasonKey] integerValue];
  859. if (routeChangeReason == AVAudioSessionRouteChangeReasonRouteConfigurationChange)
  860. return;
  861. BOOL headphonesPlugged = [self areHeadphonesPlugged];
  862. if (_headphonesWasPlugged && !headphonesPlugged && [_mediaPlayer isPlaying]) {
  863. [_mediaPlayer pause];
  864. #if TARGET_OS_IOS
  865. [self _savePlaybackState];
  866. #endif
  867. [[NSNotificationCenter defaultCenter] postNotificationName:VLCPlaybackControllerPlaybackDidPause object:self];
  868. }
  869. _headphonesWasPlugged = headphonesPlugged;
  870. }
  871. #pragma mark - Managing the media item
  872. - (VLCMedia *)currentlyPlayingMedia
  873. {
  874. return _mediaPlayer.media;
  875. }
  876. #pragma mark - metadata handling
  877. - (void)performNavigationAction:(VLCMediaPlaybackNavigationAction)action
  878. {
  879. [_mediaPlayer performNavigationAction:action];
  880. }
  881. - (void)mediaDidFinishParsing:(VLCMedia *)aMedia
  882. {
  883. [self setNeedsMetadataUpdate];
  884. }
  885. - (void)mediaMetaDataDidChange:(VLCMedia*)aMedia
  886. {
  887. [self setNeedsMetadataUpdate];
  888. }
  889. - (void)setNeedsMetadataUpdate
  890. {
  891. if (_needsMetadataUpdate == NO) {
  892. _needsMetadataUpdate = YES;
  893. dispatch_async(dispatch_get_main_queue(), ^{
  894. [_metadata updateMetadataFromMediaPlayer:_mediaPlayer];
  895. _needsMetadataUpdate = NO;
  896. if ([self.delegate respondsToSelector:@selector(displayMetadataForPlaybackController:metadata:)])
  897. [self.delegate displayMetadataForPlaybackController:self metadata:_metadata];
  898. });
  899. }
  900. }
  901. #if TARGET_OS_IOS
  902. - (void)_recoverLastPlaybackStateOfItem:(MLFile *)item
  903. {
  904. if (item) {
  905. if (_mediaPlayer.numberOfAudioTracks > 2) {
  906. if (item.lastAudioTrack.intValue > 0)
  907. _mediaPlayer.currentAudioTrackIndex = item.lastAudioTrack.intValue;
  908. }
  909. if (_mediaPlayer.numberOfSubtitlesTracks > 2) {
  910. if (item.lastSubtitleTrack.intValue > 0)
  911. _mediaPlayer.currentVideoSubTitleIndex = item.lastSubtitleTrack.intValue;
  912. }
  913. CGFloat lastPosition = .0;
  914. NSInteger duration = 0;
  915. if (item.lastPosition)
  916. lastPosition = item.lastPosition.floatValue;
  917. duration = item.duration.intValue;
  918. if (lastPosition < .95 && _mediaPlayer.position < lastPosition) {
  919. NSInteger continuePlayback;
  920. if ([item isAlbumTrack] || [item isSupportedAudioFile])
  921. continuePlayback = [[[NSUserDefaults standardUserDefaults] objectForKey:kVLCSettingContinueAudioPlayback] integerValue];
  922. else
  923. continuePlayback = [[[NSUserDefaults standardUserDefaults] objectForKey:kVLCSettingContinuePlayback] integerValue];
  924. if (continuePlayback == 1) {
  925. _mediaPlayer.position = lastPosition;
  926. } else if (continuePlayback == 0) {
  927. VLCAlertView *alert = [[VLCAlertView alloc] initWithTitle:NSLocalizedString(@"CONTINUE_PLAYBACK", nil)
  928. message:[NSString stringWithFormat:NSLocalizedString(@"CONTINUE_PLAYBACK_LONG", nil), item.title]
  929. delegate:self
  930. cancelButtonTitle:NSLocalizedString(@"BUTTON_CANCEL", nil)
  931. otherButtonTitles:NSLocalizedString(@"BUTTON_CONTINUE", nil), nil];
  932. alert.completion = ^(BOOL cancelled, NSInteger buttonIndex) {
  933. if (!cancelled) {
  934. _mediaPlayer.position = lastPosition;
  935. }
  936. };
  937. [alert show];
  938. }
  939. }
  940. }
  941. }
  942. #endif
  943. - (void)recoverDisplayedMetadata
  944. {
  945. if ([self.delegate respondsToSelector:@selector(displayMetadataForPlaybackController:metadata:)])
  946. [self.delegate displayMetadataForPlaybackController:self metadata:_metadata];
  947. }
  948. - (void)recoverPlaybackState
  949. {
  950. if ([self.delegate respondsToSelector:@selector(mediaPlayerStateChanged:isPlaying:currentMediaHasTrackToChooseFrom:currentMediaHasChapters:forPlaybackController:)])
  951. [self.delegate mediaPlayerStateChanged:_mediaPlayer.state
  952. isPlaying:self.isPlaying
  953. currentMediaHasTrackToChooseFrom:self.currentMediaHasTrackToChooseFrom
  954. currentMediaHasChapters:self.currentMediaHasChapters
  955. forPlaybackController:self];
  956. if ([self.delegate respondsToSelector:@selector(prepareForMediaPlayback:)])
  957. [self.delegate prepareForMediaPlayback:self];
  958. }
  959. - (void)scheduleSleepTimerWithInterval:(NSTimeInterval)timeInterval
  960. {
  961. if (_sleepTimer) {
  962. [_sleepTimer invalidate];
  963. _sleepTimer = nil;
  964. }
  965. _sleepTimer = [NSTimer scheduledTimerWithTimeInterval:timeInterval target:self selector:@selector(stopPlayback) userInfo:nil repeats:NO];
  966. }
  967. #pragma mark - background interaction
  968. - (void)applicationWillResignActive:(NSNotification *)aNotification
  969. {
  970. #if TARGET_OS_IOS
  971. [self _savePlaybackState];
  972. #endif
  973. if (![[[NSUserDefaults standardUserDefaults] objectForKey:kVLCSettingContinueAudioInBackgroundKey] boolValue]) {
  974. if ([_mediaPlayer isPlaying]) {
  975. [_mediaPlayer pause];
  976. _shouldResumePlaying = YES;
  977. }
  978. }
  979. }
  980. - (void)applicationDidEnterBackground:(NSNotification *)notification
  981. {
  982. _preBackgroundWrapperView = _videoOutputViewWrapper;
  983. if (_mediaPlayer.audioTrackIndexes.count > 0)
  984. [self setVideoTrackEnabled:false];
  985. }
  986. - (void)applicationDidBecomeActive:(NSNotification *)notification
  987. {
  988. if (_preBackgroundWrapperView) {
  989. [self setVideoOutputView:_preBackgroundWrapperView];
  990. _preBackgroundWrapperView = nil;
  991. }
  992. [self setVideoTrackEnabled:true];
  993. if (_shouldResumePlaying) {
  994. _shouldResumePlaying = NO;
  995. [_listPlayer play];
  996. }
  997. }
  998. #pragma mark - remoteControlDelegate
  999. - (void)remoteControlServiceHitPause:(VLCRemoteControlService *)rcs
  1000. {
  1001. [_listPlayer pause];
  1002. }
  1003. - (void)remoteControlServiceHitPlay:(VLCRemoteControlService *)rcs
  1004. {
  1005. [_listPlayer play];
  1006. }
  1007. - (void)remoteControlServiceTogglePlayPause:(VLCRemoteControlService *)rcs
  1008. {
  1009. [self playPause];
  1010. }
  1011. - (void)remoteControlServiceHitStop:(VLCRemoteControlService *)rcs
  1012. {
  1013. //TODO handle stop playback entirely
  1014. [_listPlayer stop];
  1015. }
  1016. - (BOOL)remoteControlServiceHitPlayNextIfPossible:(VLCRemoteControlService *)rcs
  1017. {
  1018. //TODO This doesn't handle shuffle or repeat yet
  1019. return [_listPlayer next];
  1020. }
  1021. - (BOOL)remoteControlServiceHitPlayPreviousIfPossible:(VLCRemoteControlService *)rcs
  1022. {
  1023. //TODO This doesn't handle shuffle or repeat yet
  1024. return [_listPlayer previous];
  1025. }
  1026. - (void)remoteControlService:(VLCRemoteControlService *)rcs jumpForwardInSeconds:(NSTimeInterval)seconds
  1027. {
  1028. [_mediaPlayer jumpForward:seconds];
  1029. }
  1030. - (void)remoteControlService:(VLCRemoteControlService *)rcs jumpBackwardInSeconds:(NSTimeInterval)seconds
  1031. {
  1032. [_mediaPlayer jumpBackward:seconds];
  1033. }
  1034. - (NSInteger)remoteControlServiceNumberOfMediaItemsinList:(VLCRemoteControlService *)rcs
  1035. {
  1036. return _mediaList.count;
  1037. }
  1038. - (void)remoteControlService:(VLCRemoteControlService *)rcs setPlaybackRate:(CGFloat)playbackRate
  1039. {
  1040. self.playbackRate = playbackRate;
  1041. }
  1042. #pragma mark - helpers
  1043. - (NSDictionary *)mediaOptionsDictionary
  1044. {
  1045. NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
  1046. return @{ kVLCSettingNetworkCaching : [defaults objectForKey:kVLCSettingNetworkCaching],
  1047. kVLCSettingStretchAudio : [[defaults objectForKey:kVLCSettingStretchAudio] boolValue] ? kVLCSettingStretchAudioOnValue : kVLCSettingStretchAudioOffValue,
  1048. kVLCSettingTextEncoding : [defaults objectForKey:kVLCSettingTextEncoding],
  1049. kVLCSettingSkipLoopFilter : [defaults objectForKey:kVLCSettingSkipLoopFilter],
  1050. kVLCSettingHardwareDecoding : [defaults objectForKey:kVLCSettingHardwareDecoding]};
  1051. }
  1052. @end