VLCPlaybackController.m 42 KB

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