VLCPlaybackController.m 41 KB

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