VLCPlaybackController.m 41 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269
  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 openVideoSubTitlesFromFile:pathToFile];
  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. [_playbackSessionManagementLock unlock];
  204. }
  205. - (void)stopPlayback
  206. {
  207. BOOL ret = [_playbackSessionManagementLock tryLock];
  208. if (!ret) {
  209. APLog(@"%s: locking failed", __PRETTY_FUNCTION__);
  210. return;
  211. }
  212. if (_mediaPlayer) {
  213. @try {
  214. [_mediaPlayer removeObserver:self forKeyPath:@"time"];
  215. [_mediaPlayer removeObserver:self forKeyPath:@"remainingTime"];
  216. }
  217. @catch (NSException *exception) {
  218. APLog(@"we weren't an observer yet");
  219. }
  220. if (_mediaPlayer.media) {
  221. [_mediaPlayer pause];
  222. #if TARGET_OS_IOS
  223. [self _savePlaybackState];
  224. #endif
  225. [_mediaPlayer stop];
  226. }
  227. _mediaPlayer = nil;
  228. _listPlayer = nil;
  229. }
  230. if (!_sessionWillRestart) {
  231. _mediaList = nil;
  232. if (_pathToExternalSubtitlesFile) {
  233. NSFileManager *fileManager = [NSFileManager defaultManager];
  234. if ([fileManager fileExistsAtPath:_pathToExternalSubtitlesFile])
  235. [fileManager removeItemAtPath:_pathToExternalSubtitlesFile error:nil];
  236. _pathToExternalSubtitlesFile = nil;
  237. }
  238. }
  239. _playerIsSetup = NO;
  240. [_shuffleStack removeAllObjects];
  241. if (_errorCallback && _mediaPlayer.state == VLCMediaPlayerStateError && !_sessionWillRestart)
  242. [[UIApplication sharedApplication] openURL:_errorCallback];
  243. else if (_successCallback && !_sessionWillRestart)
  244. [[UIApplication sharedApplication] openURL:_successCallback];
  245. [[self remoteControlService] unsubscribeFromRemoteCommands];
  246. [_playbackSessionManagementLock unlock];
  247. if (_sessionWillRestart) {
  248. _sessionWillRestart = NO;
  249. [self startPlayback];
  250. }
  251. }
  252. #if TARGET_OS_IOS
  253. - (void)_savePlaybackState
  254. {
  255. @try {
  256. [[MLMediaLibrary sharedMediaLibrary] save];
  257. }
  258. @catch (NSException *exception) {
  259. APLog(@"saving playback state failed");
  260. }
  261. NSArray *files = [MLFile fileForURL:_mediaPlayer.media.url];
  262. MLFile *fileItem = files.firstObject;
  263. if (!fileItem) {
  264. APLog(@"couldn't find file, not saving playback progress");
  265. return;
  266. }
  267. @try {
  268. float position = _mediaPlayer.position;
  269. fileItem.lastPosition = @(position);
  270. fileItem.lastAudioTrack = @(_mediaPlayer.currentAudioTrackIndex);
  271. fileItem.lastSubtitleTrack = @(_mediaPlayer.currentVideoSubTitleIndex);
  272. if (position > .95)
  273. return;
  274. if (_mediaPlayer.hasVideoOut) {
  275. NSArray *searchPaths = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES);
  276. NSString *newThumbnailPath = [searchPaths.firstObject stringByAppendingPathComponent:@"VideoSnapshots"];
  277. NSError *error;
  278. [[NSFileManager defaultManager] createDirectoryAtPath:newThumbnailPath withIntermediateDirectories:YES attributes:nil error:&error];
  279. if (error == nil) {
  280. newThumbnailPath = [newThumbnailPath stringByAppendingPathComponent:fileItem.objectID.URIRepresentation.lastPathComponent];
  281. [_mediaPlayer saveVideoSnapshotAt:newThumbnailPath withWidth:0 andHeight:0];
  282. _recheckForExistingThumbnail = YES;
  283. [self performSelector:@selector(_updateStoredThumbnailForFile:) withObject:fileItem afterDelay:.25];
  284. }
  285. }
  286. }
  287. @catch (NSException *exception) {
  288. APLog(@"failed to save current media state - file removed?");
  289. }
  290. }
  291. #endif
  292. #if TARGET_OS_IOS
  293. - (void)_updateStoredThumbnailForFile:(MLFile *)fileItem
  294. {
  295. NSFileManager *fileManager = [NSFileManager defaultManager];
  296. NSArray *searchPaths = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES);
  297. NSString* newThumbnailPath = [searchPaths[0] stringByAppendingPathComponent:@"VideoSnapshots"];
  298. newThumbnailPath = [newThumbnailPath stringByAppendingPathComponent:fileItem.objectID.URIRepresentation.lastPathComponent];
  299. if (![fileManager fileExistsAtPath:newThumbnailPath]) {
  300. if (_recheckForExistingThumbnail) {
  301. [self performSelector:@selector(_updateStoredThumbnailForFile:) withObject:fileItem afterDelay:1.];
  302. _recheckForExistingThumbnail = NO;
  303. } else
  304. return;
  305. }
  306. UIImage *newThumbnail = [UIImage imageWithContentsOfFile:newThumbnailPath];
  307. if (!newThumbnail) {
  308. if (_recheckForExistingThumbnail) {
  309. [self performSelector:@selector(_updateStoredThumbnailForFile:) withObject:fileItem afterDelay:1.];
  310. _recheckForExistingThumbnail = NO;
  311. } else
  312. return;
  313. }
  314. @try {
  315. [fileItem setComputedThumbnailScaledForDevice:newThumbnail];
  316. }
  317. @catch (NSException *exception) {
  318. APLog(@"updating thumbnail failed");
  319. }
  320. [fileManager removeItemAtPath:newThumbnailPath error:nil];
  321. }
  322. #endif
  323. - (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context
  324. {
  325. if (_mediaWasJustStarted) {
  326. _mediaWasJustStarted = NO;
  327. #if TARGET_OS_IOS
  328. if (self.mediaList) {
  329. NSArray *matches = [MLFile fileForURL:_mediaPlayer.media.url];
  330. MLFile *item = matches.firstObject;
  331. [self _recoverLastPlaybackStateOfItem:item];
  332. }
  333. #else
  334. NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
  335. BOOL bValue = [defaults boolForKey:kVLCSettingUseSPDIF];
  336. if (bValue) {
  337. _mediaPlayer.audio.passthrough = bValue;
  338. }
  339. #endif
  340. }
  341. if ([self.delegate respondsToSelector:@selector(playbackPositionUpdated:)])
  342. [self.delegate playbackPositionUpdated:self];
  343. [[NSNotificationCenter defaultCenter] postNotificationName:VLCPlaybackControllerPlaybackPositionUpdated
  344. object:self];
  345. }
  346. - (NSInteger)mediaDuration
  347. {
  348. return _mediaPlayer.media.length.intValue;;
  349. }
  350. - (BOOL)isPlaying
  351. {
  352. return _mediaPlayer.isPlaying;
  353. }
  354. - (BOOL)willPlay
  355. {
  356. return _mediaPlayer.willPlay;
  357. }
  358. - (VLCRepeatMode)repeatMode
  359. {
  360. return _listPlayer.repeatMode;
  361. }
  362. - (void)setRepeatMode:(VLCRepeatMode)repeatMode
  363. {
  364. _listPlayer.repeatMode = repeatMode;
  365. }
  366. - (BOOL)currentMediaHasChapters
  367. {
  368. return [_mediaPlayer numberOfTitles] > 1 || [_mediaPlayer numberOfChaptersForTitle:_mediaPlayer.currentTitleIndex] > 1;
  369. }
  370. - (BOOL)currentMediaHasTrackToChooseFrom
  371. {
  372. return [[_mediaPlayer audioTrackIndexes] count] > 2 || [[_mediaPlayer videoSubTitlesIndexes] count] > 1;
  373. }
  374. - (BOOL) isSeekable
  375. {
  376. return _mediaPlayer.isSeekable;
  377. }
  378. - (NSNumber *)playbackTime
  379. {
  380. return _mediaPlayer.time.value;
  381. }
  382. - (float)playbackRate
  383. {
  384. return _mediaPlayer.rate;
  385. }
  386. - (void)setPlaybackRate:(float)playbackRate
  387. {
  388. [_mediaPlayer setRate:playbackRate];
  389. _metadata.playbackRate = @(_mediaPlayer.rate);
  390. }
  391. - (void)setAudioDelay:(float)audioDelay
  392. {
  393. _mediaPlayer.currentAudioPlaybackDelay = 1000000.*audioDelay;
  394. }
  395. - (float)audioDelay
  396. {
  397. return _mediaPlayer.currentAudioPlaybackDelay/1000000.;
  398. }
  399. - (float)playbackPosition
  400. {
  401. return [_mediaPlayer position];
  402. }
  403. - (void)setPlaybackPosition:(float)position
  404. {
  405. _mediaPlayer.position = position;
  406. }
  407. - (void)setSubtitleDelay:(float)subtitleDeleay
  408. {
  409. _mediaPlayer.currentVideoSubTitleDelay = 1000000.*subtitleDeleay;
  410. }
  411. - (float)subtitleDelay
  412. {
  413. return _mediaPlayer.currentVideoSubTitleDelay/1000000.;
  414. }
  415. - (float)hue
  416. {
  417. return _mediaPlayer.hue;
  418. }
  419. - (void)setHue:(float)hue
  420. {
  421. _mediaPlayer.hue = hue;
  422. }
  423. - (float)contrast
  424. {
  425. return _mediaPlayer.contrast;
  426. }
  427. - (void)setContrast:(float)contrast
  428. {
  429. _mediaPlayer.contrast = contrast;
  430. }
  431. - (float)brightness
  432. {
  433. return _mediaPlayer.brightness;
  434. }
  435. - (void)setBrightness:(float)brightness
  436. {
  437. _mediaPlayer.brightness = brightness;
  438. }
  439. - (float)saturation
  440. {
  441. return _mediaPlayer.saturation;
  442. }
  443. - (void)setSaturation:(float)saturation
  444. {
  445. _mediaPlayer.saturation = saturation;
  446. }
  447. - (void)setGamma:(float)gamma
  448. {
  449. _mediaPlayer.gamma = gamma;
  450. }
  451. - (float)gamma
  452. {
  453. return _mediaPlayer.gamma;
  454. }
  455. - (void)resetFilters
  456. {
  457. _mediaPlayer.hue = 0.;
  458. _mediaPlayer.contrast = 1.;
  459. _mediaPlayer.brightness = 1.;
  460. _mediaPlayer.saturation = 1.;
  461. _mediaPlayer.gamma = 1.;
  462. }
  463. - (void)toggleRepeatMode
  464. {
  465. VLCRepeatMode nextRepeatMode = VLCDoNotRepeat;
  466. switch (_listPlayer.repeatMode) {
  467. case VLCDoNotRepeat:
  468. nextRepeatMode = VLCRepeatCurrentItem;
  469. break;
  470. case VLCRepeatCurrentItem:
  471. nextRepeatMode = VLCRepeatAllItems;
  472. break;
  473. default:
  474. nextRepeatMode = VLCDoNotRepeat;
  475. break;
  476. }
  477. _listPlayer.repeatMode = nextRepeatMode;
  478. }
  479. - (NSInteger)indexOfCurrentAudioTrack
  480. {
  481. return [_mediaPlayer.audioTrackIndexes indexOfObject:@(_mediaPlayer.currentAudioTrackIndex)];
  482. }
  483. - (NSInteger)indexOfCurrentSubtitleTrack
  484. {
  485. return [_mediaPlayer.videoSubTitlesIndexes indexOfObject:@(_mediaPlayer.currentVideoSubTitleIndex)];
  486. }
  487. - (NSInteger)indexOfCurrentChapter
  488. {
  489. return _mediaPlayer.currentChapterIndex;
  490. }
  491. - (NSInteger)indexOfCurrentTitle
  492. {
  493. return _mediaPlayer.currentTitleIndex;
  494. }
  495. - (NSInteger)numberOfAudioTracks
  496. {
  497. return _mediaPlayer.audioTrackIndexes.count;
  498. }
  499. - (NSInteger)numberOfVideoSubtitlesIndexes
  500. {
  501. return _mediaPlayer.videoSubTitlesIndexes.count;
  502. }
  503. - (NSInteger)numberOfTitles
  504. {
  505. return [_mediaPlayer numberOfTitles];
  506. }
  507. - (NSInteger)numberOfChaptersForCurrentTitle
  508. {
  509. return [_mediaPlayer numberOfChaptersForTitle:_mediaPlayer.currentTitleIndex];
  510. }
  511. - (NSString *)videoSubtitleNameAtIndex:(NSInteger)index
  512. {
  513. if (index >= 0 && index < _mediaPlayer.videoSubTitlesNames.count)
  514. return _mediaPlayer.videoSubTitlesNames[index];
  515. return nil;
  516. }
  517. - (NSString *)audioTrackNameAtIndex:(NSInteger)index
  518. {
  519. if (index >= 0 && index < _mediaPlayer.audioTrackNames.count)
  520. return _mediaPlayer.audioTrackNames[index];
  521. return nil;
  522. }
  523. - (NSDictionary *)titleDescriptionsDictAtIndex:(NSInteger)index
  524. {
  525. if (index >= 0 && index < _mediaPlayer.titleDescriptions.count)
  526. return _mediaPlayer.titleDescriptions[index];
  527. return nil;
  528. }
  529. - (NSDictionary *)chapterDescriptionsDictAtIndex:(NSInteger)index
  530. {
  531. NSArray *chapterDescriptions = [_mediaPlayer chapterDescriptionsOfTitle:_mediaPlayer.currentTitleIndex];
  532. if (index >= 0 && index < chapterDescriptions.count)
  533. return chapterDescriptions[index];
  534. return nil;
  535. }
  536. - (void)selectAudioTrackAtIndex:(NSInteger)index
  537. {
  538. if (index >= 0 && index < _mediaPlayer.audioTrackIndexes.count) {
  539. //we can cast this cause we won't have more than 2 million audiotracks
  540. _mediaPlayer.currentAudioTrackIndex = [_mediaPlayer.audioTrackIndexes[index] intValue];
  541. }
  542. }
  543. - (void)selectVideoSubtitleAtIndex:(NSInteger)index
  544. {
  545. if (index >= 0 && index < _mediaPlayer.videoSubTitlesIndexes.count) {
  546. _mediaPlayer.currentVideoSubTitleIndex = [_mediaPlayer.videoSubTitlesIndexes[index] intValue];
  547. }
  548. }
  549. - (void)selectTitleAtIndex:(NSInteger)index
  550. {
  551. if (index >= 0 && index < [_mediaPlayer numberOfTitles]) {
  552. //we can cast this cause we won't have more than 2 million titles
  553. _mediaPlayer.currentTitleIndex = (int)index;
  554. }
  555. }
  556. - (void)selectChapterAtIndex:(NSInteger)index
  557. {
  558. if (index >= 0 && index < [self numberOfChaptersForCurrentTitle]) {
  559. //we can cast this cause we won't have more than 2 million chapters
  560. _mediaPlayer.currentChapterIndex = (int)index;
  561. }
  562. }
  563. - (void)shortJumpForward
  564. {
  565. [_mediaPlayer shortJumpForward];
  566. }
  567. - (void)shortJumpBackward
  568. {
  569. [_mediaPlayer shortJumpBackward];
  570. }
  571. - (VLCTime *)remainingTime
  572. {
  573. return [_mediaPlayer remainingTime];
  574. }
  575. - (void)setAudioPassthrough:(BOOL)shouldPass
  576. {
  577. _mediaPlayer.audio.passthrough = shouldPass;
  578. }
  579. - (void)mediaPlayerStateChanged:(NSNotification *)aNotification
  580. {
  581. switch (_mediaPlayer.state) {
  582. case VLCMediaPlayerStateBuffering: {
  583. _mediaPlayer.media.delegate = self;
  584. /* on-the-fly values through hidden API */
  585. NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
  586. [_mediaPlayer performSelector:@selector(setTextRendererFont:) withObject:[defaults objectForKey:kVLCSettingSubtitlesFont]];
  587. [_mediaPlayer performSelector:@selector(setTextRendererFontSize:) withObject:[defaults objectForKey:kVLCSettingSubtitlesFontSize]];
  588. [_mediaPlayer performSelector:@selector(setTextRendererFontColor:) withObject:[defaults objectForKey:kVLCSettingSubtitlesFontColor]];
  589. [_mediaPlayer performSelector:@selector(setTextRendererFontForceBold:) withObject:[defaults objectForKey:kVLCSettingSubtitlesBoldFont]];
  590. break;
  591. }
  592. case VLCMediaPlayerStateError: {
  593. APLog(@"Playback failed");
  594. dispatch_async(dispatch_get_main_queue(),^{
  595. [[NSNotificationCenter defaultCenter] postNotificationName:VLCPlaybackControllerPlaybackDidFail object:self];
  596. });
  597. _sessionWillRestart = NO;
  598. [self stopPlayback];
  599. }
  600. case VLCMediaPlayerStateEnded:
  601. case VLCMediaPlayerStateStopped: {
  602. [_listPlayer.mediaList lock];
  603. NSUInteger listCount = _listPlayer.mediaList.count;
  604. if ([_listPlayer.mediaList indexOfMedia:_mediaPlayer.media] == listCount - 1 && self.repeatMode == VLCDoNotRepeat) {
  605. [_listPlayer.mediaList unlock];
  606. _sessionWillRestart = NO;
  607. [self stopPlayback];
  608. return;
  609. } else if (listCount > 1) {
  610. [_listPlayer.mediaList unlock];
  611. [_listPlayer next];
  612. } else
  613. [_listPlayer.mediaList unlock];
  614. dispatch_async(dispatch_get_main_queue(),^{
  615. [[NSNotificationCenter defaultCenter] postNotificationName:VLCPlaybackControllerPlaybackDidStop object:self];
  616. });
  617. } break;
  618. case VLCMediaPlayerStatePlaying: {
  619. dispatch_async(dispatch_get_main_queue(),^{
  620. [[NSNotificationCenter defaultCenter] postNotificationName:VLCPlaybackControllerPlaybackDidStart object:self];
  621. });
  622. break;
  623. }
  624. case VLCMediaPlayerStateOpening:
  625. case VLCMediaPlayerStatePaused:
  626. break;
  627. }
  628. if ([self.delegate respondsToSelector:@selector(mediaPlayerStateChanged:isPlaying:currentMediaHasTrackToChooseFrom:currentMediaHasChapters:forPlaybackController:)])
  629. [self.delegate mediaPlayerStateChanged:_mediaPlayer.state
  630. isPlaying:_mediaPlayer.isPlaying
  631. currentMediaHasTrackToChooseFrom:self.currentMediaHasTrackToChooseFrom
  632. currentMediaHasChapters:self.currentMediaHasChapters
  633. forPlaybackController:self];
  634. [self setNeedsMetadataUpdate];
  635. }
  636. #pragma mark - playback controls
  637. - (void)playPause
  638. {
  639. [_mediaPlayer isPlaying] ? [self pause] : [self play];
  640. }
  641. - (void)play
  642. {
  643. [_listPlayer play];
  644. [[NSNotificationCenter defaultCenter] postNotificationName:VLCPlaybackControllerPlaybackDidResume object:self];
  645. }
  646. - (void)pause
  647. {
  648. [_listPlayer pause];
  649. #if TARGET_OS_IOS
  650. [self _savePlaybackState];
  651. #endif
  652. [[NSNotificationCenter defaultCenter] postNotificationName:VLCPlaybackControllerPlaybackDidPause object:self];
  653. }
  654. - (void)next
  655. {
  656. NSInteger mediaListCount = _mediaList.count;
  657. #if TARGET_OS_IOS
  658. if (self.repeatMode != VLCRepeatCurrentItem && mediaListCount > 2 && _shuffleMode) {
  659. NSNumber *nextIndex;
  660. NSUInteger currentIndex = [_mediaList indexOfMedia:_listPlayer.mediaPlayer.media];
  661. //Reached end of playlist
  662. if (_shuffleStack.count + 1 == mediaListCount) {
  663. if ([self repeatMode] == VLCDoNotRepeat)
  664. return;
  665. [_shuffleStack removeAllObjects];
  666. }
  667. [_shuffleStack addObject:[NSNumber numberWithUnsignedInteger:currentIndex]];
  668. do {
  669. nextIndex = [NSNumber numberWithUnsignedInt:arc4random_uniform((uint32_t)mediaListCount)];
  670. } while (currentIndex == nextIndex.unsignedIntegerValue || [_shuffleStack containsObject:nextIndex]);
  671. [_listPlayer playItemAtNumber:[NSNumber numberWithUnsignedInteger:nextIndex.unsignedIntegerValue]];
  672. [[NSNotificationCenter defaultCenter] postNotificationName:VLCPlaybackControllerPlaybackMetadataDidChange object:self];
  673. return;
  674. }
  675. #endif
  676. if (mediaListCount > 1) {
  677. [_listPlayer next];
  678. [[NSNotificationCenter defaultCenter] postNotificationName:VLCPlaybackControllerPlaybackMetadataDidChange object:self];
  679. } else {
  680. NSNumber *skipLength = [[NSUserDefaults standardUserDefaults] valueForKey:kVLCSettingPlaybackForwardSkipLength];
  681. [_mediaPlayer jumpForward:skipLength.intValue];
  682. }
  683. }
  684. - (void)previous
  685. {
  686. if (_mediaList.count > 1) {
  687. [_listPlayer previous];
  688. [[NSNotificationCenter defaultCenter] postNotificationName:VLCPlaybackControllerPlaybackMetadataDidChange object:self];
  689. }
  690. else {
  691. NSNumber *skipLength = [[NSUserDefaults standardUserDefaults] valueForKey:kVLCSettingPlaybackBackwardSkipLength];
  692. [_mediaPlayer jumpBackward:skipLength.intValue];
  693. }
  694. }
  695. - (void)jumpForward:(int)interval
  696. {
  697. [_mediaPlayer jumpForward:interval];
  698. }
  699. - (void)jumpBackward:(int)interval
  700. {
  701. [_mediaPlayer jumpBackward:interval];
  702. }
  703. - (NSString *)screenAspectRatio
  704. {
  705. UIScreen *screen = [[UIDevice currentDevice] VLCHasExternalDisplay] ? [UIScreen screens][1] : [UIScreen mainScreen];
  706. return [NSString stringWithFormat:@"%d:%d", (int)screen.bounds.size.width, (int)screen.bounds.size.height];
  707. }
  708. - (void)switchIPhoneXFullScreen
  709. {
  710. BOOL inFullScreen = _mediaPlayer.videoCropGeometry && [[NSString stringWithUTF8String:_mediaPlayer.videoCropGeometry] isEqualToString:[self screenAspectRatio]];
  711. if (inFullScreen) {
  712. const char *previousAspectRatio = _currentAspectRatio == VLCAspectRatioDefault ? NULL : [[self stringForAspectRatio:_currentAspectRatio] UTF8String];
  713. _mediaPlayer.videoAspectRatio = (char *)previousAspectRatio;
  714. }
  715. _mediaPlayer.videoCropGeometry = inFullScreen ? NULL : (char *)[[self screenAspectRatio] UTF8String];
  716. }
  717. - (void)switchAspectRatio
  718. {
  719. _currentAspectRatio = _currentAspectRatio == VLCAspectRatioSixteenToTen ? VLCAspectRatioDefault : _currentAspectRatio + 1;
  720. switch (_currentAspectRatio) {
  721. case VLCAspectRatioDefault:
  722. _mediaPlayer.videoAspectRatio = NULL;
  723. _mediaPlayer.videoCropGeometry = NULL;
  724. break;
  725. case VLCAspectRatioFillToScreen:
  726. _mediaPlayer.videoCropGeometry = (char *)[[self screenAspectRatio] UTF8String];
  727. break;
  728. case VLCAspectRatioFourToThree:
  729. case VLCAspectRatioSixteenToTen:
  730. case VLCAspectRatioSixteenToNine:
  731. _mediaPlayer.videoCropGeometry = NULL;
  732. _mediaPlayer.videoAspectRatio = (char *)[[self stringForAspectRatio:_currentAspectRatio] UTF8String];
  733. }
  734. if ([self.delegate respondsToSelector:@selector(showStatusMessage:forPlaybackController:)]) {
  735. [self.delegate showStatusMessage:[NSString stringWithFormat:NSLocalizedString(@"AR_CHANGED", nil), [self stringForAspectRatio:_currentAspectRatio]] forPlaybackController:self];
  736. }
  737. }
  738. - (NSString *)stringForAspectRatio:(VLCAspectRatio)ratio
  739. {
  740. switch (ratio) {
  741. case VLCAspectRatioFillToScreen:
  742. return NSLocalizedString(@"FILL_TO_SCREEN", nil);
  743. case VLCAspectRatioDefault:
  744. return NSLocalizedString(@"DEFAULT", nil);
  745. case VLCAspectRatioFourToThree:
  746. return @"4:3";
  747. case VLCAspectRatioSixteenToTen:
  748. return @"16:10";
  749. case VLCAspectRatioSixteenToNine:
  750. return @"16:9";
  751. default:
  752. NSAssert(NO, @"this shouldn't happen");
  753. }
  754. }
  755. - (void)setVideoTrackEnabled:(BOOL)enabled
  756. {
  757. if (!enabled)
  758. _mediaPlayer.currentVideoTrackIndex = -1;
  759. else if (_mediaPlayer.currentVideoTrackIndex == -1) {
  760. for (NSNumber *trackId in _mediaPlayer.videoTrackIndexes) {
  761. if ([trackId intValue] != -1) {
  762. _mediaPlayer.currentVideoTrackIndex = [trackId intValue];
  763. break;
  764. }
  765. }
  766. }
  767. }
  768. - (void)setVideoOutputView:(UIView *)videoOutputView
  769. {
  770. if (videoOutputView) {
  771. if ([_actualVideoOutputView superview] != nil)
  772. [_actualVideoOutputView removeFromSuperview];
  773. _actualVideoOutputView.frame = (CGRect){CGPointZero, videoOutputView.frame.size};
  774. [self setVideoTrackEnabled:true];
  775. [videoOutputView addSubview:_actualVideoOutputView];
  776. [_actualVideoOutputView layoutSubviews];
  777. [_actualVideoOutputView updateConstraints];
  778. [_actualVideoOutputView setNeedsLayout];
  779. } else
  780. [_actualVideoOutputView removeFromSuperview];
  781. _videoOutputViewWrapper = videoOutputView;
  782. }
  783. - (UIView *)videoOutputView
  784. {
  785. return _videoOutputViewWrapper;
  786. }
  787. #pragma mark - 360 Support
  788. #if !TARGET_OS_TV
  789. - (BOOL)updateViewpoint:(CGFloat)yaw pitch:(CGFloat)pitch roll:(CGFloat)roll fov:(CGFloat)fov absolute:(BOOL)absolute
  790. {
  791. return [_mediaPlayer updateViewpoint:yaw pitch:pitch roll:roll fov:fov absolute:absolute];
  792. }
  793. - (NSInteger)currentMediaProjection
  794. {
  795. VLCMedia *media = [_mediaPlayer media];
  796. NSInteger currentVideoTrackIndex = [_mediaPlayer currentVideoTrackIndex];
  797. if (media && currentVideoTrackIndex >= 0) {
  798. NSArray *tracksInfo = media.tracksInformation;
  799. for (NSDictionary *track in tracksInfo) {
  800. if ([track[VLCMediaTracksInformationType] isEqualToString:VLCMediaTracksInformationTypeVideo]) {
  801. return [track[VLCMediaTracksInformationVideoProjection] integerValue];
  802. }
  803. }
  804. }
  805. return -1;
  806. }
  807. #endif
  808. #pragma mark - equalizer
  809. - (void)setAmplification:(CGFloat)amplification forBand:(unsigned int)index
  810. {
  811. if (!_mediaPlayer.equalizerEnabled)
  812. [_mediaPlayer setEqualizerEnabled:YES];
  813. [_mediaPlayer setAmplification:amplification forBand:index];
  814. // For some reason we have to apply again preamp to apply change
  815. [_mediaPlayer setPreAmplification:[_mediaPlayer preAmplification]];
  816. }
  817. - (CGFloat)amplificationOfBand:(unsigned int)index
  818. {
  819. return [_mediaPlayer amplificationOfBand:index];
  820. }
  821. - (NSArray *)equalizerProfiles
  822. {
  823. return _mediaPlayer.equalizerProfiles;
  824. }
  825. - (void)resetEqualizerFromProfile:(unsigned int)profile
  826. {
  827. [[NSUserDefaults standardUserDefaults] setObject:@(profile) forKey:kVLCSettingEqualizerProfile];
  828. [_mediaPlayer resetEqualizerFromProfile:profile];
  829. }
  830. - (void)setPreAmplification:(CGFloat)preAmplification
  831. {
  832. if (!_mediaPlayer.equalizerEnabled)
  833. [_mediaPlayer setEqualizerEnabled:YES];
  834. [_mediaPlayer setPreAmplification:preAmplification];
  835. }
  836. - (CGFloat)preAmplification
  837. {
  838. return [_mediaPlayer preAmplification];
  839. }
  840. #pragma mark - AVAudioSession Notification Observers
  841. - (void)handleInterruption:(NSNotification *)notification
  842. {
  843. NSDictionary *userInfo = notification.userInfo;
  844. if (!userInfo || !userInfo[AVAudioSessionInterruptionTypeKey]) {
  845. return;
  846. }
  847. NSUInteger interruptionType = [userInfo[AVAudioSessionInterruptionTypeKey] unsignedIntegerValue];
  848. if (interruptionType == AVAudioSessionInterruptionTypeBegan) {
  849. [_mediaPlayer pause];
  850. } else if (interruptionType == AVAudioSessionInterruptionTypeEnded
  851. && [userInfo[AVAudioSessionInterruptionOptionKey] unsignedIntegerValue] == AVAudioSessionInterruptionOptionShouldResume) {
  852. [_mediaPlayer play];
  853. }
  854. }
  855. - (BOOL)areHeadphonesPlugged
  856. {
  857. NSArray *outputs = [[AVAudioSession sharedInstance] currentRoute].outputs;
  858. NSString *portName = [[outputs firstObject] portName];
  859. return [portName isEqualToString:@"Headphones"];
  860. }
  861. - (void)audioSessionRouteChange:(NSNotification *)notification
  862. {
  863. NSDictionary *userInfo = notification.userInfo;
  864. NSInteger routeChangeReason = [[userInfo valueForKey:AVAudioSessionRouteChangeReasonKey] integerValue];
  865. if (routeChangeReason == AVAudioSessionRouteChangeReasonRouteConfigurationChange)
  866. return;
  867. BOOL headphonesPlugged = [self areHeadphonesPlugged];
  868. if (_headphonesWasPlugged && !headphonesPlugged && [_mediaPlayer isPlaying]) {
  869. [_mediaPlayer pause];
  870. #if TARGET_OS_IOS
  871. [self _savePlaybackState];
  872. #endif
  873. [[NSNotificationCenter defaultCenter] postNotificationName:VLCPlaybackControllerPlaybackDidPause object:self];
  874. }
  875. _headphonesWasPlugged = headphonesPlugged;
  876. }
  877. #pragma mark - Managing the media item
  878. - (VLCMedia *)currentlyPlayingMedia
  879. {
  880. return _mediaPlayer.media;
  881. }
  882. #pragma mark - metadata handling
  883. - (void)performNavigationAction:(VLCMediaPlaybackNavigationAction)action
  884. {
  885. [_mediaPlayer performNavigationAction:action];
  886. }
  887. - (void)mediaDidFinishParsing:(VLCMedia *)aMedia
  888. {
  889. [self setNeedsMetadataUpdate];
  890. }
  891. - (void)mediaMetaDataDidChange:(VLCMedia*)aMedia
  892. {
  893. [self setNeedsMetadataUpdate];
  894. }
  895. - (void)setNeedsMetadataUpdate
  896. {
  897. if (_needsMetadataUpdate == NO) {
  898. _needsMetadataUpdate = YES;
  899. dispatch_async(dispatch_get_main_queue(), ^{
  900. [_metadata updateMetadataFromMediaPlayer:_mediaPlayer];
  901. _needsMetadataUpdate = NO;
  902. if ([self.delegate respondsToSelector:@selector(displayMetadataForPlaybackController:metadata:)])
  903. [self.delegate displayMetadataForPlaybackController:self metadata:_metadata];
  904. });
  905. }
  906. }
  907. #if TARGET_OS_IOS
  908. - (void)_recoverLastPlaybackStateOfItem:(MLFile *)item
  909. {
  910. if (item) {
  911. if (_mediaPlayer.numberOfAudioTracks > 2) {
  912. if (item.lastAudioTrack.intValue > 0)
  913. _mediaPlayer.currentAudioTrackIndex = item.lastAudioTrack.intValue;
  914. }
  915. if (_mediaPlayer.numberOfSubtitlesTracks > 2) {
  916. if (item.lastSubtitleTrack.intValue > 0)
  917. _mediaPlayer.currentVideoSubTitleIndex = item.lastSubtitleTrack.intValue;
  918. }
  919. CGFloat lastPosition = .0;
  920. NSInteger duration = 0;
  921. if (item.lastPosition)
  922. lastPosition = item.lastPosition.floatValue;
  923. duration = item.duration.intValue;
  924. if (lastPosition < .95 && _mediaPlayer.position < lastPosition) {
  925. NSInteger continuePlayback;
  926. if ([item isAlbumTrack] || [item isSupportedAudioFile])
  927. continuePlayback = [[[NSUserDefaults standardUserDefaults] objectForKey:kVLCSettingContinueAudioPlayback] integerValue];
  928. else
  929. continuePlayback = [[[NSUserDefaults standardUserDefaults] objectForKey:kVLCSettingContinuePlayback] integerValue];
  930. if (continuePlayback == 1) {
  931. _mediaPlayer.position = lastPosition;
  932. } else if (continuePlayback == 0) {
  933. VLCAlertView *alert = [[VLCAlertView alloc] initWithTitle:NSLocalizedString(@"CONTINUE_PLAYBACK", nil)
  934. message:[NSString stringWithFormat:NSLocalizedString(@"CONTINUE_PLAYBACK_LONG", nil), item.title]
  935. delegate:self
  936. cancelButtonTitle:NSLocalizedString(@"BUTTON_CANCEL", nil)
  937. otherButtonTitles:NSLocalizedString(@"BUTTON_CONTINUE", nil), nil];
  938. alert.completion = ^(BOOL cancelled, NSInteger buttonIndex) {
  939. if (!cancelled) {
  940. _mediaPlayer.position = lastPosition;
  941. }
  942. };
  943. [alert show];
  944. }
  945. }
  946. }
  947. }
  948. #endif
  949. - (void)recoverDisplayedMetadata
  950. {
  951. if ([self.delegate respondsToSelector:@selector(displayMetadataForPlaybackController:metadata:)])
  952. [self.delegate displayMetadataForPlaybackController:self metadata:_metadata];
  953. }
  954. - (void)recoverPlaybackState
  955. {
  956. if ([self.delegate respondsToSelector:@selector(mediaPlayerStateChanged:isPlaying:currentMediaHasTrackToChooseFrom:currentMediaHasChapters:forPlaybackController:)])
  957. [self.delegate mediaPlayerStateChanged:_mediaPlayer.state
  958. isPlaying:self.isPlaying
  959. currentMediaHasTrackToChooseFrom:self.currentMediaHasTrackToChooseFrom
  960. currentMediaHasChapters:self.currentMediaHasChapters
  961. forPlaybackController:self];
  962. if ([self.delegate respondsToSelector:@selector(prepareForMediaPlayback:)])
  963. [self.delegate prepareForMediaPlayback:self];
  964. }
  965. - (void)scheduleSleepTimerWithInterval:(NSTimeInterval)timeInterval
  966. {
  967. if (_sleepTimer) {
  968. [_sleepTimer invalidate];
  969. _sleepTimer = nil;
  970. }
  971. _sleepTimer = [NSTimer scheduledTimerWithTimeInterval:timeInterval target:self selector:@selector(stopPlayback) userInfo:nil repeats:NO];
  972. }
  973. #pragma mark - background interaction
  974. - (void)applicationWillResignActive:(NSNotification *)aNotification
  975. {
  976. #if TARGET_OS_IOS
  977. [self _savePlaybackState];
  978. #endif
  979. if (![[[NSUserDefaults standardUserDefaults] objectForKey:kVLCSettingContinueAudioInBackgroundKey] boolValue]) {
  980. if ([_mediaPlayer isPlaying]) {
  981. [_mediaPlayer pause];
  982. _shouldResumePlaying = YES;
  983. }
  984. }
  985. }
  986. - (void)applicationDidEnterBackground:(NSNotification *)notification
  987. {
  988. _preBackgroundWrapperView = _videoOutputViewWrapper;
  989. if (_mediaPlayer.audioTrackIndexes.count > 0)
  990. [self setVideoTrackEnabled:false];
  991. }
  992. - (void)applicationDidBecomeActive:(NSNotification *)notification
  993. {
  994. if (_preBackgroundWrapperView) {
  995. [self setVideoOutputView:_preBackgroundWrapperView];
  996. _preBackgroundWrapperView = nil;
  997. }
  998. [self setVideoTrackEnabled:true];
  999. if (_shouldResumePlaying) {
  1000. _shouldResumePlaying = NO;
  1001. [_listPlayer play];
  1002. }
  1003. }
  1004. #pragma mark - remoteControlDelegate
  1005. - (void)remoteControlServiceHitPause:(VLCRemoteControlService *)rcs
  1006. {
  1007. [_listPlayer pause];
  1008. }
  1009. - (void)remoteControlServiceHitPlay:(VLCRemoteControlService *)rcs
  1010. {
  1011. [_listPlayer play];
  1012. }
  1013. - (void)remoteControlServiceTogglePlayPause:(VLCRemoteControlService *)rcs
  1014. {
  1015. [self playPause];
  1016. }
  1017. - (void)remoteControlServiceHitStop:(VLCRemoteControlService *)rcs
  1018. {
  1019. //TODO handle stop playback entirely
  1020. [_listPlayer stop];
  1021. }
  1022. - (BOOL)remoteControlServiceHitPlayNextIfPossible:(VLCRemoteControlService *)rcs
  1023. {
  1024. //TODO This doesn't handle shuffle or repeat yet
  1025. return [_listPlayer next];
  1026. }
  1027. - (BOOL)remoteControlServiceHitPlayPreviousIfPossible:(VLCRemoteControlService *)rcs
  1028. {
  1029. //TODO This doesn't handle shuffle or repeat yet
  1030. return [_listPlayer previous];
  1031. }
  1032. - (void)remoteControlService:(VLCRemoteControlService *)rcs jumpForwardInSeconds:(NSTimeInterval)seconds
  1033. {
  1034. [_mediaPlayer jumpForward:seconds];
  1035. }
  1036. - (void)remoteControlService:(VLCRemoteControlService *)rcs jumpBackwardInSeconds:(NSTimeInterval)seconds
  1037. {
  1038. [_mediaPlayer jumpBackward:seconds];
  1039. }
  1040. - (NSInteger)remoteControlServiceNumberOfMediaItemsinList:(VLCRemoteControlService *)rcs
  1041. {
  1042. return _mediaList.count;
  1043. }
  1044. - (void)remoteControlService:(VLCRemoteControlService *)rcs setPlaybackRate:(CGFloat)playbackRate
  1045. {
  1046. self.playbackRate = playbackRate;
  1047. }
  1048. #pragma mark - helpers
  1049. - (NSDictionary *)mediaOptionsDictionary
  1050. {
  1051. NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
  1052. return @{ kVLCSettingNetworkCaching : [defaults objectForKey:kVLCSettingNetworkCaching],
  1053. kVLCSettingStretchAudio : [[defaults objectForKey:kVLCSettingStretchAudio] boolValue] ? kVLCSettingStretchAudioOnValue : kVLCSettingStretchAudioOffValue,
  1054. kVLCSettingTextEncoding : [defaults objectForKey:kVLCSettingTextEncoding],
  1055. kVLCSettingSkipLoopFilter : [defaults objectForKey:kVLCSettingSkipLoopFilter],
  1056. kVLCSettingHardwareDecoding : [defaults objectForKey:kVLCSettingHardwareDecoding]};
  1057. }
  1058. @end