VLCPlaybackController.m 40 KB

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