VLCPlaybackController.m 35 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024
  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,
  40. #if TARGET_OS_IOS
  41. AVAudioSessionDelegate,
  42. #endif
  43. VLCMediaDelegate, VLCRemoteControlServiceDelegate>
  44. {
  45. VLCRemoteControlService *_remoteControlService;
  46. BOOL _playerIsSetup;
  47. BOOL _shouldResumePlaying;
  48. BOOL _sessionWillRestart;
  49. BOOL _shouldResumePlayingAfterInteruption;
  50. NSString *_pathToExternalSubtitlesFile;
  51. int _itemInMediaListToBePlayedFirst;
  52. NSTimer *_sleepTimer;
  53. NSUInteger _currentAspectRatio;
  54. UIView *_videoOutputViewWrapper;
  55. UIView *_actualVideoOutputView;
  56. UIView *_preBackgroundWrapperView;
  57. BOOL _needsMetadataUpdate;
  58. BOOL _mediaWasJustStarted;
  59. BOOL _recheckForExistingThumbnail;
  60. BOOL _headphonesWasPlugged;
  61. NSLock *_playbackSessionManagementLock;
  62. VLCDialogProvider *_dialogProvider;
  63. NSMutableArray *_shuffleStack;
  64. }
  65. @end
  66. @implementation VLCPlaybackController
  67. #pragma mark instance management
  68. + (VLCPlaybackController *)sharedInstance
  69. {
  70. static VLCPlaybackController *sharedInstance = nil;
  71. static dispatch_once_t pred;
  72. dispatch_once(&pred, ^{
  73. sharedInstance = [VLCPlaybackController new];
  74. });
  75. return sharedInstance;
  76. }
  77. - (void)dealloc
  78. {
  79. _dialogProvider = nil;
  80. [[NSNotificationCenter defaultCenter] removeObserver:self];
  81. }
  82. - (instancetype)init
  83. {
  84. self = [super init];
  85. if (self) {
  86. // listen to audiosessions and appkit callback
  87. _headphonesWasPlugged = [self areHeadphonesPlugged];
  88. NSNotificationCenter *defaultCenter = [NSNotificationCenter defaultCenter];
  89. [defaultCenter addObserver:self selector:@selector(audioSessionRouteChange:)
  90. name:AVAudioSessionRouteChangeNotification object:nil];
  91. // appkit because we neeed to know when we go to background in order to stop the video, so that we don't crash
  92. [defaultCenter addObserver:self selector:@selector(applicationWillResignActive:)
  93. name:UIApplicationWillResignActiveNotification object:nil];
  94. [defaultCenter addObserver:self selector:@selector(applicationDidBecomeActive:)
  95. name:UIApplicationDidBecomeActiveNotification object:nil];
  96. [defaultCenter addObserver:self selector:@selector(applicationDidEnterBackground:)
  97. name:UIApplicationDidEnterBackgroundNotification object:nil];
  98. _metadata = [VLCMetaData new];
  99. _dialogProvider = [[VLCDialogProvider alloc] initWithLibrary:[VLCLibrary sharedLibrary] customUI:NO];
  100. _playbackSessionManagementLock = [[NSLock alloc] init];
  101. _shuffleMode = NO;
  102. _shuffleStack = [[NSMutableArray alloc] init];
  103. }
  104. return self;
  105. }
  106. - (VLCRemoteControlService *)remoteControlService
  107. {
  108. if (!_remoteControlService) {
  109. _remoteControlService = [[VLCRemoteControlService alloc] init];
  110. _remoteControlService.remoteControlServiceDelegate = self;
  111. }
  112. return _remoteControlService;
  113. }
  114. #pragma mark - playback management
  115. - (void)playMediaList:(VLCMediaList *)mediaList firstIndex:(NSInteger)index subtitlesFilePath:(NSString *)subsFilePath
  116. {
  117. self.mediaList = mediaList;
  118. _itemInMediaListToBePlayedFirst = (int)index;
  119. _pathToExternalSubtitlesFile = subsFilePath;
  120. _sessionWillRestart = self.isPlaying;
  121. self.isPlaying ? [self stopPlayback] : [self startPlayback];
  122. }
  123. - (void)startPlayback
  124. {
  125. if (_playerIsSetup) {
  126. APLog(@"%s: player is already setup, bailing out", __PRETTY_FUNCTION__);
  127. return;
  128. }
  129. BOOL ret = [_playbackSessionManagementLock tryLock];
  130. if (!ret) {
  131. APLog(@"%s: locking failed", __PRETTY_FUNCTION__);
  132. return;
  133. }
  134. #if TARGET_OS_IOS
  135. [[AVAudioSession sharedInstance] setDelegate:self];
  136. #endif
  137. NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
  138. if (!self.mediaList) {
  139. APLog(@"%s: no URL and no media list set, stopping playback", __PRETTY_FUNCTION__);
  140. [_playbackSessionManagementLock unlock];
  141. [self stopPlayback];
  142. return;
  143. }
  144. /* video decoding permanently fails if we don't provide a UIView to draw into on init
  145. * hence we provide one which is not attached to any view controller for off-screen drawing
  146. * and disable video decoding once playback started */
  147. _actualVideoOutputView = [[UIView alloc] initWithFrame:[UIScreen mainScreen].bounds];
  148. _actualVideoOutputView.autoresizingMask = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight;
  149. _actualVideoOutputView.autoresizesSubviews = YES;
  150. if (_pathToExternalSubtitlesFile)
  151. _listPlayer = [[VLCMediaListPlayer alloc] initWithOptions:@[[NSString stringWithFormat:@"--%@=%@", kVLCSettingSubtitlesFilePath, _pathToExternalSubtitlesFile]] andDrawable:_actualVideoOutputView];
  152. else
  153. _listPlayer = [[VLCMediaListPlayer alloc] initWithDrawable:_actualVideoOutputView];
  154. /* to enable debug logging for the playback library instance, switch the boolean below
  155. * note that the library instance used for playback may not necessarily match the instance
  156. * used for media discovery or thumbnailing */
  157. _listPlayer.mediaPlayer.libraryInstance.debugLogging = NO;
  158. _mediaPlayer = _listPlayer.mediaPlayer;
  159. [_mediaPlayer setDelegate:self];
  160. if ([[defaults objectForKey:kVLCSettingPlaybackSpeedDefaultValue] floatValue] != 0)
  161. [_mediaPlayer setRate: [[defaults objectForKey:kVLCSettingPlaybackSpeedDefaultValue] floatValue]];
  162. if ([[defaults objectForKey:kVLCSettingDeinterlace] intValue] != 0)
  163. [_mediaPlayer setDeinterlaceFilter:@"blend"];
  164. else
  165. [_mediaPlayer setDeinterlaceFilter:nil];
  166. if (_pathToExternalSubtitlesFile)
  167. [_mediaPlayer addPlaybackSlave:[NSURL fileURLWithPath:_pathToExternalSubtitlesFile] type:VLCMediaPlaybackSlaveTypeSubtitle enforce:YES];
  168. VLCMedia *media = [_mediaList mediaAtIndex:_itemInMediaListToBePlayedFirst];
  169. [media parseWithOptions:VLCMediaParseLocal];
  170. media.delegate = self;
  171. [media addOptions:self.mediaOptionsDictionary];
  172. [_listPlayer setMediaList:self.mediaList];
  173. [_listPlayer setRepeatMode:VLCDoNotRepeat];
  174. [_playbackSessionManagementLock unlock];
  175. [self _playNewMedia];
  176. }
  177. - (void)_playNewMedia
  178. {
  179. BOOL ret = [_playbackSessionManagementLock tryLock];
  180. if (!ret) {
  181. APLog(@"%s: locking failed", __PRETTY_FUNCTION__);
  182. return;
  183. }
  184. // Set last selected equalizer profile
  185. unsigned int profile = (unsigned int)[[[NSUserDefaults standardUserDefaults] objectForKey:kVLCSettingEqualizerProfile] integerValue];
  186. [_mediaPlayer resetEqualizerFromProfile:profile];
  187. [_mediaPlayer setPreAmplification:[_mediaPlayer preAmplification]];
  188. _mediaWasJustStarted = YES;
  189. [_mediaPlayer addObserver:self forKeyPath:@"time" options:0 context:nil];
  190. [_mediaPlayer addObserver:self forKeyPath:@"remainingTime" options:0 context:nil];
  191. [_listPlayer playItemAtNumber:@(_itemInMediaListToBePlayedFirst)];
  192. if ([self.delegate respondsToSelector:@selector(prepareForMediaPlayback:)])
  193. [self.delegate prepareForMediaPlayback:self];
  194. _currentAspectRatio = VLCAspectRatioDefault;
  195. _mediaPlayer.videoAspectRatio = NULL;
  196. _mediaPlayer.scaleFactor = 0;
  197. [[self remoteControlService] subscribeToRemoteCommands];
  198. _playerIsSetup = YES;
  199. [[NSNotificationCenter defaultCenter] postNotificationName:VLCPlaybackControllerPlaybackDidStart object:self];
  200. [_playbackSessionManagementLock unlock];
  201. }
  202. - (void)stopPlayback
  203. {
  204. BOOL ret = [_playbackSessionManagementLock tryLock];
  205. if (!ret) {
  206. APLog(@"%s: locking failed", __PRETTY_FUNCTION__);
  207. return;
  208. }
  209. if (_mediaPlayer) {
  210. @try {
  211. [_mediaPlayer removeObserver:self forKeyPath:@"time"];
  212. [_mediaPlayer removeObserver:self forKeyPath:@"remainingTime"];
  213. }
  214. @catch (NSException *exception) {
  215. APLog(@"we weren't an observer yet");
  216. }
  217. if (_mediaPlayer.media) {
  218. [_mediaPlayer pause];
  219. #if TARGET_OS_IOS
  220. [self _savePlaybackState];
  221. #endif
  222. [_mediaPlayer stop];
  223. }
  224. _mediaPlayer = nil;
  225. _listPlayer = nil;
  226. }
  227. if (!_sessionWillRestart) {
  228. _mediaList = nil;
  229. if (_pathToExternalSubtitlesFile) {
  230. NSFileManager *fileManager = [NSFileManager defaultManager];
  231. if ([fileManager fileExistsAtPath:_pathToExternalSubtitlesFile])
  232. [fileManager removeItemAtPath:_pathToExternalSubtitlesFile error:nil];
  233. _pathToExternalSubtitlesFile = nil;
  234. }
  235. }
  236. _playerIsSetup = NO;
  237. [_shuffleStack removeAllObjects];
  238. if (_errorCallback && _mediaPlayer.state == VLCMediaPlayerStateError && !_sessionWillRestart)
  239. [[UIApplication sharedApplication] openURL:_errorCallback];
  240. else if (_successCallback && !_sessionWillRestart)
  241. [[UIApplication sharedApplication] openURL:_successCallback];
  242. [[self remoteControlService] unsubscribeFromRemoteCommands];
  243. [_playbackSessionManagementLock unlock];
  244. if (!_sessionWillRestart) {
  245. [[NSNotificationCenter defaultCenter] postNotificationName:VLCPlaybackControllerPlaybackDidStop object:self];
  246. } else {
  247. _sessionWillRestart = NO;
  248. [self startPlayback];
  249. }
  250. }
  251. #if TARGET_OS_IOS
  252. - (void)_savePlaybackState
  253. {
  254. @try {
  255. [[MLMediaLibrary sharedMediaLibrary] save];
  256. }
  257. @catch (NSException *exception) {
  258. APLog(@"saving playback state failed");
  259. }
  260. NSArray *files = [MLFile fileForURL:_mediaPlayer.media.url];
  261. MLFile *fileItem = files.firstObject;
  262. if (!fileItem) {
  263. APLog(@"couldn't find file, not saving playback progress");
  264. return;
  265. }
  266. @try {
  267. float position = _mediaPlayer.position;
  268. fileItem.lastPosition = @(position);
  269. fileItem.lastAudioTrack = @(_mediaPlayer.currentAudioTrackIndex);
  270. fileItem.lastSubtitleTrack = @(_mediaPlayer.currentVideoSubTitleIndex);
  271. if (position > .95)
  272. return;
  273. NSArray *searchPaths = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES);
  274. NSString* newThumbnailPath = [searchPaths[0] stringByAppendingPathComponent:@"VideoSnapshots"];
  275. NSFileManager *fileManager = [NSFileManager defaultManager];
  276. if (![fileManager fileExistsAtPath:newThumbnailPath])
  277. [fileManager createDirectoryAtPath:newThumbnailPath withIntermediateDirectories:YES attributes:nil error:nil];
  278. newThumbnailPath = [newThumbnailPath stringByAppendingPathComponent:fileItem.objectID.URIRepresentation.lastPathComponent];
  279. [_mediaPlayer saveVideoSnapshotAt:newThumbnailPath withWidth:0 andHeight:0];
  280. _recheckForExistingThumbnail = YES;
  281. [self performSelector:@selector(_updateStoredThumbnailForFile:) withObject:fileItem afterDelay:.25];
  282. }
  283. @catch (NSException *exception) {
  284. APLog(@"failed to save current media state - file removed?");
  285. }
  286. }
  287. #endif
  288. #if TARGET_OS_IOS
  289. - (void)_updateStoredThumbnailForFile:(MLFile *)fileItem
  290. {
  291. NSFileManager *fileManager = [NSFileManager defaultManager];
  292. NSArray *searchPaths = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES);
  293. NSString* newThumbnailPath = [searchPaths[0] stringByAppendingPathComponent:@"VideoSnapshots"];
  294. newThumbnailPath = [newThumbnailPath stringByAppendingPathComponent:fileItem.objectID.URIRepresentation.lastPathComponent];
  295. if (![fileManager fileExistsAtPath:newThumbnailPath]) {
  296. if (_recheckForExistingThumbnail) {
  297. [self performSelector:@selector(_updateStoredThumbnailForFile:) withObject:fileItem afterDelay:1.];
  298. _recheckForExistingThumbnail = NO;
  299. } else
  300. return;
  301. }
  302. UIImage *newThumbnail = [UIImage imageWithContentsOfFile:newThumbnailPath];
  303. if (!newThumbnail) {
  304. if (_recheckForExistingThumbnail) {
  305. [self performSelector:@selector(_updateStoredThumbnailForFile:) withObject:fileItem afterDelay:1.];
  306. _recheckForExistingThumbnail = NO;
  307. } else
  308. return;
  309. }
  310. @try {
  311. [fileItem setComputedThumbnailScaledForDevice:newThumbnail];
  312. }
  313. @catch (NSException *exception) {
  314. APLog(@"updating thumbnail failed");
  315. }
  316. [fileManager removeItemAtPath:newThumbnailPath error:nil];
  317. }
  318. #endif
  319. - (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context
  320. {
  321. if (_mediaWasJustStarted) {
  322. _mediaWasJustStarted = NO;
  323. #if TARGET_OS_IOS
  324. if (self.mediaList) {
  325. NSArray *matches = [MLFile fileForURL:_mediaPlayer.media.url];
  326. MLFile *item = matches.firstObject;
  327. [self _recoverLastPlaybackStateOfItem:item];
  328. }
  329. #else
  330. NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
  331. BOOL bValue = [defaults boolForKey:kVLCSettingUseSPDIF];
  332. if (bValue) {
  333. _mediaPlayer.audio.passthrough = bValue;
  334. }
  335. #endif
  336. }
  337. if ([self.delegate respondsToSelector:@selector(playbackPositionUpdated:)])
  338. [self.delegate playbackPositionUpdated:self];
  339. [[NSNotificationCenter defaultCenter] postNotificationName:VLCPlaybackControllerPlaybackPositionUpdated
  340. object:self];
  341. }
  342. - (NSInteger)mediaDuration
  343. {
  344. return _mediaPlayer.media.length.intValue;;
  345. }
  346. - (BOOL)isPlaying
  347. {
  348. return _mediaPlayer.isPlaying;
  349. }
  350. - (VLCRepeatMode)repeatMode
  351. {
  352. return _listPlayer.repeatMode;
  353. }
  354. - (void)setRepeatMode:(VLCRepeatMode)repeatMode
  355. {
  356. _listPlayer.repeatMode = repeatMode;
  357. }
  358. - (BOOL)currentMediaHasChapters
  359. {
  360. return [_mediaPlayer numberOfTitles] > 1 || [_mediaPlayer numberOfChaptersForTitle:_mediaPlayer.currentTitleIndex] > 1;
  361. }
  362. - (BOOL)currentMediaHasTrackToChooseFrom
  363. {
  364. return [[_mediaPlayer audioTrackIndexes] count] > 2 || [[_mediaPlayer videoSubTitlesIndexes] count] > 1;
  365. }
  366. - (NSNumber *)playbackTime
  367. {
  368. return _mediaPlayer.time.value;
  369. }
  370. - (float)playbackRate
  371. {
  372. return _mediaPlayer.rate;
  373. }
  374. - (void)setPlaybackRate:(float)playbackRate
  375. {
  376. [_mediaPlayer setRate:playbackRate];
  377. _metadata.playbackRate = @(_mediaPlayer.rate);
  378. }
  379. - (void)setAudioDelay:(float)audioDelay
  380. {
  381. _mediaPlayer.currentAudioPlaybackDelay = 1000000.*audioDelay;
  382. }
  383. - (float)audioDelay
  384. {
  385. return _mediaPlayer.currentAudioPlaybackDelay/1000000.;
  386. }
  387. -(void)setSubtitleDelay:(float)subtitleDeleay
  388. {
  389. _mediaPlayer.currentVideoSubTitleDelay = 1000000.*subtitleDeleay;
  390. }
  391. - (float)subtitleDelay
  392. {
  393. return _mediaPlayer.currentVideoSubTitleDelay/1000000.;
  394. }
  395. - (void)mediaPlayerStateChanged:(NSNotification *)aNotification
  396. {
  397. VLCMediaPlayerState currentState = _mediaPlayer.state;
  398. if (currentState == VLCMediaPlayerStateBuffering) {
  399. /* attach delegate */
  400. _mediaPlayer.media.delegate = self;
  401. /* on-the-fly values through hidden API */
  402. NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
  403. [_mediaPlayer performSelector:@selector(setTextRendererFont:) withObject:[defaults objectForKey:kVLCSettingSubtitlesFont]];
  404. [_mediaPlayer performSelector:@selector(setTextRendererFontSize:) withObject:[defaults objectForKey:kVLCSettingSubtitlesFontSize]];
  405. [_mediaPlayer performSelector:@selector(setTextRendererFontColor:) withObject:[defaults objectForKey:kVLCSettingSubtitlesFontColor]];
  406. [_mediaPlayer performSelector:@selector(setTextRendererFontForceBold:) withObject:[defaults objectForKey:kVLCSettingSubtitlesBoldFont]];
  407. } else if (currentState == VLCMediaPlayerStateError) {
  408. APLog(@"Playback failed");
  409. dispatch_async(dispatch_get_main_queue(),^{
  410. [[NSNotificationCenter defaultCenter] postNotificationName:VLCPlaybackControllerPlaybackDidFail object:self];
  411. });
  412. _sessionWillRestart = NO;
  413. [self stopPlayback];
  414. } else if (currentState == VLCMediaPlayerStateEnded || currentState == VLCMediaPlayerStateStopped) {
  415. [_listPlayer.mediaList lock];
  416. NSUInteger listCount = _listPlayer.mediaList.count;
  417. if ([_listPlayer.mediaList indexOfMedia:_mediaPlayer.media] == listCount - 1 && self.repeatMode == VLCDoNotRepeat) {
  418. [_listPlayer.mediaList unlock];
  419. _sessionWillRestart = NO;
  420. [self stopPlayback];
  421. return;
  422. } else if (listCount > 1) {
  423. [_listPlayer.mediaList unlock];
  424. [_listPlayer next];
  425. } else
  426. [_listPlayer.mediaList unlock];
  427. }
  428. if ([self.delegate respondsToSelector:@selector(mediaPlayerStateChanged:isPlaying:currentMediaHasTrackToChooseFrom:currentMediaHasChapters:forPlaybackController:)])
  429. [self.delegate mediaPlayerStateChanged:currentState
  430. isPlaying:_mediaPlayer.isPlaying
  431. currentMediaHasTrackToChooseFrom:self.currentMediaHasTrackToChooseFrom
  432. currentMediaHasChapters:self.currentMediaHasChapters
  433. forPlaybackController:self];
  434. [self setNeedsMetadataUpdate];
  435. }
  436. #pragma mark - playback controls
  437. - (void)playPause
  438. {
  439. if ([_mediaPlayer isPlaying]) {
  440. [_listPlayer pause];
  441. #if TARGET_OS_IOS
  442. [self _savePlaybackState];
  443. #endif
  444. [[NSNotificationCenter defaultCenter] postNotificationName:VLCPlaybackControllerPlaybackDidPause object:self];
  445. } else {
  446. [_listPlayer play];
  447. [[NSNotificationCenter defaultCenter] postNotificationName:VLCPlaybackControllerPlaybackDidResume object:self];
  448. }
  449. }
  450. - (void)forward
  451. {
  452. NSInteger mediaListCount = _mediaList.count;
  453. #if TARGET_OS_IOS
  454. if (mediaListCount > 2 && _shuffleMode) {
  455. NSNumber *nextIndex;
  456. NSUInteger currentIndex = [_mediaList indexOfMedia:_listPlayer.mediaPlayer.media];
  457. //Reached end of playlist
  458. if (_shuffleStack.count + 1 == mediaListCount) {
  459. if ([self repeatMode] == VLCDoNotRepeat)
  460. return;
  461. [_shuffleStack removeAllObjects];
  462. }
  463. [_shuffleStack addObject:[NSNumber numberWithUnsignedInteger:currentIndex]];
  464. do {
  465. nextIndex = [NSNumber numberWithUnsignedInt:arc4random_uniform((uint32_t)mediaListCount)];
  466. } while (currentIndex == nextIndex.unsignedIntegerValue || [_shuffleStack containsObject:nextIndex]);
  467. [_listPlayer playItemAtNumber:[NSNumber numberWithUnsignedInteger:nextIndex.unsignedIntegerValue]];
  468. [[NSNotificationCenter defaultCenter] postNotificationName:VLCPlaybackControllerPlaybackMetadataDidChange object:self];
  469. return;
  470. }
  471. #endif
  472. if (mediaListCount > 1) {
  473. [_listPlayer next];
  474. [[NSNotificationCenter defaultCenter] postNotificationName:VLCPlaybackControllerPlaybackMetadataDidChange object:self];
  475. } else {
  476. NSNumber *skipLength = [[NSUserDefaults standardUserDefaults] valueForKey:kVLCSettingPlaybackForwardSkipLength];
  477. [_mediaPlayer jumpForward:skipLength.intValue];
  478. }
  479. }
  480. - (void)backward
  481. {
  482. if (_mediaList.count > 1) {
  483. [_listPlayer previous];
  484. [[NSNotificationCenter defaultCenter] postNotificationName:VLCPlaybackControllerPlaybackMetadataDidChange object:self];
  485. }
  486. else {
  487. NSNumber *skipLength = [[NSUserDefaults standardUserDefaults] valueForKey:kVLCSettingPlaybackBackwardSkipLength];
  488. [_mediaPlayer jumpBackward:skipLength.intValue];
  489. }
  490. }
  491. - (void)switchAspectRatio
  492. {
  493. if (_currentAspectRatio == VLCAspectRatioSixteenToTen) {
  494. _mediaPlayer.videoAspectRatio = NULL;
  495. _mediaPlayer.scaleFactor = 0;
  496. _currentAspectRatio = VLCAspectRatioDefault;
  497. } else {
  498. _currentAspectRatio++;
  499. if (_currentAspectRatio == VLCAspectRatioFillToScreen) {
  500. UIScreen *screen;
  501. if (![[UIDevice currentDevice] VLCHasExternalDisplay])
  502. screen = [UIScreen mainScreen];
  503. else
  504. screen = [UIScreen screens][1];
  505. float f_ar = screen.bounds.size.width / screen.bounds.size.height;
  506. if (f_ar == (float)(4.0/3.0) ||
  507. f_ar == (float)(1366./1024.)) {
  508. // all iPads
  509. _mediaPlayer.videoCropGeometry = "4:3";
  510. } else if (f_ar == (float)(2./3.) || f_ar == (float)(480./320.)) {
  511. // all other iPhones
  512. _mediaPlayer.videoCropGeometry = "16:10"; // libvlc doesn't support 2:3 crop
  513. } else if (f_ar == .5625) {
  514. // AirPlay
  515. _mediaPlayer.videoCropGeometry = "16:9";
  516. } else if (f_ar == (float)(640./1136.) ||
  517. f_ar == (float)(568./320.) ||
  518. f_ar == (float)(667./375.) ||
  519. f_ar == (float)(736./414.)) {
  520. // iPhone 5 and 6 and 6+
  521. _mediaPlayer.videoCropGeometry = "16:9";
  522. } else
  523. APLog(@"unknown screen format %f, can't crop", f_ar);
  524. } else {
  525. _mediaPlayer.videoAspectRatio = (char *)[[self stringForAspectRatio:_currentAspectRatio] UTF8String];
  526. _mediaPlayer.videoCropGeometry = NULL;
  527. }
  528. }
  529. if ([self.delegate respondsToSelector:@selector(showStatusMessage:forPlaybackController:)]) {
  530. [self.delegate showStatusMessage:[NSString stringWithFormat:NSLocalizedString(@"AR_CHANGED", nil), [self stringForAspectRatio:_currentAspectRatio]] forPlaybackController:self];
  531. }
  532. }
  533. - (NSString *)stringForAspectRatio:(VLCAspectRatio)ratio
  534. {
  535. switch (ratio) {
  536. case VLCAspectRatioFillToScreen:
  537. return NSLocalizedString(@"FILL_TO_SCREEN", nil);
  538. case VLCAspectRatioDefault:
  539. return NSLocalizedString(@"DEFAULT", nil);
  540. case VLCAspectRatioFourToThree:
  541. return @"4:3";
  542. case VLCAspectRatioSixteenToTen:
  543. return @"16:10";
  544. case VLCAspectRatioSixteenToNine:
  545. return @"16:9";
  546. default:
  547. NSAssert(NO, @"this shouldn't happen");
  548. }
  549. }
  550. - (void)setVideoTrackEnabled:(BOOL)enabled
  551. {
  552. if (!enabled)
  553. _mediaPlayer.currentVideoTrackIndex = -1;
  554. else if (_mediaPlayer.currentVideoTrackIndex == -1) {
  555. for (NSNumber *trackId in _mediaPlayer.videoTrackIndexes) {
  556. if ([trackId intValue] != -1) {
  557. _mediaPlayer.currentVideoTrackIndex = [trackId intValue];
  558. break;
  559. }
  560. }
  561. }
  562. }
  563. - (void)setVideoOutputView:(UIView *)videoOutputView
  564. {
  565. if (videoOutputView) {
  566. if ([_actualVideoOutputView superview] != nil)
  567. [_actualVideoOutputView removeFromSuperview];
  568. _actualVideoOutputView.frame = (CGRect){CGPointZero, videoOutputView.frame.size};
  569. [self setVideoTrackEnabled:true];
  570. [videoOutputView addSubview:_actualVideoOutputView];
  571. [_actualVideoOutputView layoutSubviews];
  572. [_actualVideoOutputView updateConstraints];
  573. [_actualVideoOutputView setNeedsLayout];
  574. } else
  575. [_actualVideoOutputView removeFromSuperview];
  576. _videoOutputViewWrapper = videoOutputView;
  577. }
  578. - (UIView *)videoOutputView
  579. {
  580. return _videoOutputViewWrapper;
  581. }
  582. #pragma mark - 360 Support
  583. #if !TARGET_OS_TV
  584. - (BOOL)updateViewpoint:(CGFloat)yaw pitch:(CGFloat)pitch roll:(CGFloat)roll fov:(CGFloat)fov absolute:(BOOL)absolute
  585. {
  586. return [_mediaPlayer updateViewpoint:yaw pitch:pitch roll:roll fov:fov absolute:absolute];
  587. }
  588. - (NSInteger)currentMediaProjection
  589. {
  590. VLCMedia *media = [_mediaPlayer media];
  591. NSInteger currentVideoTrackIndex = [_mediaPlayer currentVideoTrackIndex];
  592. if (media && currentVideoTrackIndex >= 0) {
  593. NSArray *tracksInfo = media.tracksInformation;
  594. for (NSDictionary *track in tracksInfo) {
  595. if ([track[VLCMediaTracksInformationType] isEqualToString:VLCMediaTracksInformationTypeVideo]) {
  596. return [track[VLCMediaTracksInformationVideoProjection] integerValue];
  597. }
  598. }
  599. }
  600. return -1;
  601. }
  602. #endif
  603. #pragma mark - equalizer
  604. - (void)setAmplification:(CGFloat)amplification forBand:(unsigned int)index
  605. {
  606. if (!_mediaPlayer.equalizerEnabled)
  607. [_mediaPlayer setEqualizerEnabled:YES];
  608. [_mediaPlayer setAmplification:amplification forBand:index];
  609. // For some reason we have to apply again preamp to apply change
  610. [_mediaPlayer setPreAmplification:[_mediaPlayer preAmplification]];
  611. }
  612. - (CGFloat)amplificationOfBand:(unsigned int)index
  613. {
  614. return [_mediaPlayer amplificationOfBand:index];
  615. }
  616. - (NSArray *)equalizerProfiles
  617. {
  618. return _mediaPlayer.equalizerProfiles;
  619. }
  620. - (void)resetEqualizerFromProfile:(unsigned int)profile
  621. {
  622. [[NSUserDefaults standardUserDefaults] setObject:@(profile) forKey:kVLCSettingEqualizerProfile];
  623. [_mediaPlayer resetEqualizerFromProfile:profile];
  624. }
  625. - (void)setPreAmplification:(CGFloat)preAmplification
  626. {
  627. if (!_mediaPlayer.equalizerEnabled)
  628. [_mediaPlayer setEqualizerEnabled:YES];
  629. [_mediaPlayer setPreAmplification:preAmplification];
  630. }
  631. - (CGFloat)preAmplification
  632. {
  633. return [_mediaPlayer preAmplification];
  634. }
  635. #pragma mark - AVSession delegate
  636. - (void)beginInterruption
  637. {
  638. if ([_mediaPlayer isPlaying]) {
  639. [_mediaPlayer pause];
  640. _shouldResumePlayingAfterInteruption = YES;
  641. }
  642. }
  643. - (void)endInterruption
  644. {
  645. if (_shouldResumePlayingAfterInteruption) {
  646. [_mediaPlayer play];
  647. _shouldResumePlayingAfterInteruption = NO;
  648. }
  649. }
  650. - (BOOL)areHeadphonesPlugged
  651. {
  652. NSArray *outputs = [[AVAudioSession sharedInstance] currentRoute].outputs;
  653. NSString *portName = [[outputs firstObject] portName];
  654. return [portName isEqualToString:@"Headphones"];
  655. }
  656. - (void)audioSessionRouteChange:(NSNotification *)notification
  657. {
  658. NSDictionary *userInfo = notification.userInfo;
  659. NSInteger routeChangeReason = [[userInfo valueForKey:AVAudioSessionRouteChangeReasonKey] integerValue];
  660. if (routeChangeReason == AVAudioSessionRouteChangeReasonRouteConfigurationChange)
  661. return;
  662. BOOL headphonesPlugged = [self areHeadphonesPlugged];
  663. if (_headphonesWasPlugged && !headphonesPlugged && [_mediaPlayer isPlaying]) {
  664. [_mediaPlayer pause];
  665. #if TARGET_OS_IOS
  666. [self _savePlaybackState];
  667. #endif
  668. [[NSNotificationCenter defaultCenter] postNotificationName:VLCPlaybackControllerPlaybackDidPause object:self];
  669. }
  670. _headphonesWasPlugged = headphonesPlugged;
  671. }
  672. #pragma mark - Managing the media item
  673. #if TARGET_OS_IOS
  674. - (MLFile *)currentlyPlayingMediaFile {
  675. if (self.mediaList) {
  676. NSArray *results = [MLFile fileForURL:_mediaPlayer.media.url];
  677. return results.firstObject;
  678. }
  679. return nil;
  680. }
  681. #endif
  682. #pragma mark - metadata handling
  683. - (void)mediaDidFinishParsing:(VLCMedia *)aMedia
  684. {
  685. [self setNeedsMetadataUpdate];
  686. }
  687. - (void)mediaMetaDataDidChange:(VLCMedia*)aMedia
  688. {
  689. [self setNeedsMetadataUpdate];
  690. }
  691. - (void)setNeedsMetadataUpdate
  692. {
  693. if (_needsMetadataUpdate == NO) {
  694. _needsMetadataUpdate = YES;
  695. dispatch_async(dispatch_get_main_queue(), ^{
  696. [_metadata updateMetadataFromMediaPlayer:_mediaPlayer];
  697. _needsMetadataUpdate = NO;
  698. if ([self.delegate respondsToSelector:@selector(displayMetadataForPlaybackController:metadata:)])
  699. [self.delegate displayMetadataForPlaybackController:self metadata:_metadata];
  700. });
  701. }
  702. }
  703. #if TARGET_OS_IOS
  704. - (void)_recoverLastPlaybackStateOfItem:(MLFile *)item
  705. {
  706. if (item) {
  707. if (_mediaPlayer.numberOfAudioTracks > 2) {
  708. if (item.lastAudioTrack.intValue > 0)
  709. _mediaPlayer.currentAudioTrackIndex = item.lastAudioTrack.intValue;
  710. }
  711. if (_mediaPlayer.numberOfSubtitlesTracks > 2) {
  712. if (item.lastSubtitleTrack.intValue > 0)
  713. _mediaPlayer.currentVideoSubTitleIndex = item.lastSubtitleTrack.intValue;
  714. }
  715. CGFloat lastPosition = .0;
  716. NSInteger duration = 0;
  717. if (item.lastPosition)
  718. lastPosition = item.lastPosition.floatValue;
  719. duration = item.duration.intValue;
  720. if (lastPosition < .95 && _mediaPlayer.position < lastPosition && (duration * lastPosition - duration) < -50000) {
  721. NSInteger continuePlayback;
  722. if ([item isAlbumTrack] || [item isSupportedAudioFile])
  723. continuePlayback = [[[NSUserDefaults standardUserDefaults] objectForKey:kVLCSettingContinueAudioPlayback] integerValue];
  724. else
  725. continuePlayback = [[[NSUserDefaults standardUserDefaults] objectForKey:kVLCSettingContinuePlayback] integerValue];
  726. if (continuePlayback == 1) {
  727. _mediaPlayer.position = lastPosition;
  728. } else if (continuePlayback == 0) {
  729. VLCAlertView *alert = [[VLCAlertView alloc] initWithTitle:NSLocalizedString(@"CONTINUE_PLAYBACK", nil)
  730. message:[NSString stringWithFormat:NSLocalizedString(@"CONTINUE_PLAYBACK_LONG", nil), item.title]
  731. delegate:self
  732. cancelButtonTitle:NSLocalizedString(@"BUTTON_CANCEL", nil)
  733. otherButtonTitles:NSLocalizedString(@"BUTTON_CONTINUE", nil), nil];
  734. alert.completion = ^(BOOL cancelled, NSInteger buttonIndex) {
  735. if (!cancelled) {
  736. _mediaPlayer.position = lastPosition;
  737. }
  738. };
  739. [alert show];
  740. }
  741. }
  742. }
  743. }
  744. #endif
  745. - (void)recoverDisplayedMetadata
  746. {
  747. if ([self.delegate respondsToSelector:@selector(displayMetadataForPlaybackController:metadata:)])
  748. [self.delegate displayMetadataForPlaybackController:self metadata:_metadata];
  749. }
  750. - (void)recoverPlaybackState
  751. {
  752. if ([self.delegate respondsToSelector:@selector(mediaPlayerStateChanged:isPlaying:currentMediaHasTrackToChooseFrom:currentMediaHasChapters:forPlaybackController:)])
  753. [self.delegate mediaPlayerStateChanged:_mediaPlayer.state
  754. isPlaying:self.isPlaying
  755. currentMediaHasTrackToChooseFrom:self.currentMediaHasTrackToChooseFrom
  756. currentMediaHasChapters:self.currentMediaHasChapters
  757. forPlaybackController:self];
  758. if ([self.delegate respondsToSelector:@selector(prepareForMediaPlayback:)])
  759. [self.delegate prepareForMediaPlayback:self];
  760. }
  761. - (void)scheduleSleepTimerWithInterval:(NSTimeInterval)timeInterval
  762. {
  763. if (_sleepTimer) {
  764. [_sleepTimer invalidate];
  765. _sleepTimer = nil;
  766. }
  767. _sleepTimer = [NSTimer scheduledTimerWithTimeInterval:timeInterval target:self selector:@selector(stopPlayback) userInfo:nil repeats:NO];
  768. }
  769. #pragma mark - background interaction
  770. - (void)applicationWillResignActive:(NSNotification *)aNotification
  771. {
  772. #if TARGET_OS_IOS
  773. [self _savePlaybackState];
  774. #endif
  775. if (![[[NSUserDefaults standardUserDefaults] objectForKey:kVLCSettingContinueAudioInBackgroundKey] boolValue]) {
  776. if ([_mediaPlayer isPlaying]) {
  777. [_mediaPlayer pause];
  778. _shouldResumePlaying = YES;
  779. }
  780. }
  781. }
  782. - (void)applicationDidEnterBackground:(NSNotification *)notification
  783. {
  784. _preBackgroundWrapperView = _videoOutputViewWrapper;
  785. if (_mediaPlayer.audioTrackIndexes.count > 0)
  786. [self setVideoTrackEnabled:false];
  787. }
  788. - (void)applicationDidBecomeActive:(NSNotification *)notification
  789. {
  790. if (_preBackgroundWrapperView) {
  791. [self setVideoOutputView:_preBackgroundWrapperView];
  792. _preBackgroundWrapperView = nil;
  793. }
  794. [self setVideoTrackEnabled:true];
  795. if (_shouldResumePlaying) {
  796. _shouldResumePlaying = NO;
  797. [_listPlayer play];
  798. }
  799. }
  800. #pragma mark - remoteControlDelegate
  801. - (void)remoteControlServiceHitPause:(VLCRemoteControlService *)rcs
  802. {
  803. [_listPlayer pause];
  804. }
  805. - (void)remoteControlServiceHitPlay:(VLCRemoteControlService *)rcs
  806. {
  807. [_listPlayer play];
  808. }
  809. - (void)remoteControlServiceTogglePlayPause:(VLCRemoteControlService *)rcs
  810. {
  811. [self playPause];
  812. }
  813. - (void)remoteControlServiceHitStop:(VLCRemoteControlService *)rcs
  814. {
  815. //TODO handle stop playback entirely
  816. [_listPlayer stop];
  817. }
  818. - (BOOL)remoteControlServiceHitPlayNextIfPossible:(VLCRemoteControlService *)rcs
  819. {
  820. //TODO This doesn't handle shuffle or repeat yet
  821. return [_listPlayer next];
  822. }
  823. - (BOOL)remoteControlServiceHitPlayPreviousIfPossible:(VLCRemoteControlService *)rcs
  824. {
  825. //TODO This doesn't handle shuffle or repeat yet
  826. return [_listPlayer previous];
  827. }
  828. - (void)remoteControlService:(VLCRemoteControlService *)rcs jumpForwardInSeconds:(NSTimeInterval)seconds
  829. {
  830. [_mediaPlayer jumpForward:seconds];
  831. }
  832. - (void)remoteControlService:(VLCRemoteControlService *)rcs jumpBackwardInSeconds:(NSTimeInterval)seconds
  833. {
  834. [_mediaPlayer jumpBackward:seconds];
  835. }
  836. - (NSInteger)remoteControlServiceNumberOfMediaItemsinList:(VLCRemoteControlService *)rcs
  837. {
  838. return _mediaList.count;
  839. }
  840. - (void)remoteControlService:(VLCRemoteControlService *)rcs setPlaybackRate:(CGFloat)playbackRate
  841. {
  842. self.playbackRate = playbackRate;
  843. }
  844. #pragma mark - helpers
  845. - (NSDictionary *)mediaOptionsDictionary
  846. {
  847. NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
  848. return @{ kVLCSettingNetworkCaching : [defaults objectForKey:kVLCSettingNetworkCaching],
  849. kVLCSettingStretchAudio : [[defaults objectForKey:kVLCSettingStretchAudio] boolValue] ? kVLCSettingStretchAudioOnValue : kVLCSettingStretchAudioOffValue,
  850. kVLCSettingTextEncoding : [defaults objectForKey:kVLCSettingTextEncoding],
  851. kVLCSettingSkipLoopFilter : [defaults objectForKey:kVLCSettingSkipLoopFilter],
  852. kVLCSettingHardwareDecoding : [defaults objectForKey:kVLCSettingHardwareDecoding]};
  853. }
  854. @end