VLCPlaybackController.m 41 KB

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