VLCPlaybackController.m 40 KB

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