VLCPlaybackController.m 35 KB

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