VLCPlaybackController.m 36 KB

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